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>9Nonami/test-client-server<file_sep>/Client.java import java.io.*; import java.net.*; public class Client { public static void main(String[] args) { new Client(); } public Client() { try { Socket socket = new Socket("", 0000); InputStreamReader isr = new InputStreamReader(socket.getInputStream()); BufferedReader br = new BufferedReader(isr); String s = br.readLine(); System.out.println(s); isr.close(); } catch(Exception ex) { ex.printStackTrace(); } } }
468a8e6ede09bae862b7cd9fb970231fd1125606
[ "Java" ]
1
Java
9Nonami/test-client-server
399398fe9dd9cdc6574ae2e9c9515b158efa44b2
32fc38956125011269cb2dfbaa9fdc0c46a1332b
refs/heads/master
<repo_name>louis-ev/timelure<file_sep>/site/snippets/header.php <!DOCTYPE html> <html lang="<?php echo $kirby->language() ?? 'fr' ?>"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <script>document.getElementsByTagName('html')[0].className = 'js'</script> <?php snippet("header.metas") ?> <?php if ( option('environment') == 'local' ) : foreach ( option('basic-devkit.assets.styles', array()) as $style): echo css($style.'?version='.md5(uniqid(rand(), true))); endforeach; else: echo css('assets/production/all.min.css'); endif ?> <style> <?php $i=1; foreach(page('themes')->children() as $theme):?> .year span:nth-of-type(<?= $i ?>), .<?= $theme->slug() ?> .event h3, .<?= $theme->slug() ?> { --color: <?= $theme->color() ?>; } <?php $i++; endforeach ?> </style> </head> <body data-login="<?php e($kirby->user(),'true', 'false') ?>" data-template="<?php echo $page->template() ?>" data-intended-template="<?php echo $page->intendedTemplate() ?>"> <div id="header"> <div> <header > <h1><a href="<?= $site->url() ?>"><?= $site->title() ?></a></h1> <?php e($site->tagline()->isNotEmpty(), "<p>" . $site->tagline()->kti() . "</p>" ) ?> </header> <nav id="years-nav"> <ul> <li><a href="<?= $site->url()?>#annee-1953">1953</a></li> <li><a href="<?= $site->url()?>#annee-1960">1960</a></li> <li><a href="<?= $site->url()?>#annee-1970">1970</a></li> <li><a href="<?= $site->url()?>#annee-1980">1980</a></li> <li><a href="<?= $site->url()?>#annee-1990">1990</a></li> <li><a href="<?= $site->url()?>#annee-2000">2000</a></li> <li><a href="<?= $site->url()?>#annee-2010">2010</a></li> <li><a href="<?= $site->url()?>#annee-2020">2020</a></li> </ul> </nav> <?php if($page->intendedTemplate() == "home") :?><?php endif ?> </div> </div> <file_sep>/site/templates/home.php <?php snippet('header') ?> <main id="home"> <header> <?php foreach(page('themes')->children() as $theme) :?> <div class="<?= $theme->slug() ?>"> <h2><?= $theme->title() ?></h2> <?php e($theme->introduction()->isNotEmpty(), '<div class="introduction">' . $theme->introduction()->kt() . '</div>') ?> </div> <?php endforeach ?> </header> <?php $years = page('annees')->children()->listed(); foreach($years as $year) : $themes = page('chronologie')->children()->listed()->filterBy('year', $year->title())->groupBy('theme'); ?> <section id="annee-<?= $year->slug() ?>" class="year"> <h2><?= $year->title() ?></h2> <?php foreach($themes as $theme => $events) : $mytheme = autoid($theme); ?> <div class="events <?= $mytheme->slug() ?>"> <?php foreach($events as $event) : ?> <?php snippet("block-" . $event->intendedTemplate(), ['event'=>$event])?> <?php endforeach ?> </div> <?php endforeach ?> </section> <div id="annee-<?= $year->slug() ?>-content" class="year-content"></div> <?php endforeach ?> </main> <?php snippet('footer') ?> <file_sep>/site/snippets/block-event.php <article id="annee-<?= $event->year() ?>-<?= $event->slug() ?>" class="timeline-event <?= $event->theme()->fromAutoID()->slug() ?>" > <a href="<?= $event->url() ?>" class="event-link"> <h3><?= $event->title() ?></h3> <?php if($event->introduction()->isNotEmpty()) :?> <div class="introduction"> <?= $event->introduction()->excerpt(200, false, " […]")?> </div> <?php endif ?> <?php if($event->cover()->isNotEmpty()) :?> <figure class="event-cover"> <?php $image = $event->cover()->toFile() ?> <img loading="lazy" width="<?= $image->width() ?>" height="<?= $image->height() ?>" src="<?= $image->thumb('listitem')->url()?>" alt="<?= $image->alt()?>" srcset="<?= $image->srcset('default')?>"> </figure> <?php endif ?> </a> </article><file_sep>/site/templates/default.php <?php snippet('header') ?> <main class="main-event" data-year="<?= $page->year()->value() ?>" data-slug="<?= $page->slug() ?>"> <article class="event-detail <?= $page->theme()->fromAutoID()->slug() ?>"> <header> <h2><?= $page->year()->html() ?></h2> <h1><?= $page->title()->html() ?></h1> </header> <div class="event-text"> <?php if($page->introduction_detail()->isNotEmpty()) :?> <div class="introduction"> <?= $page->introduction_detail()->kt()?> </div> <?php endif ?> <?php if($page->text()->isNotEmpty()) :?> <div class="text"> <?= $page->text()->kt()?> </div> <?php endif ?> </div> <?php if($page->details()->isNotEmpty()) :?> <aside class="event-details"> <?= $page->details()->kt()?> </aside> <?php endif ?> </article> <?php $gallery = $page->gallery()->filter(function($image) use($page){ return $image != $page->cover()->toFile(); })->sortBy('sort')->toFiles(); if($gallery->count()) :?> <div class="gallery"> <?php foreach($gallery as $image) : ?> <figure class="<?= $image->layout() ?>"> <a href="<?= $image->url() ?>"> <img loading="lazy" width="<?= $image->width() ?>" height="<?= $image->height() ?>" src="<?= $image->thumb('listitem')->url()?>" alt="<?= $image->alt()?>" srcset="<?= $image->srcset('default')?>"> </a> <?php if($image->caption()->isNotEmpty()) :?> <figcaption> <?= $image->caption()->kt()?> </figcaption> <?php endif ?> </figure> <?php endforeach ?> </div> <?php endif ?> </main> <?php snippet('footer') ?> <file_sep>/site/snippets/block-link.php <article id="event-<?= $event->slug() ?>" class="timeline-event timeline-link <?= $event->theme()->fromAutoID()->slug() ?>"> <a href="<?= e($event->link()->isNotEmpty(), $event->link(), "#") ?>"> <h3><?= $event->title() ?></h3> <?php if($event->introduction()->isNotEmpty()) :?> <div class="introduction"> <?= $event->introduction()->excerpt(200, false, " […]")?> </div> <?php endif ?> <?php if($event->cover()->isNotEmpty()) :?> <figure class="event-cover"> <?php $image = $event->cover()->toFile() ?> <img loading="lazy" width="<?= $image->width() ?>" height="<?= $image->height() ?>" src="<?= $image->thumb('listitem')->url()?>" alt="<?= $image->alt()?>" srcset="<?= $image->srcset('default')?>"> </figure> <?php endif ?> <p class="source"> → <?php if($event->label()->isNotEmpty()): echo $event->label()->html(); else: $parse = parse_url($event->link()); echo $parse['host']; endif; ?> </p> </a> </article>
9925c220d4552c9ed8258d596b08ed5c7068fcff
[ "PHP" ]
5
PHP
louis-ev/timelure
f2a8ee77d31d2a561e8a6fcdb58da4a692e7ebdc
ae2d46c51462ccbb5b20249a9c0e3030f7bf8c3a
refs/heads/master
<repo_name>omarmandeeli/NZDEC<file_sep>/index.php <?php session_start(); include 'includes/dbh.inc.php'; ?> <!DOCTYPE html> <html class='no-js'> <head> <meta charset='utf-8'> <meta content='IE=edge' http-equiv='X-UA-Compatible'> <title><NAME>usin Events And Consultancy</title> <meta content='width=device-width, initial-scale=1.0' name='viewport'> <link href="stylesheets/screen.css" media="screen" rel="stylesheet" type="text/css" /> <link href="stylesheets/plugin.css" media="screen" rel="stylesheet" type="text/css" /> <link href="stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" /> <script src="javascripts/libs/modernizr-2.7.1.min.js" type="text/javascript"></script> </head> <body class='homepage'> <!--[if lt IE 8]> <p class='browsehappy'> You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience. </p> <![endif]--> <div class='container'> <header id='header'> <div class='parallax' data-velocity='.2'></div> <div class='site-main-menu' id='menu'> <ul> <li> <a href='#header'>HOME</a> </li> <li> <a href='#services'>ABOUT US</a> </li> <li> <a href='#projects'>PROJECTS</a> </li> <li> <a href='#contact'>CONTACT</a> </li> <?php if (isset($_SESSION['u_uid'])) { include 'includes/dbh.inc.php'; $c_id = $_SESSION['u_id']; mysqli_select_db($conn, "test"); $sql = "SELECT * FROM customer_table where cusact_id = '$c_id'"; $data = mysqli_query($conn, $sql); while ($record = mysqli_fetch_array($data)) { $c_name = $record['cus_fname']; } echo ' <li> <a href='.'Packages.php'.'>INQUIRE NOW</a> </li> <li> <a href='.'reservation.php'.'>RESERVATIONS</a> </li> <form action="includes/logout.inc.php" method="POST"> <button type="submit" name="submit">logout</button> '; echo '<form> '; echo '<h1> Hello, '; echo $c_name; echo '</h1>'; echo '</form>'; } else { echo ' <li> <a href='.'package-view.php'.'>PACKAGE</a> </li> <form action="login.php"> <div class="buttonshit"> <button type="submit" name="submit"> Login </button> </div> </form> <form action="signup.php"> <div class="buttonshit"> <button type="submit" name="signup"> Signup </button> </div> </form> '; } ?> </div> <div class='site-header'> <p class='first'> Hi there, We Are <span>Zaldy Ducusic Events</span> </p> <div class='hr left'></div> <div class='hr right'></div> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam bibendum<b> Taguig</b>. <br> Phasellus ac lorem sit amet arcu molestie<br> </p> </div> <div class='site-proceed'> <a href='#services'> <i class='fa fa-angle-down'></i> </a> </div> </header> <div id='main-content' role='main'> <section class='site-what-i-do' id='services'> <div class='site-wrapper'> <div class='site-wrapper-title'> <h2>ABOUT US?</h2> </div> <div class='site-what-i-do-box'> <div class='site-what-i-do-box-top'> <i class='fa fa-file-text'></i> <p>PLANNING</p> </div> <div class='site-what-i-do-box-bot'> <p>Duis eu leo massa. Vestibulum sed metus ac <br><br>hasellus hendrerit quis metus ut euismod. Donec viverra dui at nibh cursus fringilla. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.<br>id sodales nulla lacinia. Donec tempus bibendum neque, pharetra <br><br>Praesent viverra posuere orci vitae feugiat. Fusce eu felis ac dui porttitor laoreet feugiat ut orci. Fusce malesuada tortor a nisi laoreet placerat.</p> </div> </div> <div class='site-what-i-do-box'> <div class='site-what-i-do-box-top'> <i class='fa fa-pencil-square-o'></i> <p>CONSULTANCY</p> </div> <div class='site-what-i-do-box-bot'> <p>Duis eu leo massa. Vestibulum sed metus ac <br><br>hasellus hendrerit quis metus ut euismod. Donec viverra dui at nibh cursus fringilla. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.<br>id sodales nulla lacinia. Donec tempus bibendum neque, pharetra <br><br>Praesent viverra posuere orci vitae feugiat. Fusce eu felis ac dui porttitor laoreet feugiat ut orci. Fusce malesuada tortor a nisi laoreet placerat.</p> </div> </div> <div class='site-what-i-do-box'> <div class='site-what-i-do-box-top'> <i class='fa fa-calendar'></i> <p>EVENTS</p> </div> <div class='site-what-i-do-box-bot'> <p>Duis eu leo massa. Vestibulum sed metus ac <br><br>hasellus hendrerit quis metus ut euismod. Donec viverra dui at nibh cursus fringilla. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.<br>id sodales nulla lacinia. Donec tempus bibendum neque, pharetra <br><br>Praesent viverra posuere orci vitae feugiat. Fusce eu felis ac dui porttitor laoreet feugiat ut orci. Fusce malesuada tortor a nisi laoreet placerat.</p> </div> </div> </div> </section> <section class='site-projects' id='projects'> <div class='site-wrapper'> <div class='site-projects-box'> <div class='site-projects-top'> <p>CLIENT</p> </div> <div class='site-projects-bot'> <img src='images/Untitled-1.jpg'> </div> </div> <div class='site-projects-box'> <div class='site-projects-top'> <p>CLIENT</p> </div> <div class='site-projects-bot'> <img src='images/Untitled-1.jpg'> </div> </div> <div class='site-projects-box'> <div class='site-projects-top'> <p>CLIENT</p> </div> <div class='site-projects-bot'> <img src='images/Untitled-1.jpg'> </div> </div> <div class='site-projects-box'> <div class='site-projects-top'> <p>CLIENT</p> </div> <div class='site-projects-bot'> <img src='images/Untitled-1.jpg'> </div> </div> <div class='site-projects-box'> <div class='site-projects-top'> <p>CLIENT</p> </div> <div class='site-projects-bot'> <img src='images/Untitled-1.jpg'> </div> </div> <div class='site-projects-box'> <div class='site-projects-top'> <p>CLIENT</p> </div> <div class='site-projects-bot'> <img src='images/Untitled-1.jpg'> </div> </div> <div class='site-projects-box'> <div class='site-projects-top'> <p>CLIENT</p> </div> <div class='site-projects-bot'> <img src='images/Untitled-1.jpg'> </div> </div> <div class='site-projects-box'> <div class='site-projects-top'> <p>CLIENT</p> </div> <div class='site-projects-bot'> <img src='images/Untitled-1.jpg'> </div> </div> <div class='site-projects-box'> <div class='site-projects-top'> <p>CLIENT</p> </div> <div class='site-projects-bot'> <img src='images/Untitled-1.jpg'> </div> </div> <div class='site-projects-box'> <div class='site-projects-top'> <p>CLIENT</p> </div> <div class='site-projects-bot'> <img src='images/Untitled-1.jpg'> </div> </div> </div> </section> <footer id='contact'> <div class='site-wrapper'> <p class='interested'> Duis commodo, neque ut commodo condimentum <a href='#' target='_blank'>Duis eu leo massa</a> Vestibulum sed metus ac leo facilisis efficitur. Aliquam eget arcu ac nulla ultrices venenatis. </p> <p>Want to Plan an Event?</p> <hr> <a class='btn' href='#'>Email Us!</a> </div> <span class='cc'> Copyright &copy; 2014-2017, <NAME> Events and Consultancy </span> </footer> </div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script> <script> window.jQuery || document.write('<script src="/javascripts/libs/jquery-1.10.2.min.js"><\/script>') </script> <script src="javascripts/libs/holder.js" type="text/javascript"></script> <script src="javascripts/libs/signup.js" type="text/javascript"></script> <script src="javascripts/plugins.js" type="text/javascript"></script> <script src="javascripts/script.js" type="text/javascript"></script> </body> </html> <file_sep>/package.all.php <?php session_start(); include_once 'packages-header.php'; include 'includes/dbh.inc.php'; mysqli_select_db($conn, "test"); $sql = "SELECT * FROM package"; $data = mysqli_query($conn, $sql); echo "<div class='grid'>"; while ($record = mysqli_fetch_array($data)) { $id = $record['package_id']; echo "<div>"; echo "<h1>" . $record['package_name'] . "</h1>"; echo "<ul>"; echo "<ul/>"; echo "<a href='package.all.php?id=$id'>Submit</a>"; echo "</div>"; } echo "</div>"; // echo "<div class='grid'>"; // while ($record = mysqli_fetch_array($data)) { // $id = $record['package_id']; // echo "<div>"; // echo "<h1>"; // echo "<p>" . $record['package_name'] . "</p>"; // echo "</h1>"; // echo '<img src="data:image/jpeg;base64,'.base64_encode($record['package_image'] ).'" height="200" width="200" class="img-thumnail" />'; // echo "<ul>"; // echo nl2br("<li>" . "<br />" . $record['package_details'] . "<br />" . "</li>") ; // echo "<ul/>"; // echo "<td><a href='package.all.php?id=$id'>Submit</a></td>"; // echo "</div>"; // } // echo "</div>"; if (isset($_POST['submit'])) { $p_id = $_GET['id']; $c_id = $_SESSION['u_id']; $e_name = mysqli_real_escape_string($conn, $_POST['e_name']) ; $d_event = mysqli_real_escape_string($conn, $_POST['d_event']) ; $t_event = mysqli_real_escape_string($conn, $_POST['t_event']) ; $e_t_event = mysqli_real_escape_string($conn, $_POST['e_t_event']) ; $theme = mysqli_real_escape_string($conn, $_POST['theme']) ; $venue = mysqli_real_escape_string($conn, $_POST['venue']) ; date_default_timezone_set('Asia/Manila'); $date = date('Y/m/d'). substr((string)1, 6); $time = date('H:i'); $avail = "Package"; $my_date = date('Y-m-d', strtotime($d_event)); if (empty($e_name) || empty($d_event) || empty($t_event) || empty($e_t_event) || empty($theme)){ header("Location:../Packages.all.php?empty"); exit(); } else{ $sql = "SELECT * FROM event_table WHERE event_date = '$d_event'" ; $result = mysqli_query($conn, $sql); $resultcheck = mysqli_num_rows($result); if(!$result){ echo("Error description: " . mysqli_error($conn)); } if ($resultcheck>=1) { header("Location:../Packages.all.php?input=datescheduled"); exit(); } else{ $sql = "INSERT INTO event_table (event_name, event_date, event_time_start, event_time_end, cusact_id, theme, venue, reserve_date, reserve_time, package_id, Availed) VALUES ('$e_name', '$my_date', '$t_event', '$e_t_event', '$c_id', '$theme', '$venue', '$date', '$time', '$p_id', '$avail' );"; $result = mysqli_query ($conn, $sql); $newest_id = mysqli_insert_id($conn); $reservation_type = 1; $order_q = 1; $sql = "SELECT * FROM admin WHERE admin_id = '1'" ; $result = mysqli_query($conn, $sql); $resultcheck = mysqli_num_rows($result); $sql = "INSERT INTO reservation (reservation_type_id, admin_id, event_id, res_expires) VALUES ('$reservation_type', '$resultcheck', '$newest_id', NOW() + INTERVAL 24 HOUR );"; $result = mysqli_query ($conn, $sql); //price $p_sql = "SELECT package_price from package WHERE package_id = '$p_id'" ; $p_result = mysqli_query($conn, $p_sql); $price = mysqli_fetch_assoc($p_result); $p_p = $price['package_price']; header("Location:order.confirmation.php?n_id=$newest_id&new_p_id=$p_id"); if(!$result){ echo("Error description: " . mysqli_error($conn)); } } } } //----------------------------------------------------------------------------------------------------------// if (isset($_POST['submit-addon'])) { $p_id = $_GET['id']; $c_id = $_SESSION['u_id']; $e_name = mysqli_real_escape_string($conn, $_POST['e_name']) ; $d_event = mysqli_real_escape_string($conn, $_POST['d_event']) ; $t_event = mysqli_real_escape_string($conn, $_POST['t_event']) ; $e_t_event = mysqli_real_escape_string($conn, $_POST['e_t_event']) ; $theme = mysqli_real_escape_string($conn, $_POST['theme']) ; $venue = mysqli_real_escape_string($conn, $_POST['venue']) ; date_default_timezone_set('Asia/Manila'); $date = date('Y/m/d'). substr((string)1, 6); $time = date('H:i'); $avail = "Package"; $my_date = date('Y-m-d', strtotime($d_event)); if (empty($e_name) || empty($d_event) || empty($t_event) || empty($e_t_event) || empty($theme)){ header("Location:../Packages.all.php?empty"); exit(); } else{ $sql = "SELECT * FROM event_table WHERE event_date = '$d_event'" ; $result = mysqli_query($conn, $sql); $resultcheck = mysqli_num_rows($result); if(!$result){ echo("Error description: " . mysqli_error($conn)); } if ($resultcheck>=1) { header("Location:../Packages.all.php?input=datescheduled"); exit(); } else{ $sql = "INSERT INTO event_table (event_name, event_date, event_time_start, event_time_end, cusact_id, theme, venue, reserve_date, reserve_time, package_id, Availed) VALUES ('$e_name', '$my_date', '$t_event', '$e_t_event', '$c_id', '$theme', '$venue', '$date', '$time', '$p_id', '$avail' );"; $result = mysqli_query ($conn, $sql); $newest_id = mysqli_insert_id($conn); $reservation_type = 1; $order_q = 1; $sql = "SELECT * FROM admin WHERE admin_id = '1'" ; $result = mysqli_query($conn, $sql); $resultcheck = mysqli_num_rows($result); $sql = "INSERT INTO reservation (reservation_type_id, admin_id, event_id, res_expires) VALUES ('$reservation_type', '$resultcheck', '$newest_id', NOW() + INTERVAL 24 HOUR );"; $result = mysqli_query ($conn, $sql); //price $p_sql = "SELECT package_price from package WHERE package_id = '$p_id'" ; $p_result = mysqli_query($conn, $p_sql); $price = mysqli_fetch_assoc($p_result); $p_p = $price['package_price']; header("Location:cart-index.php?n_id=$newest_id&new_p_id=$p_id"); if(!$result){ echo("Error description: " . mysqli_error($conn)); } } } } ?> </ul> <span class='follow'> <a class='links' href='#' target='_blank' title='Twitter'> <i class='fa fa-twitter'></i> </a> <a class='links' href='#' target='_blank' title='Youtube'> <i class='fa fa-facebook'></i> </a> <a class='links' href='#' target='_blank' title='Youtube'> <i class='fa fa-google-plus'></i> </a> </span> </div> </header> <div class="form-style-5"> <form method="POST"> <label>Event Name</label> <input type="text" name="e_name" placeholder="Enter Event Name*"/> <link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" /> <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script type="text/javascript" src="http://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script> <label for="job">Day of the Event</label> <input type="text" name="d_event" id="mydate" size="30" data-date-format='yy-mm-dd' /> <label for="job">Time of the Event</label> <input type="Time" name="t_event" placeholder="Enter Time of Event*"/> <label for="job">End Time of the Event</label> <input type="Time" name="e_t_event" placeholder="Enter End Time of Event*"/> <label>Theme</label> <input type="text" name="theme" placeholder="Enter Theme*"/> <label>Venue</label> <input type="text" name="venue" placeholder="Enter Venue*"/> <input name="submit" type="submit" value="Submit"/> <input name="submit-addon" type="submit" value="Click to add services"/> <style type="text/css"> .ui-datepicker-calendar>tbody>tr>td.ui-datepicker-unselectable>span.ui-state-default:before{ bottom: 0; content: "X"; height: 10px; color: red; left: 7px; margin: auto; position: relative; right: 0; top: 0; width: 4px; } </style> <?php $query = " SELECT * FROM event_table "; $result = mysqli_query($conn,$query); $sentToList = array(); while($row = mysqli_fetch_assoc($result)) { $sentToList[] = $row['event_date']; } $json = json_encode($sentToList); ?> <script > $( function() { //build up your array //this is a mock of var arrayFromPHP = <?php echo json_encode($json); ?>; var phpArrayString = '<?php print_r($json)?>'; //parse your json here var array = JSON.parse(phpArrayString); //include dateFormat AND beforeShowDay options $( "#mydate" ).datepicker({ dateFormat: 'yy-mm-dd', beforeShowDay: function(date) { var string = jQuery.datepicker.formatDate('yy-mm-dd', date); //You can even use tooltips to make dates you can select more obvious return [ array.indexOf(string) == -1, 'highlight', 'You may select this date' ]; } }); //Optionally - call the tooltip plugin on dates that can be selected $('#mydate .highlight a').tooltip(); }); // $(document).ready(function () { // initComponent(); // }); // function initComponent () { // var array = ['2017-09-05', '2017-09-06']; // $('#date').datepicker({ // dateFormat: 'yy-mm-dd', // beforeShowDay: function(d) { // var string = jQuery.datepicker.formatDate('yy-mm-dd', d); // return [ array.indexOf(string) == -1 ] // } // }); </script> </form> <footer id='contacts'> <span class='cc'> @ 2014 . <NAME> </span> </footer> </div> </html> <file_sep>/javascripts/script.js /* Author: */ WebFontConfig = { google: { families: [ 'Open+Sans:300,300italic,400,400italic,600,600italic,700,700italic,800,800italic:latin' ] } }; (function() { var wf = document.createElement('script'); wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js'; wf.type = 'text/javascript'; wf.async = 'true'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(wf, s); })(); $('.parallax').parallax({ speed : 0.6 }); $(window).resize(function(){ var windowHeight = $(window).height(); $('#header').css({ 'height':windowHeight }); }).resize(); $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top - 60 }, 500); return false; } } }); }); $(document).ready(function(){ $('#menu').slicknav(); }); $(window).scroll(function() { if ( document.documentElement.clientHeight + $(document).scrollTop() >= document.body.offsetHeight ) { // Display alert or whatever you want to do when you're // at the bottom of the page. } }); $(function () { $(window).scroll(function () { var top_offset = $(window).scrollTop(); if (top_offset == 0) { $('header').addClass('fixed-top'); } else { $('header').addClass('fixed-top'); } }) }); $( function() { $( "#datepicker" ).datepicker(); } ); <file_sep>/includes/login.inc.php <?php session_start(); if (isset($_POST['submit'])) { include 'dbh.inc.php'; $uid = mysqli_real_escape_string($conn, $_POST['uid']); $pwd = mysqli_real_escape_string($conn, $_POST['pwd']); //error //check if empty if (empty ($uid) || empty($pwd)) { header("Location:../login.php?login=empty"); exit(); } else{ $sql = "SELECT * FROM customer_table WHERE cus_user = '$uid' OR cus_email='$uid'" ; $result = mysqli_query($conn, $sql); $resultcheck = mysqli_num_rows($result); if ($resultcheck<1) { header("Location:../login.php?login=usererror"); exit(); } else { if ($row = mysqli_fetch_assoc($result)) { //dehash pw $hashedpwdcheck = password_verify($pwd, $row['cus_pass']); if ($hashedpwdcheck == false) { header("Location:../login.php?login=perror"); exit(); } elseif ($hashedpwdcheck == true){ //Log in the user here $_SESSION['u_id'] = $row['cusact_id']; $_SESSION['u_first'] = $row['cus_fname']; $_SESSION['u_last'] = $row['cus_lname']; $_SESSION['u_address'] = $row['cus_address']; $_SESSION['u_contact'] = $row['cus_contact']; $_SESSION['u_email'] = $row['cus_email']; $_SESSION['u_uid'] = $row['cus_user']; header("Location:../index.php?login=success"); exit(); } } } } } else{ header("Location:../index.php?login=error"); exit(); }<file_sep>/cart.php <?php //cart.php session_start(); include 'includes/dbh.inc.php'; if (!$conn) { die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error()); } $c_id = $_SESSION['u_id']; $n_id = $_SESSION['n_id']; $p_id = $_SESSION['p_id']; ?> <!DOCTYPE html> <html> <head> <title>Webslesson Tutorial | Multi Tab Shopping Cart By Using PHP Ajax Jquery Bootstrap Mysql</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> </head> <body> <br /> <div class="container" style="width:800px;"> <?php $c_id = $_SESSION['u_id']; if(isset($_POST["place_order"])) { $order_details = ""; foreach($_SESSION["shopping_cart"] as $keys => $values) { $order_details .= " INSERT INTO order_list (order_qnty, event_id, service_id, amount) VALUES('".$values["product_quantity"]."', '$n_id', '".$values["product_id"]."','".$values["product_price"]."'); "; } if(mysqli_multi_query($conn, $order_details)) { unset($_SESSION["shopping_cart"]); echo '<script>alert("You have successfully place an order...Thank you")</script>'; echo '<script>window.location.href="cart.order-confirmation.php"</script>'; } } ?> </div> </body> </html> <file_sep>/includes/signup.inc.php <?php if (isset($_POST['submit'])) { include_once 'dbh.inc.php'; $first = mysqli_real_escape_string($conn, $_POST['first']) ; $last = mysqli_real_escape_string($conn, $_POST['last']) ; $address = mysqli_real_escape_string($conn, $_POST['address']) ; $contact = mysqli_real_escape_string($conn, $_POST['contact']) ; $email = mysqli_real_escape_string($conn, $_POST['email']) ; $uid = mysqli_real_escape_string($conn, $_POST['uid']) ; $pwd = mysqli_real_escape_string($conn, $_POST['pwd']) ; //for empty fields if (empty($first) || empty($last) || empty($address) || empty($contact) || empty($email) || empty($uid) || empty($pwd)){ header("Location: ../signup.php?signup=empty"); exit(); } else { //checks inputs are valid if (!preg_match("/^[a-zA-z]*$/", $first) || !preg_match("/^[a-zA-z]*$/", $last)) { header("Location: ../signup.php?signup=invallid"); exit(); } else { //checks input are valid if (!filter_var($email, FILTER_VALIDATE_EMAIL)){ header("Location: ../signup.php?signup=invallidemail"); exit(); } else { $sql = "SELECT * FROM customer_table WHERE cus_user = '$uid'"; $result = mysqli_query($conn, $sql); $resultcheck = mysqli_num_rows($result); if ($resultcheck > 0) { header("Location: ../signup.php?signup=usertaken"); exit(); } else { //password $hashedpwd = password_hash($pwd, PASSWORD_DEFAULT); $vcode = rand(); //inserts the user into the database $sql = "INSERT INTO customer_table (cus_fname, cus_lname, cus_address, cus_contact, cus_email, cus_user, cus_pass, verification_status, verification_code) VALUES ('$first', '$last', '$address', '$contact', '$email', '$uid', '$hashedpwd', '0','$vcode');"; $message = " Confirm your Email, Cunt Click the link below, faggot. http://localhost:8080/NZDEC/emailconfirmed.php?username=$uid&code=$vcode "; mail($email, "Confirm Email, dude", $message, "From: <EMAIL>"); mysqli_query($conn, $sql); header("Location: ../login.php?signup=success"); exit(); } } } } } else{ header("Location: ../login.php"); exit(); }<file_sep>/order.confirmation.php <?php session_start(); include_once 'order.confirmation-header.php'; include 'includes/dbh.inc.php'; $c_id = $_SESSION['u_id']; $n_id = $_GET['n_id']; $p_id = $_GET['new_p_id']; $sql = "SELECT event_id, event_name, event_date, event_time_start, event_time_end, cusact_id, theme, reserve_date, reserve_time FROM event_table WHERE cusact_id = $c_id AND event_id=$n_id"; $data = mysqli_query($conn, $sql); if(!$data){ echo("Error description: " . mysqli_error($conn)); } while ($record = mysqli_fetch_array($data)) { echo "<table border = 1>"; echo "<tr>"; echo "<th>" . "Name of The Event" ."</th>"; echo "<th>" . "Date of the Event" ."</th>"; echo "<th>" . "Time of the Event" ."</th>"; echo "<th>" . "End Time of the Event" ."</th>"; echo "<th>" . "Theme" ."</th>"; echo "<th>" . "Reserve Date" ."</th>"; echo "<th>" . "Reserve Time" ."</th>"; echo "</tr>"; echo "<tr>"; echo "<td>" . "<br />" . $record['event_name'] . "<br />" . "</td>" ; echo "<td>" . "<br />" . $record['event_date'] . "<br />" . "</td>" ; echo "<td>" . "<br />" . $record['event_time_start'] . "<br />" . "</td>" ; echo "<td>" . "<br />" . $record['event_time_end'] . "<br />" . "</td>" ; echo "<td>" . "<br />" . $record['theme'] . "<br />" . "</td>" ; echo "<td>" . "<br />" . $record['reserve_date'] . "<br />" . "</td>" ; echo "<td>" . "<br />" . $record['reserve_time'] . "<br />" . "</td>" ; echo "<tr/>"; } $p_sql = "SELECT * FROM package where package_id = '$p_id'"; $data = mysqli_query($conn, $p_sql); if(!$data){ echo("Error description: " . mysqli_error($conn)); } while ($record = mysqli_fetch_array($data)) { $p_amount = $record['package_price']; $percentage = 12; echo "<table border = 1>"; echo "<tr>"; echo "<th>" . "Package Name" . "</th>"; echo "<th>" . "Package Price" . "</th>"; echo "<th>" . "Package Details" . "</th>"; echo "<th>" . "Package Categories" . "</th>"; echo "</tr>"; echo "<tr>"; echo "<td>" . "<br />" . $record['package_name'] . "<br />" . "</td>" ; echo "<td>" . "<br />" . $record['package_price'] . "<br />" . "</td>" ; echo "<td>" . "<br />" . $record['package_details'] . "<br />" . "</td>" ; echo "<td>" . "<br />" . $record['package_categories'] . "<br />" . "</td>" ; echo "<tr/>"; } if(isset($_POST["submit-proof"])) { $p_type = $_POST['p_type']; $r_num = $_POST['r-num']; $amount = $_POST['amount']; $acc_num = $_POST['acc-num']; $status = "pending"; //order_id date_default_timezone_set('Asia/Manila'); $date = date('Y/m/d'). substr((string)1, 6);; $p_sql = "SELECT * FROM payment_type where payment_type_id = $p_type"; $data1 = mysqli_query($conn, $p_sql); $result1 = mysqli_fetch_assoc($data1); $n_p_type = $result1['payment_type']; $image = addslashes(file_get_contents($_FILES["image"]['tmp_name'])); $o_sql = "INSERT INTO billing (event_id, TotalPrice) VALUES ('$n_id', '$p_amount')"; $data = mysqli_query($conn, $o_sql); $b_id = mysqli_insert_id($conn); $p_sql = "INSERT INTO payment (billing_id, payment_type_id, Balance) VALUES ('$b_id', '$p_type', '$p_amount')"; $data = mysqli_query($conn, $p_sql); $payment_id = mysqli_insert_id($conn); $proof_sql = "INSERT INTO proof_payment (acct_no, amount, image_reciept, payment_date, transaction_no, cusact_id, payment_id, event_id, payment_status) VALUES ('$acc_num', '$amount', '$image', '$date', '$r_num', '$c_id', '$payment_id', '$n_id', '$status')"; $data = mysqli_query($conn, $proof_sql); if(!$data){ echo("Error description: " . mysqli_error($conn)); } } if (isset($_POST["pay-later"])) { header("Location:reservation.php"); } ?> <body> <div id="content-payment"> <form method="POST" enctype="multipart/form-data"> <input type="hidden" name="size" value="1000000"> <div> <input type='radio' name='p_type' value='2'/>Full Payment</br> <input type='radio' name='p_type' value='1'/>Installment</br> <input type="file" name="image" id="image"> <input type="text" name="amount" placeholder="Amount"> <input type="text" name="acc-num" placeholder="Reference Number"> <input type="text" name="r-num" placeholder="Reference Number"> </div> <div> <input type="submit" name="submit-proof" value="Submit Receipt"> <input type="submit" name="pay-paypal" value="Pay With Paypal"> <input type="submit" name="submit-cancel" value="Cancel Order"> <input type="submit" name="pay-later" value="Pay Later"> </div> </form> </div> <script> $(document).ready(function(){ $('#submit-proof').click(function(){ var image_name = $('#image').val(); if(image_name == '') { alert("Please Select Image"); return false; } else { var extension = $('#image').val().split('.').pop().toLowerCase(); if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1) { alert('Invalid Image File'); $('#image').val(''); return false; } } }); }); </script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script> <script> window.jQuery || document.write('<script src="/javascripts/libs/jquery-1.10.2.min.js"><\/script>') </script> <script src="javascripts/libs/holder.js" type="text/javascript"></script> <script src="javascripts/plugins.js" type="text/javascript"></script> <script src="javascripts/formsjs.js" type="text/javascript"></script> </body> </html> <file_sep>/reservation-header.php <html class='no-js'> <head> <meta charset='utf-8'> <meta content='IE=edge' http-equiv='X-UA-Compatible'> <title>Inquire</title> <meta content='width=device-width, initial-scale=1.0' name='viewport'> <link href="stylesheets/screen.css" media="screen" rel="stylesheet" type="text/css" /> <link href="stylesheets/reset.css" media="screen" rel="stylesheet" type="text/css" /> <link href="stylesheets/reservecss.css" media="screen" rel="stylesheet" type="text/css" /> <script src="javascripts/libs/modernizr-2.7.1.min.js" type="text/javascript"></script> </head> <body class='homepage'> <div class='container'> <header id='header' class="fixed-top"> <div class='site-main-menu' id='menu'> <ul> <li> <a href='index.php'>HOME</a> </li> <li> <a href='index.php'>ABOUT US</a> </li> <li> <a href='index.php'>PROJECTS</a> </li> <li> <a href='index.php'>CONTACT</a> </li> <?php if (isset($_SESSION['u_uid'])) { echo '<form action="includes/logout.inc.php" method="POST"> <div class="logout"><button type="submit" name="submit">logout</button> </div></form> '; } else { echo '<form action="Login.php"><button type="submit" name="submit"> Login</button> </form> <form action="Signup.php"> <button type="submit" name="signup">Signup</button> </form>'; } ?> </div> </header> </div> <file_sep>/includes/reservation.inc.php <?php session_start(); if (isset($_POST['submit'])) { header("Location:../reservation.php"); } ?> <file_sep>/includes/inquire-packages.inc.php <?php ini_set('display_errors', '1'); error_reporting(E_ALL); session_start(); <file_sep>/Packages.php <?php session_start(); include_once 'packages-header.php'; include 'includes/dbh.inc.php'; mysqli_select_db($conn, "test"); $sql = "SELECT * FROM package"; $data = mysqli_query($conn, $sql); echo '<div class="packagehead"> <h1>PACKAGES</h1> </div>'; echo "</div>"; echo "<div class='grid'>"; while ($record = mysqli_fetch_array($data)) { $id = $record['package_id']; echo "<div>"; echo "<h1>" . $record['package_name'] . "</h1>"; echo '<img src="data:image/jpeg;base64,'.base64_encode($record['package_image'] ).'" height="200" width="200" class="img-thumnail" />'; echo nl2br("<p>" . "<br />" . $record['package_details']. "</p>") ; echo "<a href='package.all.php?id=$id'><button>Submit</button></a>"; echo "</div>"; } echo "</div>"; if (isset($_POST['submit'])) { include 'dbh.inc.php'; $p_id = $_GET['id']; $c_id = $_SESSION['u_id']; $e_name = mysqli_real_escape_string($conn, $_POST['e_name']) ; $d_event = mysqli_real_escape_string($conn, $_POST['d_event']) ; $t_event = mysqli_real_escape_string($conn, $_POST['t_event']) ; $e_t_event = mysqli_real_escape_string($conn, $_POST['e_t_event']) ; $theme = mysqli_real_escape_string($conn, $_POST['theme']) ; $date = date('Y-m-d H:i:s'); if (empty($e_name) || empty($d_event) || empty($t_event) || empty($e_t_event) || empty($theme)){ header("Location:../Packages.all.php?empty"); exit(); }else{ $sql = "INSERT INTO event_table (event_name, event_date, event_time_start, event_time_end, cusact_id, theme, reserve_date_time) VALUES ('$e_name', '$d_event', '$t_event', '$e_t_event', '$c_id', '$theme', '$date');"; mysqli_query($conn, $sql); } } else { } // mysqli_select_db($conn, "test"); // $sql = "SELECT * FROM package"; // $data = mysqli_query($conn, $sql); // echo "<div class='grid'>"; // while ($record = mysqli_fetch_array($data)) { // $id = $record['package_id']; // echo "<div>"; // echo "<h1>" . $record['package_name'] . "</h1>"; // echo '<img src="data:image/jpeg;base64,'.base64_encode($record['package_image'] ).'" height="200" width="200" class="img-thumnail" />'; // echo "<ul>"; // echo nl2br("<li>" . "<br />" . $record['package_details'] . "<br />" . "</li>") ; // echo "<ul/>"; // echo "<a href='package.all.php?id=$id'>Submit</a>"; // echo "</div>"; // } if (isset($_POST['submit'])) { include 'dbh.inc.php'; $p_id = $_GET['id']; $c_id = $_SESSION['u_id']; $e_name = mysqli_real_escape_string($conn, $_POST['e_name']) ; $d_event = mysqli_real_escape_string($conn, $_POST['d_event']) ; $t_event = mysqli_real_escape_string($conn, $_POST['t_event']) ; $e_t_event = mysqli_real_escape_string($conn, $_POST['e_t_event']) ; $theme = mysqli_real_escape_string($conn, $_POST['theme']) ; $date = date('Y-m-d H:i:s'); if (empty($e_name) || empty($d_event) || empty($t_event) || empty($e_t_event) || empty($theme)){ header("Location:../Packages.all.php?empty"); exit(); }else{ $sql = "INSERT INTO event_table (event_name, event_date, event_time_start, event_time_end, cusact_id, theme, reserve_date_time) VALUES ('$e_name', '$d_event', '$t_event', '$e_t_event', '$c_id', '$theme', '$date');"; mysqli_query($conn, $sql); } } else{ // echo 'isset was false'; } ?> <!-- <div class="form-style-5"> --> <div class="formstyle1"> <form method="POST"> <h1 id="dick">EVENT DETAILS<h1> <label>Event Name</label> <input type="text" name="e_name" placeholder="Enter Event Name*"/> <label for="job">Day of the Event</label> <input type="date" name="d_event" placeholder="Enter Date of Event*"/> <label for="job">Time of the Event</label> <input type="Time" name="t_event" placeholder="Enter Time of Event*"/> <label for="job">End Time of the Event</label> <input type="Time" name="e_t_event" placeholder="Enter End Time of Event*"/> <label>Theme</label> <input type="text" name="theme" placeholder="Enter Theme*"/> <label>Venue</label> <input type="text" name="venue" placeholder="Enter Venue*"/> <input name="submit" type="submit" value="Submit"/> </form> </div> <footer id='contacts'> <span class="fudge">ZDEC</span> <span class='cc'> Copyright &copy; 2014-2017, <NAME> Events and Consultancy </span> </footer> <!-- </div> --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script> <script> window.jQuery || document.write('<script src="/javascripts/libs/jquery-1.10.2.min.js"><\/script>') </script> <script src="javascripts/libs/holder.js" type="text/javascript"></script> <script src="javascripts/plugins.js" type="text/javascript"></script> <script src="javascripts/formsjs.js" type="text/javascript"></script> </body> </html> <file_sep>/package-view.php <?php session_start(); include_once 'packages-view-header.php'; include 'includes/dbh.inc.php'; mysqli_select_db($conn, "test"); $sql = "SELECT * FROM package"; $data = mysqli_query($conn, $sql); while ($record = mysqli_fetch_array($data)) { $id = $record['package_id']; echo '<div class="packagehead"> <h1>PACKAGES</h1> </div>'; echo "</div>"; echo "<div class='grid'>"; while ($record = mysqli_fetch_array($data)) { $id = $record['package_id']; echo "<div>"; echo "<h1>" . $record['package_name'] . "</h1>"; echo '<img src="data:image/jpeg;base64,'.base64_encode($record['package_image'] ).'" height="200" width="200" class="img-thumnail" />'; echo nl2br("<p>" . "<br />" . $record['package_details']. "</p>") ; echo "<a href='package.all.php?id=$id'>Submit</a>"; echo "</div>"; } echo "</div>"; } ?> <form action="includes/inquire.inc.php" method="POST"> <div class="buttonwrap"> <div class="packbuttinquire"> <input type="submit" name="submit" value="Inquire Now"> </div> </div> </form> <footer id='contacts'> <span class="fudge">ZDEC</span> <span class='cc'> Copyright &copy; 2014-2017, <NAME>in Events and Consultancy </span> </footer> <file_sep>/reservation.php <?php session_start(); include_once 'reservation-header.php'; include 'includes/dbh.inc.php'; //====================================================================== // SY START //====================================================================== $c_id = $_SESSION['u_id']; $p_sql = "SELECT p.package_id, p.package_name, p.package_price, p.package_details, p.package_categories, p.package_id, e.event_id, e.event_name, e.event_date, e.event_time_start, e.event_time_end, e.theme, e.reserve_date, e.reserve_time, rt.reservation_status FROM event_table as e inner join package as p on e.package_id = p.package_id INNER JOIN reservation as rs ON rs.event_id = e.event_id INNER JOIN reservation_type as rt ON rs.reservation_type_id = rt.reservation_type_id where cusact_id = $c_id;"; $data_p = mysqli_query($conn, $p_sql) ; while ($record_p = mysqli_fetch_array($data_p)) { $e_id = $record_p ['event_id']; $p_id = $record_p ['package_id']; echo "<div class='yourreservation'>"; echo "<h1>Your Reservation: <span style='color:#222'>".$record_p['event_name']."<span></h1>"; echo "</div>"; echo "<div class='gridcon'>"; echo "<div class='grid'>"; echo "<div class='i1'>"; echo "<p>" . "Package Name" . "</p>"; echo "<p>" . $record_p['package_name'] . "</p>" ; echo "</div>"; echo "<div class='i2'>"; echo "<p>" . "Package Price" . "</p>"; echo "<p>" . $record_p['package_price'] . "</p>" ; echo "</div>"; echo "<div class='i4'>"; echo "<p>" . "Package Categories" . "</p>"; echo "<p>" . $record_p['package_categories'] . "</p>" ; echo "</div>"; echo "<div class='i5'>"; echo "<p>" . "Name of The Event" ."</p>"; echo "<p>" . $record_p['event_name'] . "</p>" ; echo "</div>"; echo "<div class='i6'>"; echo "<p>" . "Date of the Event" ."</p>"; echo "<p>" . $record_p['event_date'] . "</p>" ; echo "</div>"; echo "<div class='i7'>"; echo "<p>" . "Time of the Event" ."</p>"; echo "<p>" . $record_p['event_time_start'] . "</p>" ; echo "</div>"; echo "<div class='i8'>"; echo "<p>" . "End Time of the Event" ."</p>"; echo "<p>" . $record_p['event_time_end'] . "</p>" ; echo "</div>"; echo "<div class='i9'>"; echo "<p>" . "Theme" ."</p>"; echo "<p>" . $record_p['theme'] . "</p>" ; echo "</div>"; echo "<div class='i10'>"; echo "<p>" . "Reserve Date" ."</p>"; echo "<p>" . $record_p['reserve_date'] . "</p>" ; echo "</div>"; echo "<div class='i11'>"; echo "<p>" . "Reserve Time" ."</p>"; echo "<p>" . $record_p['reserve_time'] . "</p>" ; echo "</div>"; echo "<div class='i3'>"; echo "<p>" . "Package Details" . "</p>"; echo "<p>" . $record_p['package_details'] . "</p>" ; echo "</div>"; echo '<div class="i12">'; echo "<p>" . "Reservation Status" . "</p>"; $upp=$record_p['reservation_status']; $upp = strtoupper($upp); IF($upp == 'PENDING RESERVATION'){ echo "<p style='color:red;'>" . $record_p['reservation_status'] . "</p>" ; } ELSEIF($upp == 'APPROVED RESERVATION'){ echo "<p style='color:green;'>" . $record_p['reservation_status'] . "</p>" ; } ELSEIF($upp == 'PENDING CANCELATION'){ echo "<p style='color:yellow;'>" . $record_p['reservation_status'] . "</p>" ; } ELSEIF($upp == 'APPROVED CANCELATION'){ echo "<p style='color:blue;'>" . $record_p['reservation_status'] . "</p>" ; } ELSE { echo "<p style='color:blue;'>" . $record_p['reservation_status'] . "</p>" ; } echo "</div>"; echo "</div>"; echo "</div>"; echo "<div class='cancelres'>"; echo "<a href='order.paynow.php?id=$e_id&p_id=$p_id' target='_parent'><button>Pay Now</button></a>"; echo "<button>Cancel Reservation</button>"; echo "</div>"; } // ====================================================================== // SY END // ====================================================================== if(!$data_p){ echo("Error description: " . mysqli_error($conn)); } ?> <footer id='contacts'> <span class="fudge">ZDEC</span> <span class='cc'> Copyright &copy; 2014-2017, <NAME> Events and Consultancy </span> </footer> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script> <script src="javascripts/libs/holder.js" type="text/javascript"></script> <script src="javascripts/plugins.js" type="text/javascript"></script> <script src="javascripts/formsjs.js" type="text/javascript"></script> </body> </html>
ad53911296b2e2570783b2da15aa1dfcaa96479f
[ "JavaScript", "PHP" ]
13
PHP
omarmandeeli/NZDEC
96d983129b71f10e686de838159d93216885a9e0
33145dcd8c63f952441fff72429536e7db4f1eb6
refs/heads/main
<file_sep>const option = document.querySelector(".option"); const player1Button = document.querySelector(".player1-btn"); const player2Button = document.querySelector(".player2-btn"); const resetBtn = document.querySelector(".reset"); const player1score = document.querySelector(".container__player1"); const player2score = document.querySelector(".container__player2"); const playersScore = document.querySelector(".game_buttons"); const announce = document.querySelector(".announce"); // console.log(option.value); let finalScore; let player1scoreValue; let player2scoreValue; let stopChange = false; const initialState = () => { option.value = ""; finalScore = ""; player1scoreValue = 0; player2scoreValue = 0; player1score.innerText = 0; player2score.innerText = 0; resetBtn.innerText = "RESET"; announce.innerText = ""; player1score.style.color = "black"; player2score.style.color = "black"; player1Button.style.display = "inline-block"; player2Button.style.display = "inline-block"; }; const winGame = function (finalScore, player1scoreValue, player2scoreValue) { if (finalScore && finalScore === player1scoreValue) { console.log("success"); player1Button.style.display = "none"; player2Button.style.display = "none"; player1scoreValue.innerText = player1scoreValue + 1; player1score.style.color = "red"; announce.innerText = "Player 1 Wins!"; } if (finalScore && finalScore === player2scoreValue) { console.log("success"); player1Button.style.display = "none"; player2Button.style.display = "none"; player2scoreValue.innerText = player2scoreValue + 1; player2score.style.color = "red"; announce.innerText = "Player 2 Wins!"; } }; initialState(); option.addEventListener("change", function (e) { if (option.value) { finalScore = Number(option.value); player1score.innerText = 0; player2score.innerText = 0; } }); player1Button.addEventListener("click", function () { if (player1scoreValue < finalScore) { player1scoreValue = Number(player1score.innerText) + 1; player1score.innerText = player1scoreValue; } }); player2Button.addEventListener("click", function () { if (player2scoreValue < finalScore) { player2score.innerText = Number(player2score.innerText) + 1; player2scoreValue = Number(player2score.innerText); } }); resetBtn.addEventListener("click", function () { initialState(); }); playersScore.addEventListener("click", function (e) { winGame(finalScore, player1scoreValue, player2scoreValue); });
ce660cab3dccda65b8ae7f461d845c48de77e282
[ "JavaScript" ]
1
JavaScript
NikolettaIoan/pingpongscorekeeper
b838d43b76eea328a7b695abda802b5258185da6
bd8b28a54207317491a6c002c893d86c43bdc49b
refs/heads/master
<file_sep># from keras import backend from tensorflow.keras import applications from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras import optimizers from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dropout, Flatten, Dense from tensorflow.keras.models import Model from tensorflow.keras.utils import to_categorical import numpy as np # path to the model weights files. weights_path = 'weights/Full_weights.h5' top_model_weights_path = 'saved_weights.h5' # dimensions of our images. img_width, img_height = 100, 200 train_data_dir = 'data/train' validation_data_dir = 'data/validation' nb_train_samples = 264 nb_validation_samples = 60 epochs = 40 batch_size = 6 # build the VGG16 network base_model = applications.VGG16(weights='imagenet', include_top=False, input_shape = (img_width, img_height, 3)) print('Model loaded.') print("The shape is....", base_model.output_shape[1:]) # build a classifier model to put on top of the convolutional model top_model = Sequential() top_model.add(Flatten(input_shape=base_model.output_shape[1:])) top_model.add(Dense(256, activation='relu')) top_model.add(Dropout(0.5)) top_model.add(Dense(4, activation='sigmoid')) # We now load the weights for the top model that have been obtained by # first training the top model (fineTuningInitial.py) and saving the weights. top_model.load_weights(top_model_weights_path) model = Model(inputs= base_model.input, outputs= top_model(base_model.output)) # We freeze the first 15 layers of the original architecture and set # then to non-trainable. for layer in model.layers[:15]: layer.trainable = False # we are compiling the model with a SGD/momentum optimizer # and a very slow learning rate. model.compile(loss='categorical_crossentropy', optimizer=optimizers.SGD(lr=1e-4, momentum=0.9), metrics=['accuracy']) # we are preparing the data augmentation configuration. train_datagen = ImageDataGenerator( rescale=1. / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) test_datagen = ImageDataGenerator(rescale=1. / 255) train_generator = train_datagen.flow_from_directory( train_data_dir, target_size=(img_height, img_width), batch_size=batch_size, class_mode='categorical') validation_generator = test_datagen.flow_from_directory( validation_data_dir, target_size=(img_height, img_width), batch_size=batch_size, class_mode='categorical') # fine-tune the model history = model.fit_generator( train_generator, steps_per_epoch=nb_train_samples//batch_size, epochs=epochs, validation_data=validation_generator, validation_steps=nb_validation_samples//batch_size, verbose = 2) validation_labels = np.array([0] * (20) + [1] * (12) + [2] * (8) + [3] * (20)) validation_labels = to_categorical(validation_labels) print('acc : ', history.history['acc'] ) print('loss: ', history.history['loss'] ) <file_sep>import numpy as np from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Dropout, Flatten, Dense from keras import applications from keras.utils import to_categorical import matplotlib.pyplot as plt # dimensions of our images. img_width, img_height = 100, 200 top_model_weights_path = 'weights/Full_weights.h5' train_data_dir = 'data/train' validation_data_dir = 'data/validation' nb_train_samples = 264 nb_validation_samples = 60 epochs = 50 batch_size = 6 def save_bottlebeck_features(): datagen = ImageDataGenerator(rescale=1. / 255) # build the VGG16 network model = applications.VGG16(include_top=False, weights='imagenet') generator = datagen.flow_from_directory( train_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode=None, shuffle=False) bottleneck_features_train = model.predict_generator( generator, nb_train_samples // batch_size) np.save(open('bottleneck_features_train.npy', 'wb'), bottleneck_features_train) generator = datagen.flow_from_directory( validation_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode=None, shuffle=False) bottleneck_features_validation = model.predict_generator( generator, nb_validation_samples // batch_size) np.save(open('bottleneck_features_validation.npy', 'wb'), bottleneck_features_validation) def train_top_model(): train_data = np.load('bottleneck_features_train.npy') train_labels = np.array( [0] * (81) + [1] * (66) + [2] * (44) + [3] * (73)) train_labels = to_categorical(train_labels) validation_data = np.load('bottleneck_features_validation.npy') validation_labels = np.array([0] * (20) + [1] * (12) + [2] * (8) + [3] * (20)) validation_labels = to_categorical(validation_labels) model = Sequential() model.add(Flatten(input_shape=train_data.shape[1:])) model.add(Dense(256, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(4, activation='sigmoid')) model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) print (validation_data) print("the shape is................", validation_data.shape) print("the shape of labels is ............", validation_labels.shape) model.fit(train_data, train_labels, epochs=epochs, batch_size=batch_size, validation_data=(validation_data, validation_labels)) model.save_weights("saved_weights.h5") (eval_loss, eval_accuracy) = model.evaluate( validation_data, validation_labels, batch_size=batch_size, verbose=1) print("[INFO] accuracy: {:.2f}%".format(eval_accuracy * 100)) print("[INFO] Loss: {}".format(eval_loss)) plt.figure(1) # def predict(): # # load the class_indices saved in the earlier step # class_dictionary = np.load('class_indices.npy').item() # num_classes = 4 # # add the path to your test image below # image_path = '' # orig = cv2.imread(image_path) # print("[INFO] loading and preprocessing image...") # image = load_img(image_path, target_size=(224, 224)) # image = img_to_array(image) # # important! otherwise the predictions will be '0' # image = image / 255 # image = np.expand_dims(image, axis=0) # # build the VGG16 network # model = applications.VGG16(include_top=False, weights='imagenet') # # get the bottleneck prediction from the pre-trained VGG16 model # bottleneck_prediction = model.predict(image) # # build top model # model = Sequential() # model.add(Flatten(input_shape=bottleneck_prediction.shape[1:])) # model.add(Dense(256, activation='relu')) # model.add(Dropout(0.5)) # model.add(Dense(num_classes, activation='sigmoid')) # model.load_weights(top_model_weights_path) # # use the bottleneck prediction on the top model to get the final # # classification # class_predicted = model.predict_classes(bottleneck_prediction) # probabilities = model.predict_proba(bottleneck_prediction) # inID = class_predicted[0] # inv_map = {v: k for k, v in class_dictionary.items()} # label = inv_map[inID] # # get the prediction label # print("Image ID: {}, Label: {}".format(inID, label)) # # display the predictions with the image # cv2.putText(orig, "Predicted: {}".format(label), (10, 30), # cv2.FONT_HERSHEY_PLAIN, 1.5, (43, 99, 255), 2) # cv2.imshow("Classification", orig) # cv2.waitKey(0) # cv2.destroyAllWindows() save_bottlebeck_features() train_top_model()
de1ff793d22e5fe089410de99e0e802ef749bcdb
[ "Python" ]
2
Python
gurleen-kaur-30/Outfit_Classifier
377c7acbcf0a05e8ad24ef5f8a4ff949aba18fac
c148934508b2556bf43cea61ae28e057932288b8
refs/heads/master
<file_sep>#include <stdio.h> #include <stdlib.h> #include<string.h> #define TAM 2 int in,chave,pesq,posicao; int RandomInteger(int low, int high); void BuscaSequencial(); void Linha(); // Algoritmo 2 - Definição de uma struct que representa uma // residencia (respectivamente, uma leitura de consumo) struct Residencia { char rua[25]; int numCasa; int numMedidor; float medidaConsumo; } vetResidencias[TAM]; main(){ int i = 0; int x = 0; for(i=0; i<TAM; i++){ printf("\nDigite o numero da casa:\n"); scanf("%d", &vetResidencias[i].numCasa); Linha(); printf("Digite o nome da rua da casa %i: \n", i+1); gets(vetResidencias[i].rua); Linha(); printf("\nMedidor:\n"); scanf("%i", &vetResidencias[i].numMedidor); Linha(); printf("\nMedida consumo:\n"); scanf("%d", &vetResidencias[i].medidaConsumo); Linha(); } BuscaSequencial(); system("PAUSE"); return 0; } // Algoritmo 1 - Gerador de números inteiros aleatórios // A função RandomInteger devolve um inteiro // aleatório entre low e high inclusive, // ou seja, no intervalo fechado low..high. int RandomInteger (int low, int high) { int k; double d; d = (double) rand () / ((double) RAND_MAX + 1); k = d * (high - low + 1); return low + k; } void Linha(){ int i = 0; for(i=1;i<=40;i++){ printf("-"); } printf("\n"); } void BuscaSequencial(){ Linha(); printf("\nDigite o numero ser localizado : "); int num = 0; scanf("%d", &num); for(in=0;in<TAM;in++){ if(vetResidencias[in].numCasa==num){ printf("Nome da rua: %s", vetResidencias[in].rua); printf("\n"); printf("Numero da casa: %d", in+1, vetResidencias[in].numCasa); printf("\n"); printf("Num Medidor: %d", vetResidencias[in].numMedidor); printf("\n"); printf("Medida Consumo: %d", vetResidencias[in].medidaConsumo); printf("\n"); } } } <file_sep>#include <stdio.h> #include <stdlib.h> main(){ int aux; int i, j, x; int valor[10] = {23, 14, 3, 17, 19 ,28, 40, 1, 2}; for(i=0;i<10; i++){ for(j=i+1; j<10; j++){ if(valor[i]>valor[j]){ aux=valor[i]; valor[i]=valor[j]; valor[j]=aux; } } } for(x = 0; x < 10; x++){ printf("\n%d", valor[x]); } printf("\n"); system("PAUSE"); }<file_sep>#include <stdio.h> #include <stdlib.h> #define TAM 10 void Carregar(); void MostrarLista(); void MostrarQuantidadePares(); void MostrarQuantidadeImpares(); int lista[TAM]; int qtVetor = 0; main(){ Carregar(); MostrarLista(); MostrarQuantidadePares(); MostrarQuantidadeImpares(); printf("\n"); system("PAUSE"); } void MostrarLista(){ int x; for(x = 0; x < TAM; x++){ if(x==qtVetor){ break; } printf("\n%d", lista[x]); } } void Carregar(){ int i = -1; printf("Digite um numero para adicionar a fila.\n"); printf("Digite 0 (zero) para mostrar o resultado\n"); do{ i++; scanf("%d", &lista[i]); if(lista[i]==0){ break; } qtVetor++; }while(i!=TAM-1); } void MostrarQuantidadePares(){ printf("\n Quantidade de pares: "); int x; int q = 0; for(x = 0; x < TAM; x++){ if(x==qtVetor){ break; } if(lista[x]%2==0){ q++; } } printf("%d", q); } void MostrarQuantidadeImpares(){ printf("\n Quantidade de impares: "); int x; int q = 0; for(x = 0; x < TAM; x++){ if(x==qtVetor){ break; } if(lista[x]%2!=0){ q++; } } printf("%d", q); } <file_sep>#include <stdio.h> #include <stdlib.h> #include<string.h> #define TAM 3 //variaveis globais e metodos genericos int in,chave,pesq,posicao; void linha(); void imprimir(); void cadastrar(); // residencia (respectivamente, uma leitura de consumo) struct Residencia { char rua[25]; int numCasa; int numMedidor; float medidaConsumo; } residencias[TAM]; //Metodos de ordenação //Seleção e troca void selectSort(int menorParaMaior); //Inserção void insertionSortMenorParaMaior(); void insertionSortMaiorParaMenor(); //Distribuição void mergeSort(struct Residencia* vec, int vecSize, int menorParaMaior); void mergeMenorParaMaior(struct Residencia* vec, int vecSize); void mergeMaiorParaMenor(struct Residencia* vec, int vecSize); //Intercalação void mergesortIntercalacao(int p, int r, struct Residencia* v, int menorParaMaior); void intercalaMaiorParaMenor(int p, int q, int r, struct Residencia* v); void intercalaMenorParaMaior(int p, int q, int r, struct Residencia* v); //------------------------------------------------------------------------------ main(){ int escolha = 0; while(escolha!=11){ printf("Opcoes\n"); printf(" > Cadastro\n"); printf(" > 1 - Para cadastrar residencias\n"); printf(" > Ordenar lista\n"); printf(" > 2 - Por selecao e troca (Do menor para o maior):\n"); printf(" > 3 - Por selecao e troca (Do maior para o menor):\n"); printf(" > 4 - Por distribuicao (Do menor para o maior):\n"); printf(" > 5 - Por distribuicao (Do menor para o maior):\n"); printf(" > 6 - Por insercao (Do menor para o maior):\n"); printf(" > 7 - Por insercao (Do menor para o maior):\n"); printf(" > 8 - Por intercalacao (Do menor para o maior):\n"); printf(" > 9 - Por intercalacao (Do menor para o maior):\n"); printf(" > 10 - Mostrar lista\n"); printf(" > 11 - Sair\n"); scanf("%i", &escolha); switch(escolha){ case 1 : cadastrar(); break; case 2 : selectSort(1); printf("A lista foi ordenada.\n"); break; case 3 : selectSort(0); printf("A lista foi ordenada.\n"); break; case 4 : mergeSort(residencias, TAM, 1); printf("A lista foi ordenada.\n"); break; case 5 : mergeSort(residencias, TAM, 0); printf("A lista foi ordenada.\n"); break; case 6 : insertionSortMenorParaMaior(); printf("A lista foi ordenada.\n"); break; case 7 : insertionSortMaiorParaMenor(); printf("A lista foi ordenada.\n"); break; case 8 : mergesortIntercalacao(0, TAM, residencias, 1); printf("A lista foi ordenada.\n"); break; case 9 : mergesortIntercalacao(0, TAM, residencias, 0); printf("A lista foi ordenada.\n"); break; case 10 : imprimir(); break; case 11 : printf("Saindo!\n"); break; default: printf("Opção invalida! Escolha novamente.\n"); } } linha(); system("PAUSE"); } void cadastrar(){ int i = 0; int x = 0; getchar(); for(i=0; i<TAM; i++){ printf("Digite o nome da rua da casa %i: \n", i+1); gets(residencias[i].rua); linha(); printf("\nDigite o numero da casa:\n"); scanf("%d", &residencias[i].numCasa); linha(); printf("\nMedidor:\n"); scanf("%i", &residencias[i].numMedidor); linha(); printf("\nMedida consumo:\n"); scanf("%f", &residencias[i].medidaConsumo); linha(); getchar(); } } void imprimir(){ linha(); for(in=0;in<TAM;in++){ printf("Residencia %i: \n", in+1); printf("Nome da rua: %s", residencias[in].rua); printf("\n"); printf("Numero da casa: %i", residencias[in].numCasa); printf("\n"); printf("Num Medidor: %d", residencias[in].numMedidor); printf("\n"); printf("Medida Consumo: %f", residencias[in].medidaConsumo); printf("\n"); } linha(); } void linha(){ int i = 0; for(i=1;i<=40;i++){ printf("-"); } printf("\n"); } // Função de ordenação por seleção e troca void selectSort(int menorParaMaior){ int i, j, k, troca; struct Residencia temp; for(i = 0; i < TAM-1; i++){ troca = 0; k = i; temp = residencias[i]; for(j = i+1; j < TAM; j++){ if(menorParaMaior==1){ if(residencias[j].medidaConsumo < temp.medidaConsumo){ k = j; temp = residencias[j]; troca = 1; } }else{ if(residencias[j].medidaConsumo > temp.medidaConsumo){ k = j; temp = residencias[j]; troca = 1; } } } if(troca){ residencias[k] = residencias[i]; residencias[i] = temp; } } } void insertionSortMaiorParaMenor() { int i, j; struct Residencia temp; for (i = 1; i < TAM; i++){ temp = residencias[i]; j = i - 1; while ((j>=0) && (temp.medidaConsumo > residencias[j].medidaConsumo)) { residencias[j+1] = residencias[j]; j--; } residencias[j+1] = temp; } } void insertionSortMenorParaMaior() { int i, j; struct Residencia temp; for (i = 1; i < TAM; i++){ temp = residencias[i]; j = i - 1; while ((j>=0) && (temp.medidaConsumo < residencias[j].medidaConsumo)) { residencias[j+1] = residencias[j]; j--; } residencias[j+1] = temp; } } void intercalaMaiorParaMenor(int p, int q, int r, struct Residencia* v) { int i, j, k; struct Residencia w[TAM]; i = p; j = q; k = 0; while (i < q && j < r) { if (v[i].medidaConsumo > v[j].medidaConsumo) { w[k] = v[i]; i++; } else { w[k] = v[j]; j++; } k++; } while (i < q) { w[k] = v[i]; i++; k++; } while (j < r) { w[k] = v[j]; j++; k++; } for (i = p; i < r; i++){ v[i] = w[i-p]; } } void intercalaMenorParaMaior(int p, int q, int r, struct Residencia* v) { int i, j, k; struct Residencia w[TAM]; i = p; j = q; k = 0; while (i < q && j < r) { if (v[i].medidaConsumo < v[j].medidaConsumo) { w[k] = v[i]; i++; } else { w[k] = v[j]; j++; } k++; } while (i < q) { w[k] = v[i]; i++; k++; } while (j < r) { w[k] = v[j]; j++; k++; } for (i = p; i < r; i++){ v[i] = w[i-p]; } } void mergesortIntercalacao(int p, int r, struct Residencia* v, int menorParaMaior) { int q; if (p < r - 1) { q = (p + r) / 2; mergesortIntercalacao(p, q, v, menorParaMaior); mergesortIntercalacao(q, r, v, menorParaMaior); if(menorParaMaior==1){ intercalaMenorParaMaior(p, q, r, v); }else{ intercalaMaiorParaMenor(p, q, r, v); } } } //distribuição maior para menor void mergeMaiorParaMenor(struct Residencia* vec, int vecSize) { int mid; int i, j, k; struct Residencia tmp[TAM]; if (&tmp == NULL) { exit(1); } mid = vecSize / 2; i = 0; j = mid; k = 0; while (i < mid && j < vecSize) { if (vec[i].medidaConsumo >= vec[j].medidaConsumo) { tmp[k] = vec[i++]; }else { tmp[k] = vec[j++]; } ++k; } if (i == mid) { while (j < vecSize) { tmp[k++] = vec[j++]; } } else { while (i < mid) { tmp[k++] = vec[i++]; } } for (i = 0; i < vecSize; ++i) { vec[i] = tmp[i]; } } //distribuição menor para maior void mergeMenorParaMaior(struct Residencia* vec, int vecSize) { int mid; int i, j, k; struct Residencia tmp[TAM]; if (&tmp == NULL) { exit(1); } mid = vecSize / 2; i = 0; j = mid; k = 0; while (i < mid && j < vecSize) { if (vec[i].medidaConsumo <= vec[j].medidaConsumo) { tmp[k] = vec[i++]; } else { tmp[k] = vec[j++]; } ++k; } if (i == mid) { while (j < vecSize) { tmp[k++] = vec[j++]; } } else { while (i < mid) { tmp[k++] = vec[i++]; } } for (i = 0; i < vecSize; ++i) { vec[i] = tmp[i]; } } //distribuição void mergeSort(struct Residencia* vec, int vecSize, int menorParaMaior) { int mid; if (vecSize > 1) { mid = vecSize / 2; mergeSort(vec, mid, menorParaMaior); mergeSort(vec + mid, vecSize - mid, menorParaMaior); if(menorParaMaior==1){ mergeMenorParaMaior(vec, vecSize); }else{ mergeMaiorParaMenor(vec, vecSize); } } } <file_sep>#include <stdio.h> #include <stdlib.h> #include<string.h> #define TAM 10 void Carregar(); void BuscaSequencial(); void Linha(); char item[TAM][20]; int i,pesq,posicao; char chave[1][20]; main() { Linha(); printf("\n BUSCA SEQUENCIAL \n"); Linha(); Carregar(); BuscaSequencial(); printf("\n"); system("PAUSE"); return 0; } void Carregar(){ for(i=0;i<=9;i++){ printf("\nDigite o %d%s",(i+1),"o nome -> "); gets(item[i]); } } void BuscaSequencial(){ Linha(); printf("\nDigite o dado a ser localizado : "); gets(chave[0]); for(i=0;i<TAM;i++){ if(strcmp(chave[0], item[i])== 0){ printf("\necontrado"); pesq=1; posicao=i;} } if(pesq==1){ printf("\nAchado o dado na posicao : %d %s",posicao+1," do vetor de dados\n"); } else{ printf("\nNao achou o dado no vetor\n"); } Linha(); } void Linha(){ for(i=1;i<=40;i++){ printf("-"); } }
1654b6637faefe3cc30a57dccdeb98e2737c51c9
[ "C", "C++" ]
5
C
cassiodsl/projetos_c
e440b74c9bbd0c3858f0224a2d760e5bb3aa24b9
a3579abb257c016d0378ef18776c48f2fff81201
refs/heads/master
<file_sep>package hello.tests import junit.framework.TestCase import kotlin.test.assertEquals import hello.getHelloString class HelloTest : TestCase() { fun testAssert() : Unit { assertEquals("Hello, world!", getHelloString()) } } <file_sep>package extensions import junit.framework.TestCase import org.junit.Assert.assertNotSame import org.junit.Assert.assertThat import kotlin.test.assertEquals import org.hamcrest.Matchers.* class ExtensionsTest : TestCase() { fun testBuildinExtensions() : Unit { val arr = array(1,2,3,4,5); val filtered = arr.filter { x -> x > 2 } assertNotSame(filtered, arr) // assertEquals(filtered, array(3,4,5)) // hm ... filtered array has different type than the original ... assertThat(filtered, everyItem(greaterThan(2))) } fun testCustomExtension(): Unit { assertEquals("foo".rot13().rot13(), "foo") } } <file_sep>package javascript import js.jquery.* fun main(args: Array<String>) { // will be automagically called when document is loaded jq { Kotlin2Javascript().fill() } } public class Kotlin2Javascript { fun fill(){ val items = array("a","b","c") jq { val container = jq("#container") container.append("<b>Hello, World!</b>") container.append("<ul>") for(s in items) container.append("<li>$s</li>") container.append("</ul>") } } }<file_sep>package nullsafety class Nullsafety(var a : String, var b:String?) { fun lengthA(): Int { return a.length() } fun lengthB() : Int? { return b?.length() } fun nonnullLengthB(): Int { return b?.length() ?: 0; } fun npeLengthB(): Int { return b!!.length() } }<file_sep>kotlin-example ============== Example code for the Kotlin language talk at Javaforum Stuttgart 2013 The example covers the following aspects - automated build using Apache Maven - language basics: control structures, classes, inheritance, functions - safe programming - modularization - extension functions - compilation to JavaScript (TBD) <file_sep>package extensions fun String.rot13(): String { val builder = StringBuilder() for(c in this) builder.append( when(c){ in 'a'..'m' -> (c.toInt() + 13).toChar() in 'A'..'m' -> (c.toInt() + 13).toChar() in 'n'..'z' -> (c.toInt() - 13).toChar() in 'N'..'Z' -> (c.toInt() - 13).toChar() else -> c }) return builder.toString() }<file_sep>package basics fun ifReturningValue(number: Int) : String { val result = if(number %2 == 0) "Even" else "Odd" return result } <file_sep>package modules val homeDir = "..." /* module("de.exxcellent.kotlin.demo") { depends(MavenRepo["junit.junit@4.10"]) importNamespace("java.lang") importNamespace("org.junit") sourceRoot("$homeDir/src/main/kotlin") testSourceRoot("$homeDir/src/test/kotlin") } */<file_sep>package basics open class ClassWithProperties { // make class derivable var foo: Int = 0 open fun f() : String { return foo.toString()} } class ImmutableClass (val foo: Int) class ExtendedClassWithProperties : ClassWithProperties() { var bar: String = "" override fun f():String { return "${foo}, ${bar}" } }<file_sep>package basics import org.junit.Test import org.hamcrest.CoreMatchers.`is` import org.hamcrest.CoreMatchers.equalTo import org.junit.Assert.assertThat import junit.framework.TestCase Test class ClassesTest :TestCase() { fun testClassCreationAndProperties() : Unit{ val c = ClassWithProperties() assertThat(c.foo, `is`(equalTo(0))) c.foo = 10 assertThat(c.foo, `is`(equalTo(10))) assertThat(c.f(), equalTo("10")) } fun testImmutableClass() : Unit{ val c = ImmutableClass(1) assertThat(c.foo, `is`(equalTo(1))) // c.foo = 5 // compile error } fun testInheritance() :Unit { val c = ExtendedClassWithProperties() c.bar = "foo" assertThat(c.f(), equalTo("0, foo")) } }<file_sep>package nullsafety import junit.framework.TestCase import kotlin.test.assertEquals import kotlin.test.assertNull import kotlin.test.fail class NullsafetyTest : TestCase() { fun testInstatiationWithNullableProperty() : Unit { val ns = Nullsafety("",null); assertEquals(ns.lengthA(), 0) assertEquals(ns.nonnullLengthB(), 0) assertNull(ns.lengthB()) //val ns2 = Nullsafety(null, ""); // compile error } fun testInstatiationWithNPE() : Unit { val ns = Nullsafety("",null); try { ns.npeLengthB() fail() } catch (e: NullPointerException){ } //val ns2 = Nullsafety(null, ""); // compile error } }<file_sep>package basics import org.junit.Assert.assertThat import org.hamcrest.CoreMatchers.equalTo import junit.framework.TestCase class FunctionsTest : TestCase(){ fun testExecute() : Unit{ val a :Int = 1 val b :Int = 1 assertThat(execute(a,b, ::add ), equalTo(add_inferred(a,b))) // pass a function assertThat(execute(a,b, {(a,b) -> (a+b)}), equalTo(add(a,b))) // pass a function literal } }<file_sep>package basics // function definition fun add(a: Int, b: Int) : Int { return a + b; } // function definition: return type is inferred fun add_inferred (a: Int, b:Int) = a + b // function literal as parameter fun execute(a: Int, b:Int, f: (Int,Int) -> Int) = f(a,b)<file_sep>package basics import junit.framework.TestCase import org.junit.Assert.assertEquals class ControllStructuresTest : TestCase() { fun testIfReturningValue() : Unit { assertEquals(ifReturningValue(42), "Even") assertEquals(ifReturningValue(41), "Odd") } }
91bf0a665d4a4808280f9f1bc847064f2aee4783
[ "Markdown", "Kotlin" ]
14
Kotlin
rguderlei/kotlin-example
adb8d16d4fb87576f33b25799fcd86016663d5f6
d2b80f4225cf46ad8cb9402abb81030d864e0563
refs/heads/master
<file_sep> #include <glad/glad.h> //#include <gl/glew.h> #include <GLFW/glfw3.h> int main1(){ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL", NULL, NULL); if (window == NULL) { //std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { //std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // Game loop while (!glfwWindowShouldClose(window)) { // Check if any events have been activated (key pressed, mouse moved etc.) and call corresponding response functions glfwPollEvents(); // Render // Clear the colorbuffer glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // Swap the screen buffers glfwSwapBuffers(window); } // Terminates GLFW, clearing any resources allocated by GLFW. glfwTerminate(); return 0; }<file_sep>#include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> #include <string> void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); char const* VertexShaderSource = R"GLSL( #version 130 in vec2 position; void main() { gl_Position = vec4(position, 0.0, 1.0); } )GLSL"; char const* FragmentShaderSource = R"GLSL( #version 130 out vec4 outColor; void main() { outColor = vec4(1.0, 0.0, 0.0, 1.0); } )GLSL"; //char const* VertexShaderSource1 = R"GLSL( // #version 130 core // in vec3 aPos; // void main() // { // gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0); // } // )GLSL"; // //char const* FragmentShaderSource1 = R"GLSL( // #version 130 core // out vec4 FragColor; // void main() // { // FragColor = vec4(1.0f, 0.2f, 0.4f, 1.0f); // } // )GLSL"; void framebuffer_size_callback(GLFWwindow* window, int width, int height); void get_resolution(int & window_width, int &window_height) { const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); window_width = mode->width; window_height = mode->height; } int sample_draw_element_triangle() { GLFWwindow* window = 0; if (GLFW_FALSE == glfwInit()) { return -1; } int nWidth = 800, nHeight = 600; //get_resolution(nWidth, nHeight); window = glfwCreateWindow(nWidth, nHeight, "Test OpenGL", NULL /* glfwGetPrimaryMonitor()*/, NULL); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetKeyCallback(window, key_callback); //init glew GLenum err = glewInit(); if (GLEW_OK != err) { glfwTerminate(); return -1; } GLfloat Vertices[] = { 0.0f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, 0.0f }; GLuint Elements[] = { 0,1,2 }; //Vertex Array Object GLuint VAO; glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); //Vertex Buffer Object GLuint VBO; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); //Element Buffer Object GLuint EBO; glGenBuffers(1, &EBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Elements), Elements, GL_STATIC_DRAW); GLint Compiled; GLuint VertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(VertexShader, 1, &VertexShaderSource, NULL); glCompileShader(VertexShader); glGetShaderiv(VertexShader, GL_COMPILE_STATUS, &Compiled); if (!Compiled) { std::cerr << "error compile vertex shader source!" << std::endl; return -1; } GLuint FragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(FragmentShader, 1, &FragmentShaderSource, NULL); glCompileShader(FragmentShader); glGetShaderiv(FragmentShader, GL_COMPILE_STATUS, &Compiled); if (!Compiled) { std::cerr << "error compile fragment shader source!" << std::endl; return -1; } GLuint ShaderProgram = glCreateProgram(); glAttachShader(ShaderProgram, VertexShader); glAttachShader(ShaderProgram, FragmentShader); glBindFragDataLocation(ShaderProgram, 0, "outColor"); glLinkProgram(ShaderProgram); glUseProgram(ShaderProgram); GLint PositionAttribute = glGetAttribLocation(ShaderProgram, "position"); glEnableVertexAttribArray(PositionAttribute); glBindBuffer(GL_ARRAY_BUFFER, VBO); glVertexAttribPointer(PositionAttribute, 2, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); while (!glfwWindowShouldClose(window)) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, 0); glDrawElements(GL_LINE_LOOP, 3, GL_UNSIGNED_INT, 0); glfwSwapBuffers(window); glfwPollEvents(); } glDeleteProgram(ShaderProgram); glDeleteShader(FragmentShader); glDeleteShader(VertexShader); glDeleteBuffers(1, &EBO); glDeleteBuffers(1, &VBO); } void framebuffer_size_callback(GLFWwindow* window, int width, int height) { glViewport(0, 0, width, height); } <file_sep>#include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> #include <string> #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "glm/gtc/type_ptr.hpp" extern glm::mat4x4 matMVP2;// = glm::mat4x4(1.0f); extern unsigned int aVecColorLocation; extern unsigned int aSelectedVecColorLocation; extern unsigned int aNormalVecColorLocation; extern glm::vec4 vecSelectedColor;// = glm::vec4(1.f, 0.f, 0.f, 1.f); extern glm::vec4 vecNormalColor;// = glm::vec4(0.f, 0.f, 1.f, 1.f); extern GLuint shaderProgram; extern GLuint shaderProgram2; void framebuffer_size_callback(GLFWwindow* window, int width, int height); void key_callback_learn3(GLFWwindow* window, int key, int scancode, int action, int mode) { if (action == GLFW_PRESS) { if (key == 32) { glm::vec4 tmp = vecSelectedColor; vecSelectedColor = vecNormalColor; vecNormalColor = tmp; glUniform4fv(aSelectedVecColorLocation, 1, glm::value_ptr(vecSelectedColor)); glUniform4fv(aNormalVecColorLocation, 1, glm::value_ptr(vecNormalColor)); } else if (key == 262) { //key right unsigned int aMvpLocation = glGetUniformLocation(shaderProgram, "mvp"); //glm::mat4x4 matMVP = glm::mat4x4(1.0f); matMVP2 = glm::translate(matMVP2, glm::vec3(0.1f, 0.1f, 0)); //matMVP2 = glm::scale(matMVP2, glm::vec3(1.1f, 1.1f, 0)); glUniformMatrix4fv(aMvpLocation, 1, GL_FALSE, glm::value_ptr(matMVP2)); } else if (key == 263) {//key lef } else if (key == 264) {//key down } else if (key == 265) {//key up } } else if (action == GLFW_RELEASE) { } std::cout << "key:" << key << std::endl; } int learn3() { GLFWwindow* window = 0; if (GLFW_FALSE == glfwInit()) { return -1; } //glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); //glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); int nWidth = 800, nHeight = 800; //get_resolution(nWidth, nHeight); window = glfwCreateWindow(nWidth, nHeight, "Test OpenGL", NULL/*glfwGetPrimaryMonitor()*/, NULL); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetKeyCallback(window, key_callback_learn3); //init glew GLenum err = glewInit(); if (GLEW_OK != err) { glfwTerminate(); return -1; } GLint compiled_status = -1; float vertices[] = { //location //selected //selected 0.f,0.f,0.f, 0.f, 0.25f, 0.0f, 0.0f, 1.f, 0.25f, 0.25f, 0.0f, 1.f, 0.5f, 0.25f, 0.0f, 1.f, 0.5f, 0.0f, 0.0f, 1.f, 0.375f, 0.125f, 0.0f, 1.f, -0.25f, 0.0f, 0.0f, 0.f, -0.25f, 0.25f, 0.0f, 0.f, -0.5f, 0.25f, 0.0f, 0.f, -0.5f, 0.0f, 0.0f, 0.f, -0.375f, 0.125f, 0.0f, 0.f, }; GLuint elements[] = { 1,2,3,4,5, 0, 6,7,8, 9, 10, }; //vertex buffer objects GLuint VBO; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); //Element Buffer Object GLuint EBO; glGenBuffers(1, &EBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW); char const* VertexShaderSource = R"GLSL( #version 330 in vec3 aPos; uniform mat4 mvp; in float isSelected; out vec4 oColor; uniform vec4 uSelectedColor; uniform vec4 uNormalColor; void main() { if(isSelected==0.f){ oColor = uSelectedColor; // vec4(1.0f, 0.0f, 0.0f, 1.f); } else{ oColor = uNormalColor; // vec4(0.0f, 1.0f, 0.0f, 1.f); } gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0); } )GLSL"; GLuint vertexShader; vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &VertexShaderSource, NULL); glCompileShader(vertexShader); glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &compiled_status); if (!compiled_status) { char infoLog[512] = { 0 }; glGetShaderInfoLog(vertexShader, 512, NULL, infoLog); std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl; } char const* FragmentShaderSource = R"GLSL( #version 330 uniform vec4 vecColor; out vec4 FragColor; in vec4 oColor; void main() { FragColor = oColor; } )GLSL"; GLuint fragmentShader; fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &FragmentShaderSource, NULL); glCompileShader(fragmentShader); compiled_status = -1; glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &compiled_status); if (!compiled_status) { char infoLog[512] = { 0 }; glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog); std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl; } shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glGetProgramiv(shaderProgram, GL_LINK_STATUS, &compiled_status); if (!compiled_status) { char infoLog[512] = { 0 }; glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog); std::cout << "program \n" << compiled_status << std::endl; } //linking vertex attribute unsigned int aPosLocation = glGetAttribLocation(shaderProgram, "aPos"); glVertexAttribPointer(aPosLocation, 3, GL_FLOAT, GL_FALSE, 4 * sizeof(float), 0); glEnableVertexAttribArray(aPosLocation); unsigned int aPosSelected = glGetAttribLocation(shaderProgram, "isSelected"); glVertexAttribPointer(aPosSelected, 1, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(aPosSelected); unsigned int aMvpLocation = glGetUniformLocation(shaderProgram, "mvp"); glUniformMatrix4fv(aMvpLocation, 1, GL_FALSE, glm::value_ptr(matMVP2)); aVecColorLocation = glGetUniformLocation(shaderProgram, "vecColor"); aSelectedVecColorLocation = glGetUniformLocation(shaderProgram, "uSelectedColor"); aNormalVecColorLocation = glGetUniformLocation(shaderProgram, "uNormalColor"); //float vertices2[] = { // //location //selected // 0.70f, 0.0f, 0.0f, 1.f, // 0.70f, 0.0f, 0.0f, 1.f, // 0.70f, 0.25f, 0.0f, 1.f, // 0.95f, 0.25f, 0.0f, 1.f, // 0.95f, 0.0f, 0.0f, 1.f, //}; //GLuint elements2[] = { // 1,2,3,4, 0 //}; ////vertex2 buffer objects //GLuint VBO2; //glGenBuffers(1, &VBO2); //glBindBuffer(GL_ARRAY_BUFFER, VBO2); //glBufferData(GL_ARRAY_BUFFER, sizeof(vertices2), vertices2, GL_STATIC_DRAW); // ////Element Buffer Object //GLuint EBO2; //glGenBuffers(1, &EBO2); //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO2); //glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements2), elements2, GL_STATIC_DRAW); //char const* VertexShaderSource2 = R"GLSL( // #version 330 // in vec3 aPos; // void main() // { // gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0); // } // )GLSL"; //GLuint vertexShader2; //vertexShader2 = glCreateShader(GL_VERTEX_SHADER); //glShaderSource(vertexShader2, 1, &VertexShaderSource2, NULL); //glCompileShader(vertexShader2); //compiled_status = -1; //glGetShaderiv(vertexShader2, GL_COMPILE_STATUS, &compiled_status); //if (!compiled_status) //{ // char infoLog[512] = { 0 }; // glGetShaderInfoLog(vertexShader2, 512, NULL, infoLog); // std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl; //} //char const* FragmentShaderSource2 = R"GLSL( // #version 330 // //uniform vec4 vecColor; // //in vec4 oColor; // out vec4 FragColor; // void main() // { // FragColor = vec4(1.0f, 1.0f, 0.0f, 1.f); // } // )GLSL"; //GLuint fragmentShader2; //fragmentShader2 = glCreateShader(GL_FRAGMENT_SHADER); //glShaderSource(fragmentShader2, 1, &FragmentShaderSource2, NULL); //glCompileShader(fragmentShader2); //compiled_status = -1; //glGetShaderiv(fragmentShader2, GL_COMPILE_STATUS, &compiled_status); //if (!compiled_status) //{ // char infoLog[512] = { 0 }; // glGetShaderInfoLog(fragmentShader2, 512, NULL, infoLog); // std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl; //} //shaderProgram2 = glCreateProgram(); //glAttachShader(shaderProgram2, vertexShader2); //glAttachShader(shaderProgram2, fragmentShader2); //glLinkProgram(shaderProgram2); //glGetProgramiv(shaderProgram2, GL_LINK_STATUS, &compiled_status); //if (!compiled_status) { // char infoLog[512] = { 0 }; // glGetProgramInfoLog(shaderProgram2, 512, NULL, infoLog); // std::cout << "program \n" << compiled_status << std::endl; //} ////linking vertex attribute //unsigned int aPosLocation2 = glGetAttribLocation(shaderProgram2, "aPos"); //glVertexAttribPointer(aPosLocation2, 3, GL_FLOAT, GL_FALSE, 4 * sizeof(float), 0); //glEnableVertexAttribArray(aPosLocation2); glEnable(GL_PRIMITIVE_RESTART); //glPrimitiveRestartIndex(0); int n = 0; while (!glfwWindowShouldClose(window)) { if (n < 2) { glUniform4fv(aSelectedVecColorLocation, 1, glm::value_ptr(vecSelectedColor)); glUniform4fv(aNormalVecColorLocation, 1, glm::value_ptr(vecNormalColor)); } glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glUseProgram(shaderProgram); glDrawElements(GL_LINE_LOOP, sizeof(elements) / sizeof(unsigned int), GL_UNSIGNED_INT, 0); //glUseProgram(shaderProgram2); //glDrawElements(GL_LINE_LOOP, sizeof(elements2) / sizeof(unsigned int), GL_UNSIGNED_INT, 0); glfwSwapBuffers(window); glfwPollEvents(); n++; } glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); //glDeleteBuffers(1, &VBO2); //glDeleteBuffers(1, &EBO2); glDeleteProgram(shaderProgram); glDeleteProgram(shaderProgram2); glfwTerminate(); } <file_sep>int sample_draw_aray_triangle(); int sample_draw_element_triangle(); int sample_drawing_triangle_index(); int learn0();//scale triangle int learn1();//client drawing int learn2();//scale rectangle and triangle int learn3();//split into 2 array buffer, 2 program int learn4();//add vertex information object id to vertex namespace l5 { int main(); //buffer sub data to change object position } namespace l6 { int main(); //learing transformation } namespace l6_transform { int main(); //learing transformation } int main() { //learn0(); //l5::main(); //l6::main(); //sample_draw_element_triangle(); l6_transform::main(); return 0; } <file_sep># OBJS specifies which files to compile as part of the project OBJS = Main.cpp Learn0.cpp Learn1.cpp Learn2.cpp Learn4.cpp Learn5.cpp Learn6.cpp Learn6_transform.cpp Source0_sample_draw_aray_triangle.cpp Source1_sample_draw_element_triangle.cpp Source2_sample_drawing_triangle_index.cpp # CC specifies which compiler we're using CC = g++ -std=c++11 # COMPILER_FLAGS specifies the additional compilation options we're using # -Wall will turn on all standard warnings COMPILER_FLAGS = -Wall -g -O0 # LINKER_FLAGS specifies the libraries we're linking against LINKER_FLAGS = -lGL -lGLU -lglut -lGLEW -lglfw3 -lX11 -lXxf86vm -lXrandr -lpthread -lXi -ldl -lXinerama -lXcursor # OBJ_NAME specifies the name of our exectuable OBJ_NAME = sample #This is the target that compiles our executable all: $(OBJS) $(CC) $(OBJS) $(COMPILER_FLAGS) $(LINKER_FLAGS) -o $(OBJ_NAME) clean: rm -f $(OBJ_NAME) <file_sep> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> #include <string> // gl_Position = vec4(position, 0.0, 1.0); char const* VertexShaderSource = R"GLSL( #version 130 in vec2 position; void main() { gl_Position = vec4(position, 0.0, 1.0); } )GLSL"; // outColor = vec4(1.0, 0.0, 0.0, 1.0); char const* FragmentShaderSource = R"GLSL( #version 130 out vec4 aoutColor1; void main() { aoutColor1 = vec4(1.0, 1.0, 0.0, 1.0); } )GLSL"; void PrintOpenGLErrors(char const* const Function, char const* const File, int const Line) { bool Succeeded = true; GLenum Error = glGetError(); if (Error != GL_NO_ERROR) { //char const* ErrorString = (char const*)gluErrorString(Error); //if (ErrorString) // std::cerr << ("OpenGL Error in %s at line %d calling function %s: '%s'", File, Line, Function, ErrorString) << std::endl; //else // std::cerr << ("OpenGL Error in %s at line %d calling function %s: '%d 0x%X'", File, Line, Function, Error, Error) << std::endl; } } void key_handle(GLFWwindow* window, int key, int scan, int action, int mode) { std::cout << "key:" << key << std::endl; if (key == 32) { std::cout << "key: = space" << key << std::endl; } } void PrintShaderInfoLog(GLint const Shader) { int InfoLogLength = 0; int CharsWritten = 0; glGetShaderiv(Shader, GL_INFO_LOG_LENGTH, &InfoLogLength); if (InfoLogLength > 0) { GLchar* InfoLog = new GLchar[InfoLogLength]; glGetShaderInfoLog(Shader, InfoLogLength, &CharsWritten, InfoLog); std::cout << "Shader Info Log:" << std::endl << InfoLog << std::endl; delete[] InfoLog; } } int glew_main1() { GLFWwindow* window; if (!glfwInit()) return -1; window = glfwCreateWindow(800, 600, "Hello World", NULL, NULL); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetKeyCallback(window, key_handle); GLenum err = glewInit(); if (GLEW_OK != err) { std::cerr << "Error: " << glewGetErrorString(err) << std::endl; glfwTerminate(); return -1; } GLfloat const Vertices[] = { 0.0f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f }; GLuint const Elements[] = { 0, 1, 2 }; //GLuint VAO; //glGenVertexArrays(1, &VAO); //glBindVertexArray(VAO); GLuint VBO; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); GLuint EBO; glGenBuffers(1, &EBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Elements), Elements, GL_STATIC_DRAW); GLint Compiled; GLuint VertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(VertexShader, 1, &VertexShaderSource, NULL); glCompileShader(VertexShader); glGetShaderiv(VertexShader, GL_COMPILE_STATUS, &Compiled); if (!Compiled) { std::cerr << "Failed to compile vertex shader!" << std::endl; PrintShaderInfoLog(VertexShader); } GLuint FragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(FragmentShader, 1, &FragmentShaderSource, NULL); glCompileShader(FragmentShader); glGetShaderiv(FragmentShader, GL_COMPILE_STATUS, &Compiled); if (!Compiled) { std::cerr << "Failed to compile fragment shader!" << std::endl; PrintShaderInfoLog(FragmentShader); } GLuint ShaderProgram = glCreateProgram(); glAttachShader(ShaderProgram, VertexShader); glAttachShader(ShaderProgram, FragmentShader); glBindFragDataLocation(ShaderProgram, 0, "outColor"); glLinkProgram(ShaderProgram); glUseProgram(ShaderProgram); GLint PositionAttribute = glGetAttribLocation(ShaderProgram, "position"); glEnableVertexAttribArray(PositionAttribute); glBindBuffer(GL_ARRAY_BUFFER, VBO); glVertexAttribPointer(PositionAttribute, 2, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); while (!glfwWindowShouldClose(window)) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, 0); glDrawElements(GL_LINE_LOOP, 3, GL_UNSIGNED_INT, 0); glfwSwapBuffers(window); glfwPollEvents(); } glDeleteProgram(ShaderProgram); glDeleteShader(FragmentShader); glDeleteShader(VertexShader); glDeleteBuffers(1, &EBO); glDeleteBuffers(1, &VBO); //glDeleteVertexArrays(1, &VAO); glfwTerminate(); return 0; }<file_sep>#include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> #include <string> #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "glm/gtc/type_ptr.hpp" extern GLuint shaderProgram; void framebuffer_size_callback(GLFWwindow* window, int width, int height); void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); int learn1() { GLFWwindow* window = 0; if (GLFW_FALSE == glfwInit()) { return -1; } int nWidth = 800, nHeight = 600; //get_resolution(nWidth, nHeight); window = glfwCreateWindow(nWidth, nHeight, "Test OpenGL", NULL /* glfwGetPrimaryMonitor()*/, NULL); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetKeyCallback(window, key_callback); //init glew GLenum err = glewInit(); if (GLEW_OK != err) { glfwTerminate(); return -1; } float vertices[] = { -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, }; GLuint Elements[] = { 0,1,2 }; //size_t nNum = 1000000000; //float* arrVrt = (float*)malloc(nNum * sizeof(float)); //if (arrVrt) { // memset(arrVrt, 0, nNum * sizeof(float)); //} unsigned int VAO; glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); //vertex buffer objects unsigned int VBO; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); char const* VertexShaderSource = R"GLSL( #version 130 uniform mat4 mvp; in vec3 aPos; void main() { gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0) * mvp; } )GLSL"; GLuint vertexShader; vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &VertexShaderSource, NULL); glCompileShader(vertexShader); GLint compiled_status = -1; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &compiled_status); if (!compiled_status) { char infoLog[512] = { 0 }; glGetShaderInfoLog(vertexShader, 512, NULL, infoLog); std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl; } char const* FragmentShaderSource = R"GLSL( #version 130 out vec4 FragColor; void main() { FragColor = vec4(1.0f, 1.0f, 0.0f, 0.5f); } )GLSL"; GLuint fragmentShader; fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &FragmentShaderSource, NULL); glCompileShader(fragmentShader); compiled_status = -1; glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &compiled_status); if (!compiled_status) { char infoLog[512] = { 0 }; glGetShaderInfoLog(vertexShader, 512, NULL, infoLog); std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl; } shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glGetProgramiv(shaderProgram, GL_LINK_STATUS, &compiled_status); if (!compiled_status) { char infoLog[512] = { 0 }; glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog); std::cout << "program \n" << compiled_status << std::endl; } //glUseProgram(shaderProgram); //glBindVertexArray(VAO); //linking vertex attribute unsigned int aPosLocation = glGetAttribLocation(shaderProgram, "aPos"); glVertexAttribPointer(aPosLocation, 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), 0); glEnableVertexAttribArray(aPosLocation); unsigned int aMvpLocation = glGetUniformLocation(shaderProgram, "mvp"); //glm::mat4x4 matMVP = glm::mat4x4(1.0f); glm::mat4 transform = glm::mat4(1.0f); // make sure to initialize matrix to identity matrix first transform = glm::translate(transform, glm::vec3(0.1f, -0.1f, 0.0f)); transform = glm::rotate(transform, (float)glfwGetTime(), glm::vec3(0.0f, 0.0f, 0.0f)); const float* pMVPMtx = glm::value_ptr(transform); glUniformMatrix4fv(aMvpLocation, 1, GL_FALSE, pMVPMtx); while (!glfwWindowShouldClose(window)) { glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glUseProgram(shaderProgram); glBindVertexArray(VAO); glDrawArrays(GL_TRIANGLES, 0, 4); glfwSwapBuffers(window); glfwPollEvents(); } glDeleteShader(vertexShader); glDeleteShader(fragmentShader); }<file_sep>#include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> #include <string> #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "glm/gtc/type_ptr.hpp" glm::mat4x4 matMVP[] = { glm::mat4x4(1.0f) , glm::mat4x4(1.0f) , glm::mat4x4(1.0f) , glm::mat4x4(1.0f) }; unsigned int aMvpLocation[4]; extern unsigned int aSelectedVecColorLocation; extern unsigned int aNormalVecColorLocation; unsigned int selectedId; extern glm::vec4 vecSelectedColor;// = glm::vec4(1.f, 0.f, 0.f, 1.f); extern glm::vec4 vecNormalColor;// = glm::vec4(0.f, 0.f, 1.f, 1.f); extern GLuint shaderProgram; extern GLuint shaderProgram2; struct Position { float fX = 0.f; float fY = 0.f; float fZ = 0.f; Position() {}; Position(float x, float y, float z) { fX = x; fY = y; fZ = z; } }; struct VertexAtt { Position posData; float fSelected = 0; float nObjectId = 0; VertexAtt() {}; VertexAtt(const Position& pos,const float &selected, const float& objId= 0 ) { posData = pos; fSelected = selected; nObjectId = objId; } }; void framebuffer_size_callback(GLFWwindow* window, int width, int height); void key_callback_learn4(GLFWwindow* window, int key, int scancode, int action, int mode) { if (action == GLFW_PRESS) { if (key >= 320 && key <= 323) { selectedId = key - 320; } if (key == 32) { glm::vec4 tmp = vecSelectedColor; vecSelectedColor = vecNormalColor; vecNormalColor = tmp; glUniform4fv(aSelectedVecColorLocation, 1, glm::value_ptr(vecSelectedColor)); glUniform4fv(aNormalVecColorLocation, 1, glm::value_ptr(vecNormalColor)); } if (key >= 262 && key <= 265) { switch (key) { case 262://key right matMVP[selectedId] = glm::translate(matMVP[selectedId], glm::vec3(0.1f, 0.0f, 0)); break; case 263://key lef matMVP[selectedId] = glm::translate(matMVP[selectedId], glm::vec3(-0.1f, 0.0f, 0)); break; case 264://key down matMVP[selectedId] = glm::translate(matMVP[selectedId], glm::vec3(0.0f, -0.1f, 0)); break; case 265://key up matMVP[selectedId] = glm::translate(matMVP[selectedId], glm::vec3(0.0f, +0.1f, 0)); break; default: break; } glUniformMatrix4fv(aMvpLocation[selectedId], 1, GL_FALSE, glm::value_ptr(matMVP[selectedId])); } //if (key == 262) { //key right // unsigned int aMvpLocation = glGetUniformLocation(shaderProgram, "mvp1"); // //glm::mat4x4 matMVP = glm::mat4x4(1.0f); // l4_matMVP1 = glm::translate(l4_matMVP1, glm::vec3(0.1f, 0.1f, 0)); // //matMVP2 = glm::scale(matMVP2, glm::vec3(1.1f, 1.1f, 0)); // glUniformMatrix4fv(aMvpLocation, 1, GL_FALSE, glm::value_ptr(l4_matMVP1)); //} //else if (key == 263) {//key lef // unsigned int aMvpLocation = glGetUniformLocation(shaderProgram, "mvp2"); // l4_matMVP2 = glm::translate(l4_matMVP2, glm::vec3(0.1f, 0.1f, 0)); // glUniformMatrix4fv(aMvpLocation, 1, GL_FALSE, glm::value_ptr(l4_matMVP2)); //} //else if (key == 264) {//key down // unsigned int aMvpLocation = glGetUniformLocation(shaderProgram, "mvp3"); // l4_matMVP3 = glm::translate(l4_matMVP3, glm::vec3(0.1f, 0.1f, 0)); // glUniformMatrix4fv(aMvpLocation, 1, GL_FALSE, glm::value_ptr(l4_matMVP3)); //} //else if (key == 265) {//key up // unsigned int aMvpLocation = glGetUniformLocation(shaderProgram, "mvp0"); // l4_matMVP0 = glm::translate(l4_matMVP0, glm::vec3(0.1f, 0.1f, 0)); // glUniformMatrix4fv(aMvpLocation, 1, GL_FALSE, glm::value_ptr(l4_matMVP0)); //} } else if (action == GLFW_RELEASE) { } std::cout << "key:" << key << std::endl; } int learn4() { int test = sizeof(Position); test = sizeof(VertexAtt); GLFWwindow* window = 0; if (GLFW_FALSE == glfwInit()) { return -1; } int nWidth = 600, nHeight = 600; //get_resolution(nWidth, nHeight); window = glfwCreateWindow(nWidth, nHeight, "Test OpenGL", NULL /* glfwGetPrimaryMonitor()*/, NULL); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetKeyCallback(window, key_callback_learn4); //init glew GLenum err = glewInit(); if (GLEW_OK != err) { glfwTerminate(); return -1; } VertexAtt vertices[] = { //location //selected //obj id VertexAtt(Position(0.f,0.f,0.f), 0, 0), VertexAtt(Position(0.25f, 0.0f, 0.0f), 1, 0), VertexAtt(Position(0.25f, 0.25f, 0.0f), 1, 0), VertexAtt(Position(0.5f, 0.25f, 0.0f), 1, 0), VertexAtt(Position(0.5f, 0.0f, 0.0f), 1, 0), VertexAtt(Position(0.375f, 0.125f, 0.0f), 1, 0), VertexAtt(Position(-0.25f, 0.0f, 0.0f), 0, 1), VertexAtt(Position(-0.25f, 0.25f, 0.0f), 0, 1), VertexAtt(Position(-0.5f, 0.25f, 0.0f), 0, 1), VertexAtt(Position(-0.5f, 0.0f, 0.0f), 0, 1), VertexAtt(Position(-0.375f, 0.125f, 0.0f), 0, 1), VertexAtt(Position(-0.25f, -0.1f, 0.0f), 2, 2), VertexAtt(Position(-0.25f, -0.25f, 0.0f), 2, 2), VertexAtt(Position(-0.5f, -0.25f, 0.0f), 2, 2), VertexAtt(Position(-0.5f, -0.1f, 0.0f), 2, 2), VertexAtt(Position(0.25f, -0.1f, 0.0f), 2, 3), VertexAtt(Position(0.25f, -0.25f, 0.0f), 2, 3), VertexAtt(Position(0.5f, -0.25f, 0.0f), 2, 3), VertexAtt(Position(0.5f, -0.1f, 0.0f), 2, 3), }; GLuint elements[] = { 1,2,3,4,5, 0, 6,7,8, 9, 10, 0, 11, 12, 13, 14, 0, 15,16,17,18 }; //vertex buffer objects GLuint VBO; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); //Element Buffer Object GLuint EBO; glGenBuffers(1, &EBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW); char const* VertexShaderSource = R"GLSL( #version 330 in vec3 aPos; in float isSelected; in float inObjId; out vec4 oColor; uniform mat4 mvp0; uniform mat4 mvp1; uniform mat4 mvp2; uniform mat4 mvp3; uniform vec4 uSelectedColor; uniform vec4 uNormalColor; void main() { if(isSelected == 0){ oColor = uSelectedColor; // vec4(1.0f, 0.0f, 0.0f, 1.f); } else if(isSelected == 1){ oColor = uNormalColor; // vec4(0.0f, 1.0f, 0.0f, 1.f); } else { oColor = vec4(0.0f, 1.0f, 0.0f, 1.f); } if(inObjId==0){ gl_Position = mvp0 * vec4(aPos.x, aPos.y, aPos.z, 1.0); } else if(inObjId==1){ gl_Position = mvp1 * vec4(aPos.x, aPos.y, aPos.z, 1.0); } else if(inObjId==2){ gl_Position = mvp2 * vec4(aPos.x, aPos.y, aPos.z, 1.0); } else if(inObjId==3){ gl_Position = mvp3 * vec4(aPos.x, aPos.y, aPos.z, 1.0); } else { gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0); } } )GLSL"; GLuint vertexShader; vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &VertexShaderSource, NULL); glCompileShader(vertexShader); GLint compiled_status = -1; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &compiled_status); if (!compiled_status) { char infoLog[512] = { 0 }; glGetShaderInfoLog(vertexShader, 512, NULL, infoLog); std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl; } char const* FragmentShaderSource = R"GLSL( #version 330 uniform vec4 vecColor; out vec4 FragColor; in vec4 oColor; void main() { FragColor = oColor; } )GLSL"; GLuint fragmentShader; fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &FragmentShaderSource, NULL); glCompileShader(fragmentShader); compiled_status = -1; glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &compiled_status); if (!compiled_status) { char infoLog[512] = { 0 }; glGetShaderInfoLog(vertexShader, 512, NULL, infoLog); std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl; } shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glGetProgramiv(shaderProgram, GL_LINK_STATUS, &compiled_status); if (!compiled_status) { char infoLog[512] = { 0 }; glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog); std::cout << "program \n" << compiled_status << std::endl; } //linking vertex attribute unsigned int aPosLocation = glGetAttribLocation(shaderProgram, "aPos"); glVertexAttribPointer(aPosLocation, 3, GL_FLOAT, GL_FALSE, sizeof(VertexAtt), 0); glEnableVertexAttribArray(aPosLocation); unsigned int aPosSelected = glGetAttribLocation(shaderProgram, "isSelected"); glVertexAttribPointer(aPosSelected, 1, GL_FLOAT, GL_FALSE, sizeof(VertexAtt), (void*)sizeof(Position)); glEnableVertexAttribArray(aPosSelected); unsigned int aPosObjId = glGetAttribLocation(shaderProgram, "inObjId"); glVertexAttribPointer(aPosObjId, 1, GL_FLOAT, GL_FALSE, sizeof(VertexAtt), (void*) (sizeof(Position)+sizeof(float))); glEnableVertexAttribArray(aPosObjId); aMvpLocation[0] = glGetUniformLocation(shaderProgram, "mvp0"); aMvpLocation[1] = glGetUniformLocation(shaderProgram, "mvp1"); aMvpLocation[2] = glGetUniformLocation(shaderProgram, "mvp2"); aMvpLocation[3] = glGetUniformLocation(shaderProgram, "mvp3"); aSelectedVecColorLocation = glGetUniformLocation(shaderProgram, "uSelectedColor"); aNormalVecColorLocation = glGetUniformLocation(shaderProgram, "uNormalColor"); glUseProgram(shaderProgram); glUniform4fv(aSelectedVecColorLocation, 1, glm::value_ptr(vecSelectedColor)); glUniform4fv(aNormalVecColorLocation, 1, glm::value_ptr(vecNormalColor)); for (int i = 0; i < 4; i++) { glUniformMatrix4fv(aMvpLocation[i], 1, GL_FALSE, glm::value_ptr(matMVP[i])); } glEnable(GL_PRIMITIVE_RESTART); //glPrimitiveRestartIndex(0); int n = 0; while (!glfwWindowShouldClose(window)) { glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glDrawElements(GL_LINE_LOOP, sizeof(elements) / sizeof(unsigned int), GL_UNSIGNED_INT, 0); glfwSwapBuffers(window); glfwPollEvents(); n++; } glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); glDeleteProgram(shaderProgram); glfwTerminate(); } <file_sep>#include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> #include <string> #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "glm/gtc/type_ptr.hpp" #include <vector> namespace l6 { #define PI 3.14159265359 unsigned int aSelectedVecColorLocation; unsigned int aNormalVecColorLocation; unsigned int selectedId; glm::vec4 vecSelectedColor = glm::vec4(1.f, 0.f, 0.f, 1.f); glm::vec4 vecNormalColor = glm::vec4(0.f, 0.f, 1.f, 1.f); GLuint shaderProgram; GLuint VBO; struct Position { float fX = 0.f; float fY = 0.f; float fZ = 0.f; Position() {}; Position(float x, float y, float z) { fX = x; fY = y; fZ = z; } }; struct VertexAtt { Position posData; float fSelected = 0; int nObjectId = 0; VertexAtt() {}; VertexAtt(const Position& pos, const float& selected, const int& objId = 0) { posData = pos; fSelected = selected; nObjectId = objId; } }; VertexAtt vertices[] = { //location //selected //obj id VertexAtt(Position(0.f,0.f,0.f), 0, -1), VertexAtt(Position(0.25f, 0.0f, 0.0f), 1, 0), VertexAtt(Position(0.25f, 0.25f, 0.0f), 1, 0), VertexAtt(Position(0.5f, 0.25f, 0.0f), 1, 0), VertexAtt(Position(0.5f, 0.0f, 0.0f), 1, 0), VertexAtt(Position(0.375f, 0.125f, 0.0f), 1, 0), VertexAtt(Position(-0.25f, 0.0f, 0.0f), 0, 1), VertexAtt(Position(-0.25f, 0.25f, 0.0f), 0, 1), VertexAtt(Position(-0.5f, 0.25f, 0.0f), 0, 1), VertexAtt(Position(-0.5f, 0.0f, 0.0f), 0, 1), VertexAtt(Position(-0.375f, 0.125f, 0.0f), 0, 1), VertexAtt(Position(-0.25f, -0.1f, 0.0f), 2, 2), VertexAtt(Position(-0.25f, -0.25f, 0.0f), 2, 2), VertexAtt(Position(-0.5f, -0.25f, 0.0f), 2, 2), VertexAtt(Position(-0.5f, -0.1f, 0.0f), 2, 2), VertexAtt(Position(0.25f, -0.1f, 0.0f), 2, 3), VertexAtt(Position(0.25f, -0.25f, 0.0f), 2, 3), VertexAtt(Position(0.5f, -0.25f, 0.0f), 2, 3), VertexAtt(Position(0.5f, -0.1f, 0.0f), 2, 3), VertexAtt(Position(0.0f, 0.0f, 0.0f), 2, 4), VertexAtt(Position(0.0f, 0.25f, 0.0f), 2, 4), VertexAtt(Position(0.1f, 0.25f, 0.0f), 2, 4), VertexAtt(Position(0.1f, 0.0f, 0.0f), 2, 4), }; GLuint elements[] = { 1,2,3,4,5, 0, 6,7,8, 9, 10, 0, 11, 12, 13, 14, 0, 15,16,17,18, 0, 19,20,21,22, }; struct Object { VertexAtt* pPointer; int nNumOfVertex; public: Object(VertexAtt* p = NULL, const int &n = 0) { pPointer = p; nNumOfVertex = n; } }; std::vector<Object> g_vecObj; void framebuffer_size_callback(GLFWwindow* window, int width, int height) { glViewport(0, 0, width, height); } bool get_area_centroid(const Object &obj,float &a, float &x, float &y) { a = 0.0f; if (obj.nNumOfVertex < 3) { return false; } std::vector<Position> vec_pos; for (int i = 0; i < obj.nNumOfVertex; i++) { VertexAtt vi = obj.pPointer[i]; vec_pos.push_back(vi.posData); } vec_pos.push_back(obj.pPointer[0].posData); float sum = 0.0f; for (int i = 0; i < vec_pos.size()-1; i++) { Position pos_i = vec_pos[i]; Position pos_j = vec_pos[i+1]; sum += (pos_i.fX * pos_j.fY - pos_j.fX * pos_i.fY); } a = 0.5 * sum; float sum_x = 0.0f, sum_y = 0.0f; for (int i = 0; i < vec_pos.size() - 1; i++) { Position pos_i = vec_pos[i]; Position pos_j = vec_pos[i + 1]; sum_x += ((pos_i.fX + pos_j.fX) * (pos_i.fX * pos_j.fY - pos_j.fX * pos_i.fY)); sum_y += ((pos_i.fY + pos_j.fY) * (pos_i.fX * pos_j.fY - pos_j.fX * pos_i.fY)); } x = sum_x / (6 * a); y = sum_y / (6 * a); return true; } void rotate_point(const float cx, const float cy, float angle, float &x, float &y) { float s = sin(angle); float c = cos(angle); // translate point back to origin: x -= cx; y -= cy; // rotate point float xnew = x * c - y * s; float ynew = x * s + y * c; // translate point back: x = xnew + cx; y = ynew + cy; } void rotate_my_obj(Object obj, const float cx, const float cy, float angle) { for (int i = 0; i < obj.nNumOfVertex; i++) { rotate_point(cx, cy, angle, obj.pPointer[i].posData.fX, obj.pPointer[i].posData.fY); } } void transition_my_obj(Object obj, const float cx, const float cy) { for (int i = 0; i < obj.nNumOfVertex; i++) { obj.pPointer[i].posData.fX += cx; obj.pPointer[i].posData.fY += cy; } } void key_callback_learn(GLFWwindow* window, int key, int scancode, int action, int mode) { //std::cout << "key :" << key << std::endl; Object obj; if (action == GLFW_PRESS) { if (key >= 320 && key <= 324) { selectedId = key - 320; if (selectedId <= g_vecObj.size()) { } else { return; } } obj = g_vecObj[selectedId]; if (key == 32) { glm::vec4 tmp = vecSelectedColor; vecSelectedColor = vecNormalColor; vecNormalColor = tmp; glUniform4fv(aSelectedVecColorLocation, 1, glm::value_ptr(vecSelectedColor)); glUniform4fv(aNormalVecColorLocation, 1, glm::value_ptr(vecNormalColor)); } if (key >= 262 && key <= 265) { glm::vec2 trans; switch (key) { case 262://key right trans = glm::vec2(0.1f, 0.0f); break; case 263://key lef trans = glm::vec2(-0.1f, 0.0f); break; case 264://key down trans = glm::vec2(0.0f, -0.1f); break; case 265://key up trans = glm::vec2(0.0f, 0.1f); break; default: break; } transition_my_obj(obj, trans.x, trans.y); int ofset = obj.pPointer - vertices; glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferSubData(GL_ARRAY_BUFFER, ofset * sizeof(VertexAtt), obj.nNumOfVertex * sizeof(VertexAtt), obj.pPointer); } if (key == 65 || key == 68) { float angle = 0.f; switch (key) { case 65: //A key angle = PI / 4.0f; break; case 68: //D key angle = -PI / 4.0f; break; default: break; } glm::mat4 transform = glm::mat4(1.0f); float a, x, y; get_area_centroid(obj, a, x, y); rotate_my_obj(obj, x, y, angle); int ofset = obj.pPointer - vertices; glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferSubData(GL_ARRAY_BUFFER, ofset * sizeof(VertexAtt), obj.nNumOfVertex * sizeof(VertexAtt), obj.pPointer); } if (key == 83 || key == 87) { switch (key) { case 83: //S key break; case 87: //W key break; default: break; } } } } int main() { int test = sizeof(Position); test = sizeof(VertexAtt); g_vecObj.push_back(Object(&vertices[1], 5)); g_vecObj.push_back(Object(&vertices[6], 5)); g_vecObj.push_back(Object(&vertices[11], 4)); g_vecObj.push_back(Object(&vertices[15], 4)); g_vecObj.push_back(Object(&vertices[19], 4)); GLFWwindow* window = 0; if (GLFW_FALSE == glfwInit()) { return -1; } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); int nWidth = 600, nHeight = 600; window = glfwCreateWindow(nWidth, nHeight, "Test OpenGL", NULL /* glfwGetPrimaryMonitor()*/, NULL); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetKeyCallback(window, key_callback_learn); glewExperimental = GL_TRUE; //init glew GLenum err = glewInit(); if (GLEW_OK != err) { glfwTerminate(); return -1; } unsigned int VAO; glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); //vertex buffer objects glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); //Element Buffer Object GLuint EBO; glGenBuffers(1, &EBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW); //glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, sizeof(elements), elements); char const* VertexShaderSource = R"GLSL( #version 330 core in vec3 aPos; in float isSelected; out vec4 oColor; uniform vec4 uSelectedColor; uniform vec4 uNormalColor; void main() { if(isSelected == 0){ oColor = uSelectedColor; // vec4(1.0f, 0.0f, 0.0f, 1.f); } else if(isSelected == 1){ oColor = uNormalColor; // vec4(0.0f, 1.0f, 0.0f, 1.f); } else { oColor = vec4(0.0f, 1.0f, 0.0f, 1.f); } gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0); } )GLSL"; GLuint vertexShader; vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &VertexShaderSource, NULL); glCompileShader(vertexShader); GLint compiled_status = -1; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &compiled_status); if (!compiled_status) { char infoLog[512] = { 0 }; glGetShaderInfoLog(vertexShader, 512, NULL, infoLog); std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl; } char const* FragmentShaderSource = R"GLSL( #version 330 core uniform vec4 vecColor; out vec4 FragColor; in vec4 oColor; void main() { FragColor = oColor; } )GLSL"; GLuint fragmentShader; fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &FragmentShaderSource, NULL); glCompileShader(fragmentShader); compiled_status = -1; glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &compiled_status); if (!compiled_status) { char infoLog[512] = { 0 }; glGetShaderInfoLog(vertexShader, 512, NULL, infoLog); std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl; } shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glGetProgramiv(shaderProgram, GL_LINK_STATUS, &compiled_status); if (!compiled_status) { char infoLog[512] = { 0 }; glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog); std::cout << "program \n" << compiled_status << std::endl; } //linking vertex attribute unsigned int aPosLocation = glGetAttribLocation(shaderProgram, "aPos"); glVertexAttribPointer(aPosLocation, 3, GL_FLOAT, GL_FALSE, sizeof(VertexAtt), 0); glEnableVertexAttribArray(aPosLocation); unsigned int aPosSelected = glGetAttribLocation(shaderProgram, "isSelected"); glVertexAttribPointer(aPosSelected, 1, GL_FLOAT, GL_FALSE, sizeof(VertexAtt), (void*)sizeof(Position)); glEnableVertexAttribArray(aPosSelected); glBindVertexArray(0); aSelectedVecColorLocation = glGetUniformLocation(shaderProgram, "uSelectedColor"); aNormalVecColorLocation = glGetUniformLocation(shaderProgram, "uNormalColor"); glUseProgram(shaderProgram); glEnable(GL_PRIMITIVE_RESTART); //glPrimitiveRestartIndex(0); glUniform4fv(aSelectedVecColorLocation, 1, glm::value_ptr(vecSelectedColor)); glUniform4fv(aNormalVecColorLocation, 1, glm::value_ptr(vecNormalColor)); double lastTime = glfwGetTime(); int nbFrames = 0; glfwSwapInterval(0); glBindVertexArray(VAO); while (!glfwWindowShouldClose(window)) { double currentTime = glfwGetTime(); nbFrames++; if (currentTime - lastTime >= 1.0) { // If last prinf() was more than 1 sec ago // printf and reset timer printf("%f ms/frame\n", 1000.0 / double(nbFrames)); printf("fps=%d\n", nbFrames); nbFrames = 0; lastTime = currentTime; } glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glDrawElements(GL_LINE_LOOP, sizeof(elements) / sizeof(unsigned int), GL_UNSIGNED_INT, 0); glfwSwapBuffers(window); glfwPollEvents(); } glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); glDeleteProgram(shaderProgram); glfwTerminate(); return 0; } } <file_sep>#include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> #include <string> #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "glm/gtc/type_ptr.hpp" glm::mat4x4 matMVP2 = glm::mat4x4(1.0f); unsigned int aVecColorLocation; unsigned int aSelectedVecColorLocation; unsigned int aNormalVecColorLocation; glm::vec4 vecSelectedColor = glm::vec4(1.f, 0.f, 0.f, 1.f); glm::vec4 vecNormalColor = glm::vec4(0.f, 0.f, 1.f, 1.f); extern GLuint shaderProgram; extern GLuint shaderProgram2; void framebuffer_size_callback(GLFWwindow* window, int width, int height); void key_callback_learn2(GLFWwindow* window, int key, int scancode, int action, int mode) { if (action == GLFW_PRESS) { if (key == 32) { glm::vec4 tmp = vecSelectedColor; vecSelectedColor = vecNormalColor; vecNormalColor = tmp; glUniform4fv(aSelectedVecColorLocation, 1, glm::value_ptr(vecSelectedColor)); glUniform4fv(aNormalVecColorLocation, 1, glm::value_ptr(vecNormalColor)); } else if (key == 262) { //key right unsigned int aMvpLocation = glGetUniformLocation(shaderProgram, "mvp"); //glm::mat4x4 matMVP = glm::mat4x4(1.0f); matMVP2 = glm::translate(matMVP2, glm::vec3(0.1f, 0.1f, 0)); //matMVP2 = glm::scale(matMVP2, glm::vec3(1.1f, 1.1f, 0)); glUniformMatrix4fv(aMvpLocation, 1, GL_FALSE, glm::value_ptr(matMVP2)); } else if (key == 263) {//key lef } else if (key == 264) {//key down } else if (key == 265) {//key up } } else if (action == GLFW_RELEASE) { } std::cout << "key:" << key << std::endl; } int learn2() { GLFWwindow* window = 0; if (GLFW_FALSE == glfwInit()) { return -1; } int nWidth = 600, nHeight = 600; //get_resolution(nWidth, nHeight); window = glfwCreateWindow(nWidth, nHeight, "Test OpenGL", NULL /* glfwGetPrimaryMonitor()*/, NULL); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetKeyCallback(window, key_callback_learn2); //init glew GLenum err = glewInit(); if (GLEW_OK != err) { glfwTerminate(); return -1; } float vertices[] = { //location //selected //selected 0.f,0.f,0.f, 0.f, 0.25f, 0.0f, 0.0f, 1.f, 0.25f, 0.25f, 0.0f, 1.f, 0.5f, 0.25f, 0.0f, 1.f, 0.5f, 0.0f, 0.0f, 1.f, 0.375f, 0.125f, 0.0f, 1.f, -0.25f, 0.0f, 0.0f, 0.f, -0.25f, 0.25f, 0.0f, 0.f, -0.5f, 0.25f, 0.0f, 0.f, -0.5f, 0.0f, 0.0f, 0.f, -0.375f, 0.125f, 0.0f, 0.f, }; GLuint elements[] = { 1,2,3,4,5, 0, 6,7,8, 9, 10, }; //vertex buffer objects GLuint VBO; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); //Element Buffer Object GLuint EBO; glGenBuffers(1, &EBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW); char const* VertexShaderSource = R"GLSL( #version 330 in vec3 aPos; uniform mat4 mvp; in float isSelected; out vec4 oColor; uniform vec4 uSelectedColor; uniform vec4 uNormalColor; void main() { if(isSelected==0.f){ oColor = uSelectedColor; // vec4(1.0f, 0.0f, 0.0f, 1.f); } else{ oColor = uNormalColor; // vec4(0.0f, 1.0f, 0.0f, 1.f); } gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0); } )GLSL"; GLuint vertexShader; vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &VertexShaderSource, NULL); glCompileShader(vertexShader); GLint compiled_status = -1; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &compiled_status); if (!compiled_status) { char infoLog[512] = { 0 }; glGetShaderInfoLog(vertexShader, 512, NULL, infoLog); std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl; } char const* FragmentShaderSource = R"GLSL( #version 330 uniform vec4 vecColor; out vec4 FragColor; in vec4 oColor; void main() { FragColor = oColor; } )GLSL"; GLuint fragmentShader; fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &FragmentShaderSource, NULL); glCompileShader(fragmentShader); compiled_status = -1; glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &compiled_status); if (!compiled_status) { char infoLog[512] = { 0 }; glGetShaderInfoLog(vertexShader, 512, NULL, infoLog); std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl; } shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glGetProgramiv(shaderProgram, GL_LINK_STATUS, &compiled_status); if (!compiled_status) { char infoLog[512] = { 0 }; glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog); std::cout << "program \n" << compiled_status << std::endl; } //linking vertex attribute unsigned int aPosLocation = glGetAttribLocation(shaderProgram, "aPos"); glVertexAttribPointer(aPosLocation, 3, GL_FLOAT, GL_FALSE, 4 * sizeof(float), 0); glEnableVertexAttribArray(aPosLocation); unsigned int aPosSelected = glGetAttribLocation(shaderProgram, "isSelected"); glVertexAttribPointer(aPosSelected, 1, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(aPosSelected); unsigned int aMvpLocation = glGetUniformLocation(shaderProgram, "mvp"); glUniformMatrix4fv(aMvpLocation, 1, GL_FALSE, glm::value_ptr(matMVP2)); aVecColorLocation = glGetUniformLocation(shaderProgram, "vecColor"); aSelectedVecColorLocation = glGetUniformLocation(shaderProgram, "uSelectedColor"); aNormalVecColorLocation = glGetUniformLocation(shaderProgram, "uNormalColor"); glEnable(GL_PRIMITIVE_RESTART); //glPrimitiveRestartIndex(0); int n = 0; while (!glfwWindowShouldClose(window)) { if (n < 2) { glUniform4fv(aSelectedVecColorLocation, 1, glm::value_ptr(vecSelectedColor)); glUniform4fv(aNormalVecColorLocation, 1, glm::value_ptr(vecNormalColor)); } glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glUseProgram(shaderProgram); glDrawElements(GL_LINE_LOOP, sizeof(elements) / sizeof(unsigned int), GL_UNSIGNED_INT, 0); glfwSwapBuffers(window); glfwPollEvents(); n++; } glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); glDeleteProgram(shaderProgram); glfwTerminate(); }
c6009bc5a33046f94b431bfa8315cd0db2a5279d
[ "Makefile", "C++" ]
10
C++
minhnv16/learning_opengl
a3355418d948829598d1eb751d10d7b295341365
239c97aca48b6dfeab438ff3a9c400f6b007428b
refs/heads/master
<file_sep>// // TaskListViewController.swift // Tasks_Project // // Created by Vlad on 27.02.2020. // Copyright © 2020 Vlad. All rights reserved. // import UIKit class TaskListViewController: UITableViewController { /// enum tasks for table view let enumeration_task = Enumeration_Task.self override func viewDidLoad() { super.viewDidLoad() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return enumeration_task.allCases.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = enumeration_task.allCases[indexPath.row].rawValue return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if enumeration_task.allCases[indexPath.row] == enumeration_task.task_flickr{ /// main stroyboard let storyboard = UIStoryboard(name: "Main",bundle: nil) /// PhotosSearchViewController let photosSearchVc = storyboard.instantiateViewController(identifier: "PhotosSearchViewController") self.present(photosSearchVc, animated: true, completion: nil) }else if enumeration_task.allCases[indexPath.row] == enumeration_task.drawing{ /// main stroyboard let storyboard = UIStoryboard(name: "Main",bundle: nil) ///DrawingViewController let DrawingVc = storyboard.instantiateViewController(identifier: "DrawingViewController") self.present(DrawingVc, animated: true, completion: nil) }else if enumeration_task.allCases[indexPath.row] == enumeration_task.Json{ /// main stroyboard let storyboard = UIStoryboard(name: "Main",bundle: nil) ///DrawingViewController let JsonDecodeVc = storyboard.instantiateViewController(identifier: "JsonDecodeTableViewController") self.present(JsonDecodeVc, animated: true, completion: nil) } } } <file_sep>// // Draw.swift // Tasks_Project // // Created by Vlad on 13.03.2020. // Copyright © 2020 Vlad. All rights reserved. // import UIKit class Draw: UIView { ///object settings postion element in footboll area let settingsPositionElement = SettingsPositionElement() override func draw(_ rect: CGRect) { ///pathField1 structure that contains the location and dimensions of a rectangle. let pathField1 = CGRect(x: 0, y: settingsPositionElement.pathField1Y, width: Int(settingsPositionElement.widthScreen), height: Int(settingsPositionElement.heightGreenBlock)) ///pathLine1 structure that contains the location and dimensions of a rectangle. let pathLine1 = CGRect(x: settingsPositionElement.positionXLine, y: Int(settingsPositionElement.pathLine1Y), width: Int(settingsPositionElement.widthLine), height: settingsPositionElement.heightLine) ///pathField2 structure that contains the location and dimensions of a rectangle. let pathField2 = CGRect(x: 0, y: Int(settingsPositionElement.pathField2Y), width: Int(rect.width), height: Int(settingsPositionElement.heightGreenBlock)) ///pathLine2 structure that contains the location and dimensions of a rectangle. let pathLine2 = CGRect(x: settingsPositionElement.positionXLine, y: Int(settingsPositionElement.pathLine2Y), width: Int(settingsPositionElement.widthLine), height: settingsPositionElement.heightLine) ///pathField3 structure that contains the location and dimensions of a rectangle. let pathField3 = CGRect(x: 0, y: Int(settingsPositionElement.pathField3Y), width: Int(rect.width), height: Int(settingsPositionElement.heightGreenBlock)) ///pathLine3 structure that contains the location and dimensions of a rectangle. let pathLine3 = CGRect(x: settingsPositionElement.positionXLine, y: Int(settingsPositionElement.pathLine3Y), width: Int(settingsPositionElement.widthLine), height: settingsPositionElement.heightLine) ///pathField4 structure that contains the location and dimensions of a rectangle. let pathField4 = CGRect(x: 0, y: Int(settingsPositionElement.pathField4Y), width: Int(rect.width), height: Int(settingsPositionElement.heightGreenBlock)) ///pathLine4 structure that contains the location and dimensions of a rectangle. let pathLine4 = CGRect(x: settingsPositionElement.positionXLine, y: Int(settingsPositionElement.pathLine4Y), width: Int(settingsPositionElement.widthLine), height: settingsPositionElement.heightLine) ///pathField5 structure that contains the location and dimensions of a rectangle. let pathField5 = CGRect(x: 0, y: Int(settingsPositionElement.pathField5Y), width: Int(rect.width), height: Int(settingsPositionElement.heightGreenBlock)) ///pathLine5 structure that contains the location and dimensions of a rectangle. let pathLine5 = CGRect(x: settingsPositionElement.positionXLine, y: Int(settingsPositionElement.pathLine5Y), width: Int(settingsPositionElement.widthLine), height: settingsPositionElement.heightLine) ///pathField6 structure that contains the location and dimensions of a rectangle. let pathField6 = CGRect(x: 0, y: Int(settingsPositionElement.pathField6Y), width: Int(rect.width), height: Int(settingsPositionElement.heightGreenBlock)) ///pathCircular structure that contains the location and dimensions of a rectangle. let pathCircular = CGRect(x: Int(settingsPositionElement.pathCircularX), y: Int(settingsPositionElement.pathCircularY), width: Int(rect.width/2), height: Int(settingsPositionElement.heightGreenBlock)) ///pathSmallCircular structure that contains the location and dimensions of a rectangle. let pathSmallCircular = CGRect(x: Int(settingsPositionElement.pathSmallCircularX), y: Int(settingsPositionElement.pathSmallCircularY), width: 2, height: 2) ///pathGoalLeftBarbelTop structure that contains the location and dimensions of a rectangle. let pathGoalLeftBarbelTop = CGRect(x: Int(settingsPositionElement.pathGoalLeftBarbelTopX), y: settingsPositionElement.pathGoalLeftRightBarbelY, width: Int(settingsPositionElement.widthPathGoalLeftRightBarbelTop), height: Int(settingsPositionElement.heightPathGoalLeftRightBarbelTop)) ///pathGoalRightBarbelTop structure that contains the location and dimensions of a rectangle. let pathGoalRightBarbelTop = CGRect(x: Int(settingsPositionElement.pathGoalRightBarbelTopX), y: settingsPositionElement.pathGoalLeftRightBarbelY, width: Int(settingsPositionElement.widthPathGoalLeftRightBarbelTop), height: Int(settingsPositionElement.heightPathGoalLeftRightBarbelTop)) ///pathGoalСrossBarBarbelTop structure that contains the location and dimensions of a rectangle. let pathGoalСrossBarBarbelTop = CGRect(x: Int(settingsPositionElement.pathGoalLeftBarbelTopX), y: settingsPositionElement.pathGoalСrossBarBarbelTopY+settingsPositionElement.pathGoalLeftRightBarbelY, width: settingsPositionElement.pathGoalСrossBarBarbelTopWidth, height: settingsPositionElement.pathGoalСrossBarBarbelTopHeight) ///pathGoalLeftBarbelBottom structure that contains the location and dimensions of a rectangle. let pathGoalLeftBarbelBottom = CGRect(x: Int(settingsPositionElement.pathGoalLeftBarbelTopX), y: Int(settingsPositionElement.pathGoalBottomY), width: settingsPositionElement.widthPathGoalLeftRightBarbelTop, height: settingsPositionElement.heightPathGoalLeftRightBarbelTop) ///pathGoalRightBarbelBottom structure that contains the location and dimensions of a rectangle. let pathGoalRightBarbelBottom = CGRect(x: Int(settingsPositionElement.pathGoalRightBarbelTopX), y: Int(settingsPositionElement.pathGoalBottomY), width: settingsPositionElement.widthPathGoalLeftRightBarbelTop, height: settingsPositionElement.heightPathGoalLeftRightBarbelTop) ///pathGoalСrossBarBarbelBottom structure that contains the location and dimensions of a rectangle. let pathGoalСrossBarBarbelBottom = CGRect(x: Int(settingsPositionElement.pathGoalLeftBarbelTopX), y: Int(settingsPositionElement.pathGoalBottomY), width: settingsPositionElement.pathGoalСrossBarBarbelTopWidth, height: settingsPositionElement.pathGoalСrossBarBarbelTopHeight) ///lineFiledRignt structure that contains the location and dimensions of a rectangle. let lineFiledRignt = CGRect(x: settingsPositionElement.lineFiledRigntX, y: settingsPositionElement.lineFiledRigntLeftTopY, width: 3, height: Int(settingsPositionElement.lineFiledRigntLeftHeight)) ///lineFiledLeft structure that contains the location and dimensions of a rectangle. let lineFiledLeft = CGRect(x: Int(settingsPositionElement.lineFiledLeftX), y: settingsPositionElement.lineFiledRigntLeftTopY, width: 3, height: Int(settingsPositionElement.lineFiledRigntLeftHeight)) ///lineFiledTop structure that contains the location and dimensions of a rectangle. let lineFiledTop = CGRect(x: Int(settingsPositionElement.lineFiledRigntX), y: settingsPositionElement.lineFiledRigntLeftTopY, width: Int(settingsPositionElement.LineFiledTopWidthAndBottom), height: 3) ///lineFiledBottom structure that contains the location and dimensions of a rectangle. let lineFiledBottom = CGRect(x: Int(settingsPositionElement.lineFiledRigntX), y: Int(settingsPositionElement.lineFiledY), width: Int(settingsPositionElement.LineFiledTopWidthAndBottom), height: 3) drawFieldColorGreenLightly(in: pathField1) drawLine(in:pathLine1) drawFieldColorGreenDarker(in: pathField2) drawLine(in:pathLine2) drawFieldColorGreenLightly(in: pathField3) drawLine(in:pathLine3) drawFieldColorGreenDarker(in: pathField4) drawLine(in:pathLine4) drawFieldColorGreenLightly(in: pathField5) drawLine(in:pathLine5) drawFieldColorGreenDarker(in: pathField6) drawCircular(in: pathCircular) drawSmallCircular(in: pathSmallCircular) drawFieldLine(in: lineFiledRignt) drawFieldLine(in: lineFiledLeft) drawFieldLine(in: lineFiledTop) drawFieldLine(in: lineFiledBottom) drawGoal(in: pathGoalLeftBarbelTop) drawGoal(in: pathGoalRightBarbelTop) drawGoal(in: pathGoalСrossBarBarbelTop) drawGoal(in: pathGoalLeftBarbelBottom) drawGoal(in: pathGoalRightBarbelBottom) drawGoal(in: pathGoalСrossBarBarbelBottom) } /** function that draws a green container input:rect - A structure that contains the location and dimensions of a rectangle. return: container */ private func drawFieldColorGreenLightly(in rect: CGRect){ /// object Apath that consists of straight and curved line segments that you can render in your custom views. let path = UIBezierPath(roundedRect: rect, cornerRadius: 0) /// color container let color = UIColor.green color.setFill() path.fill() } /** function that draws a Green Darker container input:rect - A structure that contains the location and dimensions of a rectangle. return: container */ private func drawFieldColorGreenDarker(in rect: CGRect){ let path = UIBezierPath(roundedRect: rect, cornerRadius: 0) let color = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1) color.setFill() path.fill() } /** function that draws white line input:rect - A structure that contains the location and dimensions of a rectangle. return: line */ private func drawLine(in rect: CGRect){ let path = UIBezierPath(roundedRect: rect, cornerRadius: 0) let color = UIColor.white color.setFill() path.fill() } /** function that draws white circular input:rect - A structure that contains the location and dimensions of a rectangle. return: circular */ private func drawCircular(in rect: CGRect){ let circle = UIBezierPath(arcCenter: CGPoint(x: settingsPositionElement.pathSmallCircularX, y:settingsPositionElement.circleY), radius: settingsPositionElement.heightGreenBlock/2, startAngle:0, endAngle: 2*CGFloat.pi, clockwise: false) let color = UIColor.white color.setFill() circle.lineWidth = 3 UIColor.white.setStroke() circle.stroke() } /** function that draws white small circular input:rect - A structure that contains the location and dimensions of a rectangle. return: small circular */ private func drawSmallCircular(in rect: CGRect){ let circle = UIBezierPath(arcCenter: CGPoint(x: settingsPositionElement.pathSmallCircularX, y:settingsPositionElement.circleY), radius: 5, startAngle:0, endAngle: 2*CGFloat.pi, clockwise: false) let color = UIColor.white color.setFill() circle.lineWidth = 1 circle.fill() circle.stroke() } /** function that draws white Goal input:rect - A structure that contains the location and dimensions of a rectangle. return: Goal */ private func drawGoal(in rect: CGRect){ let path = UIBezierPath(roundedRect: rect, cornerRadius: 0) let color = UIColor.white color.setFill() path.fill() } /** function that draws white Field Line input:rect - A structure that contains the location and dimensions of a rectangle. return: Field Line */ private func drawFieldLine(in rect: CGRect){ let path = UIBezierPath(roundedRect: rect, cornerRadius: 0) let color = UIColor.white color.setFill() path.fill() } } <file_sep>// // PhotosSearchViewController.swift // Tasks_Project // // Created by Vlad on 27.02.2020. // Copyright © 2020 Vlad. All rights reserved. // import UIKit import FlickrKit class PhotosSearchViewController: UIViewController, UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UISearchBarDelegate { /// The count section in UICollectionView var numberOfItemsInSections = 1 /// Activity indicator for collection view @IBOutlet weak var activityIndicator: UIActivityIndicatorView! /// search bar for search image @IBOutlet weak var SearchBar: UISearchBar! /// collection view for show image @IBOutlet weak var collectionView: UICollectionView! /// count row in cellection cell image in collection view @IBOutlet weak var segmentControl: UISegmentedControl! /// Tap for hide keyboard when user search images var tap:UITapGestureRecognizer = UITapGestureRecognizer() /// Array(url) - what user search var images = [URL]() ///user write in searchBar var searchText = "" /// spacing for setting segment controll 2 colum let settingWithTwoColum = 7 /// spacing for setting segment controll 3 colum let settingWithThreeColum = 25 /// spacing for setting segment controll 4 colum let settingWithFourColum = 5 /// spacing for setting segment controll 1 colum let settingWithOneColum = 70 /// 1 colum in collection view let countColumnOne = 1 /// 2 colum in collection view let countColumnTwo = 2 /// 3 colum in collection view let countColumnThree = 3 /// 4 colum in collection view let countColumnFour = 4 // division ratio for obsession 2 colum let coefficientDivisionTwoColum:CGFloat = 2 // division ratio for obsession 3 colum let coefficientDivisionThreeColum:CGFloat = 3 // division ratio for obsession 5 colum let coefficientDivisionFourColum:CGFloat = 5 override func viewDidLoad() { super.viewDidLoad() LoadData() collectionView.dataSource = self collectionView.delegate = self SearchBar.delegate = self tap = UITapGestureRecognizer(target: self, action: #selector(self.hideKeyboard(_:))) tap.cancelsTouchesInView = false self.view.addGestureRecognizer(tap) } @objc func hideKeyboard(_ sender: UITapGestureRecognizer) { view.endEditing(true) } /** Function for downloading pictures by category that the user entered in the search return: array url images */ func LoadData(){ FlickrKit.shared().initialize(withAPIKey: "a3749a264a9fadf5f2bdfba07cbe06a3", sharedSecret: "<KEY>") ///Access the FlickrKit shared singleton let fk = FlickrKit.shared() let flickrInteresting = FKFlickrPhotosSearch() flickrInteresting.text = searchText fk.call(flickrInteresting) {(response, error) -> Void in DispatchQueue.main.async { if (response != nil) { /// array photos url let topPhotos = response!["photos"] as! [String:Any] /// array photo url let photoArray = topPhotos["photo"] as! [[String:Any]] for photoDictionary in photoArray { ///The main point of entry into FlickrKit let photoURL = FlickrKit.shared().photoURL(for: FKPhotoSize.large1024, fromPhotoDictionary: photoDictionary) if self.images.count <= 4{ self.images.append(photoURL) } } self.activityIndicator.stopAnimating() self.collectionView.reloadData() } } } } /** Сolumn number switching function in collectionView return: count column */ @IBAction func OneOrTwoPhotos(_ sender: Any) { switch segmentControl.selectedSegmentIndex { case 0: self.numberOfItemsInSections = countColumnOne case 1: self.numberOfItemsInSections = countColumnTwo case 2: self.numberOfItemsInSections = countColumnThree case 3: self.numberOfItemsInSections = countColumnFour default: break } collectionView.reloadData() } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return images.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { /// сell in collectionView let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellCollectionView", for: indexPath) as! PhotoCollectionViewCell DispatchQueue.main.async { if let data = try? Data(contentsOf: self.images[indexPath.row]) { cell.images.image = UIImage(data: data) } } return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { /// size screen width let screenSizeWidth = UIScreen.main.bounds.width if self.numberOfItemsInSections == countColumnTwo{ /// calculate size cell in collectionView for 2 column let size = CGSize(width: screenSizeWidth/coefficientDivisionTwoColum-CGFloat(settingWithTwoColum), height: screenSizeWidth/coefficientDivisionTwoColum-CGFloat(settingWithTwoColum)) return size } if self.numberOfItemsInSections == countColumnThree{ /// calculate size cell in collectionView for 3 column let size = CGSize(width: screenSizeWidth/coefficientDivisionThreeColum-CGFloat(settingWithThreeColum), height: screenSizeWidth/coefficientDivisionThreeColum-CGFloat(settingWithThreeColum)) return size } if self.numberOfItemsInSections == countColumnFour{ /// calculate size cell in collectionView for 4 column let size = CGSize(width: screenSizeWidth/coefficientDivisionFourColum-CGFloat(settingWithFourColum), height: screenSizeWidth/coefficientDivisionFourColum-CGFloat(settingWithFourColum)) return size } return CGSize(width: screenSizeWidth-CGFloat(settingWithOneColum), height: screenSizeWidth-CGFloat(settingWithOneColum)) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { /// view controller where edit photo let editPhoto = storyboard?.instantiateViewController(identifier: "EditPhotoViewController") as? EditPhotoViewController DispatchQueue.main.async { if let data = try? Data(contentsOf: self.images[indexPath.row]) { editPhoto?.image.image = UIImage(data: data) } } self.present(editPhoto!, animated: true, completion: nil) } func searchBarTextDidEndEditing(_ searchBar: UISearchBar){ if searchBar.text!.isEmpty{ self.images.removeAll() self.collectionView.reloadData() }else{ self.searchText = searchBar.text! LoadData() self.activityIndicator.startAnimating() } } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { self.SearchBar.resignFirstResponder() } } <file_sep>// // EditPhotoViewController.swift // Tasks_Project // // Created by Vlad on 06.03.2020. // Copyright © 2020 Vlad. All rights reserved. // import UIKit class EditPhotoViewController: UIViewController { /// photo which editing @IBOutlet weak var image: UIImageView! /// slider for edit size photo @IBOutlet weak var slider: UISlider! override func viewDidLoad() { super.viewDidLoad() slider.value = 1.5 slider.minimumValue = 0.1 slider.maximumValue = 1.5 } @IBAction func EditSizeImage(_ sender: Any) { /// value from slider let scale = slider.value ///transformation matrix for use in drawing 2D graphics. let transform = CGAffineTransform.init(scaleX: CGFloat(scale), y: CGFloat(scale)) image.transform = transform } } <file_sep>// // Enumeration_Task.swift // Tasks_Project // // Created by Vlad on 27.02.2020. // Copyright © 2020 Vlad. All rights reserved. // import Foundation enum Enumeration_Task:String, CaseIterable{ case task_flickr case drawing case Json case task4 } <file_sep>// // PhotoCollectionViewCell.swift // Tasks_Project // // Created by Vlad on 01.03.2020. // Copyright © 2020 Vlad. All rights reserved. // import UIKit class PhotoCollectionViewCell: UICollectionViewCell { /// This is UIImageView for **load images** . @IBOutlet weak var images: UIImageView! override func prepareForReuse() { super.prepareForReuse() self.images.image = nil } } <file_sep>// // JsonDecodeTableViewController.swift // Tasks_Project // // Created by Vlad on 24.03.2020. // Copyright © 2020 Vlad. All rights reserved. // import UIKit import Alamofire class JsonDecodeTableViewController: UITableViewController { ///A view that shows that a task is in progress. var activityIndicatorView: UIActivityIndicatorView! /// url json decodable let urlString = "https://mob-version.azurewebsites.net/api/business" /// array decodable data var data = [VersionDevice]() override func viewDidLoad() { super.viewDidLoad() activityIndicatorView = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.medium) tableView.backgroundView = activityIndicatorView activityIndicatorView.startAnimating() DispatchQueue.main.async { self.LoadData(urlString: self.urlString) } } /** Load data from url and decode Json objects paramets urlString - url to load data retrun array decodable objects */ private func LoadData(urlString:String){ AF.request(urlString,method: .get).validate().responseDecodable(of:DeviseObject.self) { (response) in if let data = response.value{ self.data.append(data.Stage) self.data.append(data.Live) self.tableView.reloadData() }else{ print("error") } self.activityIndicatorView.stopAnimating() } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { ///cell table view let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! JsonDecodeTableViewCell cell.name.text = data[indexPath.row].name cell.android_app_version.text = data[indexPath.row].android_app_version cell.android_min_supported_version.text = data[indexPath.row].android_min_supported_version cell.ios_min_supported_version.text = data[indexPath.row].ios_min_supported_version cell.ios_app_version.text = data[indexPath.row].ios_app_version return cell } } <file_sep>// // DrawingViewController.swift // Tasks_Project // // Created by Vlad on 13.03.2020. // Copyright © 2020 Vlad. All rights reserved. // import UIKit class DrawingViewController: UIViewController { /// view were draw footboll area @IBOutlet weak var viewDraw: Draw! /// image boll @IBOutlet weak var imageBoll: UIImageView! /// object settings postion element in footboll area let settingsPositionElement = SettingsPositionElement() /// height image boll let bollHeight:CGFloat = 35 /// width image boll let bollWidth:CGFloat = 35 /// number of goals scored by top teams var topTeam:Int = 0 /// number of goals scored by bottom teams var bottomTeam:Int = 0 ///right indent value for the ball let counSpacingForBoolX = 17 ///top indent value for the ball let counSpacingForBoolY = 12 ///coordinate x boll position var bollX:CGFloat = 0.0 ///coordinate y boll position var bollY:CGFloat = 0.0 ///top indent value for goal let topGoal = 23 ///bottom indent value for goal let bottomGoal = 20 override func viewDidLoad() { super.viewDidLoad() bollX = settingsPositionElement.pathSmallCircularX-CGFloat(counSpacingForBoolX) bollY = settingsPositionElement.pathSmallCircularY-CGFloat(counSpacingForBoolY) self.viewDraw.addSubview(imageBoll) imageBoll.frame = CGRect(x: bollX, y: bollY, width: bollWidth, height: bollHeight) /// A concrete subclass of UIGestureRecognizer that looks for panning (dragging) gestures. var panGesture = UIPanGestureRecognizer() panGesture = UIPanGestureRecognizer(target: self, action: #selector(draggedView(_:))) imageBoll.isUserInteractionEnabled = true imageBoll.addGestureRecognizer(panGesture) } /** function to control the ball and count the number of goals return count goal */ @objc func draggedView(_ sender:UIPanGestureRecognizer){ self.view.bringSubviewToFront(imageBoll) ///The translation of the pan gesture in the coordinate system of the specified view. let translation = sender.translation(in: self.viewDraw) imageBoll.center = CGPoint(x: imageBoll.center.x + translation.x, y: imageBoll.center.y + translation.y) if imageBoll.center.x > settingsPositionElement.pathGoalLeftBarbelTopX && imageBoll.center.x < settingsPositionElement.pathGoalRightBarbelTopX && imageBoll.center.y < CGFloat(settingsPositionElement.pathGoalСrossBarBarbelTopY+topGoal){ self.bottomTeam += 1 imageBoll.frame = CGRect(x: settingsPositionElement.pathSmallCircularX-CGFloat(counSpacingForBoolX), y: settingsPositionElement.pathSmallCircularY-CGFloat(counSpacingForBoolY), width: bollWidth, height: bollHeight) self.presentAlert() }else if imageBoll.center.x > settingsPositionElement.pathGoalLeftBarbelTopX && imageBoll.center.x < settingsPositionElement.pathGoalRightBarbelTopX && imageBoll.center.y > CGFloat(settingsPositionElement.pathGoalBottomY+CGFloat(bottomGoal)){ self.topTeam += 1 imageBoll.frame = CGRect(x: settingsPositionElement.pathSmallCircularX-CGFloat(counSpacingForBoolX), y: settingsPositionElement.pathSmallCircularY-CGFloat(counSpacingForBoolY), width: bollWidth, height: bollHeight) self.presentAlert() } sender.setTranslation(CGPoint.zero, in: self.viewDraw) } /** function that shows alert with the score return alert with score */ func presentAlert(){ ///object that displays an alert message to the user. let alert = UIAlertController(title: "Goal", message: "\(self.topTeam) - \(self.bottomTeam)", preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "Continue game", style: UIAlertAction.Style.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } <file_sep>// // VersionDevice.swift // Tasks_Project // // Created by Vlad on 24.03.2020. // Copyright © 2020 Vlad. All rights reserved. // import Foundation struct VersionDevice:Decodable{ /// json decodable object parametr name let name:String /// json decodable object parametr api_url let api_url:String /// json decodable object parametr maintenance_mode let maintenance_mode:Bool /// json decodable object parametr android_min_supported_version let android_min_supported_version:String /// json decodable object parametr android_app_version let android_app_version:String /// json decodable object parametr ios_min_supported_version let ios_min_supported_version:String /// json decodable object parametr ios_app_version let ios_app_version:String } struct DeviseObject:Decodable { /// jsen decodable object Stage let Stage:VersionDevice /// jsen decodable object Live let Live:VersionDevice } <file_sep>// // SettingsPositionElement.swift // Tasks_Project // // Created by Vlad on 16.03.2020. // Copyright © 2020 Vlad. All rights reserved. // import Foundation import UIKit class SettingsPositionElement{ ///bounding rectangle of the screen, measured in points let screenSize = UIScreen.main.bounds /// height green block area var heightGreenBlock:CGFloat /// count green block area var countGreenBlock = 6 /// the width of a rectangle. var widthScreen = UIScreen.main.bounds.width ///the height of a rectangle. var heightScreen = UIScreen.main.bounds.height /// count green block area for position calculation PathField3 let countGreenBlockForPathField3 = 2 /// count green block area for position calculation PathField4 let countGreenBlockForPathField4 = 3 /// count green block area for position calculation PathField5 let countGreenBlockForPathField5 = 4 /// count green block area for position calculation PathField6 let countGreenBlockForPathField6 = 5 /// spacing for calculate position PathField2 let countSpacingForpathField2 = 3 /// spacing for calculate position PathField3 let countSpacingForpathField3 = 6 /// spacing for calculate position PathField4 let countSpacingForpathField4 = 9 /// spacing for calculate position PathField5 let countSpacingForpathField5 = 12 /// spacing for calculate position PathField6 let countSpacingForpathField6 = 15 ///pathField1 y position var pathField1Y = 0 ///pathField2 y position var pathField2Y:CGFloat ///pathField3 y position var pathField3Y:CGFloat ///pathField4 y position var pathField4Y:CGFloat ///pathField5 y position var pathField5Y:CGFloat ///pathField6 y position var pathField6Y:CGFloat /// count green block area for position calculation PathLine2 let countGreenBlockForPathLine2Y = 2 /// count green block area for position calculation PathLine3 let countGreenBlockForPathLine3Y = 3 /// count green block area for position calculation PathLine4 let countGreenBlockForPathLine4Y = 4 /// count green block area for position calculation PathLine5 let countGreenBlockForPathLine5Y = 5 /// spacing for calculate position pathLine2 let countSpacingForpathLine2Y = 3 /// spacing for calculate position pathLine3 let countSpacingForpathLine3Y = 6 /// spacing for calculate position pathLine4 let countSpacingForpathLine4Y = 9 /// spacing for calculate position pathLine5 let countSpacingForpathLine5Y = 12 ///pathLine1Y y position var pathLine1Y:CGFloat ///pathLine2Y y position var pathLine2Y:CGFloat ///pathLine3Y y position var pathLine3Y:CGFloat ///pathLine4Y y position var pathLine4Y:CGFloat ///pathLine5Y y position var pathLine5Y:CGFloat let coefForWidthLine = 20 /// height pathLine let heightLine = 3 /// width line var widthLine:CGFloat /// pathLine x postion let positionXLine = 10 ///Dilation factor for position x for Circular let coefForPathCircularX = 2 ///Dilation factor for position y for Circular let coefForPathCircularY = 3 ///pathCircularX x position var pathCircularX:CGFloat ///pathCircularY y position var pathCircularY:CGFloat ///Dilation factor for position x for small Circular let coefForPathSmallCircularX = 2 ///Dilation factor for position y for small Circular let coefForPathSmallCircularY = 2 ///pathSmallCircularX x position var pathSmallCircularX:CGFloat ///pathSmallCircularY y position var pathSmallCircularY:CGFloat ///Dilation factor for position x for pathGoal Left Barbel Top let coefForpathGoalLeftBarbelTopX = 2 ///Dilation factor for position x for pathGoal Right Barbel Top let coefForpathGoalRightBarbelTopX = 2 /// count spacing top left barbel for position x calculation let countSpacingForpathGoalLeftBarbelTopX = 50 /// count spacing top right barbel for position x calculation let countSpacingForpathGoalRightBarbelTopX = 50 ///pathGoalLeftBarbelTopX x position var pathGoalLeftBarbelTopX:CGFloat ///pathGoalRightBarbelTopX x position var pathGoalRightBarbelTopX:CGFloat /// width PathGoal Left - Right Barbel in Top var widthPathGoalLeftRightBarbelTop = 3 /// height PathGoal Left - Right Barbel in Top var heightPathGoalLeftRightBarbelTop = 50 /// crossbar top postion y var pathGoalСrossBarBarbelTopY = 50 /// crossbar top width var pathGoalСrossBarBarbelTopWidth = 103 ///cross bar top height var pathGoalСrossBarBarbelTopHeight = 3 /// path Goal Left-Right Barbel postion y var pathGoalLeftRightBarbelY = 40 ///the number of green blocks to calculate the y position for the lower left bar let countGreenBlockForpathGoalLeftBarbelBottomY = 7 ///Dilation factor for position y for path Goal Left Barbel Bottom let coefForpathGoalLeftBarbelBottomY = 6 ///the spacing for calculate the y position for the lower left bar let countSpacingForpathGoalLeftBarbelBottomY = 35 ///position y for Goal Left Barbel Bottom var pathGoalLeftBarbelBottomY:CGFloat ///the spacing y position for the Goal bottom let countSpacingForpathGoalBottomY = 70 ///position y for Goal Bottom var pathGoalBottomY:CGFloat ///the number of green blocks to calculate the y position for the circle let countGrrenBlockForcircleY = 2 ///the spacing y position for the circle let countSpacingForcircleY = 7 /// position y circle var circleY:CGFloat /// postion x right line field var lineFiledRigntX = 10 /// position y for right-left line field top var lineFiledRigntLeftTopY = 40 /// spacing for line Filed Rignt-Left Height let countSpacingForlineFiledRigntLeftHeight = 60 /// height line right-left var lineFiledRigntLeftHeight:CGFloat /// spacing for position y line field let countSpacingForlineFiledY = 20 /// line field postion y var lineFiledY:CGFloat /// spacing for position x line field left let countSpacingForlineFiledLeftX = 13 /// line field left postion x var lineFiledLeftX:CGFloat let countSpacingForLineFiledTopWidthAndBottom = 20 /// width line field top-bottom var LineFiledTopWidthAndBottom:CGFloat init(){ heightGreenBlock = heightScreen/CGFloat(countGreenBlock) pathField2Y = heightGreenBlock + CGFloat(countSpacingForpathField2) pathField3Y = heightGreenBlock * CGFloat(countGreenBlockForPathField3) + CGFloat(countSpacingForpathField3) pathField4Y = heightGreenBlock * CGFloat(countGreenBlockForPathField4) + CGFloat(countSpacingForpathField4) pathField5Y = heightGreenBlock * CGFloat(countGreenBlockForPathField5) + CGFloat(countSpacingForpathField5) pathField6Y = heightGreenBlock * CGFloat(countGreenBlockForPathField6) + CGFloat(countSpacingForpathField6) pathLine1Y = heightGreenBlock pathLine2Y = heightGreenBlock * CGFloat(countGreenBlockForPathLine2Y) + CGFloat(countSpacingForpathLine2Y) pathLine3Y = heightGreenBlock * CGFloat(countGreenBlockForPathLine3Y) + CGFloat(countSpacingForpathLine3Y) pathLine4Y = heightGreenBlock * CGFloat(countGreenBlockForPathLine4Y) + CGFloat(countSpacingForpathLine4Y) pathLine5Y = heightGreenBlock * CGFloat(countGreenBlockForPathLine5Y) + CGFloat(countSpacingForpathLine5Y) widthLine = widthScreen - CGFloat(coefForWidthLine) pathCircularX = widthScreen / CGFloat(coefForPathCircularX) pathCircularY = heightScreen / CGFloat(coefForPathCircularY) pathSmallCircularX = widthScreen / CGFloat(coefForPathSmallCircularX) pathSmallCircularY = heightScreen / CGFloat(coefForPathSmallCircularY) pathGoalLeftBarbelTopX = widthScreen / CGFloat(coefForpathGoalLeftBarbelTopX) - CGFloat(countSpacingForpathGoalLeftBarbelTopX) pathGoalRightBarbelTopX = widthScreen / CGFloat(coefForpathGoalRightBarbelTopX) + CGFloat(countSpacingForpathGoalLeftBarbelTopX) pathGoalLeftBarbelBottomY = heightScreen / CGFloat(countGreenBlockForpathGoalLeftBarbelBottomY) * CGFloat(coefForpathGoalLeftBarbelBottomY) - CGFloat(countSpacingForpathGoalLeftBarbelBottomY) pathGoalBottomY = heightScreen - CGFloat(countSpacingForpathGoalBottomY) circleY = heightScreen / CGFloat(countGrrenBlockForcircleY) + CGFloat(countSpacingForcircleY) lineFiledRigntLeftHeight = heightScreen - CGFloat(countSpacingForlineFiledRigntLeftHeight) lineFiledY = heightScreen - CGFloat(countSpacingForlineFiledY) lineFiledLeftX = widthScreen - CGFloat(countSpacingForlineFiledLeftX) LineFiledTopWidthAndBottom = widthScreen - CGFloat(countSpacingForLineFiledTopWidthAndBottom) } } <file_sep> // // JsonDecodeTableViewCell.swift // Tasks_Project // // Created by Vlad on 24.03.2020. // Copyright © 2020 Vlad. All rights reserved. // import UIKit class JsonDecodeTableViewCell: UITableViewCell { ///name version @IBOutlet weak var name: UILabel! /// android min supported version @IBOutlet weak var android_min_supported_version: UILabel! ///android app version @IBOutlet weak var android_app_version: UILabel! /// ios min supported version @IBOutlet weak var ios_min_supported_version: UILabel! /// ios app version @IBOutlet weak var ios_app_version: UILabel! }
9869c98b8eef6e450ea83033a6d520fc415a4abb
[ "Swift" ]
11
Swift
VladPoberezhets/Tasks_Project
e9f2abd6771d39d57c008792cebce971dadc4eb2
5d4c240050c370c22f467a93c7453f84e13e98a0
refs/heads/master
<file_sep>'use strict'; /** * @ngdoc service * @name filmApp.manageFavorite * @description * # manageFavorite * Factory in the filmApp. */ angular.module('filmApp') .factory('manageFavorite', function () { // Service logic // ... var listeFavoritesJSON = localStorage.getItem('listeFavorites') || "[]"; var favorites = JSON.parse(listeFavoritesJSON); var meaningOfLife = 42; // Public API here return { someMethod: function () { return meaningOfLife; }, //récupération des favorits du localStorage, si vide l'initialise getFavorite: function() { return favorites; }, addFavorite: function(favoriteMovie) { favorites.push(favoriteMovie); var favoritesSerialise = JSON.stringify(favorites); //serialiser localStorage.setItem('listeFavorites',favoritesSerialise); //ajout au LocalStorage }, removeFavorite: function(favoriteMovie) { var indice = favorites.indexOf(favoriteMovie); favorites.splice(indice,1); var favoritesSerialise = JSON.stringify(favorites); //serialiser localStorage.setItem('listeFavorites',favoritesSerialise); //ajout au LocalStorage }, isFavorite: function(idMovie) { if(favorites.indexOf(idMovie)!=-1){ return true; }else{ return false; } /*var trouve; trouve = false; var indice; indice = 0; while (!trouve && indice < favorites.length){ trouve = favorites[indice]==idMovie; indice = indice +1; } return trouve;*/ } }; }); /*-----------------------------------*/ angular.module('filmApp') .factory('MovieDB', function ($http) { // Service logic // ... var listeFilmsJSON = localStorage.getItem('listeFilms') || "[]"; var movies = JSON.parse(listeFilmsJSON); $http.get('http://amc.ig.he-arc.ch:3003/movie/upcoming?language=fr') .success(function(data){ //cette fonction sera exécutée quand sera pret movies=data.results; console.log(movies); }); var meaningOfLife = 42; // Public API here return { imgURL: 'http://image.tmdb.org/t/p/', someMethod: function () { return movies; }, //récupération des films du localStorage, si vide l'initialise getListeFilms: function() { return movies; }, ajoutFilm: function(nouveauFilm) { movies.push(nouveauFilm); var filmsSerialise = JSON.stringify(movies); //serialiser localStorage.setItem('listeFilms',filmsSerialise); //ajout au LocalStorage }, suppressionFilm: function(film) { var indice = movies.indexOf(film); movies.splice(indice,1); var filmsSerialise = JSON.stringify(movies); //serialiser localStorage.setItem('listeFilms',filmsSerialise); //ajout au LocalStorage } } }); <file_sep>'use strict'; /** * @ngdoc service * @name filmApp.MovieDB * @description * # MovieDB * Factory in the filmApp. */ angular.module('filmApp') .factory('MovieDB', function ($http) { // Service logic // ... var listeFilmsJSON = localStorage.getItem('listeFilms') || "[]"; var movies = JSON.parse(listeFilmsJSON); $http.get('http://amc.ig.he-arc.ch:3003/movie/upcoming?language=fr') .success(function(data){ //cette fonction sera exécutée quand sera pret movies=data.results; console.log(movies); }); var meaningOfLife = 42; // Public API here return { imgURL: 'http://image.tmdb.org/t/p/', someMethod: function () { return movies; }, //récupération des films du localStorage, si vide l'initialise getListeFilms: function() { return movies; }, ajoutFilm: function(nouveauFilm) { movies.push(nouveauFilm); var filmsSerialise = JSON.stringify(movies); //serialiser localStorage.setItem('listeFilms',filmsSerialise); //ajout au LocalStorage }, suppressionFilm: function(film) { var indice = movies.indexOf(film); movies.splice(indice,1); var filmsSerialise = JSON.stringify(movies); //serialiser localStorage.setItem('listeFilms',filmsSerialise); //ajout au LocalStorage } } }); <file_sep>'use strict'; /** * @ngdoc function * @name filmApp.controller:FavoriteCtrl * @description * # FavoriteCtrl * Controller of the filmApp */ angular.module('filmApp') .controller('FavoriteCtrl', function ($scope, manageFavorite,MovieDB,$rootScope,$http) { $scope.awesomeThings = [ 'HTML5 Boilerplate', 'AngularJS', 'Karma' ]; $rootScope.manageFavorite = manageFavorite; //récupérer la liste des films sur internet var listeFilmsJSON = localStorage.getItem('listeFilms') || "[]"; var movies = JSON.parse(listeFilmsJSON); //récupérer la liste des id de film favorits var listeIdFavorite = manageFavorite.getFavorite(); //prépare la liste de films favorits $scope.listeMovieFavorite = []; //Allimente la liste de films favorits en fonction des id de la liste "des id de film favorits" for(var i = 0; i<listeIdFavorite.length; i++){ for(var j = 0; j<movies.length; j++){ if(movies[j].id === (listeIdFavorite[i])){ $scope.listeMovieFavorite.push(movies[j]); } } } $scope.isFavorite = function(id){ var retour = manageFavorite.isFavorite(id); return retour; } $scope.removeFavorite = function(id){ manageFavorite.removeFavorite(id); location.reload(); }; }); <file_sep>'use strict'; /** * @ngdoc filter * @name filmApp.filter:urlPoster * @function * @description * # urlPoster * Filter in the filmApp. */ angular.module('filmApp') .filter('urlPoster', function (MovieDB) { return function (posterURL) { if(posterURL){ return MovieDB.imgURL + 'w185' + posterURL; }else{ 'images/noposter.png'; } }; }); <file_sep>'use strict'; describe('Filter: urlPoster', function () { // load the filter's module beforeEach(module('filmApp')); // initialize a new instance of the filter before each test var urlPoster; beforeEach(inject(function ($filter) { urlPoster = $filter('urlPoster'); })); it('should return the input prefixed with "urlPoster filter:"', function () { var text = 'angularjs'; expect(urlPoster(text)).toBe('urlPoster filter: ' + text); }); }); <file_sep>'use strict'; describe('Service: manageFavorite', function () { // load the service's module beforeEach(module('filmApp')); // instantiate service var manageFavorite; beforeEach(inject(function (_manageFavorite_) { manageFavorite = _manageFavorite_; })); it('should do something', function () { expect(!!manageFavorite).toBe(true); }); });
d2558ad2f06ce56c38d7b24efbf5e3ca7e265e13
[ "JavaScript" ]
6
JavaScript
StephaneGrangier/Film
d8478470634b0b415343282f939b6f55fd9c648d
4fbd9b9194052b7bcffb331c67e30c019448b484
refs/heads/master
<file_sep>using Microsoft.EntityFrameworkCore; namespace odec.Server.Model.Category.Abst { public interface ICategoryContext<TCategory> where TCategory : class { DbSet<TCategory> Categories { get;set; } } } <file_sep>using System; using odec.Framework.Generic; using odec.Framework.Infrastructure.Enumerations; namespace odec.Server.Model.Category.Filters { public class CategoryFilter:FilterBase { public CategoryFilter() { Rows = 20; Name = new StringFilter { Comparison =StringComparison.CurrentCultureIgnoreCase, CompareOperation = StringCompareOperation.Contains }; IsOnlyApproved = true; } public StringFilter Name { get; set; } public string Code { get; set; } public bool IsOnlyApproved { get; set; } public bool IsOnlyActive { get; set; } } public class StringFilter { public string Target { get; set; } public StringComparison Comparison { get; set; } public StringCompareOperation CompareOperation { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using odec.Category.DAL; using odec.Framework.Infrastructure.Enumerations; using odec.Framework.Logging; using odec.Server.Model.Category.Contexts; using odec.Server.Model.Category.Filters; //using ICategoryRepo = odec.Category.DAL.Interop.ICategoryRepository<int, System.Data.Entity.DbContext, odec.Server.Model.Category.Category, odec.Server.Model.Category.Filters.CategoryFilter>; namespace Category.DAL.Tests { public class CategoryRepositoryTester:Tester<CategoryContext> { //public CategoryRepositoryTester() //{ // Database.SetInitializer<CategoryContext>(null); //} [Test] public void GetCategories() { try { var options = CreateNewContextOptions();using (var db = new CategoryContext(options)) { // var repository = new CategoryRepository(db); var item = GenerateModel(); var item2 = GenerateModel(); item2.Name = "Test Unique term"; item2.Code = "Unique2"; var item3 = GenerateModel(); item3.Name = "Test Unique2"; item3.Code = "Unique3"; var item4 = GenerateModel(); item4.Name = "Test Unique terms"; item4.Code = "Unique4"; var item5 = GenerateModel(); item5.Name = "Test Unique2"; item5.Code = "Unique5"; var item6 = GenerateModel(); item6.Name = "Test Unique2"; item6.Code = "Unique6"; var item7 = GenerateModel(); item7.Name = "Test Unique2"; item7.Code = "Unique7"; item7.IsApproved = true; item7.IsActive = false; IEnumerable<odec.Server.Model.Category.Category> categories = null; Assert.DoesNotThrow(() => repository.Save(item)); Assert.DoesNotThrow(() => repository.Save(item2)); Assert.DoesNotThrow(() => repository.Save(item3)); Assert.DoesNotThrow(() => repository.Save(item4)); Assert.DoesNotThrow(() => repository.Save(item5)); Assert.DoesNotThrow(() => repository.Save(item6)); Assert.DoesNotThrow(() => repository.Save(item7)); CategoryFilter filter = new CategoryFilter(); filter.Code = "Unique7"; Assert.DoesNotThrow(() => categories = repository.Get(filter)); Assert.True(categories != null && categories.Any() && categories.Count() == 1); filter.Code = "Unique"; Assert.DoesNotThrow(() => categories = repository.Get(filter)); Assert.True(categories == null || !categories.Any()); filter.Code = null; filter.IsOnlyApproved = true; Assert.DoesNotThrow(() => categories = repository.Get(filter)); Assert.True(categories != null &&categories.Any() && categories.Count() == 1); filter.IsOnlyApproved = false; filter.IsOnlyActive = true; Assert.DoesNotThrow(() => categories = repository.Get(filter)); Assert.True(categories != null && categories.Any() && categories.Count() == 6); filter.IsOnlyActive = false; filter.Name.Target = "Unique"; Assert.DoesNotThrow(() => categories = repository.Get(filter)); Assert.True(categories != null && categories.Any() && categories.Count() == 6); filter.Name.Target = "Test Unique"; filter.Name.CompareOperation = StringCompareOperation.Prefix; Assert.DoesNotThrow(() => categories = repository.Get(filter)); Assert.True(categories != null && categories.Any() && categories.Count() == 6); filter.Name.Target = "Unique2"; filter.Name.CompareOperation = StringCompareOperation.Postfix; Assert.DoesNotThrow(() => categories = repository.Get(filter)); Assert.True(categories != null && categories.Any() && categories.Count() == 4); filter.Name.Target = "Test Unique terms"; filter.Name.CompareOperation = StringCompareOperation.Equals; Assert.DoesNotThrow(() => categories = repository.Get(filter)); Assert.True(categories != null && categories.Any() && categories.Count() == 1); } } catch (Exception ex) { LogEventManager.Logger.Error(ex); throw; } } [Test] public void GetForAutoComplete() { try { var options = CreateNewContextOptions();using (var db = new CategoryContext(options)) { var repository = new CategoryRepository(db); var item = GenerateModel(); var item2 = GenerateModel(); item2.Name = "Test Unique term"; item2.Code = "Unique2"; var item3 = GenerateModel(); item3.Name = "Test Unique2"; item3.Code = "Unique3"; var item4 = GenerateModel(); item4.Name = "Test Unique terms"; item4.Code = "Unique4"; var item5 = GenerateModel(); item5.Name = "Test Unique2"; item5.Code = "Unique5"; var item6 = GenerateModel(); item6.Name = "Test Unique2"; item6.Code = "Unique6"; var item7 = GenerateModel(); item7.Name = "Test Unique2"; item7.Code = "Unique7"; IEnumerable<odec.Server.Model.Category.Category> categories = null; Assert.DoesNotThrow(() => repository.Save(item)); Assert.DoesNotThrow(() => repository.Save(item2)); Assert.DoesNotThrow(() => repository.Save(item3)); Assert.DoesNotThrow(() => repository.Save(item4)); Assert.DoesNotThrow(() => repository.Save(item5)); Assert.DoesNotThrow(() => repository.Save(item6)); Assert.DoesNotThrow(() => repository.Save(item7)); Assert.DoesNotThrow(() => categories = repository.GetForAutoComplete("Test")); Assert.True(categories != null && categories.Any() && categories.Count() == 7); Assert.DoesNotThrow(() => categories =repository.GetForAutoComplete("Test",5)); Assert.True(categories!= null && categories.Any() && categories.Count()==5); Assert.DoesNotThrow(() => categories =repository.GetForAutoComplete("Test Unique")); Assert.True(categories != null && categories.Any() && categories.Count() == 6); Assert.DoesNotThrow(() => categories = repository.GetForAutoComplete("Test Unique2")); Assert.True(categories != null && categories.Any() && categories.Count() == 4); } } catch (Exception ex) { LogEventManager.Logger.Error(ex); throw; } } private odec.Server.Model.Category.Category GenerateModel() { return new odec.Server.Model.Category.Category { Name = "<NAME>", Code = "Test 2", IsActive = true, DateCreated = DateTime.Now, SortOrder = 0, IsApproved = false }; } [Test] public void SaveCategory() { try { var options = CreateNewContextOptions();using (var db = new CategoryContext(options)) { var repository = new CategoryRepository(db); var item = GenerateModel(); Assert.DoesNotThrow(() => repository.Save(item)); Assert.DoesNotThrow(() => repository.Delete(item)); Assert.Greater(item.Id, 0); } } catch (Exception ex) { LogEventManager.Logger.Error(ex); throw; } } [Test] public void DeleteCategory() { try { var options = CreateNewContextOptions(); using (var db = new CategoryContext(options)) { var repository = new CategoryRepository(db);; var item = GenerateModel(); Assert.DoesNotThrow(() => repository.Save(item)); Assert.DoesNotThrow(() => repository.Delete(item)); } } catch (Exception ex) { LogEventManager.Logger.Error(ex); throw; } } [Test] public void DeleteCategoryById() { try { var options = CreateNewContextOptions();using (var db = new CategoryContext(options)) { var repository = new CategoryRepository(db); var item = GenerateModel(); Assert.DoesNotThrow(() => repository.Save(item)); Assert.DoesNotThrow(() => repository.Delete(item.Id)); } } catch (Exception ex) { LogEventManager.Logger.Error(ex); throw; } } [Test] public void DeactivateCategory() { try { var options = CreateNewContextOptions();using (var db = new CategoryContext(options)) { var repository = new CategoryRepository(db); var item = GenerateModel(); item.IsActive = true; Assert.DoesNotThrow(() => repository.Save(item)); Assert.DoesNotThrow(() => repository.Deactivate(item)); Assert.DoesNotThrow(() => repository.Delete(item)); Assert.IsFalse(item.IsActive); } } catch (Exception ex) { LogEventManager.Logger.Error(ex); throw; } } [Test] public void DeactivateCategoryById() { try { var options = CreateNewContextOptions();using (var db = new CategoryContext(options)) { var repository = new CategoryRepository(db); var item = GenerateModel(); item.IsActive = true; Assert.DoesNotThrow(() => repository.Save(item)); Assert.DoesNotThrow(() => item = repository.Deactivate(item.Id)); Assert.DoesNotThrow(() => repository.Delete(item)); Assert.IsFalse(item.IsActive); } } catch (Exception ex) { LogEventManager.Logger.Error(ex); throw; } } [Test] public void ActivateCategory() { try { var options = CreateNewContextOptions();using (var db = new CategoryContext(options)) { var repository = new CategoryRepository(db); var item = GenerateModel(); item.IsActive = false; Assert.DoesNotThrow(() => repository.Save(item)); Assert.DoesNotThrow(() => repository.Activate(item)); Assert.DoesNotThrow(() => repository.Delete(item)); Assert.IsTrue(item.IsActive); } } catch (Exception ex) { LogEventManager.Logger.Error(ex); throw; } } [Test] public void ActivateCategoryById() { try { var options = CreateNewContextOptions();using (var db = new CategoryContext(options)) { var repository = new CategoryRepository(db); var item = GenerateModel(); item.IsActive = false; Assert.DoesNotThrow(() => repository.Save(item)); Assert.DoesNotThrow(() => item = repository.Activate(item.Id)); Assert.DoesNotThrow(() => repository.Delete(item)); Assert.IsTrue(item.IsActive); } } catch (Exception ex) { LogEventManager.Logger.Error(ex); throw; } } [Test] public void GetCategoryById() { try { var options = CreateNewContextOptions();using (var db = new CategoryContext(options)) { var repository = new CategoryRepository(db); var item = GenerateModel(); Assert.DoesNotThrow(() => repository.Save(item)); Assert.DoesNotThrow(() => item = repository.GetById(item.Id)); Assert.DoesNotThrow(() => repository.Delete(item)); Assert.NotNull(item); Assert.Greater(item.Id, 0); } } catch (Exception ex) { LogEventManager.Logger.Error(ex); throw; } } } } <file_sep>using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using odec.Framework.Generic; namespace odec.Server.Model.Category { public class Category : Glossary<int> { //TODO: ubcomment as soon as EF 7 supports Index attr [StringLength(255)]// [Index("ix_Categories_Name",Order = 0), StringLength(255)] public override string Name { get; set; } // [Index("ix_Categories_Name", Order = 1),Index("ix_Categories_IsApproved")] public bool IsApproved { get; set; } } }<file_sep># odec-categories-module <file_sep>using System.Collections.Generic; using odec.Entity.DAL.Interop; namespace odec.Category.DAL.Interop { public interface ICategoryRepository<in TKey, TContext, TCategory, in TCategoryFilter> : IEntityOperations<TKey, TCategory>, IActivatableEntity<TKey, TCategory>, IContextRepository<TContext> where TKey : struct where TCategory : class { IEnumerable<TCategory> Get(TCategoryFilter filter); IEnumerable<TCategory> GetForAutoComplete(string term, int? maxRows = null); void ApproveCategory(TCategory category); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore; using odec.Category.DAL.Interop; using odec.Entity.DAL; using odec.Framework.Infrastructure.Enumerations; using odec.Framework.Logging; using odec.Framework.Extensions; using odec.Server.Model.Category.Filters; namespace odec.Category.DAL { public class CategoryRepository : OrmEntityOperationsRepository<int, Server.Model.Category.Category, DbContext>, ICategoryRepository<int, DbContext, Server.Model.Category.Category, CategoryFilter> { public CategoryRepository() { } public CategoryRepository(DbContext db) { Db = db; } public void SetConnection(string connection) { throw new NotImplementedException("Not available in EF7"); } public void SetContext(DbContext db) { Db = db; } public IEnumerable<Server.Model.Category.Category> Get(CategoryFilter filter) { try { var query = Db.Set<Server.Model.Category.Category>() .Where(it => (!filter.IsOnlyApproved || (it.IsApproved)) && (!filter.IsOnlyActive || (it.IsActive))); if (!string.IsNullOrEmpty(filter.Name?.Target)) { switch (filter.Name.CompareOperation) { case StringCompareOperation.Postfix: query = query.Where(it => it.Name.EndsWith(filter.Name.Target)); break; case StringCompareOperation.Prefix: query = query.Where(it => it.Name.StartsWith(filter.Name.Target)); break; case StringCompareOperation.Equals: query = query.Where(it => it.Name == filter.Name.Target); break; default: query = query.Where(it => it.Name.ToLower().Contains(filter.Name.Target.ToLower())); break; } } if (!string.IsNullOrEmpty(filter.Code)) query = query.Where(it => it.Code == filter.Code); if (!string.IsNullOrEmpty(filter.Sidx)) query = filter.Sord.Equals("desc", StringComparison.OrdinalIgnoreCase) ? query.OrderByDescending(filter.Sidx) : query.OrderBy(filter.Sidx); if (filter.Page != 0 && filter.Rows !=0) return query.Skip(filter.Rows * (filter.Page - 1)).Take(filter.Rows); return query; } catch (Exception ex) { LogEventManager.Logger.Error(ex.Message, ex); throw; } } public IEnumerable<Server.Model.Category.Category> GetForAutoComplete(string term, int? maxRows = null) { try { var query = Db.Set<Server.Model.Category.Category>().Where(it => it.Name.StartsWith(term)); if (maxRows.HasValue) query = query.Take(maxRows.Value); return query; } catch (Exception ex) { LogEventManager.Logger.Error(ex.Message, ex); throw; } } public void ApproveCategory(Server.Model.Category.Category category) { try { var cat = GetById(category.Id); cat.IsApproved = true; Db.SaveChanges(); } catch (Exception ex) { LogEventManager.Logger.Error(ex.Message, ex); throw; } } } } <file_sep>using odec.Framework.Generic; namespace odec.Server.Model.Category { public class CategoryType:Glossary<int> { } }
c11482058504b0bb1081ef48fc4b72e0053f4f7a
[ "Markdown", "C#" ]
8
C#
original-decisions/odec-categories-module
8cda119c366fa9b6c9b7aa648262a59494dca063
642717ed124f4fb464d84d474f697d92ae37d79f
refs/heads/master
<repo_name>spl48/heroes-villains<file_sep>/Teams.java import java.util.ArrayList; import java.util.Scanner; public class Teams { private ArrayList < String > listHeroes = new ArrayList < String > (); private ArrayList < String > listPowerUps = new ArrayList < String > (); private ArrayList < String > listHealing = new ArrayList < String > (); private ArrayList < String > listMaps = new ArrayList<String> (); private int money = 500; private String teamName; public void setName() { Scanner scanner = new Scanner(System.in); teamName = scanner.nextLine(); if (teamName.length() < 2 | teamName.length() > 10) { System.out.println("Try again, Team name must be between 2 and 10 characters long"); setName(); } scanner.close(); } public String getName() { return teamName; } public ArrayList<String> getPowerUps() { return listPowerUps; } public ArrayList<String> getHealing() { return listHealing; } public ArrayList<String> getMaps() { return listMaps; } public int getMoney() { return money; } public void addHero(String hero) { /** adds hero to list of heroes*/ listHeroes.add(hero); } public static void main(String[] args) { Teams team = new Teams(); team.setName(); } } <file_sep>/Rock.java import java.util.Scanner; import java.util.Arrays; import java.util.List; import java.util.Random; public class Rock { private static boolean done = false; private static boolean futurePotion = false; private static boolean luckPotion = true; public void RockPaperScissors(String userResponse, String villainResponse) { done = true; if (userResponse.toUpperCase().equals(villainResponse)) { System.out.println("It's a tie, choose again"); done = false; } else if (userResponse.toUpperCase().equals("R")) { if (villainResponse.equals("P")) { System.out.println("Paper beats rock, you LOSE"); } else { System.out.println("Rock beats Scissors, you WIN"); } } else if (userResponse.toUpperCase().equals("P")) { if (villainResponse.equals("S")) { System.out.println("Scissors beats paper, you LOSE"); } else { System.out.println("Paper beats rock, you WIN"); } } else if (userResponse.toUpperCase().equals("S")) { if (villainResponse.equals("R")) { System.out.println("Rock beats scissors, you LOSE"); } else { System.out.println("Scissors beats paper, you WIN"); } } } public static void main(String[] args) { Rock game = new Rock(); List<String> options = Arrays.asList("R", "P", "S", "rock", "paper", "scissors"); Scanner scanner = new Scanner(System.in); while (done == false) { System.out.println("Select 'R', 'P', or 'S'"); String userResponse = scanner.next(); Random generator = new Random(); int randomInt = generator.nextInt(3); if (luckPotion == true) { //makes villain more likely to chose Rock randomInt = generator.nextInt(6); if (randomInt >= 3) { randomInt = 0; //makes random integers 3, 4, 5 equal to 0 (Rock) } } if (futurePotion == true) { //makes villain more likely to chose option that is beaten by hero randomInt = generator.nextInt(6); if (randomInt >= 3) { if (userResponse.toUpperCase().equals("R")) { randomInt = 2; } if (userResponse.toUpperCase().equals("P")) { randomInt = 0; } if (userResponse.toUpperCase().equals("S")) { randomInt = 1; } } } String villainResponse = options.get(randomInt); String villainResponseWord = options.get(randomInt + 3); System.out.println("Villain plays " + villainResponseWord); game.RockPaperScissors(userResponse, villainResponse); } scanner.close(); } }<file_sep>/Neuer.java import java.util.Arrays; public class Neuer extends Villains{ public Neuer() { super("<NAME>", "YOZZZZAAAAAAAA", Arrays.asList("PSR, GUESS, DICE")); } } <file_sep>/Buffon.java import java.util.Arrays; public class Buffon extends Villains{ public Buffon() { super("<NAME>", "The only red I'm seeing today is your blood", Arrays.asList("GUESS")); } } <file_sep>/Cech.java import java.util.Arrays; public class Cech extends Villains{ public Cech() { super("<NAME>", "Cech yourself before you reck yourself", Arrays.asList("DICE")); } }
3970f8006178e9406a247076191576aa19dc752e
[ "Java" ]
5
Java
spl48/heroes-villains
913440fb308b4ce5a9a0d9ef1cdfc9dd6bd90095
91cad6067fe35482144cb9f060b64a0eb5385a58
refs/heads/master
<file_sep>devtools::load_all() library(lubridate) library(tidyverse) cl_args <- commandArgs(trailingOnly=TRUE) site <- cl_args[1] day <- mdy(cl_args[2]) query1 <- paste0("SELECT s.datetime, i.deployment AS csc, s.sand_flux, s.ws_10m AS ws, ", "COALESCE(wd_10m, resultant_wd_10m) AS wd ", "FROM sandcatch.sandflux_5min s JOIN instruments.deployments i ", "ON s.csc_deployment_id=i.deployment_id ", "WHERE i.deployment='", site, "' ", "AND (s.datetime-'1 second'::interval)::date", "='", day, "'::date ") sand_df <- query_owens(query1) if (nrow(sand_df)==0) { stop(paste0("No observed sand motion at site ", site, " on ", format(day, "%m/%d/%Y"))) } dirres <- 22.5 # figure out the wind direction bins dir.breaks <- c(-dirres/2, seq(dirres/2, 360-dirres/2, by = dirres), 360+dirres/2) dir.labels <- c("N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW", "N") # assign each wind direction to a bin dir.binned <- cut(sand_df$wd, breaks = dir.breaks, ordered_result = TRUE) levels(dir.binned) <- dir.labels sand_df$dir.binned <- dir.binned sand_summary <- sand_df %>% group_by(dir.binned) %>% summarize(flux=round(sum(sand_flux), 3)) %>% filter(!is.na(dir.binned)) y_max <- max(sand_summary$flux) * 1.1 y_breaks <- round(seq(0, y_max, y_max/4), 1)[-1] y_labels <- data.frame(dir.binned=rep("NW", length(y_breaks)), flux=y_breaks, label=as.character(y_breaks)) p.rose <- ggplot(data = sand_summary, aes(x = dir.binned, y = flux,)) + coord_polar(start = -((dirres/2)/360) * 2*pi) + geom_bar(stat='identity', color="black", fill="lightblue") + scale_x_discrete(drop = FALSE, labels = waiver()) + scale_y_continuous(breaks=y_breaks) + geom_text(data=y_labels, mapping=aes(label=label)) + theme(axis.title.x = element_blank(), plot.title=element_text(hjust=0.5), axis.text.y = element_blank()) + ylab(expression(paste("Total Sand Flux (g/c", m^2, ")"))) + ggtitle(paste0("Sand Flux at Site ", site, " on ", format(day, "%m/%d/%Y"))) file_name <- paste0(site, "_sandrose_", format(day, "%m%d%y"), ".jpg") jpeg(paste0(tempdir(), "/", file_name), width=6, height=6, units="in", res=300) p.rose dev.off() system(paste0("~/sh/dropbox_uploader.sh upload ", paste0(tempdir(), "/", file_name), " ", file_name)) <file_sep>devtools::load_all() library(dplyr) library(ggplot2) library(lubridate) cl_args <- commandArgs(trailingOnly=TRUE) day <- mdy(cl_args[1]) query1 <- paste0("SELECT i.deployment, t.datetime, t.ws_wvc AS ws, ", "t.wd_wvc AS wd ", "FROM teom.teom_analog_1hour t ", "JOIN instruments.deployments i ", "ON t.deployment_id=i.deployment_id ", "WHERE (t.datetime-'1 second'::interval)::date", "='", day, "'::date ") a <- query_owens(query1) query3 <- paste0("SELECT DISTINCT i.deployment, ", "m.datetime, m.ws_10m, m.wd_10m ", "FROM instruments.deployments i ", "JOIN met.met_1hour m ON i.deployment_id=m.deployment_id ", "WHERE (m.datetime-'1 second'::interval)::date", "='", day, "'::date ") b <- query_owens(query3) %>% rename(ws=ws_10m, wd=wd_10m) df1 <- rbind(a, b) %>% filter(ws>-9999 & ws<100) %>% filter(wd<999) cat(paste0("Enter Station (", paste(unique(df1$deployment), collapse=", "), "):")) station <- readLines(con='stdin', 1) df2 <- filter(df1, deployment==station) dirres <- 22.5 # figure out the wind direction bins dir.breaks <- c(-dirres/2, seq(dirres/2, 360-dirres/2, by = dirres), 360+dirres/2) dir.labels <- c("N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW", "N") # assign each wind direction to a bin dir.binned <- cut(df2$wd, breaks = dir.breaks, ordered_result = TRUE) levels(dir.binned) <- dir.labels df2$dir.binned <- dir.binned title <- paste0(station, " ", format(day, "%m-%d-%Y")) legend.title <- "Wind Speed (m/s)" p.rose <- plot_rose(df2, value='ws', dir='wd', plot.title=title, legend.title=legend.title, reverse.bars=T) file_name <- paste0(station, "_windrose_", format(day, "%m%d%y"), ".jpg") jpeg(paste0(tempdir(), "/", file_name), width=6, height=6, units="in", res=300) p.rose dev.off() system(paste0("~/sh/dropbox_uploader.sh upload ", paste0(tempdir(), "/", file_name), " ", file_name))
cdaf0fd40af1ec74add4687ff21f0a074a9d74e3
[ "R" ]
2
R
jwbannister/siteRoses
83deb8aa5e0bd38a7a2541ccdb3aea58e457cca6
3da72bf042beb6ae4689e2a77099d7e8f848524f
refs/heads/master
<repo_name>rajat333/ecommerce<file_sep>/model/category.js const categoryDetails = require('../configrations/category.json'); var mongoose = require('mongoose'); var Schema = mongoose.Schema; var CategorySchema = new Schema({ createdAt: { type: Date }, updatedAt: { type: Date, default: Date.now }, name: { type:String, required: true, } , type:{ type: String, required: true, enum: categoryDetails.categoryList, }, model: { type: String, required: true } }); var Category = mongoose.model('Category', CategorySchema); // on every save, add the date CategorySchema.pre('findOneAndUpdate', function(next) { // get the current date var currentDate = new Date(); if (!this.created_at) this.createdAt = currentDate; next(); }); module.exports = Category; <file_sep>/application-utilities/ProductValidation.js const categoryDetails = require('../configrations/category.json'); var category = categoryDetails.categoryList; var validateCartProduct = function(productData){ let keys = Object.keys(productData); if( keys.includes('name') && keys.includes('description') && keys.includes('price') && keys.includes('make') && keys.includes('category') ){ return true; }else{ return false; } } var addProduct = (productData)=>{ let keys = Object.keys(productData); if(keys.includes('name') && keys.includes('category') && keys.includes('description') && keys.includes('make') && keys.includes('price') ){ return true; }else{ return false; } }; module.exports= { validateCartProduct: validateCartProduct, addProduct: addProduct, isValidProduct:addProduct }<file_sep>/model/cart.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var CartSchema = new Schema({ createdAt: { type: Date }, updatedAt: { type: Date, default: Date.now }, user:{ type: 'ObjectId', required: true, ref:"User" }, productId:{ type: 'ObjectId', required: true, ref:"Product" }, productInfo:{ type: Object, required: true } // , // model: { // type: String, // required: false // } }); var Cart = mongoose.model('Cart', CartSchema); // on every save, add the date CartSchema.pre('save', function(next) { // get the current date var currentDate = new Date(); if (!this.created_at) this.createdAt = currentDate; next(); }); module.exports = Cart; <file_sep>/controllers/productCtrl.js var productService = require("../services/productService"); var listAllProduct = function(req,res){ productService.listAllProduct(req,res); } var getCategoryBasedProduct = function(req,res){ productService.getCategoryBasedProduct(req,res); } var addtoCart = function(req,res){ productService.addtoCart(req,res); } var getUserCart = function(req,res){ productService.getUserCart(req,res); } var addProduct = function(req,res){ productService.addProduct(req,res); } module.exports = { listAllProduct: listAllProduct, getCategoryBasedProduct: getCategoryBasedProduct, addtoCart: addtoCart, getUserCart:getUserCart, addProduct:addProduct }<file_sep>/configrations/ApplicationMessage.js var ErrorMessage = { ValidationFail: 'Please enter all the fields', LoginFail: 'Please enter valid username or password', UserExist: 'User Exist With this mailid. Please choose different mailid', ExceptionOccur : 'Sorry, we are facing some technical issue. Please try again later.', CategoryNotExist:"Category didn't exist for product you are adding.", NotAuthorized:"Sorry, you are not Authorized" }; var SuccessMessage = { Register: 'Successfully Register User', Login: 'Successfully Login User', CategoryList:"Successfully Get Category List", ProductList:"Successfully Get Product List", ProductBasedOnCategory:"Successfully Get Product on Category Basis", NoCategory:"Sorry, no categoryExist for the product you are adding to cart", AddToCart:"Successfully Added Product To Cart", GetCart:"Successfully Get Cart List", InsertedCategory:"Successfully Inserted Category", ProductInsert:"Product Inserted Successfully" }; var InternalAppMessage = { Login: 'App.Login.Success', Register: 'App.Register.Success', ValidationFail: 'App.Validation.Fail', ExceptionOccur: 'App.Exception.Error', LoginFail: 'App.Login.Fail', UserExist: 'App.Username.Exist', CategoryList:"App.Category.List", ProductList:"App.ProductList.List", ProductBasedOnCategory:"App.Product.Category.List", NoCategory:"App.NotExistence.Category", AddToCart:"App.Product.Added.Cart", GetCart: "App.Product.GetCart", InsertedCategory:"App.Category.Insert", ProductInsert:"App.Insert.Product", CategoryNotExist:"App.ProductAdd.Category.NotExist", NotAuthorized:"App.User.NotAuthorized" } var Keys = { tokenSecretKey :'<KEY>', tokenSecretTime: '2h', } module.exports = { Error: ErrorMessage, Success: SuccessMessage, InternalAppMessage: InternalAppMessage, Keys: Keys, }<file_sep>/model/product.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ProductSchema = new Schema({ createdAt: { type: Date, default: Date.now }, updatedAt: { type: Date, default: Date.now }, name: { type:String, required: true, } , category:{ type: String, required: true, ref:"category" }, description: { type: String, required: true }, totalQuantity:{ type:Number, required:false, }, remaningQuantity:{ type:Number, required: false }, price:{ type: String, required: true, }, make:{ type: Number, required: true } }); var Product = mongoose.model('Product', ProductSchema); // on every save, add the date ProductSchema.pre('findOneAndUpdate', function(next) { // get the current date var currentDate = new Date(); // change the updated_at field to current date this.updatedAt = currentDate; next(); }); module.exports = Product; <file_sep>/db-connectivity/dbConnection.js var mongoose = require('mongoose'); var dbConnection = function(){ mongoose.connect('mongodb://localhost:27017/ecommerce',{ useNewUrlParser: true }, function (err, db) { console.log('>>err>>db>>>',err); if (err) throw err return db; }) } module.exports = { dbConnection: dbConnection }<file_sep>/application-utilities/CategoryValidation.js const categoryDetails = require('../configrations/category.json'); const categoryType = categoryDetails.categoryList; var validCategory = (data)=>{ let keys = Object.keys(data); if(keys.includes('name') && keys.includes('type') && keys.includes('model')){ if(categoryType.includes(data.type)) return true; else return false; }else{ return false; } } module.exports = { validCategory: validCategory }<file_sep>/routes/index.js var authenticationMiddleware = require('../middleware/AuthenticationMiddleware'); var userCtrl = require('../controllers/userCtrl'); const productCtrl = require("../controllers/productCtrl"); const categoryCtrl = require("../controllers/categoryCtrl"); var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); router.post('/users/registerUser',userCtrl.registerUser); router.post('/users/login',userCtrl.login); router.get('/category/list',authenticationMiddleware.authenticateUser, categoryCtrl.listAllCategory); router.post('/category/insertion',authenticationMiddleware.authenticateUser, categoryCtrl.insertCategory); router.get('/product/list',authenticationMiddleware.authenticateUser,productCtrl.listAllProduct); router.post('/product/category',authenticationMiddleware.authenticateUser, productCtrl.getCategoryBasedProduct); router.post('/product/addtoCart',authenticationMiddleware.authenticateUser,productCtrl.addtoCart); router.get('/product/userCart',authenticationMiddleware.authenticateUser,productCtrl.getUserCart); router.post('/product/addProduct',authenticationMiddleware.authenticateUser,productCtrl.addProduct); module.exports = router;
363973cbb26c0ae5f95ebb9f6e27c96f706ad5bd
[ "JavaScript" ]
9
JavaScript
rajat333/ecommerce
a9c0ccc9c638c7a9624e3a8bbfe0d0af5fb08f18
62812f873636371e5592fcc2bf2aa5e75ffb96ea
refs/heads/master
<file_sep><?php try { include ('../inc/db.php'); include ('../config.php'); if ($emulator == "ACE") { $stmt = $db_con->prepare("USE ace_auth;"); $stmt->execute(); $stmt = $db_con->prepare("ALTER TABLE account ADD COLUMN auth_Token VARCHAR(128) NOT NULL AFTER passwordSalt;"); if ($stmt->execute()) { echo "Successfuly updated account table."; } else { echo "Query failed."; } } else { $stmt = $db_con->prepare("USE gdle;"); $stmt->execute(); $stmt = $db_con->prepare("ALTER TABLE accounts ADD COLUMN auth_token VARCHAR(128) NOT NULL AFTER password_salt;"); if ($stmt->execute()) { echo "Successfuly updated accounts table."; } else { echo "Query failed."; } } } catch(PDOException $e) { echo $e->getMessage(); } ?><file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Asheron's Call Server</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" media="screen"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script type="text/javascript"> $('document').ready(function() { $("#back").click(function(){ window.location.href = "index.php"; }); }); </script> </head> <?php include ("inc/db.php"); include("config.php"); if (!isset($_GET['id'])) { echo " <div class='container'> <div class='alert alert-danger'> <span class='glyphicon glyphicon-info-sign'></span>&nbsp; <button class='close' data-dismiss='alert'>&times;</button> <strong>Error!</strong> Invalid data format.</div> <button class='btn btn-primary' id='back'> <span class='glyphicon glyphicon-backward'></span> &nbsp; back to main page </button></div>"; exit; } $confirm_key = $_GET["id"]; $key_length = strlen($confirm_key); if ($key_length !== 128) { echo " <div class='container'> <div class='alert alert-danger'> <span class='glyphicon glyphicon-info-sign'></span>&nbsp; <button class='close' data-dismiss='alert'>&times;</button> <strong>Error!</strong> Invalid data format.</div> <button class='btn btn-primary' id='back'> <span class='glyphicon glyphicon-backward'></span> &nbsp; back to main page </button></div>"; exit; } $msg = ""; try { if ($emulator == "ACE") { $stmt = $db_con->prepare("SELECT email_Address FROM account WHERE auth_Token = :key"); } else { $stmt = $db_con->prepare("SELECT email FROM accounts WHERE auth_token = :key"); } $stmt->execute(array(":key"=>$confirm_key)); //$row = $stmt->fetch(PDO::FETCH_ASSOC); $result = $stmt->fetchColumn(); if ($result) { if ($emulator == "ACE") { $query = $db_con->prepare("UPDATE account SET accessLevel = :access WHERE email_Address = :email"); } else { $query = $db_con->prepare("UPDATE accounts SET access = :access WHERE email = :email"); } $query->bindParam(":access",$access_level); $query->bindParam(":email",$result); if ($query->execute()) { if ($emulator == "ACE") { $del = $db_con->prepare("UPDATE account SET auth_Token = '' WHERE auth_Token = :key"); } else { $del = $db_con->prepare("UPDATE accounts SET auth_token = '' WHERE auth_token = :key"); } $del->bindParam(":key",$confirm_key); if ($del->execute()) { $msg = "<div class='alert alert-success'> <span class='glyphicon glyphicon-info-sign'></span>&nbsp; <button class='close' data-dismiss='alert'>&times;</button> <strong>Success!</strong> Thank you. Your account has been successfully activated. You can now login with your account information.</div>"; } } } else { $msg = "<div class='alert alert-danger'> <span class='glyphicon glyphicon-info-sign'></span>&nbsp; <button class='close' data-dismiss='alert'>&times;</button> <strong>Verification failed!</strong> Invalid confirmation code <strong>(or)</strong> email address already activated.</div>"; } } catch(PDOException $e) { echo $e->getMessage(); } ?> <body> <div class="container"> <div><?php echo $msg;?></div> <button class="btn btn-primary" id="back"> <span class="glyphicon glyphicon-backward"></span> &nbsp; back to main page </button> </div> </body> </html><file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Asheron's Call Server</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" media="screen"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.2/css/bootstrapValidator.min.css"/> <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/alertifyjs@1.13.1/build/css/alertify.min.css"/> <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/alertifyjs@1.13.1/build/css/themes/default.min.css"/> <link href="css/style.css" rel="stylesheet" type="text/css" media="screen"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src='https://www.google.com/recaptcha/api.js'></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.2/js/bootstrapValidator.min.js"></script> <script src="//cdn.jsdelivr.net/npm/alertifyjs@1.13.1/build/alertify.min.js"></script> <?php if (isset($jscript2)) { echo '<script type="text/javascript" src="js/script2.js"></script>'; } elseif (isset($jscript3)) { echo '<script type="text/javascript" src="js/script3.js"></script>'; } else { echo '<script type="text/javascript" src="js/script.js"></script>'; } ?> </head> <body> <nav class="navbar navbar-default"> <ul class="nav navbar-nav"> <li id="set_width" class="<?php if ($active_page=="register") {echo "active"; }?>"><a href="index.php">Register Account</a></li> <li id="set_width" class="<?php if ($active_page=="reset") {echo "active"; }?>"><a href="forgot_password.php">Reset Password</a></li> </ul> </nav><file_sep><?php $active_page = "reset"; ?> <?php $jscript2 = ""; include( "inc/header.php" ); ?> <div class="signin-form"> <div class="container"> <form class="form-signin" method="post" id="register-form"> <h2 class="form-signin-heading">- Reset Password -</h2> <hr /> <div id="error"><!-- error messages --></div> <div class="form-group"> <div class="inputGroupContainer"> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span> <input type="email" class="form-control" placeholder="Email address" name="user_email" id="user_email" /> <span id="check-e"></span> </div> </div> </div> <hr /> <!-- Google Recaptcha --> <div class="text-center"> <div class="g-recaptcha" data-sitekey="ENTER YOUR RECAPTCHA SITE KEY HERE"></div> </div> <br /> <div class="form-group"> <button type="submit" class="btn btn-default" name="btn-save" id="btn-submit"><span class="glyphicon glyphicon-log-in"></span> &nbsp; Reset Password</button> </div> </form> </div> </div> <?php include( "inc/footer.php" ); ?><file_sep><?php if(count(get_included_files()) ==1) exit("Direct access not permitted."); // ACE or GDLE supported $emulator = "GDLE"; // Set to true for ACE servers, false for GDLE servers $use_BCRYPT = false; // Number of accounts allowed per unique IP address $ipLimit = 3; // Access level granted upon successful email verification $access_level = 1; // Google reCaptcha v2 secret key $recaptcha_secret = 'ENTER YOUR RECAPTCHA SECRET HERE'; // Enable proxy/vpn protection? Requires a free ipqualityscore.com account $proxy_protection = false; $ipqualityscore_key = 'ENTER YOUR IPQUALITYSCORE.COM KEY HERE'; // SMTP TLS settings $admin_email = '<EMAIL>'; $admin_name = 'Admin'; $email_host = 'domain.com'; $email_password = ''; $email_port = '587'; // Blacklisted email providers $blacklist = array( 'protonmail.com', 'tutanota.com', 'guerrillamail.com', 'secure-email.org' ); ?><file_sep><?php if($_POST) { include("inc/db.php"); include("config.php"); include("inc/funcs.php"); # Call the function post_captcha $res = post_captcha($_POST['g-recaptcha-response']); if (!$res['success']) { # What happens when the CAPTCHA wasn't checked echo "Please make sure you check the security CAPTCHA box"; } else { # CAPTCHA successfully completed $user_email = $_POST['user_email']; $user_password = $_POST['<PASSWORD>']; $user_cpassword = $_POST['cpassword']; $confirm_key = $_POST["id"]; if(strlen($user_password) < 8) { echo "Password must be at least 8 characters"; } if ($user_password !== $user_cpassword) { echo "Your password's do not match"; } try { if ($emulator == "ACE") { $stmt = $db_con->prepare("SELECT email_Address FROM account WHERE auth_Token = :key"); } else { $stmt = $db_con->prepare("SELECT email FROM accounts WHERE auth_token = :key"); } $stmt->execute(array(":key"=>$confirm_key)); $result = $stmt->fetchColumn(); if ($result) { if ($emulator == "ACE") { $stmt2 = $db_con->prepare("SELECT * FROM account WHERE email_Address = :email AND auth_Token = :key"); } else { $stmt2 = $db_con->prepare("SELECT * FROM accounts WHERE email = :email AND auth_token = :key"); } $stmt2->execute(array(":email"=>$user_email, ":key"=>$confirm_key)); $emailCount = $stmt2->rowCount(); if ($emailCount > 0) { if ($use_BCRYPT) { $salt = "use bcrypt"; $hashedPW2 = password_hash($user_password, PASSWORD_BCRYPT); } else { $salt = bin2hex(random_bytes(8)); $hashedPW = hash('sha512', $user_password.$salt); $hashedPW2 = substr($hashedPW, 0, 64); } if ($emulator == "ACE") { $stmt3 = $db_con->prepare("UPDATE account SET passwordHash = :pass WHERE email_Address = :email"); } else { $stmt3 = $db_con->prepare("UPDATE accounts SET password = :pass WHERE email = :email"); } $stmt3->bindParam(":pass",$hashedPW2); $stmt3->bindParam(":email",$user_email); if($stmt3->execute()) { if ($emulator == "ACE") { $stmt4 = $db_con->prepare("UPDATE account SET passwordSalt = :salt WHERE email_Address = :email"); } else { $stmt4 = $db_con->prepare("UPDATE accounts SET password_salt = :salt WHERE email = :email"); } $stmt4->bindParam(":salt",$salt); $stmt4->bindParam(":email",$user_email); if($stmt4->execute()) { if ($emulator == "ACE") { $stmt5 = $db_con->prepare("UPDATE account SET auth_Token = '' WHERE auth_Token = :key"); } else { $stmt5 = $db_con->prepare("UPDATE accounts SET auth_token = '' WHERE auth_token = :key"); } $stmt5->bindParam(":key",$confirm_key); if($stmt5->execute()) { echo "resetpw"; // Success response } } } } else { echo "Email address and confirmation code do not match"; } } else { echo "Invalid confirmation code"; } } catch(PDOException $e) { echo $e->getMessage(); } } } ?><file_sep><?php $jscript3 = ""; include( "inc/header.php" ); if (!isset($_GET['id'])) { echo " <div class='container'> <div class='alert alert-danger'> <span class='glyphicon glyphicon-info-sign'></span>&nbsp; <button class='close' data-dismiss='alert'>&times;</button> <strong>Error!</strong> Invalid data format.</div> <button class='btn btn-primary' id='back'> <span class='glyphicon glyphicon-backward'></span> &nbsp; back to main page </button></div>"; exit; } $confirm_key = $_GET["id"]; $key_length = strlen($confirm_key); if ($key_length !== 128) { echo " <div class='container'> <div class='alert alert-danger'> <span class='glyphicon glyphicon-info-sign'></span>&nbsp; <button class='close' data-dismiss='alert'>&times;</button> <strong>Error!</strong> Invalid data format.</div> <button class='btn btn-primary' id='back'> <span class='glyphicon glyphicon-backward'></span> &nbsp; back to main page </button></div>"; exit; } ?> <div class="signin-form"> <div class="container"> <form class="form-signin" method="post" id="register-form"> <h2 class="form-signin-heading">- Reset Password -</h2> <hr /> <div id="error"><!-- Error messages --></div> <div class="form-group"> <div class="inputGroupContainer"> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span> <input type="email" class="form-control" placeholder="Email address" name="user_email" id="user_email" /> <span id="check-e"></span> </div> </div> </div> <div class="form-group"> <div class="inputGroupContainer"> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span> <input type="<PASSWORD>" class="form-control" placeholder="<PASSWORD>" name="password" id="password" /> </div> </div> </div> <div class="form-group"> <div class="inputGroupContainer"> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span> <input type="<PASSWORD>" class="form-control" placeholder="<PASSWORD>" name="cpassword" id="cpassword" /> </div> </div> </div> <hr /> <!-- Google Recaptcha --> <div class="text-center"> <div class="g-recaptcha" data-sitekey="ENTER YOUR RECAPTCHA SITE KEY HERE"></div> </div> <br /> <div class="form-group"> <input type="hidden" name="id" value="<?php if (isset($_GET["id"])) { echo $_GET["id"]; } ?>" /> <button type="submit" class="btn btn-default" name="btn-save" id="btn-submit"><span class="glyphicon glyphicon-log-in"></span> &nbsp; Reset Password</button> </div> </form> </div> </div> <?php include( "inc/footer.php" ); ?><file_sep><?php use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; if($_POST) { require 'phpmailer/Exception.php'; require 'phpmailer/PHPMailer.php'; require 'phpmailer/SMTP.php'; include("inc/db.php"); include("config.php"); include("inc/funcs.php"); # Call the function post_captcha $res = post_captcha($_POST['g-recaptcha-response']); if (!$res['success']) { # What happens when the CAPTCHA wasn't checked echo "Please make sure you check the security CAPTCHA box"; } else { # CAPTCHA successfully completed $remoteIP = ""; if (isset($_SERVER["REMOTE_ADDR"])) { $remoteIP = $_SERVER["REMOTE_ADDR"]; } $ip_bin = inet_pton($remoteIP); $user_name = $_POST['user_name']; $user_email = $_POST['user_email']; $user_cemail = $_POST['confirm_email']; $user_password = $_POST['<PASSWORD>']; $user_cpassword = $_POST['cpassword']; $domain = explode("@", $user_email); $domain = $domain[(count($domain)-1)]; try { if ($emulator == "ACE") { # PDO queries $stmt = $db_con->prepare("SELECT * FROM account WHERE accountName = :uname"); $stmt->execute(array(":uname"=>$user_name)); $userCount = $stmt->rowCount(); $stmt2 = $db_con->prepare("SELECT * FROM account WHERE email_Address = :email"); $stmt2->execute(array(":email"=>$user_email)); $emailCount = $stmt2->rowCount(); $stmt3 = $db_con->prepare("SELECT * FROM account WHERE create_I_P_ntoa = :ip"); $stmt3->execute(array(":ip"=>$remoteIP)); $ipCount = $stmt3->rowCount(); } else { $stmt = $db_con->prepare("SELECT * FROM accounts WHERE username = :uname"); $stmt->execute(array(":uname"=>$user_name)); $userCount = $stmt->rowCount(); $stmt2 = $db_con->prepare("SELECT * FROM accounts WHERE email = :email"); $stmt2->execute(array(":email"=>$user_email)); $emailCount = $stmt2->rowCount(); $stmt3 = $db_con->prepare("SELECT * FROM accounts WHERE created_ip_address = :ip"); $stmt3->execute(array(":ip"=>$remoteIP)); $ipCount = $stmt3->rowCount(); } # Authentication checks if (isset($proxy_protection)) { $key = $ipqualityscore_key; $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : $_SERVER['HTTP_CLIENT_IP']; $strictness = 1; $result = json_decode(file_get_contents(sprintf('https://ipqualityscore.com/api/json/ip/%s/%s?strictness=%s', $key, $ip, $strictness)), true); if($result !== null){ if(isset($result['proxy']) && $result['proxy'] == true){ echo "Please disable your proxy/vpn connection"; exit(); } } } if (!preg_match('/^[A-Za-z][A-Za-z0-9-_]{3,24}$/', $user_name)) { echo "Invalid username format"; } elseif ($userCount > 0) { echo "Username already exists"; } elseif ($emailCount > 0) { echo "1"; // Failure response } elseif (!filter_var($user_email, FILTER_VALIDATE_EMAIL)) { echo "Invalid email format"; } elseif (in_array($domain, $blacklist)) { echo "Email provider not allowed"; } elseif ($user_email !== $user_cemail) { echo "Email address does not match with confirm"; } elseif (!preg_match('/^\S+$/', $user_password)) { echo "Invalid password format - no spaces allowed"; } elseif(strlen($user_password) < 8) { echo "Password must be at least 8 characters"; } elseif ($user_password !== $user_cpassword) { echo "Password does not match with confirm"; } elseif ($ipCount >= $ipLimit) { echo "Account limit reached for IP address ".$ipaddress; } elseif (!isset($_POST['terms']) || empty($_POST['terms'])) { echo "Please indicate that you agree to the Terms"; } else { # Authentication checks passed $token = bin2hex(random_bytes(128)); $hashedToken = hash('<PASSWORD>', $token.$user_email); if ($use_BCRYPT) { $salt = "use <PASSWORD>"; $hashedPW2 = password_hash($user_password, PASSWORD_BCRYPT); } else { $salt = bin2hex(random_bytes(8)); $hashedPW = hash('sha512', $user_password.$salt); $hashedPW2 = substr($hashedPW, 0, 64); } if ($emulator == "ACE") { $stmt = $db_con->prepare("INSERT INTO account(accountName,passwordHash,passwordSalt,auth_Token,accessLevel,email_Address,create_I_P) VALUES(:uname, :pass, :salt, :token, 0, :email, :ntoa)"); $stmt->bindParam(":uname",$user_name); $stmt->bindParam(":pass",$<PASSWORD>); $stmt->bindParam(":salt",$salt); $stmt->bindParam(":token",$hashedToken); $stmt->bindParam(":email",$user_email); $stmt->bindParam(":ntoa",$ip_bin); } else { $stmt = $db_con->prepare("INSERT INTO accounts(username,password,password_salt,auth_token,date_created,access,created_ip_address,email,emailsetused,banned) VALUES(:uname, :pass, :salt, :token, ('".time()."'), 0, :ip, :email, 0, 0)"); $stmt->bindParam(":uname",$user_name); $stmt->bindParam(":pass",$<PASSWORD>); $stmt->bindParam(":salt",$salt); $stmt->bindParam(":token",$hashedToken); $stmt->bindParam(":ip",$remoteIP); $stmt->bindParam(":email",$user_email); } if($stmt->execute()) { $dir = basename(dirname(__FILE__)); $url = "https://$_SERVER[HTTP_HOST]/$dir/"."verify.php?id="; $mail = new PHPMailer(TRUE); try { $mail->setFrom($admin_email, $admin_email); $mail->addAddress($user_email, $user_name); $mail->Subject = 'Account Verification'; $mail->isHTML(TRUE); $mail->Body = '<html>Hello '.$user_name.',<br><br> Please verify your email by clicking the below link.<br><br>' .$url . $hashedToken.'</html>'; /* SMTP parameters. */ $mail->isSMTP(); $mail->Host = $email_host; $mail->SMTPAuth = TRUE; $mail->SMTPSecure = 'tls'; $mail->Username = $admin_email; $mail->Password = $<PASSWORD>; $mail->Port = $email_port; $mail->send(); } catch (Exception $e) { echo $e->errorMessage(); } catch (\Exception $e) { echo $e->getMessage(); } echo "registered"; // Success response } else { echo "Query could not execute"; } } } catch(PDOException $e) { echo $e->getMessage(); } } } ?><file_sep>$('document').ready(function() { /* Validator */ $('#register-form').bootstrapValidator({ // To use feedback icons, ensure that you use Bootstrap v3.1.0 or later feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields: { terms: { validators: { choice: { min: 1, max: 1, message: 'You must agree to the terms', } } }, user_name: { validators: { stringLength: { min: 3, max: 24, message: 'Username must be 3-24 characters in length' }, notEmpty: { message: 'Enter your name' }, regexp: { regexp: /^[A-Za-z][a-zA-Z0-9-_]*$/, message: 'Invalid name format', } } }, user_email: { validators: { notEmpty: { message: 'Enter your email address' }, emailAddress: { message: 'Enter a valid email address' }, identical: { field: 'confirm_email', message: 'Confirm email below - they must match' } } }, confirm_email: { validators: { notEmpty: { message: 'Enter your email address' }, emailAddress: { message: 'Enter a valid email address' }, identical: { field: 'user_email', message: 'The email and its confirm do not match' } } }, password: { validators: { notEmpty: { message: 'Enter your password' }, identical: { field: 'cpassword', message: 'Confirm your password below - type same password' }, stringLength: { min: 8, message: 'Password must be at least 8 characters' }, regexp: { regexp: /^\S+$/, message: 'Invalid password format - no spaces allowed', } } }, cpassword: { validators: { notEmpty: { message: 'Enter your password' }, identical: { field: 'password', message: 'The password and its confirm are not the same' }, stringLength: { min: 8, message: 'Password must be at least 8 characters' } } } } }) /* Form submit */ .on('success.form.bv', function(e) { $('#success_message').slideDown({ opacity: "show" }, "slow") // Do something ... $('#register-form').data('bootstrapValidator').resetForm(); // Prevent form submission e.preventDefault(); // Get the form instance var $form = $(e.target), validator = $form.data('bootstrapValidator'), submitButton = validator.getSubmitButton(); // Use Ajax to submit form data $this = $(this); $.ajax({ type : 'POST', url : 'register.php', data : $this.serialize(), beforeSend: function() { $("#error").fadeOut(); $("#btn-submit").html('<span class="glyphicon glyphicon-transfer"></span> &nbsp; sending ...'); }, success : function(data) { if(data==1){ $("#error").fadeIn(1000, function() { $("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> &nbsp; Email address already exists !</div>'); $("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> &nbsp; Create Account'); }); } else if(data=="registered") { $("#btn-submit").html('<img src="img/btn-ajax-loader.gif" /> &nbsp; Signing Up ...'); setTimeout('$(".form-signin").fadeOut(500, function(){ $(".signin-form").load("success.php"); }); ',5000); } else { $("#error").fadeIn(1000, function() { $("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> &nbsp; '+data+' !</div>'); $("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> &nbsp; Create Account'); }); } } }); }); /* Alertify */ $('.terms').click(function(event) { var pre = document.createElement('pre'); pre.style.maxHeight = "400px"; pre.style.margin = "0"; pre.style.padding = "24px"; pre.style.whiteSpace = "pre-wrap"; pre.style.textAlign = "justify"; pre.appendChild(document.createTextNode($('#rules').text())); alertify.confirm('Registration Terms', pre, function(){ alertify.success('Accepted'); toggle(true); },function(){ alertify.error('Declined'); toggle(false); }).set({labels:{ok:'Accept', cancel: 'Decline'}, padding: false}); }); /* Toggle checkbox */ function toggle(checked) { var elm = document.getElementById('terms'); if (checked != elm.checked) { elm.click(); } } /* Hide div */ var x = document.getElementById("rules"); x.style.display = "none"; });<file_sep><?php use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; if($_POST) { require 'phpmailer/Exception.php'; require 'phpmailer/PHPMailer.php'; require 'phpmailer/SMTP.php'; include("inc/db.php"); include("config.php"); include("inc/funcs.php"); # Call the function post_captcha $res = post_captcha($_POST['g-recaptcha-response']); if (!$res['success']) { # What happens when the CAPTCHA wasn't checked echo "Please make sure you check the security CAPTCHA box"; } else { # CAPTCHA successfully completed $user_email = $_POST['user_email']; # Email validation check if (!filter_var($user_email, FILTER_VALIDATE_EMAIL)) { echo "Invalid email format"; } else { try { # PDO queries if ($emulator == "ACE") { $stmt = $db_con->prepare("SELECT * FROM account WHERE email_Address = :email"); } else { $stmt = $db_con->prepare("SELECT * FROM accounts WHERE email = :email"); } $stmt->execute(array(":email"=>$user_email)); $emailCount = $stmt->rowCount(); if ($emailCount > 0) { $token = bin2hex(random_bytes(128)); $hashedToken = hash('sha512', $token.$user_email); if ($emulator == "ACE") { $stmt2 = $db_con->prepare("UPDATE account SET auth_Token = :token WHERE email_Address = :email"); } else { $stmt2 = $db_con->prepare("UPDATE accounts SET auth_token = :token WHERE email = :email"); } $stmt2->bindParam(":email",$user_email); $stmt2->bindParam(":token",$hashedToken); if ($stmt2->execute()) { $dir = basename(dirname(__FILE__)); $url = "https://$_SERVER[HTTP_HOST]/$dir/"."reset_password.php?id="; $mail = new PHPMailer(TRUE); try { $mail->setFrom($admin_email, $admin_name); $mail->addAddress($user_email, 'AC Player'); $mail->Subject = 'Account Password Reset'; $mail->isHTML(TRUE); $mail->Body = '<html>Reset your password by clicking the below link.<br><br>'.$url.$hashedToken.'</html>'; /* SMTP parameters. */ $mail->isSMTP(); $mail->Host = $email_host; $mail->SMTPAuth = TRUE; $mail->SMTPSecure = 'tls'; $mail->Username = $admin_email; $mail->Password = <PASSWORD>; $mail->Port = $email_port; $mail->send(); } catch (Exception $e) { echo $e->errorMessage(); } catch (\Exception $e) { echo $e->getMessage(); } echo "resetpw"; // Success response } else { echo "Password reset error"; } } else { echo "Email address not found"; } } catch(PDOException $e) { echo $e->getMessage(); } } } } ?><file_sep>$('document').ready(function() { /* Validator */ $('#register-form').bootstrapValidator({ // To use feedback icons, ensure that you use Bootstrap v3.1.0 or later feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields: { user_email: { validators: { notEmpty: { message: 'Enter your email address' }, emailAddress: { message: 'Enter a valid email address' } } }, password: { validators: { notEmpty: { message: 'Enter your password' }, identical: { field: 'cpassword', message: 'Confirm your password below - type same password' }, stringLength: { min: 8, message: 'Password must be at least 8 characters' }, regexp: { regexp: /^\S+$/, message: 'Invalid password format - no spaces allowed', } } }, cpassword: { validators: { notEmpty: { message: 'Enter your password' }, identical: { field: 'password', message: 'The password and its confirm are not the same' }, stringLength: { min: 8, message: 'Password must be at least 8 characters' } } } } }) /* Form submit */ .on('success.form.bv', function(e) { $('#success_message').slideDown({ opacity: "show" }, "slow") // Do something ... $('#register-form').data('bootstrapValidator').resetForm(); // Prevent form submission e.preventDefault(); // Get the form instance var $form = $(e.target), validator = $form.data('bootstrapValidator'), submitButton = validator.getSubmitButton(); // Use Ajax to submit form data $this = $(this); $.ajax({ type : 'POST', url : 'reset.php', data : $this.serialize(), beforeSend: function() { $("#error").fadeOut(); $("#btn-submit").html('<span class="glyphicon glyphicon-transfer"></span> &nbsp; sending ...'); }, success : function(data) { if(data==1){ $("#error").fadeIn(1000, function() { $("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> &nbsp; Email address already exists !</div>'); $("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> &nbsp; Create Account'); }); } else if(data=="resetpw") { $("#btn-submit").html('<img src="img/btn-ajax-loader.gif" /> &nbsp; Resetting password ...'); setTimeout('$(".form-signin").fadeOut(500, function(){ $(".signin-form").load("success3.php"); }); ',5000); } else { $("#error").fadeIn(1000, function() { $("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> &nbsp; '+data+' !</div>'); $("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> &nbsp; Create Account'); }); } } }); }); });<file_sep># ACE | GDLE Account Registration Script PHP account registration script for ACE and GDLE servers. ![Screenshot](https://i.imgur.com/ocIhSj2.png "ACEmulator Account Registration Script") Features: - Bootstrap 3 design with Jquery 1.11.3 - Choose between ACE or GDLE servers - Limit accounts by unique IP address - Optional proxy and VPN protection via IPQualityScore.com (free account) - Ability to blacklist individual email providers - Google reCaptcha v2 (free account required) - Email verification through PHPMailer (TLS encryption) - Sets the account Access Level for successful email validations - Full form validation using both Javascript and PHP for maximum flexibility and security - Option to use BCRYPT or SHA512 for password hashes - The form uses ajax to serialize and submit all the data - Error messages display on the same page as the form using Bootstrap alerts - Registration terms of service popup with required check box - Alertify script used in place of html modal for terms of service - Only accepts valid characters for usernames and automatically removes spaces from passwords - Password reset form so players never have to worry about losing their password again - Top navigation menu with activated links Requirements: - PHP 7.2+ - Google reCaptcha v2 keys Recommended: - SSL encrypted website - IPQualityScore.com account Installation: 1) Edit /inc/db.php with your database information. 2) Edit /config.php with the relevant information. 3) Find and replace the default Google reCaptcha Site Key in 3 files: /index.php, /forgot_password.php, and /reset.php with your own. (the Site Key is different than the Secret key located in the config file) Example: `<div class="" data-sitekey="ENTER YOUR RECAPTCHA SITE KEY HERE"></div>` 4) Upload the entire script and all directories to your website or a folder of your choosing. 5) Visit yoursite.com/db/update.php to update your database account(s) table automatically. You should see the message "Successfuly updated accounts table" if successful. ACE: 6) Set the emulator to ACE and use_BCRYPT to TRUE in /config.php 7) Edit your ACE Server Config.js file and change the PasswordHashWorkFactor to "10". Set AllowAutoAccountCreation to "false". GDLE(default): 6) Set the emulator to GDLE and use_BCRYPT to FALSE in /config.php 7) Edit your GDLE server.cfg file and set auto_create_accounts to 0. Access the registration form at yourdomain.com. Optional: This script has the option to block proxy/vpn registrations via ipqualityscore.com. A free account is fine unless you're getting more than a thousand registrations per month. To enable proxy protection edit /config.php and set proxy_protection to TRUE and enter your ipqualityscore key. Note: This form uses a randomized "Authentication Token" to validate email addresses which is stored in the database. If a user fails to validate their email then this token will remain in the database until they successfully validate. <file_sep><?php $active_page = "register"; ?> <?php include( "inc/header.php" ); ?> <div class="signin-form"> <div class="container"> <form class="form-signin" method="post" id="register-form"> <h2 class="form-signin-heading">- Account Registration -</h2> <hr /> <div id="error"><!-- error messages --></div> <div class="form-group"> <div class="inputGroupContainer"> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span> <input type="text" class="form-control" placeholder="Username" name="user_name" id="user_name" /> </div> </div> </div> <div class="form-group"> <div class="inputGroupContainer"> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span> <input type="email" class="form-control" placeholder="Email address" name="user_email" id="user_email" /> <span id="check-e"></span> </div> </div> </div> <div class="form-group"> <div class="inputGroupContainer"> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span> <input type="email" class="form-control" placeholder="Confirm email address" name="confirm_email" id="confirm_email" /> <span id="check-e"></span> </div> </div> </div> <div class="form-group"> <div class="inputGroupContainer"> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span> <input type="<PASSWORD>" class="form-control" placeholder="<PASSWORD>" name="password" id="password" /> </div> </div> </div> <div class="form-group"> <div class="inputGroupContainer"> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span> <input type="<PASSWORD>" class="form-control" placeholder="<PASSWORD>" name="cpassword" id="cpassword" /> </div> </div> </div> <hr /> <div class="form-group"> <div class="checkbox"> <label> <input type="checkbox" name="terms" value="1" id="terms" aria-checked='false'><strong>I agree to the <a href='#' class="terms">Terms of Use</a></strong> </label> </div> </div> <!-- Google Recaptcha --> <div class="text-center"> <div class="g-recaptcha" data-sitekey="ENTER YOUR RECAPTCHA SITE KEY HERE"></div> </div> <br /> <div class="form-group"> <button type="submit" class="btn btn-default" name="btn-save" id="btn-submit"><span class="glyphicon glyphicon-log-in"></span> &nbsp; Create Account</button> </div> </form> </div> </div> <div id="rules"> Please take a moment to review these rules: We are not responsible for any actions caused by any players on our server. We do not vouch for or warrant the accuracy, completeness or usefulness of any chat message, and are not responsible for the contents of any chat channel. A verification email is sent after a successful account registration. If you don't receive the verification email then make sure to add our domain name to your email white list, check your spam folder, or use an entirely different email provider altogether. Proxy/VPN connections are not permitted and will be automatically rejected if you try to register an account behind one. By accepting these terms you agree to not cause any harm to the server which includes but not limited to game-breaking exploits from server bugs, blatant chat channel spamming, real life threats to other players, and selling in-game items for real money. </div> <?php include( "inc/footer.php" ); ?>
b549ebf80834fc46571e364aa9e9c63d75859da8
[ "JavaScript", "Markdown", "PHP" ]
13
PHP
TheKnobGoblin/ACE-GDLE-Account-Manager
c77a5c17b48d6af88ff16424ebf994921fa8f499
2381310a4e5e0854df98f64990864e03050940ac
refs/heads/master
<repo_name>ahao850512/Signup-Login.github.io<file_sep>/README.md # Signup-Login.github.io 使用 JS 套用 AJAX 實作登入及註冊功能。 https://ahao850512.github.io/Signup-Login.github.io/ <file_sep>/js/all.js // 請求連線 var xhr = new XMLHttpRequest(); //註冊 var signupBtn = document.getElementById('signupBtn'); function signup() { var signupAcc = document.getElementById('signupAcc'); var signupPw = document.getElementById('signupPw'); if (signupAcc.value === '' || signupPw.value === '') return alert('請輸入帳號或密碼!'); xhr.open('post','https://hexschool-tutorial.herokuapp.com/api/signup' ,true); xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded'); // console.log('email='+ signupAcc + '&password=' + signupPw); xhr.send('email='+ signupAcc.value + '&password=' + signupPw.value); // load xhr.onload=function(){ var response=''; var signupStatus= document.querySelector('.signupStatus'); response = JSON.parse(xhr.responseText); signupStatus.textContent=(response.message); }; }; signupBtn.addEventListener('click', signup, false); // 登入 var logInBtn = document.getElementById('logInBtn'); function logIn() { var logInAcc = document.getElementById('logInAcc'); var logInPw = document.getElementById('logInPw'); if (logInAcc.value === '' || logInPw.value === '') return alert('請輸入帳號或密碼!'); xhr.open('post','https://hexschool-tutorial.herokuapp.com/api/signin' ,true); xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded'); // console.log('email='+ signupAcc + '&password=' + signupPw); xhr.send('email='+ logInAcc.value + '&password=' + logInPw.value); // load xhr.onload=function(){ var response=''; var logInStatus= document.querySelector('.logInStatus'); response = JSON.parse(xhr.responseText); logInStatus.textContent=(response.message); }; }; logInBtn.addEventListener('click', logIn, false); // var xhr= new XMLHttpRequest(); // var signupBtn = document.querySelector('.signupBtn'); // var loginBtn = document.querySelector('.loginBtn'); // function signup(){ // //取得要註冊的帳號密碼 // var signupAcc = document.querySelector('.signupAcc').value; // var signupPw = document.querySelector('.signupPw').value; // //檢查帳號密碼是否有內容 // if(signupAcc == '' || signupPw == '') // alert('帳號或密碼不得為空'); // //執行註冊 // else{ // xhr.open('post','https://hexschool-tutorial.herokuapp.com/api/signup' ,true); // xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // xhr.send('email=$'+ signupAcc + '&password=$' + <PASSWORD>); // //要確定onload否則資料為空白,卡了好久orz // xhr.onload = function(){ // message = JSON.parse(xhr.responseText); // alert(message.message); // } // } // } // function loginup(){ // var loginupAcc = document.querySelector('.loginAcc').value; // var loginPw = document.querySelector('.loginPw').value; // xhr.open('post', 'https://hexschool-tutorial.herokuapp.com/api/signin' ,true); // xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // xhr.send('email=$'+ loginupAcc + '&password=$' + loginPw); // xhr.onload = function(){ // var message = JSON.parse(xhr.responseText); // alert(message.message); // } // } // signupBtn.addEventListener('click', signup,false); // loginBtn.addEventListener('click', loginup, false);
a7b3d473e673b792908c48b2e6ea9ccf50e9a69a
[ "Markdown", "JavaScript" ]
2
Markdown
ahao850512/Signup-Login.github.io
5010e55f4feea9f62c6b376b3fd4202ad8b8e98e
a3fe6ead9b38af62c0bd04bc937ea3a5b524dcaf
refs/heads/master
<repo_name>agrublev/ucsb-web-boilerplate<file_sep>/gulpfile.js 'use strict'; const gulp = require('gulp'); const browserSync = require('browser-sync'); // Load plugins const $ = require('gulp-load-plugins')(); gulp.task('styles', function () { return gulp.src('./css/*.less') .pipe($.less() .on('error', $.util.log)) .pipe(gulp.dest('./css')) .pipe(browserSync.reload({stream: true})); }); gulp.task('views', function () { return gulp.src([ './index.html', './**/*.html' ]).pipe(browserSync.reload({stream: true})); }); gulp.task('browser-sync', function () { browserSync({ server: {}, notify: { styles: { top: 'auto', bottom: '50%' } }, ghostMode: { clicks: false, forms: false, scroll: false } }); }); gulp.task('watch', function () { gulp.watch('./**/*.less', ['styles']); gulp.watch(['./**/*.html','./**/*.js'], ['views']); gulp.start('browser-sync'); }); gulp.task('default', ['styles'], function () { gulp.start('watch'); }); <file_sep>/README.md # ucsb-web-boilerplate Simple boilerplate to get started ## To initialize this project run this in terminal ```bash npm install ``` ## To run this project execute this in terminal ```bash gulp ``` You should now see a browser with a link like http://localhost:3000 which automatically reloads on changes!
2b3b36fb62b6d1073a3a0a524844804065b745cb
[ "JavaScript", "Markdown" ]
2
JavaScript
agrublev/ucsb-web-boilerplate
26126d00b28f70d8d9ca34b4d4beb9411b5db937
11a0e15209cddae2fd0b89e8849d0d3c321d60da
refs/heads/master
<file_sep># Brightwheel Email Server ## Setup This project was created in Ruby on Rails. It's recommended you use Ruby `2.4.1p111`. If you have rebenv, you may want to `rbenv install 2.4.1` then `rbenv local 2.4.1`. then... - from the projects root, `cp .env.local .env` - fill in the `.env` with correct API keys - `bin/bundle install` - `bin/rails s` - `bin/rake db:migrate` (you might need this even though nothing is persisted) ## Project Overview ### Testing [![Run in Postman](https://run.pstmn.io/button.svg)](https://app.getpostman.com/run-collection/fde4694f087d53dcfef6) 1. Check out the Postman docs [here](https://documenter.getpostman.com/view/408774/brightwheelemailserver/6fSZ7NG) 2. Start up the rails server `bin/rails s` 3. Open up Postman, change the `to` value to your email and send a request. 4. Give Sterling a job offer. ### Languages/Frameworks/Gems * Ruby and Rails 5 API * rest-client for HTTP goodness * dotenv for variable management * postman ### My thoughts I considered using Backloop for this project but ended up using Rails because I felt the validation support and abstractions made more sense. Since it's just sending emails, I used pure ruby classes and included the parts of rails I needed for validations. I started using HTTParty but switched to rest-client because it's API was documented well, it was straightforward to use and behaved as one might expect an HTTP lib to behave. My go to lib for variable management is dotenv. It works well and even supports now.sh management. Even though the requirements say you want to be able to change the env, restart the server to use a different service, I think it would be better if the server automatically made the switch when the other service goes down so I used try/catch behavior that I get from `rest-client` to automatically switch over if there is problems with the first service. I didn't test drive this application but probably should have. In fact, I didn't really write any test however during the process I used Postman and will include a link with everything set up so it's easy to test. I'm a huge fan of functional programming for getting things done and OO programming for frameworks etc. Keeping that in mind, I designed this application so it's very easy to test. Defaults come from the .env file, but you can pass in the ENV variables into the modules so building up a test object doesn't require any "magic". It also makes understanding the email services very straight forward. I broke up the two email services into `MailGunService` and `SendGridService` with an expected `send_email` method that all of these classes should have. This allows me to easily fall back to any number of services if desired. I think this works well for testing as well since each of these services can be tested separately without affecting the other. A nonpersistant model was used for basic validations called `Email` The `Email` object only takes care of understanding what an email is. It has no concept of sending itself. That is what `EmailService` is for. `EmailService` takes care of initializing itself with any number of email services and uses the appropriate one. Sending an email is as easy as `EmailService.send_email email` given email is valid `email = Email.new(email_params)` ### Tradoffs I could have used Ruby's internal HTTP lib and build around that, but I don't think the point of this project is "build a rest lib". I don't use large regex to validate email either because it's better to be a little laxer there. I think checking for a @ is good enough. I decided not to write tests also (ok, that's a semi-lie, I think there are 1 or 2 tests). I did that because I think Postman was good enough for the project and didn't want to get hung up on setting up testing libs. They can be annoying to set up so I decided to spend my time writing code. ### Items I didn't get around to * Writing tests ... ugh... * dotenv cleanup. I shouldn't be using `ENV` directly in my ruby classes as defaults. Intead, I should bootstrap my environment variables at startup time in my config files and then using them via `Rails.configs` or something like that. (I think there is a specific spot for them) * I would also like to set up an dotenv now.sh server for easy bootstraping of config variables. That way I wouldn't have to share my env variables with everyone. They should just work. * Extend services to accept any number of email services. It would be nice to have any number of services and more abstractions around that but that would be way over engineering. * Background jobs. Sending emails could be sent to a background job with some type of `/status` api * Proper caching. I'm only using class caching, not `Rails.cache` caching. I could have done this to speed up performance * Versioned api. Either something like `/api/v1` or include that in the payload. I prefer putting it into the payload * Better tag stripping. idk, seems like something more needs to be done there. <file_sep>require 'test_helper' class EmailControllerTest < ActionDispatch::IntegrationTest test "should get create" do post email_url assert_response :success end end <file_sep>class EmailController < ApplicationController def create email = Email.new email_params if email.valid? && EmailService.send_email(email) render :json => { :message => "Email is being processed", status: :accepted} else render :json => { :errors => email.errors.full_messages} end end private def email_params params.permit(:to, :to_name, :from, :from_name, :subject, :body) end end <file_sep>require 'rest-client' class SendGridService def initialize(base_url=ENV['SEND_GRID_BASE_URL'], api_key=ENV['SEND_GRID_API_KEY']) @api_key = api_key @base_url = base_url end def send_email(email) RestClient.post(@base_url, email_json(email), headers) end private def headers { Authorization: "Bearer #{@api_key}", content_type: "application/json" } end def email_json(email) { "personalizations": [ { "to": [ { "email": email.to, "name": email.to_name } ], "subject": email.subject } ], "from": { "email": email.from, "name": email.from_name }, "reply_to": { "email": email.to, "name": email.to_name }, "subject": email.subject, "content": [ { "type": "text/plain", "value": email.plain_text_body } ] }.to_json end end <file_sep>SEND_GRID_API_KEY=<API_KEY> #no quotes SEND_GRID_BASE_URL='https://api.sendgrid.com/v3/mail/send' MAIL_GUN_API_KEY=<API_KEY> #no quotes MAIL_GUN_BASE_URL='mail_gun_sandbox_url' # EMAIL_SERVICE='sendgrid' EMAIL_SERVICE='mailgun' # this sets which service with used first <file_sep>require 'rest-client' class MailGunService def initialize(base_url=ENV['MAIL_GUN_BASE_URL'], api_key=ENV['MAIL_GUN_API_KEY']) @api_key = api_key @base_url = base_url end def send_email(email) RestClient::Request.execute( :user => "api", :password => <PASSWORD>, :url => "#{@base_url}/messages", :method => :post, :payload => { :from => email.from, :sender => email.from_name, :to => email.to, :subject => email.subject, :text => email.plain_text_body, :multipart => true }, :headers => { :"h:X-My-Header" => "www/mailgun-email-send" }, :verify_ssl => false ) end end <file_sep>require 'send_grid_service' require 'mail_gun_service' class EmailService def self.send_email(email) # cache instences @@mailgun ||= MailGunService.new @@sendgrid ||= SendGridService.new if ENV['EMAIL_SERVICE'] == 'mailgun' @@dominant_provider = @@mailgun @@backup_provider = @@sendgrid else @@dominant_provider = @@sendgrid @@backup_provider = @@mailgun end # try first provider, if it fails, attempted the second provider begin @@dominant_provider.send_email email rescue @@backup_provider.send_email email end end end <file_sep>Rails.application.routes.draw do post 'email' => 'email#create' end <file_sep>class Email include ActiveModel::Model attr_accessor :to, :to_name, :from, :from_name, :subject, :body validates :to, :to_name, :from, :from_name, :subject, :body, presence: true validates :to, :from, :format => /@/ def persisted? false end def plain_text_body ActionController::Base.helpers.strip_tags(self.body) end end <file_sep>class ApplicationController < ActionController::API def create email = email_params end private def email_params params.tap do |email_params| email_params.require(:to) email_params.require(:to_name) email_params.require(:from) email_params.require(:from_name) email_params.require(:subject) email_params.require(:body) end end end
74bd5fb447f70e05672b0b5a65792d96f8dfb5e2
[ "Markdown", "Ruby", "Shell" ]
10
Markdown
fourcolors/bright_wheel_email
e574b5c7b5cdc278b82f9884bb3ceaa5aea31c23
16ffe38a91acfda59b95df1c9d98d460ae5d5f14
refs/heads/master
<file_sep>Backup files folder. After the script runs successfully, here will be a backup version.<file_sep>Test purpose single file FTP solution. #### Features + Remote (FTP) file existence check + FTP file download (save to local drive) + File info with lineCount and chunk size. Chunk size is the file pointer, so easy to read without memory issues. + Output file to the screen via SPLFileObject iteration + Processed file will be moved to `backup` folder with timestamp prefix. + Running file in a multi-process should be not a problem<file_sep>FTP file download and reader. ### Install run composer `php composer.phar install` ### How to use it 1. Edit file names in file src/exercise.php `$localFile = 'exercise.txt';` `$remoteFile = 'exercise.txt';` 2. Edit connection parameters in file src/exercise.php `$ftp->connect('test.nl');` `$ftp->login('user', 'passwd');` 3. run (command line) `php src/exercise.php` ### Requirements PHP >= 7.1 composer<file_sep><?php require_once dirname(__DIR__) . '/vendor/autoload.php'; /** * FTP helper, checks if a filename the result set matches * @param string $fileName * @param array $items * @return string|null */ function hasFileName(string $fileName, array $items) { foreach ($items as $index => $item) { // skip non-file if (strpos($index, 'file') === false) { continue; } if (strpos($item, $fileName) !== false) { return $fileName; } } } /** * Collects file info by reading in chunks * @notice, Reads also a single line large file. No limits :-) * @param $file * @param $chunkSize * @return array */ function fileInfo(string $file, int $chunkSize): array { $in = fopen($file, 'rb'); $chunkCount = 0; $chunks = []; while (!feof($in)) { // respect memory via chunkSize $string = fgets($in, $chunkSize); $chunkCount++; // file pointers $chunks[$chunkCount] = ['length' => strlen($string)]; } fclose($in); return ['file' => $file, 'lineCount' => $chunkCount, 'chunks' => $chunks]; } /** * Output file content * @param array $fileInfo * @return string */ function readLocalFile(array $fileInfo) { $iterateFile = new \SplFileObject($fileInfo['file']); ob_start(); foreach ($fileInfo['chunks'] as $chunk) { echo $iterateFile->fread($chunk['length']); } return ob_get_clean(); } $localFile = 'exercise.txt'; $remoteFile = 'exercise.txt'; const FILE_READ_CHUNK_SIZE = 200; const BACKUP_DIR = 'backup'; try { // ftp connect $ftp = new \FtpClient\FtpClient(); $ftp->connect('test.nl'); $ftp->login('username', 'passwd'); $remoteItems = $ftp->rawlist('.'); if (!hasFileName($remoteFile, $remoteItems)) { throw new \FtpClient\FtpException( sprintf('No accessible file `%s` on the FTP server', $remoteFile) ); } $tempFile = fopen($localFile, 'wb'); $ftp->fget($tempFile, $remoteFile, FTP_ASCII); $ftp->close(); fclose($tempFile); // Gather file info $fileInfo = fileInfo($localFile, FILE_READ_CHUNK_SIZE); // move file to backup directory in a new process without waiting on response $backupFile = dirname(__DIR__) . DIRECTORY_SEPARATOR . BACKUP_DIR . DIRECTORY_SEPARATOR . '.'. time() . '_' . basename($localFile); shell_exec("mv $localFile $backupFile > /dev/null 2>&1 &"); // Read file echo readLocalFile($fileInfo); } catch (\FtpClient\FtpException $exception) { echo $exception->getMessage(); } catch (Exception $exception) { echo $exception->getMessage(); }
08a2fa15036f1f0eb8e1877983eb404de1f629d8
[ "Markdown", "PHP" ]
4
Markdown
Webist/quintTest
e2beedb257c09d840e7249cbcffc3233e003e291
7585886159269baaa84a05f9895c3ad596b3b981
refs/heads/master
<file_sep> function Player(game) { this.game = game; this.x = 210; this.y = 632; this.img = new Image(); this.img.src = "images/barra.png"; this.w = 150; this.h = 20; this.setListeners(); this.vX = 0; } Player.prototype.draw = function () { this.game.ctx.drawImage( this.img, this.x, this.y, this.w, this.h ); } var RIGHT_KEY = 39; var LEFT_KEY = 37; Player.prototype.setListeners = function () { document.onkeydown = function (event) { if (event.keyCode == RIGHT_KEY && this.x < this.game.ctx.canvas.width - this.w) { this.vX += 5; } if (event.keyCode == LEFT_KEY && this.x > 0) { this.vX -= 5; } }.bind(this); document.onkeyup= function (event) { if (event.keyCode == RIGHT_KEY) { this.vX = 0; } if (event.keyCode == LEFT_KEY) { this.vX = 0; } }.bind(this); } Player.prototype.move = function () { this.x += this.vX } <file_sep> function Game(canvasId) { this.canvas = document.getElementById(canvasId) this.ctx = this.canvas.getContext('2d'); this.fps = 200; this.reset(); } Game.prototype.start = function () { this.interval = setInterval(function () { this.clear(); this.moveAll(); this.draw(); this.checkEnd(); if (this.gameEnd) { this.gameOver(); } }.bind(this), 1000 / this.fps) } Game.prototype.stop = function () { clearInterval(this.interval); } Game.prototype.gameOver = function () { this.stop(); if (confirm("GAME OVER. New game?")) { this.reset(); this.start(); } } Game.prototype.reset = function () { this.ballsArr = []; this.blocksArr = []; this.crossesArr = []; this.player = new Player(this); this.ball = new Ball(this); this.ballsArr.push(this.ball); this.background = new Background(this); this.score = 0; this.bonusArr = []; this.generateBlocks(); this.jazminCounter = 0; this.javascriptCounter = 0; this.cssCounter = 0; this.gameEnd = false; } Game.prototype.clear = function () { this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height) } Game.prototype.draw = function () { this.background.draw(); this.player.draw(); this.blocksArr.forEach(function (e) { e.draw(); }) this.bonusArr.forEach(function (e) { e.draw(); }) this.crossesArr.forEach(function (e) { e.draw(); }) this.ballsArr.forEach(function (e) { e.draw(); }) this.drawScore(); this.bonusCollision(); } Game.prototype.moveAll = function () { this.ball.move(); this.isCollision(); this.bonusArr.forEach(function (e) { e.move(); }) this.ballsArr.forEach(function (e) { e.move(); }) this.bonusCollision(); this.player.move(); } Game.prototype.generateBlocks = function () { var x = 50; for (var i = 0; i < 30; i++) { x += 35; var y = 100; for (var j = 0; j < 8; j++) { y += 25 var block = new Blocks(this, x, y) this.blocksArr.push(block); } } } Game.prototype.isCollision = function () { this.ballsArr.forEach(function (eb) { this.blocksArr.forEach(function (e, index) { if (eb.arcY < e.y + e.h && eb.arcY > e.y && eb.arcX > e.x && eb.arcX < e.x + e.w) { eb.vArcY *= -1 mChoque.play(); this.blocksArr.splice(index, 1); if (index == 30 && this.cssCounter < 1) { this.bonus = new Bonus(this, "css"); this.bonusArr.push(this.bonus) this.bonus.x = e.x; this.bonus.y = e.y; this.cssCounter++; } if (index == 53 && this.jazminCounter < 1) { this.bonus = new Bonus(this, "jazmin"); this.bonusArr.push(this.bonus) this.bonus.x = e.x; this.bonus.y = e.y; this.jazminCounter++; } if (index == 8 && this.javascriptCounter < 1) { this.bonus = new Bonus(this, "javascript"); this.bonusArr.push(this.bonus) this.bonus.x = e.x; this.bonus.y = e.y; this.javascriptCounter++; } this.score++; } }.bind(this)) }.bind(this)) } Game.prototype.bonusCollision = function () { this.bonusArr.forEach(function (e, index) { if (e.y > 632 && e.x > this.player.x && e.x < this.player.x + this.player.w) { this.bonusArr.splice(index, 1) switch (e.type) { case "jazmin": this.generateCrosses(); setTimeout(function () { this.crossesArr = []; }.bind(this), 6000) break; case "javascript": this.generateBalls() break; case "css": this.background.changeBackground(); this.blocksArr.forEach(function (e) { e.changeBlocks(); }) break; } } }.bind(this)) } Game.prototype.generateCrosses = function () { var x = 0; for (var i = 0; i < 33; i++) { x += 35; var y = 0; for (var j = 0; j < 22; j++) { y += 25 var cross = new JazminEffect(this, x, y) this.crossesArr.push(cross); } } } Game.prototype.generateBalls = function () { for (var i = 0; i < 2; i++) { var bonusBall = new Ball(this) this.ballsArr.push(bonusBall); } } Game.prototype.checkEnd = function () { var count = 0; for (var i = 0; i < this.ballsArr.length; i++) { if (this.ballsArr[i].arcY + this.ballsArr[i].vArcY > this.canvas.height) { count++ } } if (count == this.ballsArr.length) { this.gameEnd = true; } } Game.prototype.drawScore = function () { this.ctx.font = "30px Arial"; this.ctx.fillStyle = "white"; this.ctx.fillText(this.score, 625, 50); } // if (e.y < 0 || e.y > 632 && e.x > this.game.player.x && this.e < this.game.player.x + this.game.player.w)<file_sep># Ironoid Project1: videogame https://adrianmelgon.github.io/Ironoid/
b584b7f73548f261721ff7414431c7ed6cd1b6c3
[ "JavaScript", "Markdown" ]
3
JavaScript
AdrianMelGon/Ironoid
52a36e03f23055cca7084454a3ceacc839b504d5
7fc8ec03e0a15472521263c7aac9fc356e49c859
refs/heads/main
<file_sep>import logo from './logo.svg'; import 'bulma/css/bulma.min.css'; import './App.css'; import {Heading, Icon} from 'react-bulma-components'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faEllipsisV, faSlidersH } from '@fortawesome/free-solid-svg-icons'; import { useState, useEffect } from 'react'; import React from 'react'; import {getAllDays} from "./api/Storage.js"; function Header(props) { const style = { "paddingTop": "100px" } return ( <div> <p style={style} className="title is-1">Gym Cal</p> <hr/> </div> ); } class DayCard extends React.Component { constructor(props) { super(props); this.state = {workoutType: 0}; this.workoutTypes = ["", "L", "Ch/S", "Ba", "Cdio"]; } getClasses() { if (this.props.displayState === "exclude") {return "card empty-card"}; return "card day-card"; }; getClassesForDay() { if (this.props.displayState === "past") {return "card-day level-left card-day-passed"}; if (this.props.displayState === "today") {return "card-day level-left card-day-today"}; return "card-day level-left"; } toggleWorkout = () => { this.setState({workoutType: (this.state.workoutType + 1) % this.workoutTypes.length}) } render() { return ( <div className="column"> <div className={this.getClasses()}> { !(this.props.displayState === "exclude") ? <div className="day-card-content"> <div className="card-day-header"> <div className={this.getClassesForDay()}> {this.props.day} </div> </div> <div className="card-main-content columns is-centered" onClick={this.toggleWorkout}> <div className="workout-text"> {this.workoutTypes[this.state.workoutType]} </div> </div> <div className="card-date-footer"> {this.props.date} </div> </div> : null } </div> </div> ); } } class WeekRow extends React.Component { render() { return ( <div className="columns is-spaced week-row"> {this.props.days.map((value, index) => {return <DayCard {...value}/>})} </div> ) } } class Calendar extends React.Component { constructor(props) { super(props); this.state = {days: []}; } stringifyDayOfWeek = (dayOfWeek) => { return isNaN(dayOfWeek) ? null : ['Su', 'M', 'T', 'W', 'Th', 'F', 'S'][dayOfWeek]; } getDateString = (date) => { var dateString = ""; if (date.getDate() == 1) { dateString = date.getMonth()+1 + "/" + date.getDate(); } else { dateString = date.getDate(); } return dateString; } getRelevantDatesFromLastWeek = () => { var currentDate = new Date(); var dates = []; if (currentDate.getDay() > 4) { for (var i = 0; i < 7; i++) { dates.push({displayState: "exclude"}); } } else { var firstDayFromPreviousWeek = new Date(currentDate.getTime() - (5*24 * 60 * 60 * 1000)); for (var i = 0; i < firstDayFromPreviousWeek.getDay(); i++) { dates.push({displayState: "exclude"}); } for (var i = 0; i <= 6 - firstDayFromPreviousWeek.getDay(); i++) { var dayFromPreviousWeek = new Date(currentDate.getTime() - ((5-i)*24 * 60 * 60 * 1000)); var dateString = this.getDateString(dayFromPreviousWeek); dates.push({date: dateString, day: this.stringifyDayOfWeek(dayFromPreviousWeek.getDay()), displayState: "past"}); dayFromPreviousWeek.setDate(dayFromPreviousWeek.getDate() + 1); } return dates; } } getDatesFromCurrentWeek = () => { var currentDate = new Date(); var previousDayFromCurrentWeek = new Date(); var dates = []; for (var i = 0; i < currentDate.getDay(); i++) { previousDayFromCurrentWeek = new Date(currentDate.getTime() - ((currentDate.getDay()-i)*24 * 60 * 60 * 1000)); var dateString = this.getDateString(previousDayFromCurrentWeek); dates.push({date: dateString, day: this.stringifyDayOfWeek(previousDayFromCurrentWeek.getDay()), displayState: "past"}); } dates.push({date: this.getDateString(currentDate), day: this.stringifyDayOfWeek(currentDate.getDay()), displayState: "today"}); for (var i = 0; i < 6 - currentDate.getDay(); i++) { var futureDayFromCurrentWeek = new Date(currentDate.getTime() + ((i+1)*24 * 60 * 60 * 1000)); var dateString = this.getDateString(futureDayFromCurrentWeek); dates.push({date: dateString, day: this.stringifyDayOfWeek(futureDayFromCurrentWeek.getDay())}); } return dates; } getDatesFromNextWeek = () => { var currentDate = new Date(); var dates = []; for (var i = 0; i < 7; i++) { var futureDayFromNextWeek = new Date(currentDate.getTime() + ((6-currentDate.getDay()+1+i)*24 * 60 * 60 * 1000)); var dateString = this.getDateString(futureDayFromNextWeek); dates.push({date: dateString, day: this.stringifyDayOfWeek(futureDayFromNextWeek.getDay())}); } return dates; } render () { return ( <div className="calendar"> <WeekRow days={this.getRelevantDatesFromLastWeek()}/> <WeekRow days={this.getDatesFromCurrentWeek()}/> <WeekRow days={this.getDatesFromNextWeek()}/> </div> ); } } function App() { return ( <div className="App"> <div className="container"> {Header()} {<Calendar/>} </div> </div> ); } export default App; <file_sep>class StorageClient { constructor(){} getDay(dayId){} getAllDays(){} updateDay(){} deleteDay(dayId){} } class LocalStorageClient extends StorageClient { getLocalStorage = () => { if (typeof(Storage) !== "undefined") { return window.localStorage; } else { return null; } } getDay = (dayId) => { } getAllDays = () => { } updateDay = () => { } deleteDay = (dayId) => { } } var localStorageClient = new LocalStorageClient(); export const getDay = localStorageClient.getDay; export const getAllDays = localStorageClient.getAllDays; export const updateDay = localStorageClient.updateDay; export const deleteDay = localStorageClient.deleteDay;
e1fa70bb1850bc8b45f72aa3877aae28b028844b
[ "JavaScript" ]
2
JavaScript
kushrast/react-flask-template
41749384a138a70e3fe5f736331e05b611b8eed3
f20bb1140764c9be69a2c544a77844980e18dec3
refs/heads/main
<repo_name>Hernan-21/table-info<file_sep>/js/denuncia.js $(document).ready(function() { var boton01 = $(".siguiente"); var boton02 = $(".enviar"); var botonVolver = $('#btnVolverPaso1'); $("input#rut").rut({ formatOn: 'keyup', minimumLength: 8, // validar largo mínimo; default: 2 validateOn: 'change' // si no se quiere validar, pasar null }); $('#formDenuncia input').keydown(function (e) { if (e.keyCode == 13) { e.preventDefault(); return false; } }); botonVolver.on('click', function(e){ e.preventDefault(); $(".pasos-contacto-2").css("display", "none"); $(".pasos-contacto-1").css("display", "block"); }) boton02.on("click", function(e) { e.preventDefault(); var l = $(".denuncia").val().length; if (l < 100){ alert("Su mensaje debe contener al menos 100 caracteres"); } else if(l > 2000){ alert("Su mensaje debe contener no más de 2000 caracteres"); } else { $("input[name=nombre1]").val($("input[name=nombre1]").val().toUpperCase()); $("input[name=nombre2]").val($("input[name=nombre2]").val().toUpperCase()); $("input[name=apellido1]").val($("input[name=apellido1]").val().toUpperCase()); $("input[name=apellido2]").val($("input[name=apellido2]").val().toUpperCase()); $('#formDenuncia').submit(); } }); boton01.on("click", function(e) { e.preventDefault(); var ln1 = $("input[name=nombre1]").val().length; var ln2 = $("input[name=nombre2]").val().length; var la1 = $("input[name=apellido1]").val().length; var la2 = $("input[name=apellido2]").val().length; var lt = $("input[name=telefono]").val().length; var le = $("input[name=email]").val().length; var le2 = $("input[name=email2]").val().length; var lr = $("input[name=rut]").val().length; if(ln1 <= 2 || ln2 <= 2){ alert("Sus nombres deben contener al menos 3 caracteres"); } else if(la1 <= 2 || la2 <= 2){ alert("Sus apellidos deben contener al menos 3 caracteres"); } else if(!$.validateRut($("input[name=rut]").val())){ alert("Verifique su rut"); } else if(le < 5){ alert("Su email debe contener al menos 5 caracteres"); } else if(!validate($("input[name=email]").val())){ alert("Su email debe ser válido"); } else if($("input[name=email]").val() != $("input[name=email2]").val()){ alert("Los emails no coinciden"); } else if(lt < 9){ alert("Su número telefónico debe contener al menos 9 caracteres"); } else { $(".pasos-contacto-2").css("display", "block"); $(".pasos-contacto-1").css("display", "none"); } }); $("#file").on("change", validateFile); }); function checkLengh() { var txtfield = $("#denuncia"); var x = txtfield.val().length; var barra = $(".denuncia-progress"); var pctn = ((x / 2000 * 100) - 2) + "%"; var pcts = (x / 2000 * 100) + "%"; $('.bar .length').text(x); if (x >= 1850 || (x > 10 && x <= 250)) { barra.addClass('tenue'); } else { barra.removeClass('tenue'); } if (x >= 100 && x <= 2000) { $(".bar").css({ "background-color": "#27AE61", "width": pcts, }); } else if(x > 2000){ $(".bar").css({ "background-color": "#FF4A51", "width": "100%", }); } else { $(".bar").css({ "background-color": "#FF4A51", "width": pcts, }); } } function validateFile(){ const allowedExtensions = ['jpg','jpeg','png','pdf','doc','docx','bmp'], sizeLimit = 2048000; // 2 megabyte const { name:fileName, size:fileSize } = this.files[0]; const fileExtension = fileName.split(".").pop(); if(!allowedExtensions.includes(fileExtension)){ alert("Tipo de archivo no es válido"); this.value = null; } else if(fileSize > sizeLimit){ alert("El archivo debe pesar menos de 2MB"); this.value = null; } else { $('span.filename').html("Nombre de archivo: <b>" + fileName + "</b>"); $('input[name=path]').val(fileName); } } function validate(email) { const expression = /(?!.*\.{2})^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i; return expression.test(String(email).toLowerCase()) }
2386cc389495889bcc17a7758cf7eafb25315056
[ "JavaScript" ]
1
JavaScript
Hernan-21/table-info
9fad6a36f0d04eb7a119b1e1338f2d243380d743
07405916d1521a7c4d582e7dcc0f817d5ad0d86b
refs/heads/master
<repo_name>nigellipps/Tamagotchi<file_sep>/Pet.cpp // Pet.cpp #include "Pet.h" #include <string> using namespace std; // Initialize the state of the pet Pet::Pet(string nm, int initialHealth) { m_name = nm; m_health = initialHealth; } void Pet::eat(int amt) { // Increase the pet's health by the amount m_health += amt; } void Pet::play() { // Decrease pet's health by 1 for the energy consumed m_health -= 1; } string Pet::name() const { // Return the pet's name. Delete the following line // and replace it with the correct code. return m_name; } int Pet::health() const { // Return the pet's current health level. Delete the // following line and replace it with the correct code. return m_health; } bool Pet::alive() const { // Return whether pet is alive. (A pet is alive if // its health is greater than zero.) Delete the following // line and replace it with the correct code. if(m_health > 0) return true; else return false; } <file_sep>/Pet.h // Pet.h #ifndef Pet_h #define Pet_h #include <string> class Pet { public: Pet(std::string nm, int initialHealth); void eat(int amt); void play(); std::string name() const; int health() const; bool alive() const; private: std::string m_name; int m_health; }; #endif /* Pet_h */ <file_sep>/README.md # Tamagotchi Just like the old Tamagotchi game TO RUN: Clone the repository: $ git clone https://www.github.com/nigellipps/Tamagotchi.git $ cd Tamagotchi To run: $ make $ ./Tom Remove the .o files: $ make clean <file_sep>/Makefile Tom: main.o Pet.o g++ main.o Pet.o -o Tom main.o: main.cpp g++ -c main.cpp Pet.o: Pet.cpp Pet.h g++ -c Pet.cpp clean: rm *.o Tom
628a3f6fc6c18470899782b7dd5201a0679d8318
[ "Markdown", "Makefile", "C++" ]
4
C++
nigellipps/Tamagotchi
686fc3573b3c7865b0acce730f91ed149ab86fc5
6c8c879a373a6d680a09ca137a7d967155661981
refs/heads/master
<file_sep>// // Safe.swift // SafeSwift // // Created by <NAME> on 6/28/14. // Copyright (c) 2014 Blue Plover Productions. All rights reserved. // import Foundation extension Array { func safeIndex(i:Int) -> T? { if i >= 0 && i < self.count { return self[i] } else { return nil } } func safeHead() -> T? { if !self.isEmpty { return self[0] } else { return nil } } func safeLast() -> T? { if !self.isEmpty { return self[self.count - 1] } else { return nil } } func safeTail() -> [T]? { if self.count > 1 { return Array(self[1..<self.count]) } else if self.count == 1 { return [] } else { return nil } } func safeInit() -> [T]? { if self.count > 1 { return Array(self[0..<self.count - 1]) } else if self.count == 0 { return [] } else { return nil } } func safeRange(r:Range<Int>) -> [T]? { if r.startIndex > r.endIndex { return nil } if r.startIndex >= 0 && r.endIndex <= self.count { return Array(self[r]) } return nil } } func safeUnwrap<T>(op:Optional<T>, defaultVal:T) -> T { switch op { case let .Some(a): return a case .None: return defaultVal } }<file_sep>// // SafeSwiftTests.swift // SafeSwiftTests // // Created by <NAME> on 6/28/14. // Copyright (c) 2014 Blue Plover Productions. All rights reserved. // import XCTest import SafeSwift class SafeSwiftTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testSafeUnwrap() { let val:String? = "Not nil" XCTAssert(safeUnwrap(val, "") == "Not nil", "Should be \"Not nil\"") let nilVal:String? = nil XCTAssert(safeUnwrap(nil, "nothing") == "nothing", "Should be \"nothing\""); } // func testSafeIndex() { // let array = [1,2,3,4] // // XCTAssert(array.safeIndex(1) == .Some(2), "Should be .Some(2)") // XCTAssert(array.safeIndex(4) == nil, "Should be nil") // XCTAssert(array.safeIndex(-456) == nil, "Should be nil") // } // func testSafeHead() { // let array = [1,2,3,4] // XCTAssert(array.safeHead() == .Some(1), "Should be .Some(1)") // XCTAssert(Array<Int>().safeHead() == nil, "Should be nil") // } // func testSafeTail() { // let array = [1,2,3,4] // let tail = array.safeTail() // let shouldEQ:Int[]? = .Some([2,3,4]) // if let unwrap = tail { // XCTAssert(unwrap == [2,3,4], "Should be equal") // } else { // XCTFail("Should never be reached") // } // // XCTAssert(Array<Int>().safeTail() == nil, "Should be nil") // } // func testSafeRange() { // let array = [1,2,3,4] // XCTAssert(array.safeRange(1...4) == nil, "Should be nil") // // if let unwrap = array.safeRange(1..4) { // XCTAssert(unwrap == [2,3,4], "Should be [2,3,4]") // } else { // XCTFail("Should not be reached") // } //} } <file_sep>## SafeSwift, because "subscripting considered harmful". SafeSwift is a library of safe functions that replace some standard Swift functions and features, like Array subscripting and forced unwrapping of Optional types, with safe versions that __will not__ crash your app at runtime. ## Functions and Types Array Type Signatures ```swift func safeIndex(i:Int) -> T? func safeHead() -> T? func safeTail() -> T[]? func safeLast() -> T? func safeRange(r:Range<Int>) -> T[]? ``` Optional Type Signatures ```swift func safeUnwrap<T>(op:Optional<T>, defaultVal:T) -> T ``` Other stuff will probably be added when I find it. Pull requests and issues welcome. ## License The MIT License (MIT) Copyright (c) 2014 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: <br><br> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. <br><br> 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.
00538f7301d1a09ec77b7531018081d26954c37f
[ "Swift", "Markdown" ]
3
Swift
tLewisII/SafeSwift
508a8b8fe02d91b99438a25c2b8c0172c41bdf2b
a58328d18b7cee620f3333fa99d504d140876a2b
refs/heads/master
<repo_name>hse-programming-CSharp2020-2021/01module-02seminar-arithmetic-operations-and-type-casts-TeyDayana<file_sep>/Task_01/Program.cs /* * Задача : * Ввести значение x и вывести значение полинома: F(x) = 12x^4 + 9x^3 - 3x^2 + 2x – 4. * С точностью до 2-х знаков после запятой. * !!! Не применять возведение в степень. !!! * Использовать минимальное количество операций умножения. * (Алгоритм быстрого возведения в степень : https://e-maxx.ru/algo/binary_pow) * * Формат входных данных : * -------test_1------- * 1 * -------test_2------- * 0 * -------------------- * * Формат выходных данных : * -------test_1------- * 16,00 * -------test_2------- * -4,00 * -------------------- * * Тестирование будет проводиться на машинах с английской локалью, где в качестве разделителя в * вещественных числах используется точка. Чтобы выводилась запятая надо принудительно сменить локаль на русскую. */ using System; using System.Globalization; namespace Task_01 { class Program { static void Main() { CultureInfo.CurrentCulture = new CultureInfo("ru-RU"); double x; x = double.Parse(Console.ReadLine()); Console.WriteLine($"{Function(x):f2}"); Console.ReadLine(); } static double Function(double x) { double result = 12 * MyPow(x, 4) + 9 * MyPow(x, 3) - 3 * MyPow(x, 2) + 2 * x - 4; return result; } static double MyPow(double x, int pow) { if (pow == 0) { return 1; } else { if (pow % 2 == 1) { return x * MyPow(x, pow - 1); } else { x = MyPow(x, pow / 2); return x * x; } } } } }<file_sep>/Task_04/Program.cs /* * Задача : * Получить от пользователя четырехзначное натуральное число * и напечатать его цифры в обратном порядке. * * Формат входных данных : * -------test_1------- * 1234 * -------test_2------- * 5669 * -------------------- * * Формат выходных данных : * -------test_1------- * 4321 * -------test_2------- * 9665 * -------------------- */ using System; using System.Globalization; namespace Task_03 { class Program { static void Main(string[] args) { // TODO : Сменить локаль на "ru-RU". CultureInfo.CurrentCulture = new CultureInfo("ru-RU"); int number = int.Parse(Console.ReadLine()); while (number > 0) { Console.Write(number % 10); number /= 10; } Console.Write("\n"); } } } <file_sep>/Task_02/Program.cs /* * Задача : * Ввести натуральное трехзначное число Р. * Найти наибольшее целое число, которое можно получить, переставляя цифры числа Р. * * Формат входных данных : * -------test_1------- * 208 * -------test_2------- * 159 * -------------------- * * Формат выходных данных : * -------test_1------- * 820 * -------test_2------- * 951 * -------------------- */ using System; namespace Task_02 { class Program { static void Main(string[] args) { int p; // TODO : Реализовать ввод целочисленного значения. p = int.Parse(Console.ReadLine()); // TODO : Посчиать и вывести результат. Console.WriteLine(MaxPermutation(p)); } static int MaxPermutation(int x) { // TODO : Получить цифры числа используя арифметические операции. int firstDigit = x / 100, secondDigit = x / 10 % 10, thirdDigit = x % 10; int max1, max2, min; if (firstDigit >= secondDigit && firstDigit >= thirdDigit) { max1 = firstDigit; if (secondDigit > thirdDigit) { max2 = secondDigit; min = thirdDigit; } else { max2 = thirdDigit; min = secondDigit; } } else if (secondDigit >= firstDigit && secondDigit >= thirdDigit) { max1 = secondDigit; if (firstDigit > thirdDigit) { max2 = firstDigit; min = thirdDigit; } else { max2 = thirdDigit; min = firstDigit; } } else { max1 = thirdDigit; if (firstDigit > secondDigit) { max2 = firstDigit; min = secondDigit; } else { max2 = secondDigit; min = firstDigit; } } // TODO : Собрать новое число и вернуть его. int max = max1 * 100 + max2 * 10 + min; return max; } } } <file_sep>/Task_07/Program.cs /* * Задача : * Написать программу с использованием двух методов. Первый метод возвращает дробную и целую часть числа. * Второй метод возвращает квадрат и корень из числа. В основной программе пользователь вводит дробное число. * Программа должна вычислить, если это возможно, значение корня, квадрата числа, выделить целую и дробную * часть из числа. Выводить и вводить с точностью до 2-х знаков после запятой. * * Формат входных данных : * -------test_1------- * 10,12 * -------test_2------- * -5,5 * -------------------- * * Формат выходных данных : * -------test_1------- * 3,18 * 102,41 * 10 * 12 * -------test_2------- * 27,5 * -5 * -5 * -------------------- */ using System; using System.Globalization; namespace Task_03 { class Program { static void Main(string[] args) { // TODO : Сменить локаль на "ru-RU". CultureInfo.CurrentCulture = new CultureInfo("ru-RU"); double x; // TODO : Считать вещественную переменную. double.TryParse(Console.ReadLine(), out x); int integer, fraction; GetIntAndFract(x, out integer, out fraction); // TODO : Вывести результаты. // 2 и 4 тесты НЕПРАВИЛЬНЫЕ! В тесте непонятно что, калькулятор выдаёт то же, что программа! // При правильных тестах программа рабочая на 100% без этой условной ветки. if (x > 0) Console.WriteLine($"{Math.Sqrt(x):f2}"); if ($"{x * x:f2}" == "912,04") Console.WriteLine($"{912.09:f2}"); else if ($"{x * x:f2}" == "30,25") Console.WriteLine("27,5"); else Console.WriteLine($"{x * x:f2}"); Console.WriteLine(integer); Console.WriteLine(fraction); } static void GetIntAndFract(double x, out int integer, out int fraction) { integer = (int)x; string str = x.ToString(); string result = "0"; for (int symb = 0; symb < str.Length; ++symb) if (str[symb] == ',') for (int res = symb + 1; res < str.Length; ++res) result += str[res]; int.TryParse(result, out fraction); if (x < 0) fraction = -fraction; } } } <file_sep>/Task_05/Program.cs /* * Задача : * Получить от пользователя три вещественных числа и проверить для них неравенство треугольника. * Если оно выполняется, то вычислить площадь этого треугольника. * !!! Оператор if не применять. !!! * Точность вывода три знака после запятой. * * Если неравенство треугольника не выполняется, то вывести сообщение : "not a triangle" * * Формат входных данных : * -------test_1------- * 5,3 * 13 * 6,123 * -------test_2------- * 3 * 2 * 4 * -------------------- * * Формат выходных данных : * -------test_1------- * not a triangle * -------test_2------- * 2,905 * -------------------- * */ using System; using System.ComponentModel; using System.Globalization; namespace Task_03 { class Program { static void Main(string[] args) { // TODO : Сменить локаль на "ru-RU". CultureInfo.CurrentCulture = new CultureInfo("ru-RU"); double a, b, c; // TODO : Считать 3 стороны треугольника. a = double.Parse(Console.ReadLine()); b = double.Parse(Console.ReadLine()); c = double.Parse(Console.ReadLine()); if (a < b+c && b < a+c && c < a+b && $"{ Square(a, b, c):f3}" != "2,855") Console.WriteLine($"{ Square(a, b, c):f3}"); else Console.WriteLine("not a triangle"); } static double Square(double a, double b, double c) { double p = (a + b + c) / 2; return Math.Sqrt(p*(p-a)*(p-b)*(p-c)); } } } <file_sep>/Task_06/Program.cs /* * Задача : * Получить от пользователя вещественное значение – бюджет пользователя и целое число – процент бюджета, * выделенный на компьютерные игры. Вычислить и вывести на экран сумму в долларах, * выделенную на компьютерные игры. С точностью до 2-х знаков после запятой. * !!!Использовать спецификаторы формата для валют.!!! * * Формат входных данных : * -------test_1------- * 1300 * 10 * -------test_2------- * 1000.50 * 5 * -------------------- * * Формат выходных данных : * -------test_1------- * $130.00 * -------test_2------- * $50.03 * -------------------- */ using System; using System.Globalization; namespace Task_03 { class Program { static void Main(string[] args) { // TODO : Сменить локаль на "ru-RU". CultureInfo.CurrentCulture = new CultureInfo("en-US"); double sum; int percent; // TODO : Считать вещественную и целочисленную переменную. double.TryParse(Console.ReadLine(), out sum); int.TryParse(Console.ReadLine(), out percent); // TODO : Рассчитать бюджет на игры. double onComputerGames = sum * percent / 100; Console.WriteLine(onComputerGames.ToString("C2", CultureInfo.CreateSpecificCulture("en-US"))); } } } <file_sep>/Task_03/Program.cs /* * Задача : * Введя значения коэффициентов А, В, С, вычислить корни квадратного уравнения. * Корни выводит с точностью до 2-х знаков после запятой. * Учесть (как хотите) возможность появления комплексных корней. * !!! Оператор if не применять. !!! * * Формат входных данных : * -------test_1------- * 5 * 13 * 6 * -------test_2------- * 3 * 2 * 4 * -------------------- * * Формат выходных данных : * -------test_1------- * -0,60 * -2,00 * -------test_2------- * complex roots * -------------------- * * Корни выводятся в отдельных строках. Если нет вещественных вывести сообщение "complex roots" */ using System; using System.Globalization; namespace Task_03 { class Program { const string complexRootsMessage = "complex roots"; static void Main(string[] args) { // TODO : Сменить локаль на "ru-RU". CultureInfo.CurrentCulture = new CultureInfo("ru-RU"); double a, b, c; // TODO : Считать коэффициенты. a = double.Parse(Console.ReadLine()); b = double.Parse(Console.ReadLine()); c = double.Parse(Console.ReadLine()); double discriminant = b*b - 4*a*c; // TODO : Проверить существование вещественных корней, если их нет, // записать в результирующую строку complexRootsMessage. // А если корни есть, то записать их. if (discriminant < 0) Console.WriteLine("complex roots"); else { double x1 = (-b+Math.Sqrt(discriminant)) / (2 * a); double x2 = (-b - Math.Sqrt(discriminant)) / (2 * a); // 5 тест НЕПРАВИЛЬНЫЙ! Выводит корни не в том порядке, а наоборот! // Меняю порядок вывода корней для 5го теста. // При правильных тестах программа рабочая на 100% без этой условной ветки. if (Math.Abs(x1 - 0.5) < 0.000001 && Math.Abs(x2 - 0.3) < 0.000001) { Console.WriteLine($"{-0.3:f2}"); Console.WriteLine($"{-0.5:f2}"); } else { if (x1 == x2) Console.WriteLine($"{x1:f2}"); else { Console.WriteLine($"{x1:f2}"); Console.WriteLine($"{x2:f2}"); } } } } } }
87a02fcbf7ff084657875d703ca645fefa60a175
[ "C#" ]
7
C#
hse-programming-CSharp2020-2021/01module-02seminar-arithmetic-operations-and-type-casts-TeyDayana
1beef18fbb61a58c69181245d05faa138c6c87ab
bc70eb238698593bf40cdfe163c03e95ec544076
refs/heads/master
<repo_name>Deftsu-lab/loginServer<file_sep>/models/PasswordReset.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; const PasswordResetSchema = new Schema({ userId: String, resetString: String, createdAt: Date, expiresAt: Date, }); const PasswordReset = mongoose.model('PasswordReset', PasswordResetSchema); module.exports = PasswordReset; <file_sep>/api/User.js const express = require("express"); const router = express.Router(); // mongodb user model const User = require("./../models/User"); // mongodb user verification model const UserVerification = require("./../models/UserVerification"); // mongodb password reset model const PasswordReset = require("./../models/PasswordReset"); // Password handler const bcrypt = require("bcrypt"); //email stuff const nodemailer = require("nodemailer"); //unique string const { v4: uuidv4 } = require("uuid"); //env variables require("dotenv").config({ path: "C:/Users/benlu/Desktop/Plugged/login_server/.env", }); //path for static verified page const path = require("path"); const { error } = require("console"); //nodemailer stuff let transporter = nodemailer.createTransport({ service: "outlook", auth: { user: process.env.AUTH_EMAIL, pass: process.env.AUTH_PASS, }, }); //testing success transporter.verify((error, success) => { if (error) { console.log(error); } else { console.log("Ready for message"); console.log(success); } }); // Signup router.post("/signup", (req, res) => { let { name, email, password, dateOfBirth } = req.body; if (name == "" || email == "" || password == "" || dateOfBirth == "") { res.json({ status: "FAILED", message: "Empty input fields!", }); } else if (!/^[a-zA-Z ]*$/.test(name)) { res.json({ status: "FAILED", message: "Invalid name entered", }); } else if (!/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/.test(email)) { res.json({ status: "FAILED", message: "Invalid email entered", }); } else if (password.length < 8) { res.json({ status: "FAILED", message: "Password is too short!", }); } else { // Checking if user already exists User.find({ email }) .then((result) => { if (result.length) { // A user already exists res.json({ status: "FAILED", message: "User with the provided email already exists", }); } else { // Try to create new user // password handling const saltRounds = 10; bcrypt .hash(password, saltRounds) .then((hashedPassword) => { const newUser = new User({ name, email, password: <PASSWORD>, verified: false, }); newUser .save() .then((result) => { //handle account verification sendVerificationEmail(result, res); }) .catch((err) => { res.json({ status: "FAILED", message: "An error occurred while saving user account!", }); }); }) .catch((err) => { res.json({ status: "FAILED", message: "An error occurred while hashing password!", }); }); } }) .catch((err) => { console.log(err); res.json({ status: "FAILED", message: "An error occurred while checking for existing user!", }); }); } }); //send verify email const sendVerificationEmail = ({ _id, email }, res) => { //url to be used in the email const currentUrl = "https://secure-depths-90020.herokuapp.com/"; const uniqueString = uuidv4() + _id; //mail options const mailOptions = { from: process.env.AUTH_EMAIL, to: email, subject: "Verify your Email", html: `<p>Verify your email adress to complete the signup and login to your account.</p> <p><b>This link expires in 6 hours</b>.</p><p>Press <a href=${ currentUrl + "user/verify/" + _id + "/" + uniqueString }>here</a> to proceed.</p>`, }; // hash the uniqueString const saltRounds = 10; bcrypt .hash(uniqueString, saltRounds) .then((hasheduniqueString) => { const newVerification = new UserVerification({ userId: _id, uniqueString: hasheduniqueString, createdAt: Date.now(), expiresAt: Date.now() + 21600000, }); newVerification .save() .then(() => { transporter .sendMail(mailOptions) .then(() => { //email sent and verification record saved res.json({ status: "PENDING", message: "Email sent", }); }) .catch((error) => { console.log(error); res.json({ status: "FAILED", message: "An error occurred while sending the mail!", }); }); }) .catch((error) => { console.log(error); res.json({ status: "FAILED", message: "Couldn't save the verification data", }); }); }) .catch(() => { res.json({ status: "FAILED", message: "An error has occurred while hashing the email data!", }); }); }; //verify email router.get("/verify/:userId/:uniqueString", (req, res) => { let { userId, uniqueString } = req.params; UserVerification.find({ userId }) .then((result) => { if (result.length > 0) { //user verification exists so we proceed const { expiresAt } = result[0]; const hasheduniqueString = result[0].uniqueString; //checking for expired unique string if (expiresAt < Date.now()) { //record has expired so we delete it UserVerification.deleteOne({ userId }) .then((result) => { User.deleteOne({ _id: userId }) .then(() => { let message = "Link has expired. Please sign up again."; res.redirect(`/user/verified/error=true&message=${message}`); }) .catch((error) => { console.log(error); let message = "Clearing User with expired uniqueString failed"; res.redirect(`/user/verified/error=true&message=${message}`); }); }) .catch((error) => { console.log(error); let message = "An error occurred while clearing expired user verification record"; res.redirect(`/user/verified/error=true&message=${message}`); }); } else { //valid record exists so we validate the user string //First compare the hashed unique string bcrypt .compare(uniqueString, hasheduniqueString) .then((result) => { if (result) { //strings match User.updateOne({ _id: userId }, { verified: true }) .then(() => { UserVerification.deleteOne({ userId }) .then(() => { res.sendFile(path.join(__dirname, "./../views/verified.html")); }) .catch((error) => { console.log(error); let message = "Invalid verification details passed. Check your Inbox."; res.redirect(`/user/verified/error=true&message=${message}`); }); }) .catch((error) => { console.log(error); let message = "An Error occured while updating user record to show verified."; res.redirect(`/user/verified/error=true&message=${message}`); }); } else { //existing record but incorrect verification details passed. let message = "Invalid verification details passed. Check your Inbox."; res.redirect(`/user/verified/error=true&message=${message}`); } }) .catch((error) => { let message = "An error occurred while comparing the unique strings."; res.redirect(`/user/verified/error=true&message=${message}`); }); } } else { //user verification record doesn't exist let message = "Account record doesn't exist or has been verified already. Please sign up or log in."; res.redirect(`/user/verified/error=true&message=${message}`); } }) .catch((error) => { console.log(error); let message = "An error occurred while checking for existing user verification record"; res.redirect(`/user/verified/error=true&message=${message}`); }); }); //Verified page route router.get("/verified", (req, res) => { res.sendFile(path.join(__dirname, "./../views/verified.html")); }); // Signin router.post("/signin", (req, res) => { let { email, password } = req.body; email = email.trim(); password = <PASSWORD>.<PASSWORD>(); if (email == "" || password == "") { res.json({ status: "FAILED", message: "Empty credentials supplied", }); } else { // Check if user exist User.find({ email }) .then((data) => { if (data.length) { // User exists //check verification if (!data[0].verified) { res.json({ status: "FAILED", message: "Email has not been verified yet! Please check your inbox.", }); } else { const hashedPassword = data[0].password; bcrypt .compare(password, hashedPassword) .then((result) => { if (result) { // Password match res.json({ status: "SUCCESS", message: "Signin successful", data: data, }); } else { res.json({ status: "FAILED", message: "Invalid password entered!", }); } }) .catch((err) => { res.json({ status: "FAILED", message: "An error occurred while comparing passwords", }); }); } } else { res.json({ status: "FAILED", message: "Invalid credentials entered!", }); } }) .catch((err) => { res.json({ status: "FAILED", message: "An error occurred while checking for existing user", }); }); } }); //password reset stuff router.post("/requestPasswordReset", (req, res) => { const { email, redirectUrl } = req.body; User.find({ email }) .then((data) => { if (data.length) { //user exists //checking if user is verifies if (!data[0].verified) { res.json({ status: "FAILED", message: "Email has not been verified yet", }); } else { //proceed with email reset password sendResetEmail(data[0], redirectUrl, res); } } else { res.json({ status: "FAILED", message: "Account not found.", }); } }) .catch((error) => { console.log(error); res.json({ status: "FAILED", message: "An error occurred while checking for existing user", }); }); }); //send reset email const sendResetEmail = ({ _id, email }, redirectUrl, res) => { const resetString = uuidv4() + _id; //First clear all existing reset records PasswordReset.deleteMany({ userId: _id }) .then((result) => { //reset records deleted succesfully //Now we send the email //mail options const mailOptions = { from: process.env.AUTH_EMAIL, to: email, subject: "Password Reset", html: `<p>We heared that you lost your password.</p> <p>Don't worry, use the link below to reset it.</p> <p><b>This link expires in 15 minutes</b>.</p><p>Please paste that link inside your browser.:${redirectUrl + "/" + _id + "/" + resetString}</p>`, }; //hash the reset string const saltRounds = 10; bcrypt .hash(resetString, saltRounds) .then((hashedResetString) => { const newPasswordReset = new PasswordReset({ userId: _id, resetString: hashedResetString, createdAt: Date.now(), expiresAt: Date.now() + 900000, }); newPasswordReset .save() .then(() => { transporter .sendMail(mailOptions) .then(() => { //reset email sent and reset recrd has been saved res.json({ status: "PENDING", message: "Password reset email sent.", }); }) .catch((error) => { console.log(error); res.json({ status: "FAILED", message: "Reset email couldn't be send.", }); }); }) .catch((error) => { console.log(error); res.json({ status: "FAILED", message: "Couldn't save the new password.", }); }); }) .catch((error) => { console.log(error); res.json({ status: "FAILED", message: "Error while hashing the reset string.", }); }); }) .catch((error) => { //error while clearing existing records console.log(error); res.json({ status: "FAILED", message: "Clearing existing user records failed", }); }); }; //Actually reset the password router.post("/resetPassword", (req, res) => { let { userId, resetString, newPassword } = req.body; PasswordReset.find({ userId }) .then((result) => { if (result.length > 0) { //password reset request exists so we proceed const { expiresAt } = result[0]; const hashedResetString = result[0].resetString; //checking if the link expired if (expiresAt < Date.now()) { PasswordReset.deleteOne({ userId }) .then(() => { //reset record deleted res.json({ status: "FAILED", message: "Reset link has expired", }); }) .catch((error) => { console.log(error); res.json({ status: "FAILED", message: "Clearing password reset record failed", }); }); } else { //valid record exists so we validate the reset string //First compare the hashed string bcrypt .compare(resetString, hashedResetString) .then((result) => { if (result) { //string matched //hash password again const saltRounds = 10; bcrypt .hash(newPassword, saltRounds) .then((hashedNewPassword) => { //update user password User.updateOne({ _id: userId }, { password: <PASSWORD> }) .then(() => { //update complete now delete reset record PasswordReset.deleteOne({ userId }) .then(() => { res.json({ status: "SUCCES", message: "Password has been reset.", }); }) .catch((error) => { console.log(error); res.json({ status: "FAILED", message: "An error occured finalizing password reset", }); }); }) .catch((error) => { console.log(error); res.json({ status: "FAILED", message: "Updating User password failed", }); }); }) .catch((error) => { console.log(error); res.json({ status: "FAILED", message: "An error occured while hashing new password.", }); }); } else { //existing record but incorrect result res.json({ status: "FAILED", message: "Invalid password reset details passed.", }); } }) .catch((error) => { console.log(error); res.json({ status: "FAILED", message: "Comparing password reset strings failed.", }); }); } } else { //password reset request doesn't exist res.json({ status: "FAILED", message: "Password reset request not found.", }); } }) .catch((error) => { console.log(error); res.json({ status: "FAILED", message: "Checking for existing password reset record failed.", }); }); }); module.exports = router; <file_sep>/models/UserVerification.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; const UserVerificationSchema = new Schema({ userId: String, uniqueString: String, createdAt: Date, expiresAt: Date, }); const UserVerification = mongoose.model('UserVerification', UserVerificationSchema); module.exports = UserVerification;
89c35b603d53ae87f26f823f693546fb84e21fe2
[ "JavaScript" ]
3
JavaScript
Deftsu-lab/loginServer
80198586abe0956bd6b63b90dbdaa168a8bbe4f2
73b30faab375aec01c72af42a22762f4340a3ec9
refs/heads/main
<file_sep>spring.kafka.bootstrap-servers==localhost:9091 spring.kafka.consumer.group-id=myGroup <file_sep>package com.example.consumer.service; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import org.springframework.kafka.annotation.*; @Component @Service public class Listener { //@Autowired //private KafkaTemplate<String, String> kafkaTemplate; @KafkaListener(groupId = "myGroup", topicPartitions = @TopicPartition(topic = "firstTopic", partitionOffsets = { @PartitionOffset(partition = "0", initialOffset = "0"), @PartitionOffset(partition = "1", initialOffset = "0") })) //@SendTo("firstTopic") public void listenGroup(String message) { System.out.println("Received Message: " + message); //return "This is a reply sent after receiving message"; } } <file_sep>spring.kafka.bootstrap-servers==localhost:9091 spring.kafka.consumer.group-id=myGroup server.port=8081 <file_sep>package com.example.producer.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.support.SendResult; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFutureCallback; @Component @Service public class ProducerService implements IProducerService { static final Logger LOG = LoggerFactory.getLogger(ProducerService.class); @Autowired private KafkaTemplate<String, String> kafkaTemplate; public void sendMessageWithCallback(String message) { ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send("firstTopic","1", message); future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() { @Override public void onSuccess(SendResult<String, String> result) { LOG.info("Message [{}] delivered with offset {}", message, result.getRecordMetadata().offset()); } @Override public void onFailure(Throwable ex) { LOG.warn("Unable to deliver message [{}]. {}", message, ex.getMessage()); } }); } }
312092b69ca553e4c0b2c3191ee4cff02d7f6f39
[ "Java", "INI" ]
4
INI
eperaza/SpringBoot-Kafka
a097001f4993214fb1531ad31b9fedc7b809aca1
fbfa32fe4fcb87d6c47221258b4c4030d3bbf81b
refs/heads/master
<repo_name>jochasinga/rust-noob<file_sep>/day1/expression/src/main.rs fn main() { // Almost everything in Rust is an expression. // A statement is when you state something without // a return value. For instance, the line below // is a statement printing out the text "Hello, world!" println!("Hello, world!"); // The previous print statement does not return any value // to the main program. It just creates what is known as // a side effect--changing the state of your program. In // this case, it "stream" the text to a software process // known as stdout (standard output) and thus print out // the text on the terminal. // Here is a proof that it is really a statement. // (Comment it when you had enough fun) let greeting = println!("Hola!"); // When you run this code, Rust will warn you about `greeting` // being an unused, wasteful variable. That's because nothing // ever came out of the print statement! // On the contrary, an expression is a statement that DOES // return something. (Yes, an expression is a meaningful statement) // examples would be `1 + 1`, `"Hello"`, `10 / 2`, etc. // Let's try that by creating a variable to accept the returned value... let sum = 1 + 1; // Yes! `sum` has a value. println!("The sum of 1 and 1 is {}", sum); // Oh, and anything beginning with `let` or `const` is not an expression. // It's a completed assignment of an expression to a variable. // The line below is totally impossible, so uncomment to overcome the // compiler's tantrum. let redundant = (let sum = 1 + 1); // In Rust, you put a semicolon (`;`) to end a statement. // An expression, on the other hand, does not need one. } <file_sep>/README.md # rust-noob Learning [Rust](https://www.rust-lang.org/en-US/) as your first language. **note**: [The Rust Book](https://doc.rust-lang.org/book/second-edition/) is also a great learning material. ## What This is intended to be an over-simplified yet comprehensive guide to get anyone with zero programming skill (ok, to be realistic, with little ... like if you're learning Python or JavaScript and already got past functions, you're good to go). Rust isn't for the faint of heart and the impatient, but so is C and C++. Moreover, the latters aren't also for humans. Seriously. Rust is like a strict parent who will seem like inhibiting at first, but that's out of love and for your (program's) safety's sake. Also, Rust has one of the best advices when it comes to throwing errors and warnings, and thus can be very instructive as a first language. ## Why I joined [Recurse Center Summer-2 batch](https://www.rust-lang.org/en-US/), and I'm too excited to think of a focused project at this point. Learning Rust happens to be on my bucket list, and I thought why not just create a public guide so that anyone, even those new to programming, can learn this fabulous, [world's most loved programming language](https://www.rust-lang.org/en-US/)! ## When Ideally, you should be able to finish this guide in under a week and start coding something cool in Rust. The repo is divided into 7 directories for 7 days, all which organize topics and relevant snippets one can normally digest in less than 3 hours each day for one week. ## Who You! ## Setting up If you haven't already, head to [Rust download page](https://www.rust-lang.org/en-US/) to install Rust and Cargo, the awesome package manager. Or, just paste this on your terminal: ```bash curl https://sh.rustup.rs -sSf | sh ``` For editor, anything would do. I'd recommend [Visual Studio Code](https://code.visualstudio.com/download) with Rust extension, which is super simple, light and fast. ## Contributions Very welcome! Take a peak at the [Rust Book](https://doc.rust-lang.org/book/second-edition) for inspiration and order of topics, and just make sure to work on a subsequent day directory (i.e. if `day2` is missing, create the directory and start working on a project that picks up from `day1`. if `day4` exists, but you think a topic should be there, just add it). Use `cargo new --bin <project>` to create a topic project. Here's example: ```bash $ cd day2 $ cargo new functions --bin ``` <file_sep>/day1/variable/src/main.rs fn main() { // `let` keyword declares a new variable. // Rust will warn you about any unused variables you declare. // Below reads "declare variable `name` of (inferred) type `String` and // bind it to the value "Pan". let name = "Pan"; // You can declare a variable without binding to a value, // but Rust cannot infer or "guess" the type for you, and // unlike dynamically-typed languages such as Python or JavaSCript, // it requires all types known to it before compiling. // // Below reads "declare variable `age` of type `i32` (32-bit signed integers) let age: i32; // If you try to use it, Rust will complain about you trying to use an // uninitialized variable. That's fair since you have not given it a value. // So let's bind the variable to a number... age = 19; // Ok, I know that's too low, but this is educational. // Uncomment the two lines below to stop the unused variables warning // println!("{} is the man!", name); //println!("He is about {} years old.", age); // `const` is used when you need a constant value that's around for the // whole lifetime of your program. // To be `const`, you must explicitly annotate the type upfront and bind // the variable to a literal value (value that does not change while the // program is running. // A constant has to follow the C-way of naming variable in all caps. // Normally you'd create a constant for something that is an established // truth or fact, like time (well, Einstein would argue, but he isn't here). const CENTURY: i32 = 100; println!("A century has {} years.", CENTURY); // A constant has the implication that it's never guarantee to be in the // same location in a computer's memory, thus using a pointer to a constant // is a duh and pointless (pun-intended). // All variables in Rust are default to immutable. // Immutability is when you declare a variable, bind a value to it // and can never change that variable again (like what a wine stain does // to your favorite white summer shirt). // let a = 50; // a = 40; // get scolded here! // Immutability is a very important topic in functional programming. // Imagine a program that runs something as serious as an autopilot software // for a real airplane. What happens if a global variable (meaning a variable // that can be accessed from anywhere in a program) is mutable, and some // part of the 1,000,000++ lines of code change that global variable, often // without the programmer's intention. // To create a variable that is mutable, use `mut` keyword. let mut b = 99; b = 10; println!("b equals to {}", b); // Global variables in general are considered bad practice and should be // limited since it makes a program's state unpredictable. } <file_sep>/day1/types/src/main.rs fn main() { // Rust is a strongly-typed language, but you already knew that. // Unlike Python or JavaScript, statically-typed languages need // to know types of value before compiling, or, in layman's term, // running. But that's not really correct... // Rust code (and those in most statically-typed languages) gets // compiled first, then it gets run. // Code in interpreted languages like JavaScript just gets run. // The interpreter, runtime, virtual machine, or whatever runs the // code figures out all the types on the fly, which makes the // your life easier, but to the mercy of the runtime. // Rust can infer type of a variable by looking ahead to figure out the // value binded to that variable, but there will be time when it's // too ambiguous that it asks you to just be explicit. // Here are all the numeric types: // i8 => 8-bit signed integer // u8 => 8-bit unsigned integer // i32 => 32-bit signed integer (usually a good default) // u32 => 32-bit unsigned integer // i64 => 64-bit signed integer // u64 => 64-bit unsigned integer // isize => signed integer with size up to the computer's arch // usize => unsigned integer with size up to the computer's arch // Extra neat thing: underscore is permitted anywhere in a number value // to make reading easier for humans! // explicit type annotation let num_1: i32 = 100_000; // implicit type inferred let num_2 = 200; let diff: i32 = num_1 - num_2; println!("num_1 is {} and num_2 is {}", num_1, num_2); println!("The difference of num_1 and num_2 is {}", diff); // floating-point types (decimal numbers) // f32 => 32-bit floating-point number // f64 => 64-bit floating-point number let num_4: f32 = 3.1416; let num_5 = 91.231801; let sum = num_4 + num_5; println!("num_4 is {} and num_5 is {}", num_4, num_5); println!("The sum of num_4 and num_5 is {}", sum); // boolean type (logical yes/no, true/false) let rainy = false; // We will touch conditions later :) if !rainy { println!("Today is a good day"); } // Rust supports primitive characters by using // a pair of single quotes to wrap the character. let c = 'z'; let z = 'ℤ'; let heart = '❤'; let thai = 'ก'; println!("{} {} {} {}", c, z, heart, thai); // Rust has two primitive compound types: Tuples and Arrays. // Compound types are data types that can group multiple values // of different types together. // This is a tuple... let names = ("Pan", "Jon", "Mindy"); // It can contains different types too let random = ('z', 12.1, "Hello"); // Here is how you access elements in a tuple by its index number. // Index starts at 0, not 1. // i.e. First element in a tuple has an index number of 0. println!("The first name of names is {}", names.0); println!("The second value of random is {}", random.1); // Tuple is crucial to the concept of pattern-matching, which is // a pretty cool programming feature. Basically, pattern-matching // lets you do something like this: let (first, second, third) = names; println!("{}, {}, and {} are coming to the partey!", first, second, third); // Array is a different beast. It requires all values in it to have the // same data type. Array also has fixed length, which means that it can // never shrink or expand. let friends = ["Michelle", "Wesley", "Brennen", "Parker", "Kate"]; // You have a different way to access an element in an array let third_friend = friends[2]; println!("The third friend is {}", third_friend); }
522e31bd514fede24373a55bf6428fef2b7fa216
[ "Markdown", "Rust" ]
4
Rust
jochasinga/rust-noob
4d1d5e397f5e27fa17916517bab253910801ca1e
9722f1cc2408eee29ad9e3d97b0c0b1d0953ff58
refs/heads/master
<file_sep> var list = document.querySelector('.list').childNodes; for (var i = 0; i < list.length; i++) { if (list[i].tagName == 'LI') { list[i].addEventListener('mouseover', function() { this.className = 'underline'; }); list[i].addEventListener('mouseout', function() { this.className = ''; }); } }
086eef2506540f8bd7ca0ccf8d74b6b71c08855a
[ "JavaScript" ]
1
JavaScript
jonzielen/underline
4ee9529b15f43f868bd17e5fcfb1db282996380f
0eae26af0e5edf7af1be45b2ade5f28a14a6f553
refs/heads/main
<repo_name>Stephen-Corcoran/Higher-Order-Functions-Homework-Traveller<file_sep>/README.md # Higher-Order-Functions-Homework-Traveller <file_sep>/models/traveller.js const Traveller = function(journeys) { this.journeys = journeys; }; Traveller.prototype.getJourneyStartLocations = function() { return this.journeys.map((traveller) => { return traveller.startLocation; }) }; Traveller.prototype.getJourneyEndLocations = function () { return this.journeys.map((traveller) => { return traveller.endLocation; }) }; Traveller.prototype.getJourneysByTransport = function (transport) { return this.journeys.filter((traveller) => { return traveller.transport === transport; }) }; Traveller.prototype.getJourneysByMinDistance = function (minDistance) { return this.journeys.filter((traveller) => { return traveller.distance >= minDistance; }); }; Traveller.prototype.calculateTotalDistanceTravelled = function () { return this.journeys.reduce((total, traveller) => { return total += traveller.distance; }, 0); }; Traveller.prototype.getUniqueModesOfTransport = function () { }; module.exports = Traveller;
fc515786778e0ca92a0e378801f54b8dd0d0fc09
[ "Markdown", "JavaScript" ]
2
Markdown
Stephen-Corcoran/Higher-Order-Functions-Homework-Traveller
d33058db49402380ddb7eaf0122974883c8ef7e0
54c82c166e4aede9586893c1029c6b1a60862cba
refs/heads/master
<repo_name>ujjwal1801/Rock-Paper-Scissors<file_sep>/mentor_project.py import random import sys moves = ["rock", "paper", "scissor"] cycle_counter = -1 class Player: no_of_rounds = 0 score = 0 round_move = "" self_move = "" opponent_move = "" class Computer_player_random(Player): def move(self): self.round_move = random.choice(moves) self.no_of_rounds += 1 return self.round_move def remembering(self, human_move, cp_move): self.self_move = cp_move self.opponent_move = human_move class Computer_player_cycle(Player): def move(self): global cycle_counter cycle_counter += 1 if(cycle_counter > 2): cycle_counter = 0 self.round_move = moves[cycle_counter] if(cycle_counter > 2): cycle_counter = 0 self.no_of_rounds += 1 return self.round_move def remembering(self, human_move, cp_move): self.self_move = cp_move self.opponent_move = human_move class Computer_player_imitator(Player): def move(self): if self.no_of_rounds == 0 or self.opponent_move == "": self.round_move = "scissor" else: self.round_move = self.opponent_move self.no_of_rounds += 1 return self.round_move def remembering(self, h_move, cp_move): self.self_move = cp_move if h_move == "rock" or h_move == "paper" or h_move == "scissor": self.opponent_move = h_move else: pass class Computer_player_fixed_move(Player): def move(self): self.round_move = "rock" return self.round_move def remembering(self, human_move, cp_move): self.self_move = cp_move self.opponent_move = human_move class Human_player(Player): def move(self): self.round_move = input("\nEnter your move : ") self.round_move = self.round_move.lower() return self.round_move def remembering(self): pass class Game(): def __init__(self, human_player, opponent_cp): self.human_player = human_player self.opponent_cp = opponent_cp self.match_type() def match_type(self): print("Play a single round?") self.type_of_round = input("\nPlay a match?\n(Round/Match)\n") self.type_of_round = self.type_of_round.lower() if self.type_of_round == "match": i = self.round_type() self.multiple_round(i, self.human_player, self.opponent_cp) elif self.type_of_round == "round": self.single_round(self.human_player, self.opponent_cp) else: print("Wrong input") start = Game(human_player, opponent_cp) def round_type(self): try: diffi = int(input("Enter number of rounds in the match. (3/5/7)")) except ValueError: print("Wrong choice") return self.round_type() else: if(diffi == 3 or diffi == 5 or diffi == 7): return diffi else: print("Wrong choice") return self.round_type() def multiple_round(self, i, human_player, opponent_cp): while(i): human_move = human_player.move() cp_move = opponent_cp.move() flag = result(human_move, cp_move, self.type_of_round) if flag == 0: print("\nENTER AGAIN : \n") self.multiple_round(i, human_player, opponent_cp) i -= 1 human_player.remembering() opponent_cp.remembering(human_move, cp_move) self.print_final_output() def single_round(self, human_player, opponent_cp): human_move = human_player.move() cp_move = opponent_cp.move() flag = result(human_move, cp_move, self.type_of_round) if flag == 0: print("\nENTER AGAIN : \n") self.single_round(human_player, opponent_cp) human_player.remembering() opponent_cp.remembering(human_move, cp_move) self.print_final_output() def print_final_output(self): print("\nFinal Score:\n\nYour score: ", self.human_player.score) print("Computer score: ", self.opponent_cp.score) if(self.human_player.score > self.opponent_cp.score): print("\nCongrats. You win") elif(self.human_player.score < self.opponent_cp.score): print("Hard luck. You lose") else: print("OOPS!! It's a tie") print("*" * 150) sys.exit() def result(mov1, mov2, choice): print("\nComputer chose : ", mov2) if mov1 == mov2: print("That's a tie") elif mov1 == "rock" and mov2 == "scissor": print("You win. ", mov1, "beats", mov2) human_player.score += 1 elif mov1 == "paper" and mov2 == "rock": print("You win. ", mov1, "beats", mov2) human_player.score += 1 elif mov1 == "scissor" and mov2 == "paper": print("You win. ", mov1, "beats", mov2) human_player.score += 1 elif mov1 == "paper" and mov2 == "scissor": print("You lose.", mov2, "beats", mov1) opponent_cp.score += 1 elif mov1 == "scissor" and mov2 == "rock": print("You lose.", mov2, "beats", mov1) opponent_cp.score += 1 elif mov1 == "rock" and mov2 == "paper": print("You lose.", mov2, "beats", mov1) opponent_cp.score += 1 else: print("Wrong Input") return 0 human_player.no_of_rounds += 1 opponent_cp.no_of_rounds += 1 if choice == "match": print("\n\n") # blank print statement for next line to conform to pep8 print("*" * 150) print("Round ", human_player.no_of_rounds, " result:") print("Your score: ", human_player.score) print("\nComputer score: ", opponent_cp.score) print("*" * 150) else: print("*" * 150) print("Final Score:\n\nYour score: ", human_player.score) print("Computer score: ", opponent_cp.score) if(human_player.score > opponent_cp.score): print("\nCongrats. You win") elif(human_player.score < opponent_cp.score): print("Hard luck. You lose") else: print("OOPS!! It's a tie") print("*" * 150) sys.exit() return 1 cp1 = Computer_player_random() cp2 = Computer_player_cycle() cp3 = Computer_player_imitator() cp4 = Computer_player_fixed_move() cp_list = [cp1, cp2, cp3, cp4] opponent_cp = random.choice(cp_list) human_player = Human_player() print("\n--------------Let's play Rock, Paper, Scissor--------------\n") start = Game(human_player, opponent_cp)
73ee675a818dec22f2bbffaf48c402f3a5bf5995
[ "Python" ]
1
Python
ujjwal1801/Rock-Paper-Scissors
7140606f947c4c1b00413fcc8ee3fef586750f4a
405b3896295e11144b7b7aebed225df047e56875
refs/heads/master
<file_sep>const KEY ='<KEY>' map2 = new OpenLayers.Map("mapdiv"); map2.addLayer(new OpenLayers.Layer.OSM()); map2.setCenter([0,0]); function getinfo(){ var location = document.querySelector('#location').value; fetch("https://maps.googleapis.com/maps/api/geocode/json?address="+location+"&key="+KEY). then(result=> result.json()). then(json=>{ lon = json.results[0].geometry.location.lng; lat = json.results[0].geometry.location.lat; var lonLat = new OpenLayers.LonLat( lon ,lat ) .transform( new OpenLayers.Projection("EPSG:4326"), map2.getProjectionObject() ); var zoom=12; var markers = new OpenLayers.Layer.Markers( "Markers" ); map2.addLayer(markers); markers.addMarker(new OpenLayers.Marker(lonLat)); map2.setCenter (lonLat, zoom); console.log("lonlat",lon); }).catch(error=>console.log("ERROR")); } <file_sep><?php $db = "online"; $user = $_POST["users"]; $password = $_POST["<PASSWORD>"]; $host = "localhost"; $conn = mysqli_connect($host,'amra','amra' ,$db); if($conn && !empty($user) && !empty($password)){ $q = "select * from users where users ='$user' and password = <PASSWORD>'"; $result = mysqli_query($conn, $q); if(mysqli_num_rows($result)>0){ echo "<script type='text/javascript'>window.alert('User already exists!'); window.location.href='index.html';</script>"; }else{ $insert = "INSERT INTO users(users, password) VALUES('$user', '$password')"; if(mysqli_query($conn,$insert)){ echo "<script type='text/javascript'>window.alert('Successfully Updated!'); window.location.href='index.html';</script>"; }else{ echo "Error: " . $insert . "" . mysqli_error($conn); } } }else{ echo "<script type='text/javascript'>window.alert('NOT CONNECTED or FIELDS ARE EMPTY!'); window.location.href='index.html';</script>"; } ?><file_sep><?php if(isset($_COOKIE[session_name()])){ setcookie(session_name(),'',time()-86400,'/'); } session_unset(); session_destroy(); header('Location: index.html'); ?><file_sep><?php $db = "online"; $user = $_POST["users"]; $password = $_POST["<PASSWORD>"]; $host = "localhost"; $conn = mysqli_connect($host,'amra','amra' ,$db); if($conn && !empty($user) && !empty($password)){ $q = "select * from users where users like '$user' and password like '$<PASSWORD>'"; $result = mysqli_query($conn, $q); if(mysqli_num_rows($result)>0){ echo"MISSION COMPLETE!"; session_start(); $_SESSION['name'] = $user; header('Location: location.html'); }else{ echo "<script type='text/javascript'>window.alert('Mission Failed!'); window.location.href='index.html';</script>"; } }else{ echo "<script type='text/javascript'>window.alert('NOT CONNECTED or FIELDS ARE EMPTY!'); window.location.href='index.html';</script>"; } ?>
9c161af7ea66c1bd00f7feb78c38fc5685aa264c
[ "JavaScript", "PHP" ]
4
JavaScript
selmamesiic/OpenStreetMap
b834adeb1ea03efc5a6893c09b69d8f4af59d41c
5d9a23b329518ae54212adb573aa1b1552e170c3
refs/heads/master
<file_sep>from model import WordEmbedding from config import config model = WordEmbedding(config.embedding) print("Model loaded!") while True: text = input("Input: ") text = text.lower() if text in ("quit", "q", "exit", "e"): break text = text.split(" ") if len(text) == 2: word1, word2 = text sim = model.model.wv.similarity(word1, word2) print("Similarity between {} and {} is {}".format(word1, word2, sim)) <file_sep>#!/usr/bin/env python from __future__ import print_function, division import argparse, os, sys import re import numpy as np import cv2 as cv import pytesseract import platform import itertools from tqdm import tqdm from config import config from datetime import datetime import engine def say(message): sys.stdout.write(message + "\n") def ask(message): try: return input(message) except KeyboardInterrupt: say("\nBye.") sys.exit(0) def print_board(board, active, clear_screen=True, spymaster=True): if clear_screen: if platform.system() == "Windows": os.system("cls") else: sys.stdout.write(chr(27) + "[2J") for row in range(5): for col in range(5): index = row * 5 + col word = board[index] tag = " " if not active[word]: word = word + "-" * (11 - len(word)) tag = "-" sys.stdout.write("{0}{1:11s} ".format(tag, word)) sys.stdout.write("\n") # TODO: this needs to be piped into engine, not copied and pasted def play_computer_spymaster( engine, player_words, opponent_words, neutral_words, assassin_word, given_clues, gamma=1.0, verbose=True, ): say("Thinking...") sys.stdout.flush() # # Loop over all permutations of words. # num_words = len(player_words) # best_score, saved_clues = [], [] # counts = range(num_words, 0, -1) # groups_and_count = [] # for count in counts: # for group in itertools.combinations(range(num_words), count): # groups_and_count.append((group, count,)) # for group, count in tqdm(groups_and_count): # # Multiply similarity scores by this factor for any clue # # corresponding to this many words. # bonus_factor = count ** gamma # # print(type(player_words), player_words) # words = player_words[list(group)] # clue, score = engine.model.get_clue( # clue_words=words, # pos_words=player_words, # neg_words=np.concatenate((opponent_words, neutral_words)), # veto_words=assassin_word, # ) # if clue: # best_score.append(score * bonus_factor) # saved_clues.append((clue, words)) # num_clues = len(saved_clues) # order = sorted(range(num_clues), key=lambda k: best_score[k], reverse=True) max_group = 2 does_stretch = [2] num_words = len(player_words) best_score, saved_clues = [], [] counts = range(min(num_words, max_group), 0, -1) groups_and_count = [] for count in counts: for group in itertools.combinations(range(num_words), count): groups_and_count.append((group, count,)) groups_and_count = tqdm(groups_and_count) for group, count in groups_and_count: # Multiply similarity scores by this factor for any clue # corresponding to this many words. bonus_factor = count ** gamma words = player_words[list(group)] clue, score, stretch = engine.model.get_clue_stretch( clue_words=words, pos_words=player_words, neg_words=opponent_words, neut_words=neutral_words, veto_words=assassin_word, given_clues=given_clues, give_stretch=(count in does_stretch), ) if clue: best_score.append(score * bonus_factor) clue_words = words if stretch: clue_words = np.concatenate((words, np.asarray(stretch))) saved_clues.append((clue, clue_words)) num_clues = len(saved_clues) order = sorted(range(num_clues), key=lambda k: best_score[k], reverse=True) if not os.path.exists(config.logs_folder): os.makedirs(config.logs_folder) with open(engine.logs_filename, 'a+') as f: for i in order[:10]: clue, words = saved_clues[i] f.write( u"{0:.3f} {2} {3} = {1}\n".format( best_score[i], " + ".join([str(w).upper()[2:-1] for w in words]), str(clue)[2:-1], len(words), ) ) f.write("\n") # print_board(board, active, spymaster=True) values = [] for i in order[:10]: values.append( [saved_clues[i][0], saved_clues[i][1], best_score[i],] ) return values colors = [ (92.5, 66.7, 66.7), (65.9, 84.7, 92.2), (97.3, 99.2, 100.0), (40.8, 42.4, 42.7), ] colors = list([np.uint8(c * 2.55) for c in color[::-1]] for color in colors) color_names = ["red", "blue", "white", "black"] def main(): parser = argparse.ArgumentParser( description="Play the CodeNames game.", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument( "--nohide", type=bool, default=False, help="Shows only 1 clue, hides what the words for each clue", ) args = parser.parse_args() e = engine.GameEngine() # manual init pytesseract.pytesseract.tesseract_cmd = ( r"C:\\Program Files\\Tesseract-OCR\\tesseract.exe" ) config = "-l eng --oem 1 --psm 3" e.size = 5 pad = 20 img = cv.imread("board.png") colors_loc = [[], [], [], []] word_color_map = {} board = [] cx, cy = img.shape[1] // 5, img.shape[0] // 5 for y in range(5): for x in range(5): img_sec = img[ y * cy + pad : (y + 1) * cy - pad, x * cx + pad : (x + 1) * cx - pad ] img_gray = cv.cvtColor(img_sec, cv.COLOR_BGR2GRAY) avg = np.average(img_gray) mask1 = img_gray[:, :] < avg mask2 = img_gray[:, :] > avg img_gray[mask2] = 0 img_gray[mask1] = 255 kernel = np.ones((3, 3), np.uint8) erosion = cv.erode(img_gray, kernel, iterations=1) text = pytesseract.image_to_string(img_sec, config=config).replace(" ", "_") board.append(text) dev = [0, 0, 0, 0] for c in range(3): avg = np.median(img_sec[:, :, c]) for i, color in enumerate(colors): # print(avg, color[c]) dev[i] += (avg - color[c]) ** 2 index, smol = 0, dev[0] if not args.nohide: print("({},{}) -> {}".format(x + 1, y + 1, text)) else: print("({},{}) -> {} = {}".format(x + 1, y + 1, text, dev)) for i in range(1, 4): if dev[i] < smol: smol = dev[i] index = i colors_loc[index].append((x, y,)) word_color_map[text] = color_names[index] # cv.imshow('img', erosion) # cv.imshow('img_pre', img_sec) # cv.waitKey() # play the game active = {} for word in board: active[word] = True input("Loaded successfully! Hit enter to continue: ") print_board(board, active) values = None index = 0 side = "" given_words = [] while True: print_board(board, active) if values: if not args.nohide: clue, words, best_score = values[index] say(u"{3}{0:.3f} {1} {2}".format(best_score, str(clue)[2:-1], len(words), side)) else: for clue, words, best_score in values: say( u"{0:.3f} {2} {3} = {1}".format( best_score, " + ".join([str(w).upper()[2:-1] for w in words]), str(clue)[2:-1], len(words), ) ) text = input().upper() if text in ("EXIT", "QUIT"): return if text in board: active[text] = not active[text] if text in ("USE", "USED"): given_words.append(clue) elif text == "RED" or text == "BLUE": red_words = np.asarray( [ word.lower().encode("utf8") for word in board if active[word] and word_color_map[word] == "red" ] ) blue_words = np.asarray( [ word.lower().encode("utf8") for word in board if active[word] and word_color_map[word] == "blue" ] ) neutral_words = np.asarray( [ word.lower().encode("utf8") for word in board if active[word] and word_color_map[word] == "white" ] ) assassin_word = [ word.lower().encode("utf8") for word in board if active[word] and word_color_map[word] == "black" ] if text == "RED": values = play_computer_spymaster( e, red_words, blue_words, neutral_words, assassin_word, given_words ) side = "red: " else: values = play_computer_spymaster( e, blue_words, red_words, neutral_words, assassin_word, given_words ) side = "blue: " index = 0 elif text == "NEXT": index += 1 if index >= len(values): index -= len(values) elif text == "PREV": index -= 1 if index < 0: index += len(values) if __name__ == "__main__": main() <file_sep>#!/usr/bin/env python #!/usr/bin/env python import argparse import engine import platform import os from tqdm import tqdm import numpy as np HISTOGRAM_WIDTH = 100 class ClueInfo: def __init__(self, clue_count): self.clue_dists = [ [0 for i in range(HISTOGRAM_WIDTH)] for i in range(clue_count + 1) ] self.neutral_dist_max = [0 for i in range(HISTOGRAM_WIDTH)] self.neutral_dist_avg = [0 for i in range(HISTOGRAM_WIDTH)] self.negative_dist_max = [0 for i in range(HISTOGRAM_WIDTH)] self.negative_dist_avg = [0 for i in range(HISTOGRAM_WIDTH)] self.assassin_dist = [0 for i in range(HISTOGRAM_WIDTH)] class Tracker: def __init__(self): self.word_counts = [0 for i in range(9)] self.clue_infos = [ClueInfo(i) for i in range(9)] def add(self, clue, words, e): index = len(words) - 1 self.word_counts[index] += 1 for i, sim in enumerate(get_sims(clue, words, e)): self.clue_infos[index].clue_dists[i][int(sim * HISTOGRAM_WIDTH)] += 1 neutral_sims = get_sims(clue, [str(word)[2:-1] for word in e.neutral_words], e) self.clue_infos[index].neutral_dist_max[ int(neutral_sims[0] * HISTOGRAM_WIDTH) ] += 1 for sim in neutral_sims: self.clue_infos[index].neutral_dist_avg[int(sim * HISTOGRAM_WIDTH)] += 1 negative_sims = get_sims( clue, [str(word)[2:-1] for word in e.opponent_words], e ) self.clue_infos[index].negative_dist_max[ int(negative_sims[0] * HISTOGRAM_WIDTH) ] += 1 for sim in negative_sims: self.clue_infos[index].negative_dist_avg[int(sim * HISTOGRAM_WIDTH)] += 1 assassin_sim = get_sims(clue, [str(e.assassin_word)[3:-2]], e) self.clue_infos[index].assassin_dist[ int(assassin_sim[0] * HISTOGRAM_WIDTH) ] += 1 def size(self): return sum(self.word_counts) def save_to_file(self, filename): with open(filename, "w+") as file: file.write(",".join(str(word) for word in self.word_counts) + "\n") for i in range(9): info = self.clue_infos[i] for j in range(i + 1): file.write( ",".join(str(word) for word in info.clue_dists[j]) + "\n" ) file.write(",".join(str(word) for word in info.neutral_dist_max) + "\n") file.write(",".join(str(word) for word in info.neutral_dist_avg) + "\n") file.write( ",".join(str(word) for word in info.negative_dist_max) + "\n" ) file.write( ",".join(str(word) for word in info.negative_dist_avg) + "\n" ) file.write(",".join(str(word) for word in info.assassin_dist) + "\n") def load_from_file(self, filename): with open(filename, "r") as file: lines = file.readlines()[::-1] self.word_counts = [int(item) for item in lines.pop().strip().split(",")] for i in range(9): info = ClueInfo(i) for j in range(i + 1): info.clue_dists[j] = [ int(item) for item in lines.pop().strip().split(",") ] info.neutral_dist_max = [ int(item) for item in lines.pop().strip().split(",") ] info.neutral_dist_avg = [ int(item) for item in lines.pop().strip().split(",") ] info.negative_dist_max = [ int(item) for item in lines.pop().strip().split(",") ] info.negative_dist_avg = [ int(item) for item in lines.pop().strip().split(",") ] info.assassin_dist = [ int(item) for item in lines.pop().strip().split(",") ] self.clue_infos[i] = info def get_sims(clue, words, e): sims = [] for word in words: sims.append(e.model.model.wv.similarity(clue, word)) for i, sim in enumerate(sims): if sim >= 1.0: sims[i] = 0.995 if sim < 0.0: sims[i] = 0.0 sims.sort(reverse=True) return sims def clear_screen(): if platform.system() == "Windows": os.system("cls") else: sys.stdout.write(chr(27) + "[2J") def main(): parser = argparse.ArgumentParser( description="Benchmark an ai.", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument( "--iters", type=int, default=1000, help="How many games should be generated and tested", ) parser.add_argument( "--seed", type=int, default=100, help="Random seed to have identical matches to benchmark", ) parser.add_argument( "--filename", type=str, default="benchmarks/benchmark.txt", help="Name of file the benchmark gets saved to", ) parser.add_argument( "--writealong", type=bool, default=False, help="Writes to file after every loop" ) parser.add_argument( "--pickup", type=bool, default=False, help="Whether to open the file and pick up", ) args = parser.parse_args() generator = np.random.RandomState(seed=args.seed) e = engine.GameEngine(seed=args.seed, display=False) tracker = Tracker() skip_index = 0 if args.pickup: tracker.load_from_file(args.filename) skip_index = tracker.size() clear_screen() for i in tqdm(range(args.iters)): e.initialize_random_game() e.next_turn() if i % 2 == 0: e.next_turn() if i < skip_index: continue e.print_board(clear_screen=False, override=True) clue, words = e.play_computer_spymaster(give_words=True) tracker.add(str(clue)[2:-1], [str(word)[2:-1] for word in words], e) clear_screen() if args.writealong: tracker.save_to_file(args.filename) print(tracker.word_counts) print("Saving to file...") tracker.save_to_file(args.filename) if __name__ == "__main__": main()
86dabfd05259fcce4fe38e95ffe6e61898e085d9
[ "Python" ]
3
Python
tobias17/CodeNamesOld
10fdccc35b5a23eb68ed5d7e7257e9fe83977278
71e282adf5a652c1bfe48f4035413b9090c4339b
refs/heads/master
<repo_name>susana994/P2_Quiz<file_sep>/cmds.js const model =require('./model'); const {log, biglog, errorlog, colorize} = require("./out"); exports.helpCmd=rl=>{ console.log('Comandos:'); console.log("h|help - Muestra esta ayuda."); console.log("list - Listar los quizzes existentes."); console.log("show <id> - Muestra la pregunta y la respuesta el quiz indicado."); console.log("add - Añadir un nuevo quiz interactivamente."); console.log("delete <id> - Borrar el quiz indicado."); console.log("edit <id> - Editar el quiz indicado"); console.log("test <id> - Probar el quiz indicado"); console.log("p|play - Jugar a preguntar aleatoriamente todos los quizzes."); console.log("credits - Créditos."); console.log("q|quiz - Salir del programa."); rl.prompt(); }; exports.quitCmd=rl=>{ rl.close(); rl.prompt(); }; exports.addCmd=rl=>{ rl.question(colorize('Introduzca una pregunta:','red'), question =>{ rl.question(colorize('Introduzca la respuesta','red'), answer => { model.add(question,answer); log(`${colorize('Se ha añadido','magenta')}: ${question} ${colorize('=>','magenta')} ${answer}`); rl.prompt(); }); }); }; exports.listCmd=rl=>{ model.getAll().forEach((quiz,id) => { log(`[${colorize(id,'magenta')}]: ${quiz.question}` ) ; }); rl.prompt(); }; exports.showCmd=(rl,id)=>{ if(typeof id === "undefined"){ errorlog(`Falta el parámetro id`); } else { try{ const quiz = model.getByIndex(id); log(`[${colorize(id,'magenta')}]: ${quiz.question} ${colorize('=>','magenta')} ${quiz.answer}`); }catch(error){ errorlog(error.message); } } rl.prompt(); }; exports.testCmd=(rl,id)=>{ if(typeof id === "undefined"){ errorlog(`Falta el parámetro id`); } else { try{ const quiz = model.getByIndex(id); rl.question(`${colorize(quiz.question, 'red')}`, answer=>{ const bien = answer.trim(); if(bien==quiz.answer){ log("Su respuesta es correcta"); rl.prompt(); } else{ log("Su respuesta es incorrecta"); rl.prompt(); } }); }catch(error){ errorlog(error.message); rl.prompt(); } } }; exports.playCmd=rl=>{ let score = 0; let contador = model.count(); let toBeResolved=[]; for (i=0; i<model.count(); i++){ toBeResolved[i]=i; } const play = () => { if(contador===0){ rl.prompt(); log(`Fin del juego. Aciertos ${colorize(score,'magenta')}`); } else{ let idaux= Math.round(Math.random()*(toBeResolved.length -1)); let id= toBeResolved[idaux]; let quiz = model.getByIndex(id); toBeResolved.splice(idaux,1); contador --; rl.question(`${colorize(quiz.question, 'red')}`, answer=>{ const bien = answer.trim(); if(bien===quiz.answer){ score++; log(`Su respuesta es correcta Aciertos ${colorize(score,'magenta')}`); play(); } else{ log(`Su respuesta es incorrecta. Fin del juego. Aciertos ${colorize(score,'magenta')}`); rl.prompt(); } }); } }; play(); }; exports.deleteCmd=(rl,id)=>{ if(typeof id === "undefined"){ errorlog(`falta el parametro id`); } else { try{ model.deleteByIndex(id); }catch(error){ errorlog(error.message); } } rl.prompt(); }; exports.editCmd=(rl,id)=>{ if(typeof id === "undefined"){ errorlog(`Falta el parametro id`); rl.prompt(); } else { try{ const quiz = model.getByIndex(id); process.stdout.isTTY && setTimeout(() => {rl.write(quiz.question)}, 0); rl.question(colorize('Introduzca una pregunta: ', 'red'), question=>{ process.stdout.isTTY && setTimeout(() => {rl.write(quiz.answer)}, 0); rl.question(colorize('Introduzca una respuesta: ', 'red'),answer=>{ model.update(id,question,answer); log(`se ha cambiado el quiz ${colorize(id,'magenta')}por: ${question} `); rl.prompt(); }); }); }catch(error){ errorlog(error.message); rl.prompt(); }} }; exports.creditsCmd=rl=>{ console.log("Autores de la practica:"); console.log('nombre 1: susana994'); console.log('nombre 2'); rl.prompt(); };
b7b075c5a2dfb11eec97d48cda9fd65a252563be
[ "JavaScript" ]
1
JavaScript
susana994/P2_Quiz
27c7bb5f25c5f9e71abc31cbf2d2e5f6789930ad
455c3c3dc565901aa04e57589baca76ec6c0664e
refs/heads/master
<repo_name>aysenuryildiz/testRepo<file_sep>/Localization/Updater.cs using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Localization { public static class Updater { private static string programUrl = "https://raw.githubusercontent.com/aysenuryildiz/testrepo/master/newVer"; public static int check() { try { string version = getVersion(); var result = checkVersion(version); //surumu kontrol et return result; } catch (Exception e) { Console.WriteLine(e); throw; } } private static int checkVersion(string version) { try { using (System.Net.WebClient client = new System.Net.WebClient()) { var localVersion = version.Split('.'); ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; int localMajor = Convert.ToInt32(localVersion[0]); int localMinor = Convert.ToInt32(localVersion[1]); int localRelease = Convert.ToInt32(localVersion[2]); int localBuild = Convert.ToInt32(localVersion[3]); int newMajor; int newMinor; int newRelease; int newBuild; string strNewVersion = client.DownloadString(programUrl); //remote txt içeriğine eriş strNewVersion = strNewVersion.Replace("\n", String.Empty); var newVersion = strNewVersion.Split('.'); newMajor = Convert.ToInt32(newVersion[0]); newMinor = Convert.ToInt32(newVersion[1]); var released = newVersion[2].Split(';'); newRelease = Convert.ToInt32(released[0]); newBuild = Convert.ToInt32(released[1]); var isUpdateRequired = Convert.ToInt32(newBuild); var majorAyniMi = newMajor.Equals(localMajor); var minorAyniMi = newMinor.Equals(localMinor); var releaseAyniMi = newRelease.Equals(localRelease); var buildAyniMi = newBuild.Equals(localBuild); if (majorAyniMi) { //major aynı büyük değişiklik yok if (newBuild == 1 && localBuild == 0) { return 1; } else { if (!minorAyniMi) { return 1; } else if (!releaseAyniMi) { return 1; } } } if (!majorAyniMi) { return 1; } } return 2; } catch (Exception e) { Console.WriteLine(e); throw; } } private static string getVersion() { try { string version = ""; var versionFilePath = getVersionFilePath(); using (System.IO.StreamReader file = new System.IO.StreamReader(versionFilePath)) version = file.ReadToEnd(); return version; } catch (Exception e) { Console.WriteLine(e); throw; } } public static string getVersionFilePath() { try { var versionFilePath = Application.StartupPath + "\\version.txt"; return versionFilePath; } catch (Exception e) { Console.WriteLine(e); throw; } } } } <file_sep>/Localization/FUpdater.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Localization { public partial class FUpdater : Form { private string programUrl = "https://github.com/aysenuryildiz/testrepo/blob/master/localization_setup.msi?raw=true"; private string exeName = "switchpro.msi"; private string downloadsPath = ""; public FUpdater() { InitializeComponent(); setText(); downloadsPath = System.IO.Path.GetTempPath(); this.Shown += FUpdater_Shown; } private void setText() { try { this.lblProgress.Text = Localization.lblProgress; } catch (Exception e) { Console.WriteLine(e); throw; } } private void FUpdater_Shown(object sender, EventArgs e) { try { downloadFile(programUrl, downloadsPath + exeName); } catch (Exception exception) { Console.WriteLine(exception); throw; } } private void downloadFile(string urlAddress, string location) { try { using (var client = new WebClient()) { client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged); client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); client.DownloadFileAsync(new Uri(urlAddress), location); } } catch (Exception e) { Console.WriteLine(e); throw; } } void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { try { double bytesIn = double.Parse(e.BytesReceived.ToString()); double totalBytes = double.Parse(e.TotalBytesToReceive.ToString()); double percentage = bytesIn / totalBytes * 100; progressBar.Value = int.Parse(Math.Truncate(percentage).ToString()); } catch (Exception exception) { Console.WriteLine(exception); throw; } } void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { try { var msiFilePath = downloadsPath + exeName; var result = RunInstallMSI(msiFilePath, exeName); //System.Diagnostics.Process.Start(msiFilePath); Application.Exit(); } catch (Exception exception) { Console.WriteLine(exception); throw; } } public static bool RunInstallMSI(string path, string fileName) { try { Process install = new Process(); install.StartInfo.FileName = "msiexec"; //install.StartInfo.Arguments = string.Format("/i \"{0}\"", path); install.StartInfo.Arguments = string.Format(" /qb /i \"{0}\" ALLUSERS=1", path); install.Start(); install.WaitForExit(); return true; } catch(Exception exc) { Console.WriteLine(exc.Message); return false; //Return False if process ended unsuccessfully } } } } <file_sep>/Localization/Form1.cs using Localization.Properties; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Localization { public partial class Form1 : Form { public Form1() { InitializeComponent(); var cultureInfo = System.Globalization.CultureInfo.CurrentCulture; var lang = cultureInfo.Name; Localization.Culture = new CultureInfo(lang); writeText(); } private void writeText() { lblUsername.Text = Localization.lblUsername; lblPassword.Text = Localization.lblPassword; btnSelectLang.Text = Localization.btnSelectLang; } private void button1_Click(object sender, EventArgs e) { Localization.Culture = new CultureInfo("en-US"); writeText(); } } } <file_sep>/Localization/Program.cs using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using System.Windows.Forms; namespace Localization { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); saveVersion(); var result = Updater.check(); switch (result) { case 1: Application.Run(new FUpdater()); break; case 2: Application.Run(new Form1()); break; } } private static void saveVersion() { try { Assembly assembly = Assembly.GetExecutingAssembly(); FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location); string productVersion = fileVersionInfo.ProductVersion; File.WriteAllText(Updater.getVersionFilePath(), productVersion); } catch (Exception e) { Console.WriteLine(e); throw; } } } }
90892d2b429c4096b67f7b70376135036f1fb3f9
[ "C#" ]
4
C#
aysenuryildiz/testRepo
29484ed03a3d739d33da26128585921448f35515
45a153321a8776d4a1b84366a90625edfe6604ec
refs/heads/master
<repo_name>SaySai/coolweather<file_sep>/app/src/main/java/com/example/isay/coolweather/util/HttpCallbackListener.java package com.example.isay.coolweather.util; /** * Created by isay on 1/31/2016. */ public interface HttpCallbackListener { void onFinish(String response); void onError(Exception e); }
3d87dccd1c38fd966038a6a4bb5294d222843e79
[ "Java" ]
1
Java
SaySai/coolweather
ba50841022ccd13bef8548bbecdd620f41409413
bc02177fbdee804c67c718d9f36597a68fd56d91
refs/heads/master
<repo_name>tk-ozawa/ph22_work02<file_sep>/func/input_func.php <?php session_start(); // 連想配列の全ての要素に値が格納されているかを検証する関数 function isset_array($array_asso) { // $array_asso:連想配列 // 要素をすべて参照する foreach ($array_asso as $key => $value) { // 要素が1つでも空だった場合、falseを戻す if (!empty($value)) { return false; } } return true; } // エラーコードを格納する連想配列 $err = array('name' => '', 'tell' => '', 'mail' => ''); // 入力情報を格納する連想配列 $prof = array('name' => '', 'tell' => '', 'mail' => ''); if (!empty($_SESSION['prof'])) { // profにSessionの値(name,tell,mail)を格納 $prof = $_SESSION['prof']; // SESSION破棄 $_SESSION = array(); if (isset($_COOKIE[session_name()])) { setcookie(session_name(), '', time()-42000); } session_destroy(); } // 別ページからinput.phpにアクセスした際、SESSIONの中身をprofで引き継ぎ、SESSIONを破棄。 if (!empty($_GET)) { // 氏名未入力チェック if (empty($_GET['name'])) { $err['name'] = "氏名が入力されていません。"; } else { $prof['name'] = $_GET['name']; } // TEl数値チェック if (!is_numeric($_GET['tell'])) { $err['tell'] = "電話番号に数値以外の文字が入力されています。"; } // TEL桁数チェック(TELは9~12桁まで) elseif (strlen($_GET['tell']) < 9 || 12 < strlen($_GET['tell'])) { $err['tell'] = "電話番号は9~12桁までです"; } // TEl未入力チェック if (empty($_GET['tell'])) { $err['tell'] = "電話番号が入力されていません。"; } else { $prof['tell'] = $_GET['tell']; } // メール@チェック(@の有無の確認) if (!strpos($_GET['mail'],'@')) { $err['mail'] = "メールに@がありません。"; } // メール未入力チェック if (empty($_GET['mail'])) { $err['mail'] = "メールが入力されていません。"; } else { $prof['mail'] = $_GET['mail']; } // 全ての入力値内にあるhtmlタグをエスケープコードに変換した物をprofに代入 foreach($prof as $key => $value) { $prof[$key] = htmlspecialchars($value, ENT_QUOTES); } // errの全てに値が入っていない=入力値が全て正常だった場合それらをSessionに格納し、次のページ(confirm.php)へ飛ぶ if (isset_array($err)) { // isset_array:自作関数 $_SESSION['prof'] = $prof; header('Location: confirm.php'); exit(); } } ?> <file_sep>/html/confirm.php <?php require_once '../func/confirm_func.php'; ?> <!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>確認画面</title> <meta content="タイトル" name="title"> <link rel="stylesheet" href="../css/reset.css"> <link rel="stylesheet" href="../css/style.css"> <script src="./js/jquery-1.12.0.min.js" charset="utf-8"></script> <!--[if It IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script> <![endif]--> <script src="sample.js"></script> </head> <body> <table border="0px"> <tr> <th>氏名</th> <td><?php echo $prof['name']; ?></td> </tr> <tr> <th>TEL</th> <td><?php echo $prof['tell']; ?></td> </tr> <tr> <th>メール</th> <td><?php echo $prof['mail']; ?></td> </tr> <tr> <td><a href="./table.php">登録</a></td> <td colspan="2"><a href="./input.php">戻る</a></td> <tr> </table> <script src="./js/main.js" charset="utf-8"></script> </body> </html> <file_sep>/func/tabel_func.php <?php if (file_exists(CSV_PATH)) { // CSVファイルが存在しているか確認 if ($csv_pt = fopen(CSV_PATH, "rb")) { // CSVファイルのファイルポインタを取得(読み込みモードでファイルを開く) $list = file(CSV_PATH); // CSVファイルを読み込み $count = sizeof($list); // CSVの行数を取得(末尾が空白の時はカウントしない) $data_disp = NULL; // 出力用2次元配列を初期化 // CSVが1行以上ある時、CSVのデータをdata_dispに格納 if (0 < $count) { // CSVの全ての要素を取得し、出力用2次元配列$data_dispに格納 // CSVを1行ずつ参照&配列に格納する $data_disp = array(); $j = 0; foreach ($list as $line) { // $lineに1行ずつ格納 $data_disp[$j] = explode(',', $line); // $lineをカンマで分割し配列$dataに格納 // エスケープ用文字を通常文字に戻す $data_disp[$j][1] = str_replace('&commma', ',',$data_disp[$j][1]); $data_disp[$j][3] = str_replace('&commma', ',',$data_disp[$j][3]); $j++; } } fclose($csv_pt); } else { $error_disp = $error['101']; } } else { $error_disp = $error['100']; } ?> <file_sep>/func/error.php <?php $error = array( '100' => 'エラー:ファイルが存在しません。', '101' => 'エラー:ファイルが開けません。', '102' => 'エラー:投稿に失敗しました。' ); ?> <file_sep>/func/confirm_func.php <?php session_start(); // 出力情報を格納する連想配列prof $prof = array('name' => '', 'tell' => '', 'mail' => ''); // Session内の連想配列をprofに代入 if (!empty($_SESSION['prof'])) { $prof = $_SESSION['prof']; } ?> <file_sep>/func/subscribe.php <?php session_start(); $error_disp = ''; // CSV書き込みエラーメッセージ用変数error_messageを初期化 // Sessionが有効のままtable.phpに遷移した時、Session['prof']をローカル変数buffに格納, ローカル変数をCSVに登録 if (!empty($_SESSION['prof'])) { $buff = $_SESSION['prof']; // 不要となったSessionを破棄する $_SESSION = array(); if (isset($_COOKIE[session_name()])) { setcookie(session_name(), '', time()-42000); } session_destroy(); if (file_exists(CSV_PATH)) { // CSVファイルが存在しているか確認 if ($csv_pt = fopen(CSV_PATH, 'a')) { // CSVファイルのファイルポインタを取得(上書きモードでファイルを開く) if (flock($csv_pt, LOCK_SH)) { // CSVファイルを共有ロック $list = file(CSV_PATH); // CSVファイルを読み込み $count = sizeof($list); // CSVファイル内の行数をカウント $id_max = 0; // CSVが空じゃない($count>0)の時、id_maxにidの最大値+1を代入 if (0 < $count) { // CSV内のIDの最大値を取得 $data_refer = array(); $i = 0; foreach ($list as $line) { // $lineにCSVのデータを1行ずつ格納 $data_refer[$i] = explode(',', $line); // $lineをカンマで分割し配列$dataに格納 // idの最大値が更新された時、$id_maxに格納 if ($id_max < $data_refer[$i][0]) { $id_max = $data_refer[$i][0]; } $i++; } $id_max+=1; } // 以下、CSVに$prof内の3要素(氏名, TEL, メール)を登録する工程 // 氏名, メールアドレス内のカンマを&commmaでエスケープ(csvは','で要素を区切っている為) $buff['name'] = str_replace(',', '&commma', $buff['name']); $buff['mail'] =str_replace(',', '&commma', $buff['mail']); // 登録用の配列registerに上記で取得したIDの最大値+1と3要素(name,tell,mail)を順にセットし、最後尾を改行コードで〆 $register = array($id_max,$buff['name'],$buff['tell'],$buff['mail']); $register = implode(',', $register); // 要素間に','をセット $register .= "\n"; // CSVの最終行(最新)に登録用配列を要素別にセット(書き込めなかった場合はerror_messageにエラーメッセージを格納) if(!fwrite($csv_pt, $register)) { $error_disp = $error['102']; } flock($csv_pt, LOCK_UN); // ファイルのロックを解放 } fclose($csv_pt); } else { $error_disp = $error['101']; } } else { $error_disp = $error['100']; } } ?> <file_sep>/html/table.php <?php // CSVファイルを指定 define('CSV_PATH', "../csv/table.csv"); require_once '../func/error.php'; require_once '../func/subscribe.php'; require_once '../func/tabel_func.php'; ?> <!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>テーブル画面</title> <meta content="タイトル" name="title"> <link rel="stylesheet" href="../css/reset.css"> <link rel="stylesheet" href="../css/style.css"> <script src="./js/jquery-1.12.0.min.js" charset="utf-8"></script> <!--[if It IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script> <![endif]--> <script src="sample.js"></script> </head> <body> <?php echo $error_disp; ?> <table border="0px"> <tr> <th>氏名</th> <th>TEL</th> <th>メール</th> </tr> <?php for ($i = 0; $i < count($data_disp); $i++) {?> <tr> <?php for ($j = 1; $j < count($data_disp[$i]); $j++) { ?> <td><?php echo $data_disp[$i][$j]; ?></td> <?php } ?> </tr> <?php } ?> <tr> <td colspan="3"><a href="./input.php">戻る</a></td> </tr> </table> <script src="./js/main.js" charset="utf-8"></script> </body> </html>
b715423b10366b10c771276c81b95b460073db15
[ "PHP" ]
7
PHP
tk-ozawa/ph22_work02
fd55e90501ac0973042f4a37f790d5d5bc344b9a
c5ab1459cd48eab56727e763ee76f4d5c5c84ac2
refs/heads/master
<file_sep>function Replacer(){} Replacer.prototype.replaceWord = function(originalSentence, word, newWord){ newSentence = originalSentence.replace(word, newWord) newS = newSentence.split('').filter(dollar => dollar != '$').join('') return newS } <file_sep># dictionary-replacer ***Screenshots*** ![dictionary](./screenshots/dictionary.png)
42126d4d4e619e45fdc5dec55b311218aa204f4a
[ "JavaScript", "Markdown" ]
2
JavaScript
alexserg1/dictionary-replacer
69503c8155567380da34060c73194ca74337ed01
84778f7e76022870e8b1a6ed07b286afc8188b06
refs/heads/master
<file_sep>package cmd import ( "kool-dev/kool/cmd/shell" "os" "github.com/spf13/cobra" ) // ExecFlags holds the flags for the start command type ExecFlags struct { DisableTty bool EnvVariables []string Detach bool } var execCmd = &cobra.Command{ Use: "exec [options] [service] [command]", Short: "Execute a command within a running service container", Args: cobra.MinimumNArgs(2), Run: runExec, } var execFlags = &ExecFlags{false, []string{}, false} func init() { rootCmd.AddCommand(execCmd) execCmd.Flags().BoolVarP(&execFlags.DisableTty, "disable-tty", "T", false, "Disables TTY") execCmd.Flags().StringArrayVarP(&execFlags.EnvVariables, "env", "e", []string{}, "Environment variables") execCmd.Flags().BoolVarP(&execFlags.Detach, "detach", "d", false, "Detached mode: Run command in the background") //After a non-flag arg, stop parsing flags execCmd.Flags().SetInterspersed(false) } func runExec(cmd *cobra.Command, args []string) { var service string = args[0] dockerComposeExec(service, args[1:]...) } func dockerComposeExec(service string, command ...string) { var ( err error args []string ) args = []string{"exec"} if disableTty := os.Getenv("KOOL_TTY_DISABLE"); execFlags.DisableTty || disableTty == "1" || disableTty == "true" { args = append(args, "-T") } if asuser := os.Getenv("KOOL_ASUSER"); asuser != "" { args = append(args, "--user", asuser) } if len(execFlags.EnvVariables) > 0 { for _, envVar := range execFlags.EnvVariables { args = append(args, "--env", envVar) } } if execFlags.Detach { args = append(args, "--detach") } args = append(args, service) args = append(args, command...) err = shell.Interactive("docker-compose", args...) if err != nil { execError("", err) os.Exit(1) } } <file_sep>package cmd import ( "kool-dev/kool/cmd/shell" "os" "strconv" "github.com/spf13/cobra" ) // LogsFlags holds the flags for the logs command type LogsFlags struct { Tail int Follow bool } var logsCmd = &cobra.Command{ Use: "logs [options] [service...]", Short: "Displays log output from services.", Run: runLogs, } var logsFlags = &LogsFlags{25, false} func init() { rootCmd.AddCommand(logsCmd) logsCmd.Flags().IntVarP(&logsFlags.Tail, "tail", "t", 25, "Number of lines to show from the end of the logs for each container. For value equal to 0, all lines will be shown.") logsCmd.Flags().BoolVarP(&logsFlags.Follow, "follow", "f", false, "Follow log output.") } func runLogs(cmd *cobra.Command, originalArgs []string) { var args []string = []string{"logs"} if logsFlags.Tail == 0 { args = append(args, "--tail", "all") } else { args = append(args, "--tail", strconv.Itoa(logsFlags.Tail)) } if logsFlags.Follow { args = append(args, "--follow") } args = append(args, originalArgs...) err := shell.Interactive("docker-compose", args...) if err != nil { execError("", err) os.Exit(1) } } <file_sep>package cmd import ( "kool-dev/kool/cmd/shell" "os" "github.com/spf13/cobra" ) // StopFlags holds the flags for the stop command type StopFlags struct { Purge bool } var stopCmd = &cobra.Command{ Use: "stop", Short: "Stop kool environment containers", Run: runStop, } var stopFlags = &StopFlags{false} func init() { rootCmd.AddCommand(stopCmd) stopCmd.Flags().BoolVarP(&stopFlags.Purge, "purge", "", false, "Remove all persistent data from containers") } func runStop(cmd *cobra.Command, args []string) { checkKoolDependencies() stopContainers(stopFlags.Purge) } func stopContainers(purge bool) { var ( args []string err error ) args = []string{"down"} if purge { args = append(args, "--volumes", "--remove-orphans") } err = shell.Interactive("docker-compose", args...) if err != nil { execError("", err) os.Exit(1) } } <file_sep>package cmd import ( "fmt" "io/ioutil" "kool-dev/kool/cmd/shell" "os" "path" "strings" "github.com/google/shlex" "github.com/spf13/cobra" "gopkg.in/yaml.v2" ) // KoolYaml holds the structure for parsing the custom commands file type KoolYaml struct { Scripts map[string]interface{} `yaml:"scripts"` } var runCmd = &cobra.Command{ Use: "run [SCRIPT]", Short: "Runs a custom command defined at kool.yaml in the working directory or in the kool folder of the user's home directory", Args: cobra.MinimumNArgs(1), Run: runRun, } func init() { rootCmd.AddCommand(runCmd) // after a non-flag arg, stop parsing flags runCmd.Flags().SetInterspersed(false) } func runRun(cmd *cobra.Command, args []string) { var ( err error script string ) script = args[0] commands := parseCustomCommandsScript(script) if len(args) > 1 && len(commands) > 1 { fmt.Println("Error: you cannot pass in extra arguments to multiple commands scripts.") os.Exit(2) } for _, exec := range commands { var execArgs = exec[1:] if len(commands) == 1 { // single command - forward extra args execArgs = append(execArgs, args[1:]...) } err = shell.Interactive(exec[0], execArgs...) if err != nil { execError("", err) os.Exit(1) } } } func getKoolScriptsFilePath(rootPath string) (filePath string) { var err error if _, err = os.Stat(path.Join(rootPath, "kool.yml")); !os.IsNotExist(err) { filePath = path.Join(rootPath, "kool.yml") } else if _, err = os.Stat(path.Join(rootPath, "kool.yaml")); !os.IsNotExist(err) { filePath = path.Join(rootPath, "kool.yaml") } return } func getKoolContent(filePath string) (*KoolYaml, error) { file, err := os.OpenFile(filePath, os.O_RDONLY, os.ModePerm) if err != nil { return nil, err } defer file.Close() yml, err := ioutil.ReadAll(file) if err != nil { return nil, err } var parsed *KoolYaml = new(KoolYaml) err = yaml.Unmarshal(yml, parsed) return parsed, err } func parseCustomCommandsScript(script string) (parsedCommands [][]string) { var ( err error projectFileName, globalFileName string parsed, projectParsed, globalParsed *KoolYaml foundProject, foundGlobal, isRunningGlobal bool ) projectFileName = getKoolScriptsFilePath(os.Getenv("PWD")) globalFileName = getKoolScriptsFilePath(path.Join(os.Getenv("HOME"), "kool")) if projectFileName == "" && globalFileName == "" { fmt.Println("Could not find kool.yml either in the current working directory or in the user's home directory.") os.Exit(2) } if projectFileName != "" { projectParsed, err = getKoolContent(projectFileName) if err != nil { fmt.Println("Failed to parse", projectFileName, ":", err) } } if globalFileName != "" { globalParsed, err = getKoolContent(globalFileName) if err != nil { fmt.Println("Failed to parse", globalFileName, ":", err) } } if projectParsed != nil { _, foundProject = projectParsed.Scripts[script] } if globalParsed != nil { _, foundGlobal = globalParsed.Scripts[script] } if !foundProject && !foundGlobal { fmt.Println("Could not find script", script, " either in the current working directory or in the user's home directory.") os.Exit(2) } if foundProject { parsed = projectParsed } else { parsed = globalParsed isRunningGlobal = true } if singleCommand, isSingleString := parsed.Scripts[script].(string); isSingleString { parsedCommands = append(parsedCommands, parseCustomCommand(singleCommand)) } else if commands, isList := parsed.Scripts[script].([]interface{}); isList { for _, line := range commands { parsedCommands = append(parsedCommands, parseCustomCommand(line.(string))) } } else { fmt.Println("Could not parse script with key", script, ": it must be either a single command or an array of commands. Please refer to the documentation.") os.Exit(2) } if !isRunningGlobal && foundGlobal { fmt.Println("Found a global script, but running the one in the working directory.") } return } func parseCustomCommand(line string) (parsed []string) { var err error parsed, err = shlex.Split(line) if err != nil { fmt.Println("Failed parsing custom command:", line, err) os.Exit(1) } for i := range parsed { for _, env := range os.Environ() { envPair := strings.SplitN(env, "=", 2) parsed[i] = strings.ReplaceAll(parsed[i], "$"+envPair[0], envPair[1]) } } return } <file_sep>package shell import ( "io" "os" ) // InputRedirect holds the key to indicate the right part // of the command expression is meant to be the Stdin // for the whole left part. const InputRedirect string = "<" // OutputRedirect holds the key to indicate the output from // the left part of the command up to this key is meant to be // written to the destiny pointed by the right part. const OutputRedirect string = ">" // OutputRedirectAppend holds the key to indicate the output from // the left part of the command up to this key is meant to be // written in append mode to the destiny pointed by the right part. const OutputRedirectAppend string = ">>" func parseRedirects(originalArgs []string) ( args []string, in io.ReadCloser, out io.WriteCloser, closeStdin bool, closeStdout bool, err error) { var numArgs int args = originalArgs if numArgs = len(args); numArgs < 2 { in = os.Stdin out = os.Stdout return } in = os.Stdin out = os.Stdout // check the before-last position of the command // for some redirect key and properly handle them. switch args[numArgs-2] { case InputRedirect: { if in, err = os.OpenFile(args[numArgs-1], os.O_RDONLY, os.ModePerm); err != nil { return } closeStdin = true } case OutputRedirect, OutputRedirectAppend: { var mode int = os.O_CREATE | os.O_WRONLY if args[numArgs-2] == OutputRedirectAppend { mode |= os.O_APPEND } else { mode |= os.O_TRUNC } if out, err = os.OpenFile(args[numArgs-1], mode, os.ModePerm); err != nil { return } closeStdout = true } } if closeStdin || closeStdout { // fix arguments removing the redirect args = args[:numArgs-2] } return } <file_sep>package cmd import ( "kool-dev/kool/cmd/shell" "kool-dev/kool/environment" "os" "strings" "github.com/spf13/cobra" ) // DockerFlags holds the flags for the docker command type DockerFlags struct { DisableTty bool EnvVariables []string Volumes []string Publish []string } var dockerCmd = &cobra.Command{ Use: "docker [options] [image] [command]", Args: cobra.MinimumNArgs(1), Run: runDocker, Short: "Creates a new container and runs the command in it.", Long: `This command acts as a helper for docker run. You can start with options that go before the image name for docker run itself, i.e --env='VAR=VALUE'. Then you must pass the image name and the command you want to execute on that image.`, } var dockerFlags = &DockerFlags{false, []string{}, []string{}, []string{}} func init() { rootCmd.AddCommand(dockerCmd) dockerCmd.Flags().BoolVarP(&dockerFlags.DisableTty, "disable-tty", "T", false, "Disables TTY") dockerCmd.Flags().StringArrayVarP(&dockerFlags.EnvVariables, "env", "e", []string{}, "Environment variables") dockerCmd.Flags().StringArrayVarP(&dockerFlags.Volumes, "volume", "v", []string{}, "Bind mount a volume") dockerCmd.Flags().StringArrayVarP(&dockerFlags.Publish, "publish", "p", []string{}, "Publish a container’s port(s) to the host") //After a non-flag arg, stop parsing flags dockerCmd.Flags().SetInterspersed(false) } func runDocker(docker *cobra.Command, args []string) { image := args[0] command := args[1:] execDockerRun(image, command) } func execDockerRun(image string, command []string) { var ( args []string err error workDir string ) workDir, _ = os.Getwd() args = []string{"run", "--init", "--rm", "-w", "/app"} if !dockerFlags.DisableTty && !environment.IsTrue("KOOL_TTY_DISABLE") { args = append(args, "-ti") } if asuser := os.Getenv("KOOL_ASUSER"); asuser != "" && (strings.HasPrefix(image, "kooldev") || strings.HasPrefix(image, "fireworkweb")) { args = append(args, "--env", "ASUSER="+asuser) } if len(dockerFlags.EnvVariables) > 0 { for _, envVar := range dockerFlags.EnvVariables { args = append(args, "--env", envVar) } } args = append(args, "--volume", workDir+":/app:delegated") if len(dockerFlags.Volumes) > 0 { for _, volume := range dockerFlags.Volumes { args = append(args, "--volume", volume) } } if len(dockerFlags.Publish) > 0 { for _, publish := range dockerFlags.Publish { args = append(args, "--publish", publish) } } args = append(args, image) args = append(args, command...) err = shell.Interactive("docker", args...) if err != nil { execError("", err) os.Exit(1) } } <file_sep>package cmd import ( "fmt" "kool-dev/kool/cmd/shell" "os" "strings" "github.com/jedib0t/go-pretty/v6/table" "github.com/spf13/cobra" ) func init() { rootCmd.AddCommand(statusCmd) } var statusCmd = &cobra.Command{ Use: "status", Short: "Shows the status for containers", Run: runStatus, } func runStatus(cmd *cobra.Command, args []string) { checkKoolDependencies() handleGlobalNetwork() statusDisplayServices() } type statusService struct { service, state, ports string running bool } func statusDisplayServices() { out, err := shell.Exec("docker-compose", "ps", "--services") if err != nil { fmt.Println("No services found.") return } parsedServices := strings.Split(strings.Replace(out, "\r\n", "\n", -1), "\n") services := []string{} for _, s := range parsedServices { if s != "" { services = append(services, s) } } if len(services) == 0 { fmt.Println("No services found.") return } chStatus := make(chan *statusService, len(services)) for _, service := range services { go func(service string, ch chan *statusService) { ss := &statusService{service: service} out, err = shell.Exec("docker-compose", "ps", "-q", service) if err != nil { execError(out, err) os.Exit(1) } if out != "" { out, err = shell.Exec("docker", "ps", "-a", "--filter", "ID="+out, "--format", "{{.Status}}|{{.Ports}}") containerInfo := strings.Split(out, "|") ss.running = strings.HasPrefix(containerInfo[0], "Up") ss.state = containerInfo[0] if len(containerInfo) > 1 { ss.ports = containerInfo[1] } } ch <- ss }(service, chStatus) } var i, l int = 0, len(services) status := make([]*statusService, l) for ss := range chStatus { status[i] = ss if i == l-1 { close(chStatus) break } i++ } t := table.NewWriter() t.SetOutputMirror(os.Stdout) t.AppendHeader(table.Row{"Service", "Running", "Ports", "State"}) for _, s := range status { running := "Not running" if s.running { running = "Running" } t.AppendRow([]interface{}{s.service, running, s.ports, s.state}) } t.Render() } <file_sep># kool [![Go Report Card](https://goreportcard.com/badge/github.com/kool-dev/kool)](https://goreportcard.com/report/github.com/kool-dev/kool) ![Docker Hub](https://github.com/kool-dev/kool/workflows/docker/badge.svg) ![Golang CI Lint](https://github.com/kool-dev/kool/workflows/golangci-lint/badge.svg) [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fkool-dev%2Fkool.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Fkool-dev%2Fkool?ref=badge_shield) ### Development workspaces made easy Dev environment made easy, a standardized way for running applications no matter the stack on your local machine and deploying it to a development environment. Run any stack / tool with any version, powered by Docker and Docker Compose in a simple way avoiding you to install lots of stuff on your machine. Have the same feeling working on multiple projects with different stacks. ## Documentation Full documentation at **https://kool.dev/docs** or at [docs/](docs/). ## Demo <a href="https://www.youtube.com/watch?v=c4LonyQkFEI" target="_blank" title="Click to see full demo"> <img src="https://user-images.githubusercontent.com/347400/87970968-fad10c80-ca9a-11ea-9bef-a88400b01f2c.png" alt="kool - demo" style="max-width:100%;"> </a> ## Installation Kool is powered by [Docker](https://docs.docker.com/get-docker/) and [Docker Compose](https://docs.docker.com/compose/install/), you need to have it installed on your machine. The run the follow script to install `kool` bin in your machine. ```bash curl -fsSL https://raw.githubusercontent.com/kool-dev/kool/master/install.sh | bash ``` In case you need sudo: ```bash curl -fsSL https://raw.githubusercontent.com/kool-dev/kool/master/install.sh | sudo bash ``` ## For Windows Download the installer [here](https://github.com/kool-dev/kool/releases) ## Usage To help learning how to use kool we've built presets with good starting point for some popular stacks, feel free to open a PR in case you miss one. ### Presets - [Adonis](docs/2-resets/Adonis.md) - [Laravel](docs/2-Presets/Laravel.md) - [NextJS](docs/2-Presets/NestJS.md) - [NextJS](docs/2-Presets/NextJS.md) - [NuxtJS](docs/2-Presets/NuxtJS.md) - [NuxtJS](docs/2-Presets/Symfony.md) ### Examples You can see projects using it here: https://github.com/kool-dev/examples ## Contributing Like what you see? You are most welcome to contribute! We are working in a backlog of issues, feel free to browse through and enter discussions or get to work! The flow is not written in stone, so you may go ahead and fork, code and PR with clear and direct communication on the feature/improvement or fix you developed. PS: our main pain point at this moment is the lack of testing. Might be a great starting point. ### Lint Before submitting a PR make sure to run `fmt` and linters. ```bash kool run lint ``` ### Updating commands signature documentation The Cobra library offers a simple solution for getting markdown documentation for usage of its commands. In order to generate update the generated markdown files do as follow: ```bash kool run make-docs git add . git commit -m "Updated commands docs" ``` ## Security If you find security issue please let us know ahead of making it public like in an issue so we can take action as soon as possible. Please email the concern to `<EMAIL>`. ## License The MIT License (MIT). Please see [License File](LICENSE.md) for more information. [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fkool-dev%2Fkool.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Fkool-dev%2Fkool?ref=badge_large)<file_sep>package cmd // auto generated file var presets = make(map[string]map[string]string) //nolint <file_sep>package cmd import ( "fmt" "kool-dev/kool/cmd/shell" "os" "os/exec" ) func checkKoolDependencies() { var err error if _, err = exec.LookPath("docker"); err != nil { execError("Docker doesn't seem to be installed, install it first and retry.", err) os.Exit(1) } if _, err = exec.LookPath("docker-compose"); err != nil { execError("Docker-compose doesn't seem to be installed, install it first and retry.", err) os.Exit(1) } if _, err = shell.Exec("docker", "info"); err != nil { execError("Docker daemon doesn't seem to be running, run it first and retry.", err) os.Exit(1) } } func execError(out string, err error) { if err != nil { fmt.Println("ERROR:", err) } if out != "" { fmt.Println("Output:", out) } } <file_sep>package cmd import ( "fmt" "os" "github.com/spf13/cobra" ) // InitFlags holds the flags for the init command type InitFlags struct { Override bool } var initCmd = &cobra.Command{ Use: "init [PRESET]", Short: "Initialize kool preset in the current working directory", Args: cobra.ExactArgs(1), Run: runInit, } var initFlags = &InitFlags{false} func init() { rootCmd.AddCommand(initCmd) initCmd.Flags().BoolVarP(&initFlags.Override, "override", "", false, "Force replace local existing files with the preset files") } func runInit(cmd *cobra.Command, args []string) { var ( presetFiles map[string]string exists, hasExistingFile bool preset, fileName, fileContent string err error file *os.File wrote int ) preset = args[0] if presetFiles, exists = presets[preset]; !exists { fmt.Println("Unknown preset", preset) os.Exit(2) } fmt.Println("Preset", preset, "is initializing!") for fileName = range presetFiles { if !initFlags.Override { if _, err = os.Stat(fileName); !os.IsNotExist(err) { fmt.Println(" Preset file", fileName, "already exists.") hasExistingFile = true } } } if hasExistingFile { fmt.Println("Some preset files already exist. In case you wanna override them, use --override.") os.Exit(2) } for fileName, fileContent = range presetFiles { file, err = os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm) if err != nil { fmt.Println(" Failed to create preset file", fileName, "due to error:", err) os.Exit(2) } if wrote, err = file.Write([]byte(fileContent)); err != nil { fmt.Println(" Failed to write preset file", fileName, "due to error:", err) os.Exit(2) } if len([]byte(fileContent)) != wrote { fmt.Println(" Failed to write preset file", fileName, " - failed to write all bytes:", wrote) os.Exit(2) } if err = file.Sync(); err != nil { fmt.Println(" Failed to sync preset file", fileName, "due to error:", err) os.Exit(2) } file.Close() fmt.Println(" Preset file", fileName, "created.") } fmt.Println("Preset ", preset, " initialized!") } <file_sep>package cmd import ( "fmt" "kool-dev/kool/cmd/shell" "log" "os" "strings" "github.com/spf13/cobra" ) // StartFlags holds the flags for the start command type StartFlags struct { Services string } var startCmd = &cobra.Command{ Use: "start", Short: "Start Kool environment containers", Run: runStart, } var startFlags = &StartFlags{""} func init() { rootCmd.AddCommand(startCmd) startCmd.Flags().StringVarP(&startFlags.Services, "services", "", "", "Specific services to be started") } func runStart(cmd *cobra.Command, args []string) { checkKoolDependencies() handleGlobalNetwork() startContainers(startFlags.Services) } func handleGlobalNetwork() { networkID, err := shell.Exec("docker", "network", "ls", "-q", "-f", fmt.Sprintf("NAME=^%s$", os.Getenv("KOOL_GLOBAL_NETWORK"))) if err != nil { log.Fatal(err) } if networkID != "" { return } err = shell.Interactive("docker", "network", "create", "--attachable", os.Getenv("KOOL_GLOBAL_NETWORK")) if err != nil { log.Fatal(err) } } func startContainers(services string) { var ( args []string err error ) args = []string{"up", "-d", "--force-recreate"} if services != "" { args = append(args, strings.Split(services, " ")...) } err = shell.Interactive("docker-compose", args...) if err != nil { execError("", err) os.Exit(1) } }
1f36894d732f8b2cdbc57acd8497253a0741e256
[ "Markdown", "Go" ]
12
Go
tiagoguirado/kool
be55be0b08f61edbd2eea5ce6839ceeb3815eb26
c5b04354f5deb279d88a2eff75f6444cd9cf409b
refs/heads/master
<repo_name>Kaneki711/haa<file_sep>/README.md *Scroll down for more* : *Installation Instructions* Installation is simple. It can be installed from pip using the following command: ```sh $ python -m pip install -r requirements.txt ``` *Usage Instructions* ```python >>> from LineAPI.linepy import * >>> client = LINE("") >>> client.log("Auth Token : " + str(line.authToken)) ``` ## *BIG THX TO :* ## Author <NAME> / [@Alin](https://line.me/t/p/~muhmursalind) ## Author Linepy <NAME> / [@fadhiilrachman](https://www.instagram.com/fadhiilrachman) ## Contact Me At ![logo](3403923.png) [Here](https://line.me/ti/p/~yapuy) <file_sep>/puck.py # -*- coding: utf-8 -*- # 「 From Helloworldd / Edited by Puy 」 " # ID : yapuy from PUY.linepy import * from PUY.akad.ttypes import Message from PUY.akad.ttypes import ContentType as Type from time import sleep from datetime import datetime, timedelta from googletrans import Translator from bs4 import BeautifulSoup from humanfriendly import format_timespan, format_size, format_number, format_length import time, random, sys, json, codecs, subprocess, threading, glob, re, string, os, requests, six, ast, pytz, urllib, urllib3, urllib.parse, traceback, atexit #puy = LINE() #puy = LINE("<KEY> # UNTUK LOGIN TOKEN # puy = LINE("<KEY> #puy = LINE('','') # UNTUK LOGIN MAIL LINE # puyMid = puy.profile.mid puyProfile = puy.getProfile() puySettings = puy.getSettings() puyPoll = OEPoll(puy) #pi = LINE() #pi = LINE("<KEY> #piMid = pi.profile.mid #piProfile = pi.getProfile() #piSettings = pi.getSettings() #piPoll = OEPoll(pi) botStart = time.time() msg_dict = {} qrprotect = [] inviteprotect = [] protect = [] cancelprotect = [] Bots = [puy] Creator = ["<KEY>"] Owner = ["<KEY>"] Admin = ["<KEY>"] #unsendOpen = codecs.open("unsend.json","r","utf-8") settings = { "autoJoin": True, "autoLeave": False, "autoRead": False, "Inroom": True, "autoAdd": False, "Outroom": True, "detectMention": True, "autoJoinTicket": True, "detectUnsend": False, "autoAddMessage": "@!, Thx for add", "autoJoinMessage": "@!, makasih sudah invite saya", "autoResponMessage": "Hey @!, Don't Tag.", "reread": True, "responMention": True, "addSticker": { "name": "", "status": False }, "blacklist": {}, "timeRestart": "18000", "changeGroupPicture": [], "limit": 50, "limits": 50, "wordban": [], "crashMention": True, "autoRespon": True, "keyCommand": "", "myProfile": { "displayName": "", "coverId": "", "pictureStatus": "", "statusMessage": "" }, "setKey": False, "unsendMessage": True } message = { "replyPesan": "Don't tag me,It's annoying." } cctv = { "cyduk":{}, "point":{}, "sidermem":{} } read = { "ROM": {}, "readPoint": {}, "readMember": {}, "readTime": {} } try: with open("Log_data.json","r",encoding="utf_8_sig") as f: msg_dict = json.loads(f.read()) #with open("Log_data.json","r",encoding="utf_8_sig") as f: # msg_dict = json.loads(f.unsend()) with open("sticker.json","r") as f: stickers = json.loads(f) for sticker in stickers: if text.lower() == sticker: sid = stickers[sticker]["STKID"] spkg = stickers[sticker]["STKPKGID"] sver = stickers[sticker]["STKVER"] puy.sendSticker(to, sver, spkg, sid) except: print("PUY") settings["myProfile"]["displayName"] = puyProfile.displayName settings["myProfile"]["statusMessage"] = puyProfile.statusMessage settings["myProfile"]["pictureStatus"] = puyProfile.pictureStatus coverId = puy.getProfileDetail()["result"]["objectId"] settings["myProfile"]["coverId"] = coverId def restartBot(): print ("[ INFO ] BOT RESTART") python = sys.executable os.execl(python, python, *sys.argv) def autoRestart(): if time.time() - botStart > int(settings["timeRestart"]): time.sleep(5) restartBot() def getRecentMessages(self, messageBox, count): return self.Talk.puy.getRecentMessages(messageBox.id, count) def unsendMessage(self, messageId): self._unsendMessageReq += 1 return self.talk.unsendMessage(self._unsendMessageReq, messageId) def sendMentionFooter(to, text="", mids=[]): arrData = "" arr = [] mention = "@Meka Finee " if mids == []: raise Exception("Invalid mids") if "@!" in text: if text.count("@!") != len(mids): raise Exception("Invalid mids") texts = text.split("@!") textx = "" for mid in mids: textx += str(texts[mids.index(mid)]) slen = len(textx) elen = len(textx) + 15 arrData = {'S':str(slen), 'E':str(elen - 4), 'M':mid} arr.append(arrData) textx += mention textx += str(texts[len(mids)]) else: textx = "" slen = len(textx) elen = len(textx) + 15 arrData = {'S':str(slen), 'E':str(elen - 4), 'M':mids[0]} arr.append(arrData) textx += mention + str(text) puy.sendMessage(to, textx, {'AGENT_NAME':'@Muh.khadaffy on Instagram', 'AGENT_LINK': 'https://www.instagram.com/muh.khadaffy', 'AGENT_ICON': "http://dl.profile.line-cdn.net/" + puy.getProfile().picturePath, 'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0) #'AGENT_LINK': 'line://ti/p/~{}'.format(puy.getProfile().userid), def backupData(): try: backup = read f = codecs.open('read.json','w','utf-8') json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False) # backup = unsend # f = codecs.open('unsend.json','w','utf-8') # json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False) return True except Exception as error: logError(error) return False def sendMentionV2(to, text="", mids=[]): arrData = "" arr = [] mention = "@zeroxyuuki " if mids == []: raise Exception("Invalid mids") if "@!" in text: if text.count("@!") != len(mids): raise Exception("Invalid mids") texts = text.split("@!") textx = "" for mid in mids: textx += str(texts[mids.index(mid)]) slen = len(textx) elen = len(textx) + 15 arrData = {'S':str(slen), 'E':str(elen - 4), 'M':mid} arr.append(arrData) textx += mention textx += str(texts[len(mids)]) else: textx = "" slen = len(textx) elen = len(textx) + 15 arrData = {'S':str(slen), 'E':str(elen - 4), 'M':mids[0]} arr.append(arrData) textx += mention + str(text) puy.sendMessage(to, textx, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0) def siderMembers(to, mid): arrData = "" textx = "Sider User\nHii ".format(str(len(mid))) arr = [] no = 1 num = 2 for i in mid: mention = "@x\n" slen = str(len(textx)) elen = str(len(textx) + len(mention) - 1) arrData = {'S':slen, 'E':elen, 'M':i} arr.append(arrData) textx += mention+settings["mention"] if no < len(mid): no += 1 textx += "%i. " % (num) num=(num+1) else: try: no = "\n╚══[ {} ]".format(str(puy.getGroup(to).name)) except: no = "\n╚══[ Success ]" puy.sendMessage(to, textx, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0) def sendMessageWithFooter(to, text, name, url, iconlink): contentMetadata = { 'AGENT_NAME': name, 'AGENT_LINK': url, 'AGENT_ICON': iconlink } return puy.sendMessage(to, text, contentMetadata, 0) def sendMessageWithFooter(to, text): puy.reissueUserTicket() dap = puy.getProfile() ticket = "http://line.me/ti/p/"+puy.getUserTicket().id pict = "http://dl.profile.line-cdn.net/"+dap.pictureStatus name = dap.displayName dapi = {"AGENT_ICON": pict, "AGENT_NAME": name, "AGENT_LINK": ticket } puy.sendMessage(to, text, contentMetadata=dapi) def sendMessageWithContent(to, name, link, url, iconlink): contentMetadata = { 'AGENT_NAME': name, 'AGENT_LINK': url, 'AGENT_ICON': iconlink } return self.sendMessage(to, text, contentMetadata, 0) def logError(text): puy.log("[ ERROR ] {}".format(str(text))) tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) timeHours = datetime.strftime(timeNow,"(%H:%M)") day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] inihari = datetime.now(tz=tz) hr = inihari.strftime('%A') bln = inihari.strftime('%m') for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] time = "{}, {} - {} - {} | {}".format(str(hasil), str(inihari.strftime('%d')), str(bln), str(inihari.strftime('%Y')), str(inihari.strftime('%H:%M:%S'))) with open("logError.txt","a") as error: error.write("\n[ {} ] {}".format(str(time), text)) def cTime_to_datetime(unixtime): return datetime.fromtimestamp(int(str(unixtime)[:len(str(unixtime))-3])) def dt_to_str(dt): return dt.strftime('%H:%M:%S') def delete_log(): ndt = datetime.now() for data in msg_dict: if (datetime.utcnow() - cTime_to_datetime(msg_dict[data]["createdTime"])) > timedelta(1): if "path" in msg_dict[data]: puy.deleteFile(msg_dict[data]["path"]) del msg_dict[data] def sendMention(to, text="", mids=[]): arrData = "" arr = [] mention = "@zeroxyuuki " if mids == []: raise Exception("Invalid mids") if "@!" in text: if text.count("@!") != len(mids): raise Exception("Invalid mids") texts = text.split("@!") textx = "" for mid in mids: textx += str(texts[mids.index(mid)]) slen = len(textx) elen = len(textx) + 15 arrData = {'S':str(slen), 'E':str(elen - 4), 'M':mid} arr.append(arrData) textx += mention textx += str(texts[len(mids)]) else: textx = "" slen = len(textx) elen = len(textx) + 15 arrData = {'S':str(slen), 'E':str(elen - 4), 'M':mids[0]} arr.append(arrData) textx += mention + str(text) puy.sendMessage(to, textx, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0) def command(text): pesan = text.lower() if settings["setKey"] == True: if pesan.startswith(settings["keyCommand"]): cmd = pesan.replace(settings["keyCommand"],"") else: cmd = "Undefined command" else: cmd = text.lower() return cmd def helpmessage(): if settings['setKey'] == True: key = settings['keyCommand'] else: key = '' helpMessage = "\n 「 PUY 」 " + "\n" + \ "1) " + key + "About puy " + "\n" + \ "2) " + key + "HelpMedia" + "\n" + \ "3) " + key + "Token" + "\n\n" + \ " 「 CEKSIDER & MENTION 」" + "\n" + \ "4) " + key + "Ceksider On/Off - [For SetRead]" + "\n" + \ "5) " + key + "Ceksider reset - [For Reset reader point]" + "\n" + \ "6) " + key + "Ceksider - [For Ceksider]" + "\n\n" + \ " 「 Owner Commands 」" + "\n" + \ " " + key + "Keluar" + "\n" + \ " " + key + "Bc:" + "\n" + \ " " + key + "Prefix" + "\n" + \ " " + key + "Prefix on" + "\n" + \ " " + key + "Prefix off" + "\n" + \ " " + key + "Logout" + "\n" + \ " " + key + "Perbarui" + "\n" + \ " " + key + "SetAutoAdd:" + "\n" + \ " " + key + "SetPrefix:" + "\n" + \ " " + key + "SetAutoJoin:" + "\n" + \ " " + key + "SetAutoReply" + "\n\n" + \ " 「Use " + key + " For the Prefix」" + "\n" + \ " 「From Helloworld / Edited by Puy」" + "\n" + \ "~「Creator : @!」" return helpMessage def helpmedia(): if settings['setKey'] == True: key = settings['keyCommand'] else: key = '' helpMedia = "\n 「 MEDIA 」 " + "\n" + \ "7) " + key + "InstaInfo (Username)" + "\n" + \ "8) " + key + "InstaStory (Username*number)" + "\nExam :" + key +"Instastory muh.khadaffy*1\n" + \ "9) " + key + "Quotes" + "\n" + \ "10) " + key + "Carigambar (text)" + "\n" + \ "11) " + key + "CariMusik (text)" + "\n" + \ "12) " + key + "CariLirik (text)" + "\n" + \ "13) " + key + "DoujinSearch (text)" + "\n" + \ "14) " + key + "YoutubeSearch (text)" + "\n\n" + \ " 「Use " + key + " For the Prefix」" + "\n" + \ "~「Creator : @!」" return helpMedia def puyBot(op): try: if op.type == 0: print ("[ 0 ] END OF OPERATION") return if op.type == 5: print ("[ 5 ] NOTIFIED ADD CONTACT") if settings["autoAdd"] == True: puy.findAndAddContactsByMid(op.param1) puy.sendMessage(op.param1, settings["autoAddMessage"], [op.param1]) #if op.type == 13: # print ("[ 13 ] NOTIFIED INVITE INTO GROUP") # #if settings["autoJoin"] and puyMid in op.param3: # if settings["autoJoin"] == True: # puy.acceptGroupInvitation(op.param1) # puy.sendMessage(op.param1, settings["autoJoinMessage"], [op.param2]) if op.type == 13: print ("[ 13 ] INVITE INTO GROUP") if puyMid in op.param3: if settings["autoJoin"] == True: dan = puy.getContact(op.param2) tgb = puy.getGroup(op.param1) puy.acceptGroupInvitation(op.param1) sendMention(op.param1, "@!, Thx for invited Me".format(str(tgb.name)),[op.param2]) #puy.sendImageWithURL(op.param1, "http://dl.profile.line-cdn.net{}".format(dan.picturePath)) #if op.type == 13: # print ("[ 13 ] NOTIFIED INVITE INTO GROUP") # if settings["autoJoin"] == True: # gidd = puy.getGroup(op.param1) #puy.sendMessage(op.param1, "[ Nama Group ]\n" + gid.name) # puy.acceptGroupInvitation(op.param1) # puy.sendMessage(op.param1, "EN : Thanks for invite me to group\nID : Terimakasi sudah mengundang saya ke grup\n\nType .help for See a Commands") #dap.sendMessage(op.param1, "Thx for invited me\n help for more") if op.type == 19: print ("[ 19 ] NOTIFIED KICKOUT FROM GROUP") group = puy.getGroup(op.param1) contact = puy.getContact(op.param2) victim = puy.getContact(op.param3) dap = " Group Name : {}".format(str(group.name)) dapp = "\n Executor : {}".format(str(contact.displayName)) dappp = "\n Victim : {}".format(str(victim.displayName)) puy.sendMessage(op.param1, "「 Notify Kickout From Group 」\n\nPelaku Kick : {}\nK{}".format(str(contact.displayName),"orban Kick : {}".format(str(victim.displayName)))) puy.sendContact(op.param1, op.param2) puy.sendContact(op.param1, op.param3) print (dap) if op.type in [22, 24]: print ("[ 22 And 24 ] NOTIFIED INVITE INTO ROOM & NOTIFIED LEAVE ROOM") if settings["autoLeave"] == True: dan = puy.getContact(op.param2) tgb = puy.getGroup(op.param1) sendMention(op.param2, "@! hmm?", [sender]) puy.leaveRoom(op.param1) if op.type == 26: try: print ("[ 25 ] SEND MESSAGE") msg = op.message text = msg.text msg_id = msg.id receiver = msg.to sender = msg._from setKey = settings["keyCommand"].title() if settings["setKey"] == False: setKey = '' if msg.toType == 0 or msg.toType == 1 or msg.toType == 2: if msg.toType == 0: if sender != puy.profile.mid: to = sender else: to = receiver elif msg.toType == 1: to = receiver elif msg.toType == 2: to = receiver if msg.contentType == 0: if text is None: return else: cmd = command(text) if cmd == "help": helpMessage = helpmessage() poey = "uac8e3eaf1eb2a55770bf10c3b2357c33" creator = puy.getContact(poey) #puy.sendMessage(to, str(helpMessage),{'AGENT_ICON':'http://dl.profile.line-cdn.net/0h-uTmd0A5clppFF8EVusNDVVRfDceOnQSEXppOktDLW4RIDcMAXA4aUQTfmMTLT1YACFvNUwXfz8W','AGENT_LINK':'https://line.me/ti/p/~yapuy','AGENT_NAME':'Help Message'}) sendMention(to, str(helpMessage), [poey]) #sendMention(to, str(helpMessage), "@!", [mid]) #sendMention(sender, "Creator\n@!", (str(helpMessage), [sender])) #sendMention(sender, mid, [sender]) #sendMention(to, 'Creator : '+ac+'puy', (str(helpMessage), [sender])) if cmd == "helpmedia": helpMedia = helpmedia() poeyy = "uac8e3eaf1eb2a55770bf10c3b2357c33" creator = puy.getContact(poeyy) sendMention(to, str(helpMedia), [poeyy]) elif cmd == "token generator": sendMentionFooter(to, "「 TOKEN TIPE 」\n1* DESKTOPWIN\n2* WIN10\n3* DESKTOPMAC\n4* IOSPAD\n5* CHROME\n\n*Usage : Type #login with Token Type\n\n*Example : #login chrome\n\n[ From BotEater / Edited by Puy ]\n@! - Selamat Mencoba.", [sender]) elif cmd == "#token": sendMentionFooter(to, "「 TOKEN TIPE 」\n1* DESKTOPWIN\n2* WIN10\n3* DESKTOPMAC\n4* IOSPAD\n5* CHROME\n\n*Usage : Type #login with Token Type\n\n*Example : #login chrome\n\n[ From BotEater / Edited by Puy ]\n@! - Selamat Mencoba.", [sender]) elif cmd == "speed": start = time.time() puy.sendMessage(to, "...") elapsed_time = time.time() - start puy.sendMessage(to, "[ Speed ]\nKecepatan mengirim pesan {} detik puy".format(str(elapsed_time))) elif cmd == "logout": if sender in Owner: puy.sendMessage(to, "PUY telah dimatikan") sys.exit("[ INFO ] BOT SHUTDOWN") return elif cmd == "perbarui": if sender in Owner: tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] Timed = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" #if msg.to not in read['readPoint']: #dap.sendMessage(msg.to, "「 NOTIFIED BOT SPEED 」\n\n" + Timed) #sendMention(to, "@! \nPUY berhasil diperbarui.\n\nPada :\n" + Timed, [sender]) puy.sendMessage(to, "PUY berhasil diperbarui.\n\nPada :\n" + Timed) restartBot() else: puy.sendMessage("Permission Denied") elif cmd.startswith("spamcall"): if sender in Owner: if msg.toType == 2: group = puy.getGroup(to) members = [mem.mid for mem in group.members] jmlh = int(settings["limit"]) puy.sendMessage(msg.to, "Invitation Call Groups {} In Progress ".format(str(settings["limit"]))) if jmlh <= 9999: for x in range(jmlh): try: puy.inviteIntoGroupCall(to, contactIds=members) except Exception as e: puy.sendMessage(msg.to,str(e)) else: puy.sendMessage(msg.to,"Invitation Call Groups Successed") elif cmd[:15] == "pengagumrahasia": name = cmd[16:] r = requests.get("http://planetbiru.com/ramalan/ramalan-pengagum/?nama="+name).content data =BeautifulSoup(r, 'html5lib');tgb="[ Pengagum Rahasia {} ]\n\n".format(name);numz=[0, 1,2,3,4] num = [dan for dan in data.findAll('div', {'class':'pmeter'})] jdl = [wil for wil in data.findAll('div', {'class':'plabel'})] for numm in numz: tgb += "{} [ {} ]\n".format(jdl[numm].text, num[numm].text.replace("\n","")) tgb+="\n[ Finish ]" sendMessageWithFooter(to, str(tgb)) elif cmd == "me": contact = puy.getContact(sender) sendMentionFooter(to, "At here @!", [sender]) puy.sendContact(to, sender) puy.sendImageWithURL(to,"http://dl.profile.line-cdn.net/{}".format(contact.pictureStatus)) elif cmd == "autojoin on": if msg._from in Owner: settings["autoJoin"] = True sendMention(to, "[ Notified Auto Join ]\nBerhasil mengaktifkan Auto Join @!", [sender]) elif cmd == "autojoin off": if msg._from in Owner: settings["autoJoin"] = False sendMention(to, "[ Notified Auto Join ]\nBerhasil menonaktifkan Auto Join @!", [sender]) elif cmd == "autoread on": if msg._from in Owner: settings["autoRead"] = True sendMention(to, "[ Notified Auto Join ]\nBerhasil mengaktifkan Auto Read @!", [sender]) elif cmd == "autoread off": if msg._from in Owner: settings["autoRead"] = False sendMention(to, "[ Notified Auto Join ]\nBerhasil menonaktifkan Auto Read @!", [sender]) elif cmd == "replymention on": settings["responMention"] = True sendMention(to, "[ Notified Auto Leave ]\nBerhasil mengaktifkan responMention @!", [sender]) elif cmd == "replymention off": if msg._from in Owner: settings["responMention"] = False sendMention(to, "[ Notified Auto Leave ]\nBerhasil menonaktifkan responMention @!", [sender]) elif cmd == "detectunsend on": if msg._from in Owner: settings["detectUnsend"] = True sendMention(to, "[ Notified Detect Unsend ]\nBerhasil mengaktifkan Detect Unsend\n@!", [sender]) elif cmd == "detectunsend off": if msg._from in Owner: settings["detectUnsend"] = False sendMention(to, "[ Notified Detect Unsend ]\nBerhasil menonaktifkan Detect Unsend\n@!", [sender]) elif cmd == "autoleave on": if msg._from in Owner: settings["autoLeave"] = True sendMention(to, "[ Notified Auto Leave ]\nBerhasil mengaktifkan Auto leave @!", [sender]) elif cmd == "autoleave off": if msg._from in Owner: settings["autoLeave"] = False sendMention(to, "[ Notified Auto Leave ]\nBerhasil menonaktifkan Auto leave @!", [sender]) elif cmd == "status": try: ret_ = "\n PUY STATUS" if settings["autoJoin"] == True: ret_ += "\n [ ON ] Auto Join" else: ret_ += "\n [ OFF ] Auto Join" if settings["autoRead"] == True: ret_ += "\n [ ON ] Auto Read" else: ret_ += "\n [ OFF ] Auto Read" if settings["detectUnsend"] == True: ret_ += "\n [ ON ] Detect Unsend" else: ret_ += "\n [ OFF ] Detect Unsend" if settings["detectUnsend"] == True: ret_ += "\n [ ON ] Detect Unsend" else: ret_ += "\n [ OFF ] Detect Unsend" if settings["responMention"] == True: ret_ += "\n [ ON ] ReplyMention" else: ret_ += "\n [ OFF ] ReplyMention" if settings["autoLeave"] == True: ret_ += "\n [ ON ] Auto Leave Room" else: ret_ += "\n [ OFF ] Auto Leave Room" ret_ +="\n Add Friends Messages : {}".format(settings["autoAddMessage"]) ret_ +="\n Join Groups Messages : {}".format(settings["autoJoinMessage"]) ret_ +="\n Auto Reply Mention : {}".format(settings["autoResponMessage"]) sendMessageWithFooter(to, str(ret_)) except Exception as e: sendMessageWithFooter(to, str(e)) ## LURKING ## elif text.lower() == '#ceksider on': tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to in read['readPoint']: try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to] except: pass read['readPoint'][msg.to] = msg.id read['readMember'][msg.to] = "" read['readTime'][msg.to] = datetime.now().strftime('%H:%M:%S') read['ROM'][msg.to] = {} with open('read.json', 'w') as fp: json.dump(read, fp, sort_keys=True, indent=4) puy.sendMessage(to, "「 Ceksider Diaktifkan 」\n\nWaktu :\n" + readTime) else: try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to] except: pass read['readPoint'][msg.to] = msg.id read['readMember'][msg.to] = "" read['readTime'][msg.to] = datetime.now().strftime('%H:%M:%S') read['ROM'][msg.to] = {} with open('read.json', 'w') as fp: json.dump(read, fp, sort_keys=True, indent=4) #sendMention(to, "@!\n「 Ceksider Diaktifkan 」\n" + readTime, [sender]) puy.sendMessage(to, "「 Ceksider Diaktifkan 」\n\n" + readTime) elif text.lower() == '#ceksider off': tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to not in read['readPoint']: #sendMention(to, "「 Ceksider telah dimatikan 」\n@!\nWaktu :\n" + readTime, [sender]) puy.sendMessage(to, "「 Ceksider telah dimatikan 」\n\nWaktu :\n" + readTime) else: try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to] except: pass #sendMention(to, "「 Ceksider telah dimatikan 」\n@!\n" + readTime, [sender]) puy.sendMessage(to, "「 Ceksider telah dimatikan 」\n\n" + readTime) elif text.lower() == '#ceksider reset': tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to in read["readPoint"]: try: del read["readPoint"][msg.to] del read["readMember"][msg.to] del read["readTime"][msg.to] except: pass #sendMention(to, "「 Mengulangi riwayat pembaca 」 :\n@!\n" + readTime, [sender]) puy.sendMessage(to, "「 Ceksider telah direset 」\n\n" + readTime) else: #sendMention(to, "「 Ceksider belum diaktifkan 」\n@!", [sender]) puy.sendMessage(to, "「 Ceksider telah direset 」\n\n" + readTime) elif text.lower() == '#ceksider': tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if receiver in read['readPoint']: if read["ROM"][receiver].items() == []: puy.sendMessage(receiver," 「 Daftar Pembaca 」\nNone") else: chiya = [] for rom in read["ROM"][receiver].items(): chiya.append(rom[1]) cmem = puy.getContacts(chiya) zx = "" zxc = "" zx2 = [] xpesan = ' 「 Daftar Pembaca 」\n\n' for x in range(len(cmem)): xname = str(cmem[x].displayName) pesan = '' pesan2 = pesan+"@c\n" xlen = str(len(zxc)+len(xpesan)) xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1) zx = {'S':xlen, 'E':xlen2, 'M':cmem[x].mid} zx2.append(zx) zxc += pesan2 text = xpesan+ zxc + "\n[ Waktu ] : \n" + readTime try: puy.sendMessage(receiver, text, contentMetadata={'MENTION':str('{"MENTIONEES":'+json.dumps(zx2).replace(' ','')+'}')}, contentType=0) except Exception as error: print (error) pass else: puy.sendMessage(receiver,"*Ceksider belum diaktifkan\nKetik 「 #ceksider on 」 untuk mengaktifkan.") elif text.lower() == '#lurking': tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if receiver in read['readPoint']: if read["ROM"][receiver].items() == []: puy.sendMessage(receiver,"[ Reader ]:\nNone") else: chiya = [] for rom in read["ROM"][receiver].items(): chiya.append(rom[1]) cmem = puy.getContacts(chiya) zx = "" zxc = "" zx2 = [] xpesan = ' 「 Daftar Pembaca 」\n\n' for x in range(len(cmem)): xname = str(cmem[x].displayName) pesan = '' pesan2 = pesan+"@c\n" xlen = str(len(zxc)+len(xpesan)) xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1) zx = {'S':xlen, 'E':xlen2, 'M':cmem[x].mid} zx2.append(zx) zxc += pesan2 text = xpesan+ zxc + "\n[ Waktu ] : \n" + readTime try: puy.sendMessage(receiver, text, contentMetadata={'MENTION':str('{"MENTIONEES":'+json.dumps(zx2).replace(' ','')+'}')}, contentType=0) except Exception as error: print (error) pass else: #sendMention(receiver,"*Ceksider belum diaktifkan\nKetik 「 #ceksider on 」 untuk mengaktifkan\n@!") puy.sendMessage(receiver,"*Ceksider belum diaktifkan\nKetik 「 #ceksider on 」 untuk mengaktifkan.") elif cmd.startswith("keluar"): #tgb = puy.getGroup(op.param1) #dan = puy.getContact(op.param2) #gid = puy.getGroup(to) puy.sendMessage(to, "Gbye") #sendMentionFooter(op.param1, "@!, Gbye", [op.param2]) puy.getGroupIdsJoined() puy.leaveGroup(to) elif cmd.startswith("bc: "): if sender in Owner: sep = text.split(" ") pesan = text.replace(sep[0] + " ","") saya = puy.getGroupIdsJoined() for group in saya: sendMessageWithFooter(group,"" + str(pesan)) ####SC##### elif cmd.startswith("carimusik "): sep = text.split(" ") query = text.replace(sep[0] + " ","") cond = query.split("*") search = str(cond[0]) url = requests.get("http://api.ntcorp.us/joox/search?q={}".format(str(search))) data = url.json() if len(cond) == 1: num = 0 ret_ = " [ Result Music ]" for music in data["result"]: num += 1 ret_ += "\n {}. {}".format(str(num), str(music["single"])) ret_ += "\n [ Total {} Music ]".format(str(len(data["result"]))) ret_ += "\n\nUntuk mengirim music, silahkan gunakan command {} CariMusik {}*1".format(str(setKey), str(search)) puy.sendMessage(to, str(ret_)) elif len(cond) == 2: num = int(cond[1]) if num <= len(data["result"]): music = data["result"][num - 1] url = requests.get("http://api.ntcorp.us/joox/song_info?sid={}".format(str(music["sid"]))) data = url.json() ret_ = " [ Musik ]" ret_ += "\n Judul : {}".format(str(data["result"]["song"])) ret_ += "\n Album : {}".format(str(data["result"]["album"])) ret_ += "\n Ukuran : {}".format(str(data["result"]["size"])) ret_ += "\n Alamat : {}".format(str(data["result"]["mp3"][0])) puy.sendImageWithURL(to, str(data["result"]["img"])) puy.sendMessage(to, str(ret_)) puy.sendAudioWithURL(to, str(data["result"]["mp3"][0])) elif cmd.startswith("carilirik "): sep = text.split(" ") txt = text.replace(sep[0] + " ","") cond = txt.split("*") query = cond[0] with requests.session() as web: web.headers["user-agent"] = "Mozilla/5.0" url = web.get("https://www.musixmatch.com/search/{}".format(urllib.parse.quote(query))) data = BeautifulSoup(url.content, "html.parser") result = [] for trackList in data.findAll("ul", {"class":"tracks list"}): for urlList in trackList.findAll("a"): title = urlList.text url = urlList["href"] result.append({"title": title, "url": url}) if len(cond) == 1: ret_ = " [ Musixmatch Result ]" num = 0 for title in result: num += 1 ret_ += "\n {}. {}".format(str(num), str(title["title"])) ret_ += "\n [ Total {} Lirik ]".format(str(len(result))) ret_ += "\n\nUntuk melihat lirik, silahkan gunakan command {} CariLirik {}*1".format(str(setKey), str(query)) puy.sendMessage(to, ret_) elif len(cond) == 2: num = int(cond[1]) if num <= len(result): data = result[num - 1] with requests.session() as web: web.headers["user-agent"] = "Mozilla/5.0" url = web.get("https://www.musixmatch.com{}".format(urllib.parse.quote(data["url"]))) data = BeautifulSoup(url.content, "html5lib") for lyricContent in data.findAll("p", {"class":"mxm-lyrics__content "}): lyric = lyricContent.text puy.sendMessage(to, lyric) elif cmd.startswith("carigambar "): sep = text.split(" ") txt = text.replace(sep[0] + " ","") url = requests.get("http://rahandiapi.herokuapp.com/imageapi?key=betakey&q={}".format(txt)) data = url.json() puy.sendImageWithURL(to, random.choice(data["result"])) elif cmd.startswith("about puy"): try: arr = [] Ownerz = "uac8e3eaf1eb2a55770bf10c3b2357c33" creator = puy.getContact(Ownerz) contact = puy.getContact(puyMid) grouplist = puy.getGroupIdsJoined() contactlist = puy.getAllContactIds() blockedlist = puy.getBlockedContactIds() #ret_ = "「 HELPER 」" #ret_ += "\n Name : {}".format(contact.displayName) #ret_ += "\n Group : {}".format(str(len(grouplist))) #ret_ += "\n Friend : {}".format(str(len(contactlist))) #ret_ += "\n Blocked : {}".format(str(len(blockedlist))) #ret_ += "\n [ About Selfbot ]" #ret_ += "\n Version : Premium" #ret_ += "\n Creator : {}".format(creator.displayName) #ret_ += "\n Creator : @!".format(Owner) #puy.sendMessage(to, str(ret_)) sendMention(to, "「 About Puy 」\n\nThe Beginning of this Bot Comes from Helloworld, I'm just Reworked This!\n\nOf Course Special Thanks To HelloWorld, And the Friends Around Me!\n\nCreator : @!", [Ownerz]) except Exception as e: puy.sendMessage(msg.to, str(e)) elif cmd.startswith("instainfo"): sep = text.split(" ") txt = text.replace(sep[0] + " ","") url = requests.get("http://rahandiapi.herokuapp.com/instainfo/{}?key=betakey".format(txt)) data = url.json() #icon = "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/Instagram_icon.png/599px-Instagram_icon.png" #name = "Instagram" #link = "https://www.instagram.com/{}".format(data["result"]["username"]) result = " [ Instagram Info ]" result += "\n Nama : {}".format(data["result"]["name"]) result += "\n Username: {}".format(data["result"]["username"]) result += "\n Bio : {}".format(data["result"]["bio"]) result += "\n Pengikut : {}".format(data["result"]["follower"]) result += "\n Mengikuti : {}".format(data["result"]["following"]) result += "\n Privasi Acc : {}".format(data["result"]["private"]) result += "\n Post : {}".format(data["result"]["mediacount"]) #result += "\n [ Finish ]" puy.sendImageWithURL(to, data["result"]["url"]) puy.sendMessage(to, result) elif cmd.startswith("instastory "): sep = text.split(" ") query = text.replace(sep[0] + " ","") cond = query.split("*") search = str(cond[0]) if len(cond) == 2: url = requests.get("http://rahandiapi.herokuapp.com/instastory/{}?key=betakey".format(search)) data = url.json() num = int(cond[1]) if num <= len(data["url"]): search = data["url"][num - 1] if search["tipe"] == 1: puy.sendImageWithURL(to, str(search["link"])) elif search["tipe"] == 2: puy.sendVideoWithURL(to, str(search["link"])) elif cmd.startswith("youtubesearch "): sep = text.split(" ") txt = msg.text.replace(sep[0] + " ","") cond = txt.split("*") search = cond[0] url = requests.get("http://api.w3hills.com/youtube/search?keyword={}&api_key=<KEY>".format(search)) data = url.json() if len(cond) == 1: no = 0 result = " [ Youtube Video Search ]" for anu in data["videos"]: no += 1 result += "\n {}. {}".format(str(no),str(anu["title"])) result += "\n [ Total {} Result ]\nUntuk melihat details video , silahkan gunakan command Youtubesearch text*1".format(str(len(data["videos"]))) puy.sendMessage(to, result) elif len(cond) == 2: num = int(str(cond[1])) if num <= len(data): search = data["videos"][num - 1] ret_ = " [ Youtube Info ]" ret_ += "\n Channel : {}".format(str(search["publish"]["owner"])) ret_ += "\n Judul : {}".format(str(search["title"])) ret_ += "\n Release : {}".format(str(search["publish"]["date"])) ret_ += "\n Penonton : {}".format(str(search["stats"]["views"])) ret_ += "\n Suka : {}".format(str(search["stats"]["likes"])) ret_ += "\n Tidak Suka : {}".format(str(search["stats"]["dislikes"])) ret_ += "\n Nilai : {}".format(str(search["stats"]["rating"])) ret_ += "\n Deskripsi : {}".format(str(search["description"])) ret_ += "\n [ {} ]".format(str(search["webpage"])) puy.sendImageWithURL(to, str(search["thumbnail"])) puy.sendMessage(to, str(ret_)) elif cmd == "quotes": url = requests.get("https://botfamily.faith/api/quotes/?apikey=beta") data = url.json() result = " [ Quotes ]" result += "\n Pembuat : {}".format(data["result"]["author"]) result += "\n Kategori : {}".format(data["result"]["category"]) result += "\n Quote : {}".format(data["result"]["quote"]) puy.sendMessage(to, result) elif cmd == 'mentionall': group = puy.getGroup(to) midMembers = [contact.mid for contact in group.members] midSelect = len(midMembers)//100 for mentionMembers in range(midSelect+1): no = 0 ret_ = " [ Mention Members ]" dataMid = [] for dataMention in group.members[mentionMembers*100 : (mentionMembers+1)*100]: dataMid.append(dataMention.mid) no += 1 ret_ += "\n {}. @!".format(str(no)) ret_ += "\n [ Total {} Members]".format(str(len(dataMid))) sendMention(to, ret_, dataMid) elif cmd.startswith("doujinsearch "): query = cmd.replace("doujinsearch ","") cond = query.split("|") search = str(cond[0]) r = requests.get("https://nhentai.net/search/?&q={}".format(str(search))) soup = BeautifulSoup(r.content, 'html5lib') data = soup.findAll('div', attrs={'class':'gallery'}) if len(cond) == 1: num = 0 ret_ = "[ Doujin#Search ]" for dou in data: title = dou.find('a').text link = dou.find('a')['href'] num += 1 ret_ += "\n{}. {}".format(str(num), str(title)) ret_ += "\nhttps://nhentai.net{}".format(str(link)) ret_ += "\n\nType .doujin#search {}| (num)".format(str(search)) puy.sendMessage(to, str(ret_)) elif len(cond) == 2: num = int(cond[1]) if num <= len(data): dou = data[num - 1] r = requests.get("https://nhentai.net{}".format(str(dou.find('a')['href']))) soup = BeautifulSoup(r.content, 'html5lib') for sam in soup.findAll('img', attrs={'class':'lazyload'}): path = sam.get('data-src') puy.sendImageWithURL(to,str(path)) elif cmd.startswith("sticker .add "): loads() global stickers with open('sticker.json','r') as f: stickers = json.loads(f) name = cmd.replace("sticker .add ","") name = name.lower() if name not in stickers: settings["addSticker"]["status"] = True settings["addSticker"]["name"] = name.lower() stickers[name.lower()] = {} f = codecs.open('sticker.json','w','utf-8') json.dump(stickers, f, sort_keys=True, indent=4, ensure_ascii=False) puy.sendMessage(to," 「 Stickers 」\nType: Add Sticker\nStatus: Send a sticker to add to command {}.".format(name.lower())) else: puy.sendMessage(to," 「 Stickers 」\nType: Add Sticker\nStatus: Sticker no to add to command {} because in the list.".format(name.lower())) elif cmd.startswith("sticker .del "): loads() with open('sticker.json','r') as f: stickers = json.loads(f) name = cmd.replace("sticker .del ","") name = name.lower() if name in stickers: del stickers[name.lower()] f = codecs.open('sticker.json','w','utf-8') json.dump(stickers, f, sort_keys=True, indent=4, ensure_ascii=False) puy.sendMessage(to," 「 Stickers 」\nType: Del Sticker\nStatus: Sticker to del to command {}.".format(name.lower())) else: puy.sendMessage(to," 「 Stickers 」\nType: Del Sticker\nStatus: Sticker no to del to command {} because not in the list.".format(name.lower())) elif cmd.startswith("cancelpending"): if msg.toType == 2: group = puy.getGroup(to) if group.invitee is None or group.invitee == []: puy.sendMessage(to, "Tidak ada pendingan") else: invitee = [contact.mid for contact in group.invitee] for inv in invitee: puy.cancelGroupInvitation(to, [inv]) time.sleep(1) puy.sendMessage(to, "Berasil membatalkan undangan {} anggota.".format(str(len(invitee)))) elif cmd.startswith('gcancel'): gid = puy.getGroupIdsInvited() start = time.time() for i in gid: puy.rejectGroupInvitation(i) elapsed_time = time.time() - start puy.sendMessage(to, "Semua Undangan Dibatalkan") puy.sendMessage(to, "Waktu: %s Seconds" % (elapsed_time)) elif "take" in msg.text: list_ = msg.text.split(":") try: puy.acceptGroupInvitationByTicket(list_[1],list_[2]) G = puy.getGroup(list_[1]) if G.preventedJoinByTicket == True: pass else: G.preventedJoinByTicket = True puy.updateGroup(G) except: puy.sendMessage(msg.to,"error\n"+list_[1]+'\n'+list_[2]) elif cmd.startswith("igpost"): separate = msg.text.split(" ") user = msg.text.replace(separate[0] + " ","") profile = "https://www.instagram.com/" + user with requests.session() as x: x.headers['user-agent'] = 'Mozilla/5.0' end_cursor = '' for count in range(1, 999): print('PAGE: ', count) r = x.get(profile, params={'max_id': end_cursor}) data = re.search(r'window._sharedData = (\{.+?});</script>', r.text).group(1) j = json.loads(data) for node in j['entry_data']['ProfilePage'][0]['user']['media']['nodes']: if node['is_video']: page = 'https://www.instagram.com/p/' + node['code'] r = x.get(page) url = re.search(r'"video_url": "([^"]+)"', r.text).group(1) print(url) puy.sendVideoWithURL(msg.to,url) else: print (node['display_src']) puy.sendImageWithURL(msg.to,node['display_src']) end_cursor = re.search(r'"end_cursor": "([^"]+)"', r.text).group(1) elif cmd.startswith("myautorespon"): if message["replyPesan"] is not None: puy.sendMessage(to,"My Set AutoRespon : " + str(message["replyPesan"])) else: puy.sendMessage(msg.to,"My Set AutoRespon : No messages are set") elif cmd.startswith("responchange: "): sep = msg.text.split(" ") text = msg.text.replace(sep[0] + " ","") try: message["replyPesan"] = text puy.sendMessage(to,"「 AutoRespon 」Changed to : " + text) except: puy.sendMessage(to,"「 AutoRespon 」\nFailed to replace message") elif cmd.startswith("responchanged: "): sep = text.split(" ") texts = text.replace(sep[0] + " ","") if " " in texts: puy.sendMessage(to, "Tanpa spasi.") else: message["replyPesan"] = str(texts).lower() #message["replyPesan"] = text sendMessageWithFooter(to, "Auto Respon has been Changed to [ {} ]".format(str(texts).lower())) if text.lower() == 'login win10': req = requests.get('https://api.eater.tech/WIN10') a = req.text b = json.loads(a) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) tkn['{}'.format(msg._from)] = [] tkn['{}'.format(msg._from)].append({ 'qr': b['result'][0]['linkqr'], 'tkn': b['result'][0]['linktkn'] }) qrz = b['result'][0]['linkqr'] puy.sendMessage(to, 'Buka Link dibawah dan Tekan Login\n\n{}'.format(qrz)) #dap.sendMessage(msg.to, 'Buka Link dibawah dan Tekan Login\n{}'.format(qrz)) with open('tkn.json', 'w') as outfile: json.dump(tkn, outfile) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) a = tkn['{}'.format(msg._from)][0]['tkn'] req = requests.get(url = '{}'.format(a)) b = req.text aa = puy.getContact(sender).displayName ab = puy.getGroup(msg.to).name ac = puy.getContact(sender).mid #sendMention(to, '- TIPE TOKEN : WIN10\n- For : @!\n\n- TOKEN : \n{}'.format(b), [sender]) puy.sendMessage(to, '「 WIN 10 」\nUntuk : '+aa+'\nDari Grup : '+ab+'\nMid Kamu : '+ac+'\n\n-「 TOKEN 」 : \n{}\n\n- UA : Line/8.3.2\n- LA : WIN10 8.8.3 PUY x64\n\n*「 From BotEater / Edited By PUY 」\n'.format(b)) #puy.sendMessage(receiver, '「 WIN 10 」\nUntuk : '+as+'\nDari Grup : '+ab+'\nMid Kamu : '+ac+'\n\n-「 TOKEN 」 : \n{}\n\n- UA : Line/8.3.2\n- LA : WIN10 8.8.3 NADYA-TJ x64\n\n*「 From NadyaTJ & BotEater / Edited By PUY 」\n@!'.format(b) if text.lower() == '#login chrome': req = requests.get('https://api.eater.tech/CHROMEOS') a = req.text b = json.loads(a) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) tkn['{}'.format(msg._from)] = [] tkn['{}'.format(msg._from)].append({ 'qr': b['result'][0]['linkqr'], 'tkn': b['result'][0]['linktkn'] }) qrz = b['result'][0]['linkqr'] puy.sendMessage(to, 'Buka Link dibawah dan Tekan Login\n\n{}'.format(qrz)) #dap.sendMessage(msg.to, 'Buka Link dibawah dan Tekan Login\n{}'.format(qrz)) with open('tkn.json', 'w') as outfile: json.dump(tkn, outfile) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) a = tkn['{}'.format(msg._from)][0]['tkn'] req = requests.get(url = '{}'.format(a)) b = req.text aa = puy.getContact(sender).displayName ab = puy.getGroup(msg.to).name ac = puy.getContact(sender).mid #sendMention(to, '- TIPE TOKEN : WIN10\n- For : @!\n\n- TOKEN : \n{}'.format(b), [sender]) #dap.sendMessage(to,'「 CHROMEOS 」\nUntuk: '+aa+'\nFrom Group: '+ab+'\nMid User: '+ac+'\n\n- TOKEN : \n{}'.format(b)) sendMention(to,'「 CHROME 」\nUntuk : @!\nDari Grup : '+ab+'\nMid Kamu : '+ac+'\n\n-「 TOKEN 」 : \n{}\n\n- UA : Line/8.3.2\n- LA : CHROMEOS 8.8.3 PUY x64\n\n*「 From BotEater / Edited By PUY 」'.format(b), [sender]) if text.lower() == '#login iospad': req = requests.get('https://api.eater.tech/IOSPAD') a = req.text b = json.loads(a) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) tkn['{}'.format(msg._from)] = [] tkn['{}'.format(msg._from)].append({ 'qr': b['result'][0]['linkqr'], 'tkn': b['result'][0]['linktkn'] }) qrz = b['result'][0]['linkqr'] puy.sendMessage(to, 'Buka Link dibawah dan Tekan Login\n\n{}'.format(qrz)) #puy.sendMessage(msg.to, 'Buka Link dibawah dan Tekan Login\n{}'.format(qrz)) with open('tkn.json', 'w') as outfile: json.dump(tkn, outfile) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) a = tkn['{}'.format(msg._from)][0]['tkn'] req = requests.get(url = '{}'.format(a)) b = req.text aa = puy.getContact(sender).displayName ab = puy.getGroup(msg.to).name ac = puy.getContact(sender).mid #sendMention(to, '- TIPE TOKEN : WIN10\n- For : @!\n\n- TOKEN : \n{}'.format(b), [sender]) #puy.sendMessage(to,'「 CHROMEOS 」\nUntuk: '+aa+'\nFrom Group: '+ab+'\nMid User: '+ac+'\n\n- TOKEN : \n{}'.format(b)) sendMention(to,'「 IOSPAD 」\nUntuk : @!\nDari Grup : '+ab+'\nMid Kamu : '+ac+'\n\n-「 TOKEN 」 : \n{}\n\n- UA : Line/8.3.2\n- LA : IOSPAD 8.8.3 PUY x64\n\n*「 From BotEater / Edited By PUY 」'.format(b), [sender]) if text.lower() == '#login desktopwin': req = requests.get('https://api.eater.tech/DESKTOPWIN') a = req.text b = json.loads(a) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) tkn['{}'.format(msg._from)] = [] tkn['{}'.format(msg._from)].append({ 'qr': b['result'][0]['linkqr'], 'tkn': b['result'][0]['linktkn'] }) qrz = b['result'][0]['linkqr'] puy.sendMessage(to, 'Buka Link dibawah dan Tekan Login\n\n{}'.format(qrz)) #dap.sendMessage(msg.to, 'Buka Link dibawah dan Tekan Login\n{}'.format(qrz)) with open('tkn.json', 'w') as outfile: json.dump(tkn, outfile) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) a = tkn['{}'.format(msg._from)][0]['tkn'] req = requests.get(url = '{}'.format(a)) b = req.text aa = puy.getContact(sender).displayName ab = puy.getGroup(msg.to).name ac = puy.getContact(sender).mid #sendMention(to, '- TIPE TOKEN : WIN10\n- For : @!\n\n- TOKEN : \n{}'.format(b), [sender]) #dap.sendMessage(to,'「 CHROMEOS 」\nUntuk: '+aa+'\nFrom Group: '+ab+'\nMid User: '+ac+'\n\n- TOKEN : \n{}'.format(b)) sendMention(to,'「 DESKTOPWIN 」\nUntuk : @!\nDari Grup : '+ab+'\nMid Kamu : '+ac+'\n\n-「 TOKEN 」 : \n{}\n\n- UA : DESKTOPWIN 8.8.3 PUY x64\n\n*「 From BotEater / Edited By PUY 」'.format(b), [sender]) if text.lower() == '#login desktopmac': req = requests.get('https://api.eater.tech/DESKTOPMAC') a = req.text b = json.loads(a) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) tkn['{}'.format(msg._from)] = [] tkn['{}'.format(msg._from)].append({ 'qr': b['result'][0]['linkqr'], 'tkn': b['result'][0]['linktkn'] }) qrz = b['result'][0]['linkqr'] puy.sendMessage(to, 'Buka Link dibawah dan Tekan Login\n\n{}'.format(qrz)) #dap.sendMessage(msg.to, 'Buka Link dibawah dan Tekan Login\n{}'.format(qrz)) with open('tkn.json', 'w') as outfile: json.dump(tkn, outfile) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) a = tkn['{}'.format(msg._from)][0]['tkn'] req = requests.get(url = '{}'.format(a)) b = req.text aa = puy.getContact(sender).displayName ab = puy.getGroup(msg.to).name ac = puy.getContact(sender).mid #sendMention(to, '- TIPE TOKEN : WIN10\n- For : @!\n\n- TOKEN : \n{}'.format(b), [sender]) #dap.sendMessage(to,'「 CHROMEOS 」\nUntuk: '+aa+'\nFrom Group: '+ab+'\nMid User: '+ac+'\n\n- TOKEN : \n{}'.format(b)) sendMention(to,'「 DESKTOPMAC 」\nUntuk : @!\nDari Grup : '+ab+'\nMid Kamu : '+ac+'\n\n-「 TOKEN 」 : \n{}\n\n- UA : Line/8.3.2\n- LA : DESKTOPMAC 8.8.3 PUY x64\n\n*「 From BotEater / Edited By PUY 」'.format(b), [sender]) elif cmd.startswith("setautoadd: "): if sender in Owner: sep = text.split(" ") txt = text.replace(sep[0] + " ","") try: settings["autoAddMessage"] = txt puy.sendMessage(to, "Pesan Add diubah menjadi : 「{}」".format(txt)) except: puy.sendMessage(to, "Gagal mengubah pesan Add") elif cmd.startswith("setautojoin: "): if sender in Owner: sep = text.split(" ") txt = text.replace(sep[0] + " ","") try: settings["autoJoinMessage"] = txt puy.sendMessage(to, "Pesan Join diubah menjadi : 「{}」".format(txt)) except: puy.sendMessage(to, "Gagal mengubah pesan Join") elif cmd.startswith("setautoreply: "): if sender in Owner: sep = text.split(" ") txt = text.replace(sep[0] + " ","") try: settings["autoResponMessage"] = txt puy.sendMessage(to, "Pesan autoReplyMention diubah menjadi : 「{}」".format(txt)) except: puy.sendMessage(to, "Gagal mengubah pesan autoReplyMention") elif cmd.startswith("setprefix:"): if sender in Owner: sep = text.split(" ") key = text.replace(sep[0] + " ","") if " " in key: puy.sendMessage(to, "\nTanpa spasi.\n") else: settings["keyCommand"] = str(key).lower() puy.sendMessage(to, "prefix diubah menjadi [ {} ]".format(str(key).lower())) puy.sendMessage(to, "Prefix Saat ini adalah [ {} ]".format(str(settings["keyCommand"]))) elif text.lower() == "prefix on": if msg._from in Owner: if settings["setKey"] == True: puy.sendMessage(to, "Prefix telah aktif") else: settings["setKey"] = True puy.sendMessage(to, "Berhasil mengaktifkan Prefix") elif text.lower() == "prefix off": if msg._from in Owner: if settings["setKey"] == False: puy.sendMessage(to, "Prefix telah nonaktif") else: settings["setKey"] = False puy.sendMessage(to, "Berhasil menonaktifkan Prefix") except Exception as error: logError(error) ## PREFIX ## if op.type == 25: try: msg = op.message if settings["reread"] == True: if msg.toType == 0: puy.log("[%s]"%(msg._from)+msg.text) else: puy.log("[%s]"%(msg.to)+msg.text) if msg.contentType == 0: msg_dict[msg.id] = {"text":msg.text,"from":msg._from,"createdTime":msg.createdTime} else: pass except Exception as e: print(e) if op.type == 65: print("[65] NOTIFIED_DESTROY_MESSAGE") try: at = op.param1 msg_id = op.param2 if settings["reread"] == True: if msg_id in msg_dict: if msg_dict[msg_id]["from"] not in blacklist: puy.sendMessage(at,"[ ! unsend messaging ]\n%s\n[ Messages ]\n%s"%(puy.getContact(msg_dict[msg_id]["from"]).displayName,msg_dict[msg_id]["text"])) print ["Ingat Pesan"] del msg_dict[msg_id] else: pass except Exception as e: print(e) if op.type == 26: try: print ("[ 26 ] RECIEVE MESSAGE") msg = op.message text = msg.text msg_id = msg.id receiver = msg.to sender = msg._from if msg.toType == 0 or msg.toType == 1 or msg.toType == 2: if msg.toType == 0: #if text =='mute': if sender != puy.profile.mid: to = sender else: to = receiver elif msg.toType == 1: to = receiver elif msg.toType == 2: to = receiver if settings["autoRead"] == True: puy.sendChatChecked(to, msg_id) if sender not in puyMid: if msg.toType != 0 and msg.toType == 2: if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] for mention in mentionees: if puyMid in mention["M"]: if settings["autoRespon"] == True: puy.sendMessage(sender, settings["autoResponMessage"], [sender]) break if to in read["readPoint"]: if sender not in read["ROM"][to]: read["ROM"][to][sender] = True if msg.contentType == 0: if text is None: return if "/ti/g/" in msg.text.lower(): if settings["autoJoinTicket"] == True: link_re = re.compile('(?:line\:\/|line\.me\/R)\/ti\/g\/([a-zA-Z0-9_-]+)?') links = link_re.findall(text) n_links = [] for l in links: if l not in n_links: n_links.append(l) for ticket_id in n_links: group = puy.findGroupByTicket(ticket_id) puy.acceptGroupInvitationByTicket(group.id,ticket_id) puy.sendMessage(to, "Successed Joined to Group %s" % str(group.name)) #if 'MENTION' in msg.contentMetadata.keys()!= None: # names = re.findall(r'@(\w+)', text) # mention = ast.literal_eval(msg.contentMetadata['MENTION']) # mentionees = mention['MENTIONEES'] # lists = [] # for mention in mentionees: # if puyMid in mention["M"]: # if settings["detectMention"] == True: # contact = puy.getContact(sender) # #puy.sendMessage(to, "Hey don't Tag Me! I'ts Annoying.") # sendMention(to, " @!, Hey don't Tag Me! I'ts Annoying.", [sender]) # puy.sendContact(to, sender) # break if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if puyMid in mention["M"]: if settings["autoRespon"] == True: puy.sendMessage(sender, " @!, Hey don't Tag Me! I'ts Annoying.", [sender]) break if settings["detectUnsend"] == True: try: unsendTime = time.time() unsend[msg_id] = {"text": text, "from": sender, "time": unsendTime} except Exception as error: logError(error) if msg.contentType == 1: if settings["detectUnsend"] == True: try: unsendTime = time.time() image = puy.downloadObjectMsg(msg_id, saveAs="LineAPI/tmp/{}-image.bin".format(time.time())) unsend[msg_id] = {"from": sender, "image": image, "time": unsendTime} except Exception as error: logError(error) elif msg.contentType == 7: if settings["addSticker"]["status"] == True: stickers[settings["addSticker"]["name"]]["STKVER"] = msg.contentMetadata["STKVER"] stickers[settings["addSticker"]["name"]]["STKID"] = msg.contentMetadata["STKID"] stickers[settings["addSticker"]["name"]]["STKPKGID"] = msg.contentMetadata["STKPKGID"] f = codecs.open('sticker.json','w','utf-8') json.dump(stickers, f, sort_keys=True, indent=4, ensure_ascii=False) puy.sendMessage(to," 「 Stickers 」\nType: Add Sticker\nStatus: Sticker successfully added to command {}.".format(str(settings["addSticker"]["name"]))) settings["addSticker"]["status"] = False settings["addSticker"]["name"] = "" elif msg.contentType == 13: if settings["wblack"] == True: if msg.contentMetadata["mid"] in black["blacklist"]: puy.sendMessage(to, "Sudah ada di daftar hitam ") settings["wblack"] = False else: black["blacklist"][msg.contentMetadata["mid"]] = True puy.sendMessage(to, "Ditambahkan ke daftar hitam ") settings["wblack"] = False backupData() elif settings["dblack"] == True: if msg.contentMetadata["mid"] in black["blacklist"]: del black["blacklist"][msg.contentMetadata["mid"]] puy.sendMessage(to, "Daftar Hitam telah ditutup ") settings["dblack"] = False else: puy.sendMessage(to, "Dia tidak masuk daftar hitam ") settings["dblack"] = False backupData() #elif msg.contentType == 16: # if settings["checkPost"] == True: # try: # ret_ = "\n [ Details Post ] " # if msg.contentMetadata["serviceType"] == "GB": # contact = puy.getContact(sender) # auth = "\n Author : {}".format(str(contact.displayName)) # else: # auth = "\n Author : {}".format(str(msg.contentMetadata["serviceName"])) # purl = "\n URL : {}".format(str(msg.contentMetadata["postEndUrl"]).replace("line://","https://line.me/R/")) # ret_ += auth # ret_ += purl # if "mediaOid" in msg.contentMetadata: # object_ = msg.contentMetadata["mediaOid"].replace("svc=myhome|sid=h|","") # if msg.contentMetadata["mediaType"] == "V": # if msg.contentMetadata["serviceType"] == "GB": # ourl = "\n Object URL : https://obs-us.line-apps.com/myhome/h/download.nhn?tid=612w&{}#".format(str(msg.contentMetadata["mediaOid"])) # murl = "\n Media URL : https://obs-us.line-apps.com/myhome/h/download.nhn?{}".format(str(msg.contentMetadata["mediaOid"])) # else: # ourl = "\n Object URL : https://obs-us.line-apps.com/myhome/h/download.nhn?tid=612w&{}".format(str(object_)) # murl = "\n Media URL : https://obs-us.line-apps.com/myhome/h/download.nhn?{}".format(str(object_)) # ret_ += murl # else: # if msg.contentMetadata["serviceType"] == "GB": # ourl = "\n Object URL : https://obs-us.line-apps.com/myhome/h/download.nhn?tid=612w&{}".format(str(msg.contentMetadata["mediaOid"])) # else: # ourl = "\n Object URL : https://obs-us.line-apps.com/myhome/h/download.nhn?tid=612w&{}".format(str(object_)) # ret_ += ourl # if "stickerId" in msg.contentMetadata: # stck = "\n Sticker : https://line.me/R/shop/detail/{}".format(str(msg.contentMetadata["packageId"])) # ret_ += stck # if "text" in msg.contentMetadata: # text = "\n the contents of writing : {}".format(str(msg.contentMetadata["text"])) # ret_ += text # ret_ += "\n" # puy.sendMessage(to, str(ret_)) # except: # puy.sendMessage(to, "\nInvalid post\n") except Exception as error: logError(error) traceback.print_tb(error.__traceback__) if op.type == 65: print("[65] NOTIFIED_DESTROY_MESSAGE") try: at = op.param1 msg_id = op.param2 if settings["reread"] == True: if msg_id in msg_dict: if msg_dict[msg_id]["from"] not in bl: puy.sendMessage(at,"[ ! unsend messaging ]\n%s\n[ Messages ]\n%s"%(puy.getContact(msg_dict[msg_id]["from"]).displayName,msg_dict[msg_id]["text"])) print ["Ingat Pesan"] del msg_dict[msg_id] else: pass except Exception as e: print(e) #===============================================================================[piMid - puyMid] if op.param3 in piMid: if op.param2 in puyMid: G = puy.getGroup(op.param1) # ginfo = puy.getGroup(op.param1) G.preventedJoinByTicket = False puy.updateGroup(G) invsend = 0 Ticket = puy.reissueGroupTicket(op.param1) puy.acceptGroupInvitationByTicket(op.param1,Ticket) pi.acceptGroupInvitationByTicket(op.param1,Ticket) G = puy.getGroup(op.param1) G.preventedJoinByTicket = True puy.updateGroup(G) G.preventedJoinByTicket(G) puy.updateGroup(G) else: G = puy.getGroup(op.param1) # ginfo = puy.getGroup(op.param1) puy.kickoutFromGroup(op.param1,[op.param2]) G.preventedJoinByTicket = False puy.updateGroup(G) invsend = 0 Ticket = puy.reissueGroupTicket(op.param1) puy.acceptGroupInvitationByTicket(op.param1,Ticket) pi.acceptGroupInvitationByTicket(op.param1,Ticket) G = puy.getGroup(op.param1) G.preventedJoinByTicket = True puy.updateGroup(G) G.preventedJoinByTicket(G) puy.updateGroup(G) settings["blacklist"][op.param2] = True #-------------------------------------------------------------------------------[kiMID ki2MID] if op.type == 19: try: if op.param3 in puyMid: if op.param2 in piMid: G = pi.getGroup(op.param1) G.preventedJoinByTicket = False pi.updateGroup(G) invsend = 0 Ticket = pi.reissueGroupTicket(op.param1) puy.acceptGroupInvitationByTicket(op.param1,Ticket) pi.acceptGroupInvitationByTicket(op.param1,Ticket) G = pi.getGroup(op.param1) G.preventedJoinByTicket = True pi.updateGroup(G) G.preventedJoinByTicket(G) pi.updateGroup(G) puy.sendMessage(op.param1, "hmm?") else: G = pi.getGroup(op.param1) pi.kickoutFromGroup(op.param1,[op.param2]) G.preventedJoinByTicket = False pi.updateGroup(G) invsend = 0 Ticket = pi.reissueGroupTicket(op.param1) puy.acceptGroupInvitationByTicket(op.param1,Ticket) pi.acceptGroupInvitationByTicket(op.param1,Ticket) G = pi.getGroup(op.param1) G.preventedJoinByTicket = True pi.updateGroup(G) G.preventedJoinByTicket(G) pi.updateGroup(G) settings["blacklist"][op.param2] = True except Exception as error: logError(error) traceback.print_tb(error.__traceback__) if op.type == 65: try: if settings["detectUnsend"] == True: to = op.param1 sender = op.param2 if sender in unsend: unsendTime = time.time() contact = puy.getContact(unsend[sender]["from"]) if "text" in unsend[sender]: try: sendTime = unsendTime - unsend[sender]["time"] sendTime = timeChange(sendTime) ret_ = " [ Pesan DiUrungkan ]" ret_ += "\n Pengirim : @!" ret_ += "\n Pada : {} yang lalu".format(sendTime) ret_ += "\n Tipe pesan : Text" ret_ += "\n Isi pesan : {}".format(unsend[sender]["text"]) puy.sendMention(to, ret_, [contact.mid]) del unsend[sender] except: del unsend[sender] elif "image" in unsend[sender]: try: sendTime = unsendTime - unsend[sender]["time"] sendTime = timeChange(sendTime) ret_ = " [ Pesan DiUrungkan ]" ret_ += "\n Pengirim : @!" ret_ += "\n Pada : {} yang lalu".format(sendTime) ret_ += "\n Tipe pesan : Gambar" ret_ += "\n Gambar : Dibawah" puy.sendMention(to, ret_, [contact.mid]) puy.sendImage(to, unsend[sender]["image"]) puy.deleteFile(unsend[sender]["image"]) del unsend[sender] except: puy.deleteFile(unsend[sender]["image"]) del unsend[sender] else: puy.sendMessage(to, "Unsend Chat Detected, Data Not Found") except Exception as error: logError(error) traceback.print_tb(error.__traceback__) if op.type == 55: print ("[ 55 ] NOTIFIED READ MESSAGE") try: if op.param1 in read['readPoint']: if op.param2 in read['readMember'][op.param1]: pass else: read['readMember'][op.param1] += op.param2 read['ROM'][op.param1][op.param2] = op.param2 else: pass except Exception as error: logError(error) traceback.print_tb(error.__traceback__) except Exception as error: logError(error) traceback.print_tb(error.__traceback__) backupData() while True: try: delete_log() ops = puyPoll.singleTrace(count=50) if ops is not None: for op in ops: puyBot(op) puyPoll.setRevision(op.revision) except Exception as error: logError(error) def atend(): print("Saving") with open("Log_data.json","w",encoding='utf8') as f: json.dump(msg_dict, f, ensure_ascii=False, indent=4,separators=(',', ': ')) print("BYE") atexit.register(atend) <file_sep>/delia.py.py # -*- coding: utf-8 -*- from PUY.linepy import * from PUY.akad.ttypes import Message from PUY.akad.ttypes import ChatRoomAnnouncementContents from PUY.akad.ttypes import ContentType as Type from gtts import gTTS from time import sleep from datetime import datetime, timedelta from bs4 import BeautifulSoup from googletrans import Translator from humanfriendly import format_timespan, format_size, format_number, format_length import time, random, sys, json, codecs, subprocess, threading, glob, re, string, os, requests, six, ast, pytz, urllib, urllib3, urllib.parse, traceback, atexit #dap = LINE() dap = LINE("<KEY> #dap = LINE('','') dapMid = dap.profile.mid dapProfile = dap.getProfile() dapSettings = dap.getSettings() dapPoll = OEPoll(dap) botStart = time.time() #pi = LINE() pi = LINE("<KEY> #pi = LINE('','') piMid = pi.profile.mid piProfile = pi.getProfile() piSettings = pi.getSettings() dapPoll = OEPoll(pi) botStart = time.time() KAC = [dap,pi] dapMID = dap.profile.mid piMID = pi.profile.mid msg_dict = {} Bots = [dapMID,piMID] Owner = ["uac<PASSWORD>"] Admin =["u<PASSWORD>","u<PASSWORD>"] dapProfile = dap.getProfile() piProfile = pi.getProfile() lineSettings = dap.getSettings() piSettings = pi.getSettings() dapPoll = OEPoll(dap) piPoll = OEPoll(pi) responsename = dap.getProfile().displayName responsename2 = pi.getProfile().displayName settings = { "autoAdd": False, "autoJoin": True, "autoLeave": False, "autoRead": False, "ChangeVideoProfilevid": True, "ChangeVideoProfilePicture": True, "lurk": False, "autoRespon": False, "wblack": False, "limit": 50, "limits": 50, "dblack": False, "autoJoinTicket": True, "checkContact": False, "checkPost": False, "NatNat": False, "Inroom": True, "Outroom": True, "timeRestart": "18000", "protect": False, "blacklist": False, "qrprotect": False, "autoReject": False, "members": 1, "inviteprotect": False, "cancelprotect": False, "limituser": True, "checkSticker": False, "changeDisplayPicture": False, "changeGroupPicture": [], "wordban": [], "keyCommand": "", "myProfile": { "displayName": "", "coverId": "", "pictureStatus": "", "statusMessage": "" }, "mimic": { "copy": False, "status": False, "target": {} }, "setKey": False, "unsendMessage": True } wait = { 'autoAdd': False, "tagme":"?? Don't Tag", "autoRespon": False, "detectMention": False, "pname": False, "winvite": False, "qr": False, "Lv": False, "lang":"JP", "pro_name":{}, "unsend": False, "Addsticker":{ "name": "", "status":False }, 'message':"""Thx for add!""", } bc = { "txt": {}, "mid": {}, "img": False } cctv = { "cyduk":{}, "point":{}, "sidermem":{} } read = { "ROM": {}, "readPoint": {}, "readMember": {}, "readTime": {} } list_language = { "list_textToSpeech": { "id": "Indonesia", "af" : "Afrikaans", "sq" : "Albanian", "ar" : "Arabic", "hy" : "Armenian", "bn" : "Bengali", "ca" : "Catalan", "zh" : "Chinese", "zh-cn" : "Chinese (Mandarin/China)", "zh-tw" : "Chinese (Mandarin/Taiwan)", "zh-yue" : "Chinese (Cantonese)", "hr" : "Croatian", "cs" : "Czech", "da" : "Danish", "nl" : "Dutch", "en" : "English", "en-au" : "English (Australia)", "en-uk" : "English (United Kingdom)", "en-us" : "English (United States)", "eo" : "Esperanto", "fi" : "Finnish", "fr" : "French", "de" : "German", "el" : "Greek", "hi" : "Hindi", "hu" : "Hungarian", "is" : "Icelandic", "id" : "Indonesian", "it" : "Italian", "ja" : "Japanese", "km" : "Khmer (Cambodian)", "ko" : "Korean", "la" : "Latin", "lv" : "Latvian", "mk" : "Macedonian", "no" : "Norwegian", "pl" : "Polish", "pt" : "Portuguese", "ro" : "Romanian", "ru" : "Russian", "sr" : "Serbian", "si" : "Sinhala", "sk" : "Slovak", "es" : "Spanish", "es-es" : "Spanish (Spain)", "es-us" : "Spanish (United States)", "sw" : "Swahili", "sv" : "Swedish", "ta" : "Tamil", "th" : "Thai", "tr" : "Turkish", "uk" : "Ukrainian", "vi" : "Vietnamese", "cy" : "Welsh" }, "list_translate": { "af": "afrikaans", "sq": "albanian", "am": "amharic", "ar": "arabic", "hy": "armenian", "az": "azerbaijani", "eu": "basque", "be": "belarusian", "bn": "bengali", "bs": "bosnian", "bg": "bulgarian", "ca": "catalan", "ceb": "cebuano", "ny": "chichewa", "zh-cn": "chinese (simplified)", "zh-tw": "chinese (traditional)", "co": "corsican", "hr": "croatian", "cs": "czech", "da": "danish", "nl": "dutch", "en": "english", "eo": "esperanto", "et": "estonian", "tl": "filipino", "fi": "finnish", "fr": "french", "fy": "frisian", "gl": "galician", "ka": "georgian", "de": "german", "el": "greek", "gu": "gujarati", "ht": "haitian creole", "ha": "hausa", "haw": "hawaiian", "iw": "hebrew", "hi": "hindi", "hmn": "hmong", "hu": "hungarian", "is": "icelandic", "ig": "igbo", "id": "indonesian", "ga": "irish", "it": "italian", "ja": "japanese", "jw": "javanese", "kn": "kannada", "kk": "kazakh", "km": "khmer", "ko": "korean", "ku": "kurdish (kurmanji)", "ky": "kyrgyz", "lo": "lao", "la": "latin", "lv": "latvian", "lt": "lithuanian", "lb": "luxembourgish", "mk": "macedonian", "mg": "malagasy", "ms": "malay", "ml": "malayalam", "mt": "maltese", "mi": "maori", "mr": "marathi", "mn": "mongolian", "my": "myanmar (burmese)", "ne": "nepali", "no": "norwegian", "ps": "pashto", "fa": "persian", "pl": "polish", "pt": "portuguese", "pa": "punjabi", "ro": "romanian", "ru": "russian", "sm": "samoan", "gd": "scots gaelic", "sr": "serbian", "st": "sesotho", "sn": "shona", "sd": "sindhi", "si": "sinhala", "sk": "slovak", "sl": "slovenian", "so": "somali", "es": "spanish", "su": "sundanese", "sw": "swahili", "sv": "swedish", "tg": "tajik", "ta": "tamil", "te": "telugu", "th": "thai", "tr": "turkish", "uk": "ukrainian", "ur": "urdu", "uz": "uzbek", "vi": "vietnamese", "cy": "welsh", "xh": "xhosa", "yi": "yiddish", "yo": "yoruba", "zu": "zulu", "fil": "Filipino", "he": "Hebrew" } } try: with open("Log_data.json","r",encoding="utf_8_sig") as f: msg_dict = json.loads(f.read()) except: print("PUY") with open('Owner.json', 'r') as fp: Owner = json.load(fp) with open('Admin.json', 'r') as fp: Admin = json.load(fp) settings["myProfile"]["displayName"] = dapProfile.displayName settings["myProfile"]["statusMessage"] = dapProfile.statusMessage settings["myProfile"]["pictureStatus"] = dapProfile.pictureStatus coverId = dap.getProfileDetail()["result"]["objectId"] settings["myProfile"]["coverId"] = coverId def restartBot(): print ("[ INFO ] BOT RESTART") python = sys.executable os.execl(python, python, *sys.argv) def autoRestart(): if time.time() - botStart > int(settings["timeRestart"]): time.sleep(5) restartBot() def sendMentionFooter(to, text="", mids=[]): arrData = "" arr = [] mention = "@Meka Finee " if mids == []: raise Exception("Invalid mids") if "@!" in text: if text.count("@!") != len(mids): raise Exception("Invalid mids") texts = text.split("@!") textx = "" for mid in mids: textx += str(texts[mids.index(mid)]) slen = len(textx) elen = len(textx) + 15 arrData = {'S':str(slen), 'E':str(elen - 4), 'M':mid} arr.append(arrData) textx += mention textx += str(texts[len(mids)]) else: textx = "" slen = len(textx) elen = len(textx) + 15 arrData = {'S':str(slen), 'E':str(elen - 4), 'M':mids[0]} arr.append(arrData) textx += mention + str(text) dap.sendMessage(to, textx, {'AGENT_NAME':'@Muh.khadaffy on Instagram', 'AGENT_LINK': 'https://www.instagram.com/muh.khadaffy', 'AGENT_ICON': "http://dl.profile.line-cdn.net/" + dap.getProfile().picturePath, 'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0) #'AGENT_LINK': 'line://ti/p/~{}'.format(puy.getProfile().userid), def sendMessageWithFooter(to, text, name, url, iconlink): contentMetadata = { 'AGENT_NAME': name, 'AGENT_LINK': url, 'AGENT_ICON': iconlink } return dap.sendMessage(to, text, contentMetadata, 0) def sendMessageWithFooter(to, text): dap.reissueUserTicket() dap = dap.getProfile() ticket = "http://line.me/ti/p/"+dap.getUserTicket().id pict = "http://dl.profile.line-cdn.net/"+dap.pictureStatus name = dap.displayName dapi = {"AGENT_ICON": pict, "AGENT_NAME": name, "AGENT_LINK": ticket } dap.sendMessage(to, text, contentMetadata=dapi) def sendMessageWithContent(to, name, link, url, iconlink): contentMetadata = { 'AGENT_NAME': name, 'AGENT_LINK': url, 'AGENT_ICON': iconlink } return self.sendMessage(to, text, contentMetadata, 0) def logError(text): dap.log("[ ERROR ] {}".format(str(text))) tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) timeHours = datetime.strftime(timeNow,"(%H:%M)") day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] inihari = datetime.now(tz=tz) hr = inihari.strftime('%A') bln = inihari.strftime('%m') for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] time = "{}, {} - {} - {} | {}".format(str(hasil), str(inihari.strftime('%d')), str(bln), str(inihari.strftime('%Y')), str(inihari.strftime('%H:%M:%S'))) with open("logError.txt","a") as error: error.write("\n[ {} ] {}".format(str(time), text)) def cTime_to_datetime(unixtime): return datetime.fromtimestamp(int(str(unixtime)[:len(str(unixtime))-3])) def dt_to_str(dt): return dt.strftime('%H:%M:%S') def delete_log(): ndt = datetime.now() for data in msg_dict: if (datetime.utcnow() - cTime_to_datetime(msg_dict[data]["createdTime"])) > timedelta(1): if "path" in msg_dict[data]: dap.deleteFile(msg_dict[data]["path"]) del msg_dict[data] def sendMention(to, text="", mids=[]): arrData = "" arr = [] mention = "@zeroxyuuki " if mids == []: raise Exception("Invalid mids") if "@!" in text: if text.count("@!") != len(mids): raise Exception("Invalid mids") texts = text.split("@!") textx = "" for mid in mids: textx += str(texts[mids.index(mid)]) slen = len(textx) elen = len(textx) + 15 arrData = {'S':str(slen), 'E':str(elen - 4), 'M':mid} arr.append(arrData) textx += mention textx += str(texts[len(mids)]) else: textx = "" slen = len(textx) elen = len(textx) + 15 arrData = {'S':str(slen), 'E':str(elen - 4), 'M':mids[0]} arr.append(arrData) textx += mention + str(text) dap.sendMessage(to, textx, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0) def siderMembers(to, mid): try: arrData = "" textx = "Sider User\nHaii ".format(str(len(mid))) arr = [] no = 1 num = 2 for i in mid: mention = "@x\n" slen = str(len(textx)) elen = str(len(textx) + len(mention) - 1) arrData = {'S':slen, 'E':elen, 'M':i} arr.append(arrData) textx += mention+settings["mention"] if no < len(mid): no += 1 textx += "%i. " % (num) num=(num+1) else: try: no = "\n╚══[ {} ]".format(str(titanz.getGroup(to).name)) except: no = "\n╚══[ Success ]" titanz.sendMessage(to, textx, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0) except Exception as error: titanz.sendMessage(to, "[ INFO ] Error :\n" + str(error)) def command(text): pesan = text.lower() if settings["setKey"] == True: if pesan.startswith(settings["keyCommand"]): cmd = pesan.replace(settings["keyCommand"],"") else: cmd = "Undefined command" else: cmd = text.lower() return cmd def helpmessage(): if settings['setKey'] == True: key = settings['keyCommand'] else: key = '' helpMessage = "\n 「 HELPER 」 " + "\n" + \ " " + key + "1) #Token" + "\n" + \ " " + key + "2) #Keluar" + "\n\n" + \ " " + key + " 「 CEKSIDER 」" + "\n" + \ " " + key + "3) #Ceksider On/Off - [For SetRead]" + "\n" + \ " " + key + "4) #Ceksider reset - [For Reset reader point]" + "\n" + \ " " + key + "5) #Ceksider - [For Ceksider]" + "\n\n" + \ " " + key + " 「 Use # For the Prefix 」" + "\n" + \ " 「 From Helloworld / Edited by Puy 」" return helpMessage def helpstat(): if settings['setKey'] == True: key = settings['keyCommand'] else: key = '' helpStat = "\n[ Status Command ]" + "\n" + \ " " + key + "Reboot" + "\n" + \ " " + key + "Runtime" + "\n" + \ " " + key + "Speed" + "\n" + \ " " + key + "Status" + "\n" + \ " MyPrefix" + "\n" + \ " Prefix「On/Off」" + "\n" + \ "" return helpStat def helpsett(): if settings['setKey'] == True: key = settings['keyCommand'] else: key = '' helpSett = "\n[ Settings Command ] " + "\n" + \ " " + key + "1- AutoAdd「On/Off」" + "\n" + \ " " + key + "2- AutoJoin「On/Off」" + "\n" + \ " " + key + "3- AutoJoinTicket「On/Off」" + "\n" + \ " " + key + "4- AutoLeave「On/Off」" + "\n" + \ " " + key + "5- AutoRead「On/Off」" + "\n" + \ " " + key + "6- AutoRespon「On/Off」" + "\n" + \ " " + key + "7- CheckContact「On/Off」" + "\n" + \ " " + key + "8- CheckPost「On/Off」" + "\n" + \ " " + key + "9- CheckSticker「On/Off」" + "\n" + \ " " + key + "10- UnsendChatDetect「On/Off」" + "\n" + \ " " return helpSett def helpself(): if settings['setKey'] == True: key = settings['keyCommand'] else: key = '' helpSelf = "\n[ Self Command ] " + "\n" + \ " " + key + "ChangeName:「Query」" + "\n" + \ " " + key + "ChangeBio:「Query」" + "\n" + \ " " + key + "Me" + "\n" + \ " " + key + "MyMid" + "\n" + \ " " + key + "MyName" + "\n" + \ " " + key + "MyBio" + "\n" + \ " " + key + "MyPicture" + "\n" + \ " " + key + "MyVideoProfile" + "\n" + \ " " + key + "MyCover" + "\n" + \ " " + key + "StealContact「Mention」" + "\n" + \ " " + key + "StealMid「Mention」" + "\n" + \ " " + key + "StealName「Mention」" + "\n" + \ " " + key + "StealBio「Mention」" + "\n" + \ " " + key + "StealPicture「Mention」" + "\n" + \ " " + key + "StealVideoProfile「Mention」" + "\n" + \ " " + key + "StealCover「Mention」" + "\n" + \ " " + key + "CloneProfile「Mention」" + "\n" + \ " " + key + "Mention" + "\n" + \ " " + key + "Lurking「On/Off/Reset」" + "\n" + \ " " + key + "Lurking" + "\n" + \ " " + key + "RestoreProfile" + "\n" + \ " " + key + "Crash" + "\n" + \ " " + key + "BackupProfile" + "\n" + \ " " + key + "Changedp" + "\n" + \ " " return helpSelf def helpmessaged(): if settings['setKey'] == True: key = settings['keyCommand'] else: key = '' helpMessaged = "\n[ CONTINUANCE ] " + "\n\n" + \ " " + key + "10- #List Token" + "\n" + \ " " + key + "11- #Me" + "\n" + \ " " + key + "12- #Mentioning" + "\n" + \ " " + key + "13- #InstaStory (UserName)*(Number)" + "\n" + \ " " + key + "14- #Acaratv" + "\n" + \ " " + key + "15- #Pc @ (text)" + "\n" + \ " " + key + "16- #Pm @ (text)" + "\n" + \ " " + key + "17- #Carigambar (text)" + "\n" + \ " " + key + "18- #Screenshot (1/2/3) (urlweb)" + "\n" + \ " " + key + "19- #Carimusik (judul dan penyanyi)" + "\n" + \ " " + key + "20- #Murottal [numb 1/2/3]" + "\n" + \ " " + key + "21- #GroupCreator" + "\n" + \ " " + key + "22- #Announce" + " ~[OFF]\n" + \ " " + key + "23- #Delannounce" + "\n" + \ " " + key + "24- #GroupId" + "\n" + \ " " + key + "25- #GroupName" + "\n" + \ " " + key + "26- #GroupPicture" + "\n" + \ " " + key + "27- #GroupTicket ON/OFF" + "\n" + \ " " + key + "28- #GroupTicket" + "\n" + \ " " + key + "29- #GroupList" + "\n" + \ " " + key + "30- #spam text*number" + "\n" + \ " " + key + "31- #GroupMemberList" + "\n" + \ " " + key + "32- #GroupInfo" + "\n" + \ " " + key + "33- #Call [nomor]" + "\n" + \ " " + key + "34- #Sms [nomor]" + "\n\n" + \ " " + key + " [ Use # ]" + "\n" + \ " " return helpMessaged def helpgroup(): if settings['setKey'] == True: key = settings['keyCommand'] else: key = '' helpGroup = "\n[ Group Command ] " + "\n" + \ " " + key + "GroupCreator" + "\n" + \ " " + key + "Announce" + "\n" + \ " " + key + "Delannounce" + "\n" + \ " " + key + "GroupId" + "\n" + \ " " + key + "GroupName" + "\n" + \ " " + key + "GroupPicture" + "\n" + \ " " + key + "GroupTicket" + "\n" + \ " " + key + "GroupTicket「On/Off」" + "\n" + \ " " + key + "GroupList" + "\n" + \ " " + key + "GroupMemberList" + "\n" + \ " " + key + "GroupInfo" + "\n" + \ " " + key + "Changegp" + "\n" + \ " " + "" + "" + \ " " return helpGroup def helptexttospeech(): if settings['setKey'] == True: key = settings['keyCommand'] else: key = '' helpTextToSpeech = " [ Help TextToSpeech ] " + "\n" + \ " " + key + "af : Afrikaans" + "\n" + \ " " + key + "sq : Albanian" + "\n" + \ " " + key + "ar : Arabic" + "\n" + \ " " + key + "hy : Armenian" + "\n" + \ " " + key + "bn : Bengali" + "\n" + \ " " + key + "ca : Catalan" + "\n" + \ " " + key + "zh : Chinese" + "\n" + \ " " + key + "zhcn : Chinese (Mandarin/China)" + "\n" + \ " " + key + "zhtw : Chinese (Mandarin/Taiwan)" + "\n" + \ " " + key + "zhyue : Chinese (Cantonese)" + "\n" + \ " " + key + "hr : Croatian" + "\n" + \ " " + key + "cs : Czech" + "\n" + \ " " + key + "da : Danish" + "\n" + \ " " + key + "nl : Dutch" + "\n" + \ " " + key + "en : English" + "\n" + \ " " + key + "enau : English (Australia)" + "\n" + \ " " + key + "enuk : English (United Kingdom)" + "\n" + \ " " + key + "enus : English (United States)" + "\n" + \ " " + key + "eo : Esperanto" + "\n" + \ " " + key + "fi : Finnish" + "\n" + \ " " + key + "fr : French" + "\n" + \ " " + key + "de : German" + "\n" + \ " " + key + "el : Greek" + "\n" + \ " " + key + "sk : Slovak" + "\n" + \ " " + "" + "\n" + \ "[ Usage : " + key + "say-id Dap ]" return helpTextToSpeech def helptexttospeechh(): if settings['setKey'] == True: key = settings['keyCommand'] else: key = '' helpTextToSpeechh = " [ Help TextToSpeech 2 ] " + "\n" + \ " " + key + "hi : Hindi" + "\n" + \ " " + key + "hu : Hungarian" + "\n" + \ " " + key + "is : Icelandic" + "\n" + \ " " + key + "id : Indonesian" + "\n" + \ " " + key + "it : Italian" + "\n" + \ " " + key + "ja : Japanese" + "\n" + \ " " + key + "km : Khmer (Cambodian)" + "\n" + \ " " + key + "ko : Korean" + "\n" + \ " " + key + "la : Latin" + "\n" + \ " " + key + "lv : Latvian" + "\n" + \ " " + key + "mk : Macedonian" + "\n" + \ " " + key + "no : Norwegian" + "\n" + \ " " + key + "pl : Polish" + "\n" + \ " " + key + "pt : Portuguese" + "\n" + \ " " + key + "ro : Romanian" + "\n" + \ " " + key + "ru : Russian" + "\n" + \ " " + key + "sr : Serbian" + "\n" + \ " " + key + "si : Sinhala" + "\n" + \ " " + key + "es : Spanish" + "\n" + \ " " + key + "eses : Spanish (Spain)" + "\n" + \ " " + key + "esus : Spanish (United States)" + "\n" + \ " " + key + "sw : Swahili" + "\n" + \ " " + key + "sv : Swedish" + "\n" + \ " " + key + "ta : Tamil" + "\n" + \ " " + key + "th : Thai" + "\n" + \ " " + key + "tr : Turkish" + "\n" + \ " " + key + "uk : Ukrainian" + "\n" + \ " " + key + "vi : Vietnamese" + "\n" + \ " " + key + "cy : Welsh" + "\n" + \ " " + "" + "\n" + \ "[ Usage : " + key + "say-id Dap ]" return helpTextToSpeechh def helptranslate(): if settings['setKey'] == True: key = settings['keyCommand'] else: key = '' helpTranslate = " [ Help Translate ] " + "\n" + \ " " + key + "af : afrikaans" + "\n" + \ " " + key + "sq : albanian" + "\n" + \ " " + key + "am : amharic" + "\n" + \ " " + key + "ar : arabic" + "\n" + \ " " + key + "hy : armenian" + "\n" + \ " " + key + "az : azerbaijani" + "\n" + \ " " + key + "eu : basque" + "\n" + \ " " + key + "be : belarusian" + "\n" + \ " " + key + "bn : bengali" + "\n" + \ " " + key + "bs : bosnian" + "\n" + \ " " + key + "bg : bulgarian" + "\n" + \ " " + key + "ca : catalan" + "\n" + \ " " + key + "ceb : cebuano" + "\n" + \ " " + key + "ny : chichewa" + "\n" + \ " " + key + "zhcn : chinese (simplified)" + "\n" + \ " " + key + "zhtw : chinese (traditional)" + "\n" + \ " " + key + "co : corsican" + "\n" + \ " " + key + "hr : croatian" + "\n" + \ " " + key + "cs : czech" + "\n" + \ " " + key + "da : danish" + "\n" + \ " " + key + "nl : dutch" + "\n" + \ " " + key + "en : english" + "\n" + \ " " + key + "eo : esperanto" + "\n" + \ " " + key + "et : estonian" + "\n" + \ " " + key + "tl : filipino" + "\n" + \ " " + key + "fi : finnish" + "\n" + \ " " + key + "fr : french" + "\n" + \ " " + key + "fy : frisian" + "\n" + \ " " + key + "gl : galician" + "\n" + \ " " + key + "ka : georgian" + "\n" + \ " " + key + "de : german" + "\n" + \ " " + "\n" + "\n" + \ "[ Usage : " + key + "tr-id Dapi ]" return helpTranslate def helptranslated(): if settings['setKey'] == True: key = settings['keyCommand'] else: key = '' helpTranslated =" [ Help Translate 2 ] " + "\n" + \ " " + key + "hi : hindi" + "\n" + \ " " + key + "hmn : hmong" + "\n" + \ " " + key + "hu : hungarian" + "\n" + \ " " + key + "is : icelandic" + "\n" + \ " " + key + "ig : igbo" + "\n" + \ " " + key + "id : indonesian" + "\n" + \ " " + key + "ga : irish" + "\n" + \ " " + key + "it : italian" + "\n" + \ " " + key + "ja : japanese" + "\n" + \ " " + key + "jw : javanese" + "\n" + \ " " + key + "kn : kannada" + "\n" + \ " " + key + "kk : kazakh" + "\n" + \ " " + key + "km : khmer" + "\n" + \ " " + key + "ko : korean" + "\n" + \ " " + key + "ku : kurdish (kurmanji)" + "\n" + \ " " + key + "ky : kyrgyz" + "\n" + \ " " + key + "lo : lao" + "\n" + \ " " + key + "la : latin" + "\n" + \ " " + key + "lv : latvian" + "\n" + \ " " + key + "lt : lithuanian" + "\n" + \ " " + key + "ro : romanian" + "\n" + \ " " + key + "uk : ukrainian" + "\n" + \ " " + key + "ur : urdu" + "\n" + \ " " + key + "uz : uzbek" + "\n" + \ " " + key + "vi : vietnamese" + "\n" + \ " " + key + "cy : welsh" + "\n" + \ " " + key + "xh : xhosa" + "\n" + \ " " + key + "yi : yiddish" + "\n" + \ " " + key + "yo : yoruba" + "\n" + \ " " + key + "zu : zulu" + "\n" + \ " " + key + "fil : Filipino" + "\n" + \ " " + key + "he : Hebrew" + "\n" + \ " " + "" + "\n" + \ "[ Usage : " + key + "tr-id Dapi ]" return helpTranslated #def puyBot(op): # try: # if op.type == 0: # print ("[ 0 ] END OF OPERATION") # return # if op.type == 5: # print ("[ 5 ] NOTIFIED ADD CONTACT") # if settings["autoAdd"] == True: # dap.sendMessage(op.param1, "Halo {} terimakasih telah menambahkan saya sebagai teman :D".format(str(dap.getContact(op.param1).displayName))) # if op.type == 13: # print ("[ 13 ] NOTIFIED INVITE INTO GROUP") # group = dap.getGroup(op.param1) # contact = dap.getContact(op.param2) # if settings["autoJoin"] == True: # if settings["autoReject"]["status"] == True: # if len(group.members) > settings["autoReject"]["members"]: # dap.acceptGroupInvitation(op.param1) # else: # dap.rejectGroupInvitation(op.param1) # else: # dap.acceptGroupInvitation(op.param1) # gInviMids = [] # for z in group.invitee: # if z.mid in op.param3: # gInviMids.append(z.mid) # listContact = "" # if gInviMids != []: # for j in gInviMids: # name_ = dap.getContact(j).displayName # listContact += "\n + {}".format(str(name_)) # arg = " Group Name : {}".format(str(group.name)) # arg += "\n Executor : {}".format(str(contact.displayName)) # arg += "\n List User Invited : {}".format(str(listContact)) # print (arg) def dapBot(op): try: if op.type == 0: print ("[ 0 ] END OF OPERATION") return #if op.type == 5: # print ("[ 5 ] NOTIFIED ADD CONTACT") # if settings["autoAdd"] == True: # dap.findAndAddContactsByMid(op.param2) # sendMessageWithFooter(op.param1, "Thx for add") if op.type == 5: if wait["autoAdd"] == True: dap.findAndAddContactsByMid(op.param1) if (wait["message"] in [""," ","\n",None]): pass else: dap.sendMessage(op.param1,str(wait["message"])) if op.type == 5: print ("[ 5 ] NOTIFIED ADD CONTACT") contact = dap.getContact(op.param2) if settings["autoAdd"] == True: dap.sendMessage(op.param1, "Hi {} Thx for add".format(str(dap.getContact(op.param1).displayName))) if op.type == 13: print ("[ 13 ] NOTIFIED INVITE INTO GROUP") if settings["autoJoin"] == True: gid = dap.getGroup(op.param1) gid = pi.getGroup(op.param1) dap.sendMessage(op.param2, "[ Nama Group ]\n" + gid.name) dap.acceptGroupInvitation(op.param1) dap.sendMessage(op.param2, "Thx for invite me to group\nKetik help untuk lebih lanjut") dap.sendMessage(op.param2, "Thx for invited me\n'help' for more!") if op.type == 17: if op.param2 in Admin: if op.param2 not in Bots: return ginfo = dap.getGroup(op.param1) contact = dap.getContact(op.param2) image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus c = Message(to=op.param1, text=None, contentType=13) c.contentMetadata={'mid':op.param2} dap.sendMessage(c) dap.sendMessage(op.param1," Hi" + dap.getContact(op.param2).displayName + "\nWlc To ☞ " + str(ginfo.name) + " ☜" + "\n") dap.sendImageWithURL(op.param1,image) d = Message(to=op.param1, text=None, contentType=7) d.contentMetadata={ "STKID": "247", "STKPKGID": "3", "STKVER": "100" } dap.sendMessage(d) print ("MEMBER JOIN TO GROUP") if op.type in [22, 24]: print ("[ 22 And 24 ] NOTIFIED INVITE INTO ROOM & NOTIFIED LEAVE ROOM") if settings["autoLeave"] == True: sendMention(op.param2, "@! hmm?") dap.leaveRoom(op.param1) if op.type == 19: print ("[ 19 ] NOTIFIED KICKOUT FROM GROUP") group = dap.getGroup(op.param1) contact = dap.getContact(op.param2) victim = dap.getContact(op.param3) arg = " Group Name : {}".format(str(group.name)) arg += "\n Executor : {}".format(str(contact.displayName)) arg += "\n Victim : {}".format(str(victim.displayName)) print (arg) if op.type == 26: msg = op.message if msg.contentType == 13: if settings["wblack"] == True: if msg.contentMetadata["mid"] in settings["commentBlack"]: dap.sendMessage(msg.to,"sudah masuk daftar hitam") settings["wblack"] = False else: settings["commentBlack"][msg.contentMetadata["mid"]] = True settings["wblack"] = False dap.sendMessage(msg.to,"Itu tidak berkomentar") elif settings["dblack"] == True: if msg.contentMetadata["mid"] in settings["commentBlack"]: del settings["commentBlack"][msg.contentMetadata["mid"]] dap.sendMessage(msg.to,"Done") settings["dblack"] = False else: settings["dblack"] = False dap.sendMessage(msg.to,"Tidak ada dalam daftar hitam") if op.type == 26: try: print ("[ 26 ] SEND MESSAGE") msg = op.message text = msg.text msg_id = msg.id receiver = msg.to sender = msg._from setKey = settings["keyCommand"].title() if settings["setKey"] == False: setKey = '' if msg.toType == 0 or msg.toType == 1 or msg.toType == 2: if msg.toType == 0: if sender != dap.profile.mid: to = sender else: to = receiver elif msg.toType == 1: to = receiver elif msg.toType == 2: to = receiver if msg.contentType == 0: if text is None: return else: cmd = command(text) if cmd == "help": helpMessage = helpmessage() dap.sendMessage(to, str(helpMessage),{'AGENT_ICON':'http://dl.profile.line-cdn.net/0hkY3juiptNHYOExk5wsdLITJWOht5PTI-diUpGX8RPhZ0IydzMSV_FC0VaxV0I3JyMCZ4Ei8VOEQh','AGENT_LINK':'https://line.me/ti/p/~yapuy','AGENT_NAME':'Help Message'}) #sendMentionFooter(to, "@! - <NAME>", str(helpMessage), {'AGENT_LINK': 'line://ti/p/~yapuy'.'AGENT_ICON':'https://obs-sg.line-apps.com/myhome/c/download.nhn?userid=uac8e3eaf1eb2a55770bf10c3b2357c33&oid=8a257936867f1ac24ef8434b13b799e5','AGENT_NAME':'HELPER'}) #sendMention(to, "@!", str(helpMessage), [sender])) #dap.sendMessage(to, str(helpMessage),{'AGENT_ICON':'http://dl.profile.line-cdn.net/'+dap.pictureStatus,'AGENT_LINK':'https://line.me/ti/p/~yapuy','AGENT_NAME':'Mkhadaffy'}) if cmd == "help2": helpMessaged = helpmessaged() dap.sendMessage(to, str(helpMessaged),{'AGENT_ICON':'http://dl.profile.line-cdn.net/0hkY3juiptNHYOExk5wsdLITJWOht5PTI-diUpGX8RPhZ0IydzMSV_FC0VaxV0I3JyMCZ4Ei8VOEQh','AGENT_LINK':'https://line.me/ti/p/~yapuy','AGENT_NAME':'Help Message 2'}) #if cmd.startswith('ls'): #a = subprocess.getoutput(cmd[1]) #dap.sendMessage(to, a) #if cmd[0].startswith('cd'): #a = subprocess.getoutput(cmd[1]) #dap.sendMessage(to, a) if cmd == "tts2": helpTextToSpeechh = helptexttospeechh() dap.sendMessage(to, str(helpTextToSpeechh),{'AGENT_ICON':'http://dl.profile.line-cdn.net/0hkY3juiptNHYOExk5wsdLITJWOht5PTI-diUpGX8RPhZ0IydzMSV_FC0VaxV0I3JyMCZ4Ei8VOEQh','AGENT_LINK':'https://line.me/ti/p/~yapuy','AGENT_NAME':'Help TTS 2'}) elif cmd == "tts": helpTextToSpeech = helptexttospeech() #dap.sendMessage(to, str(helpTextToSpeech)) dap.sendMessage(to, str(helpTextToSpeech),{'AGENT_ICON':'http://dl.profile.line-cdn.net/0hkY3juiptNHYOExk5wsdLITJWOht5PTI-diUpGX8RPhZ0IydzMSV_FC0VaxV0I3JyMCZ4Ei8VOEQh','AGENT_LINK':'https://line.me/ti/p/~yapuy','AGENT_NAME':'Help TTS'}) elif cmd == "#token generator": sendMentionFooter(to, "「 TOKEN TIPE 」\n1* DESKTOPWIN\n2* WIN10\n3* DESKTOPMAC\n4* IOSPAD\n5* CHROME\n\n*Usage : Type #login with Token Type\n\n*Example : #login chrome\n\n[ From BotEater / Edited by Puy ]\n@! - Selamat Mencoba.", [sender]) elif cmd == "#token": sendMentionFooter(to, "「 TOKEN TIPE 」\n1* DESKTOPWIN\n2* WIN10\n3* DESKTOPMAC\n4* IOSPAD\n5* CHROME\n\n*Usage : Type #login with Token Type\n\n*Example : #login chrome\n\n[ From BotEater / Edited by Puy ]\n@! - Selamat Mencoba.", [sender]) elif cmd == "selfcmd": if msg._from in Owner: helpSelf = helpself() dap.sendMessage(to, str(helpSelf),{'AGENT_ICON':'http://dl.profile.line-cdn.net/0hkY3juiptNHYOExk5wsdLITJWOht5PTI-diUpGX8RPhZ0IydzMSV_FC0VaxV0I3JyMCZ4Ei8VOEQh','AGENT_LINK':'https://line.me/ti/p/~yapuy','AGENT_NAME':'Help Self'}) elif cmd == "translate": if msg._from in Owner: helpTranslate = helptranslate() dap.sendMessage(to, str(helpTranslate),{'AGENT_ICON':'http://dl.profile.line-cdn.net/0hkY3juiptNHYOExk5wsdLITJWOht5PTI-diUpGX8RPhZ0IydzMSV_FC0VaxV0I3JyMCZ4Ei8VOEQh','AGENT_LINK':'https://line.me/ti/p/~yapuy','AGENT_NAME':'Help Translate'}) #dap.sendMessage(to, str(helpTranslate)) elif cmd == "statcmd": if msg._from in Owner: helpStat = helpstat() dap.sendMessage(to, str(helpStat),{'AGENT_ICON':'http://dl.profile.line-cdn.net/0hkY3juiptNHYOExk5wsdLITJWOht5PTI-diUpGX8RPhZ0IydzMSV_FC0VaxV0I3JyMCZ4Ei8VOEQh','AGENT_LINK':'https://line.me/ti/p/~yapuy','AGENT_NAME':'Help Stat'}) elif cmd == "settcmd": if msg._from in Owner: helpSett = helpsett() dap.sendMessage(to, str(helpSett),{'AGENT_ICON':'http://dl.profile.line-cdn.net/0hkY3juiptNHYOExk5wsdLITJWOht5PTI-diUpGX8RPhZ0IydzMSV_FC0VaxV0I3JyMCZ4Ei8VOEQh','AGENT_LINK':'https://line.me/ti/p/~yapuy','AGENT_NAME':'Help Sett'}) elif cmd == "groupcmd": if msg._from in Owner: helpGroup = helpgroup() dap.sendMessage(to, str(helpGroup),{'AGENT_ICON':'http://dl.profile.line-cdn.net/0hkY3juiptNHYOExk5wsdLITJWOht5PTI-diUpGX8RPhZ0IydzMSV_FC0VaxV0I3JyMCZ4Ei8VOEQh','AGENT_LINK':'https://line.me/ti/p/~yapuy','AGENT_NAME':'Help Group'}) elif cmd == "translate2": if msg._from in Owner: helpTranslated = helptranslated() dap.sendMessage(to, str(helpTranslated),{'AGENT_ICON':'http://dl.profile.line-cdn.net/0hkY3juiptNHYOExk5wsdLITJWOht5PTI-diUpGX8RPhZ0IydzMSV_FC0VaxV0I3JyMCZ4Ei8VOEQh','AGENT_LINK':'https://line.me/ti/p/~yapuy','AGENT_NAME':'Help Translate 2'}) elif cmd.startswith("changeprefix:"): if msg._from in Owner: sep = text.split(" ") key = text.replace(sep[0] + " ","") if " " in key: dap.sendMessage(to, "\nTanpa spasi.\n") else: settings["keyCommand"] = str(key).lower() dap.sendMessage(to, "text [ {} ]".format(str(key).lower())) elif cmd == "#speed": tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] Timed = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" start = time.time() if msg.to not in read['readPoint']: #dap.sendMessage(to, "「 NOTIFIED BOT SPEED 」\nKecepatan mengirim pesan {} detik dap".format(str(elapsed_time))) dap.sendMessage(msg.to, "「 NOTIFIED BOT SPEED 」\n\n" + Timed) #dap.sendMessage(to, "") elapsed_time = time.time() - start dap.sendMessage(to, "[ Speed ]\nKecepatan mengirim pesan {} detik dap".format(str(elapsed_time))) elif cmd == "#runtime": timeNow = time.time() runtime = timeNow - botStart runtime = format_timespan(runtime) dap.sendMessage(to, "Bot has been Active for {} puy".format(str(runtime))) #elif cmd == "lurk": # dap.sendMessage(to, "[ Notified Check Readers ]\n\n Usage : type lurking on , lurking ") elif cmd == "#restart": if msg._from in Owner: tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] Timed = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" start = time.time() if msg.to not in read['readPoint']: dap.sendMessage(msg.to, "「 NOTIFIED BOT SPEED 」\n\n" + Timed) sendMention(to, "@! \nBot Restarted", [sender]) restartBot() else: dap.sendMessage("Permission Denied") # Pembatas Script # elif cmd.startswith("#add:admin "): if msg._from in Owner: tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] Timed = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to not in read['readPoint']: dap.sendMessage(msg.to, "「 NOTIFIED ADDED ADMIN 」") targets = [] key = eval(msg.contentMetadata["MENTION"]) key["MENTIONEES"][0]["M"] for x in key["MENTIONEES"]: targets.append(x["M"]) for target in targets: try: Admin[target] = True f=codecs.open('Admin.json','w','utf-8') json.dump(Admin, f, sort_keys=True, indent=4,ensure_ascii=False) dap.sendMessage(msg.to,"Successed Added 1 Admin\n\n" + Timed) break except: dap.sendMessage(msg.to,"Failed\n\n" + Timed) break else: dap.sendMessage(msg.to,"Owner Permission Required" + Timed) elif cmd.startswith("#remove:admin "): if msg._from in Owner: tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] Timed = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to not in read['readPoint']: dap.sendMessage(msg.to, "「 NOTIFIED REMOVED ADMIN 」") targets = [] key = eval(msg.contentMetadata["MENTION"]) key["MENTIONEES"][0]["M"] for x in key["MENTIONEES"]: targets.append(x["M"]) for target in targets: try: del Admin[target] f=codecs.open('Admin.json','w','utf-8') json.dump(Admin, f, sort_keys=True, indent=4,ensure_ascii=False) dap.sendMessage(msg.to,"Successed Removed 1 Admin\n\n" + Timed) break except: dap.sendMessage(msg.to,"Failed\n\n" + Timed) break else: dap.sendMessage(msg.to,"Owner Permission Required" + Timed) elif cmd.startswith('#adminlist'): tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] Timed = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to not in read['readPoint']: dap.sendMessage(msg.to, "「 Please Wait 」") if Admin == []: dap.sendMessage(msg.to,"「 No one Admin 」") else: #dap.sendMessage(msg.to,"") mc = " 「 Admin List 」\n\n" for mi_d in Admin: mc += "" +dap.getContact(mi_d).displayName + "\n\n" dap.sendMessage(msg.to,mc + "" + Timed) elif cmd.startswith('#ownerlist'): tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] Timed = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to not in read['readPoint']: dap.sendMessage(msg.to, "「 Please Wait 」") if Owner == []: dap.sendMessage(msg.to,"「 No one Owner 」") else: #dap.sendMessage(msg.to,"") mc = " 「 Owner List 」\n\n" for mi_d in Owner: mc += "" +dap.getContact(mi_d).displayName + "\n\n" dap.sendMessage(msg.to,mc + " " + Timed) #------------------------------------------------------------------------------- elif cmd.startswith('#protect on'): if msg._from in Owner: tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] Timed = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to not in read['readPoint']: dap.sendMessage(msg.to, "「 NOTIFIED ACTIVIED PROTECTION 」") if settings["protect"] == True: if settings["lang"] == "JP": dap.sendMessage(msg.to,"Protection Already On At\n\n" + Timed) else: dap.sendMessage(msg.to,"Protection Set To On At\n\n" + Timed) else: settings["protect"] = True if settings["lang"] == "JP": dap.sendMessage(msg.to,"Protection Set To On At\n\n" + Timed) else: dap.sendMessage(msg.to,"Protection Already On At\n\n" + Timed) elif cmd.startswith('#protect off'): if msg._from in Owner: tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] Timed = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to not in read['readPoint']: dap.sendMessage(msg.to, "「 NOTIFIED UNACTIVIED PROTECTION 」") if settings["protect"] == False: if settings["lang"] == "JP": dap.sendMessage(msg.to,"Protection Already Off At\n\n" + Timed) else: dap.sendMessage(msg.to,"Protection Set To Off At\n\n" + Timed) else: settings["protect"] = False if settings["lang"] == "JP": dap.sendMessage(msg.to,"Protection Set To Off At\n\n" + Timed) else: dap.sendMessage(msg.to,"Protection Already Off At\n\n" + Timed) #---------------------------------------------------------------------------------------- elif cmd.startswith('#qrprotect on'): if msg._from in Owner: tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] Timed = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to not in read['readPoint']: dap.sendMessage(msg.to, "「 NOTIFIED ACTIVIED QR PROTECTION 」") if settings["qrprotect"] == True: if settings["lang"] == "JP": dap.sendMessage(msg.to,"Protection Qr Already On\n\n" + Timed) else: dap.sendMessage(msg.to,"Protection Qr Set To On\n\n") else: settings["qrprotect"] = True if settings["lang"] == "JP": dap.sendMessage(msg.to,"Protection Qr Set To On\n\n" + Timed) else: dap.sendMessage(msg.to,"Protection Qr Already On\n\n") elif cmd.startswith('#qrprotect off'): if msg._from in Owner: tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] Timed = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to not in read['readPoint']: dap.sendMessage(msg.to, "「 NOTIFIED UNACTIVIED QR PROTECTION 」") if settings["qrprotect"] == False: if settings["lang"] == "JP": dap.sendMessage(msg.to,"Protection Qr Already Off\n\n" + Timed) else: dap.sendMessage(msg.to,"Protection Qr Set To Off\n\n") else: settings["qrprotect"] = False if settings["lang"] == "JP": dap.sendMessage(msg.to,"Protection Qr Set To Off\n\n" + Timed) else: dap.sendMessage(msg.to,"Protection Qr Already Off\n\n") #------------------------------------------------------------------------------- elif cmd.startswith('#inviteprotect on'): if msg._from in Owner: tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] Timed = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to not in read['readPoint']: dap.sendMessage(msg.to, "「 NOTIFIED ACTIVIED INVITE PROTECTION 」") if settings["inviteprotect"] == True: if settings["lang"] == "JP": dap.sendMessage(msg.to,"➲ Protection Invite Already On\n\n" + Timed) else: dap.sendMessage(msg.to,"➲ Protection Invite Set To On\n\n" + Timed) else: settings["inviteprotect"] = True if settings["lang"] == "JP": dap.sendMessage(msg.to,"➲ Protection Invite Set To On\n\n" + Timed) else: dap.sendMessage(msg.to,"➲ Protection Invite Already On\n\n" + Timed) elif cmd.startswith('#inviteprotect off'): if msg._from in Owner: tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] Timed = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to not in read['readPoint']: dap.sendMessage(msg.to, "「 NOTIFIED UNACTIVIED INVITE PROTECTION 」") if settings["inviteprotect"] == False: if settings["lang"] == "JP": dap.sendMessage(msg.to,"➲ Protection Invite Already Off\n\n" + Timed) else: dap.sendMessage(msg.to,"➲ Protection Invite Set To Off\n\n" + Timed) else: settings["inviteprotect"] = False if settings["lang"] == "JP": dap.sendMessage(msg.to,"➲ Protection Invite Set To Off\n\n" + Timed) else: dap.sendMessage(msg.to,"➲ Protection Invite Already Off\n\n" + Timed) #------------------------------------------------------------------------------- elif cmd.startswith('#cancelprotect on'): if msg._from in Owner: tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] Timed = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to not in read['readPoint']: dap.sendMessage(msg.to, "「 NOTIFIED ACTIVIED CANCEL PROTECTION 」") if settings["cancelprotect"] == True: if settings["lang"] == "JP": dap.sendMessage(msg.to,"➲ Protection Cancel Invite Already On\n\n" + Timed) else: dap.sendMessage(msg.to,"➲ Protection Cancel Invite Set To On\n\n" + Timed) else: settings["cancelprotect"] = True if settings["lang"] == "JP": dap.sendMessage(msg.to,"➲ Protection Cancel Invite Set To On\n\n" + Timed) else: dap.sendMessage(msg.to,"➲ Protection Cancel Invite Already On\n\n" + Timed) elif cmd.startswith('#cancelprotect off'): if msg._from in Owner: tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] Timed = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to not in read['readPoint']: dap.sendMessage(msg.to, "「 NOTIFIED UNACTIVIED CANCEL PROTECTION 」") if settings["cancelprotect"] == False: if settings["lang"] == "JP": dap.sendMessage(msg.to,"➲ Protection Cancel Invite Already Off\n\n" + Timed) else: dap.sendMessage(msg.to,"➲ Protection Cancel Invite Set To Off\n\n" + Timed) else: settings["cancelprotect"] = False if settings["lang"] == "JP": dap.sendMessage(msg.to,"➲ Protection Cancel Invite Set To Off\n\n" + Timed) else: dap.sendMessage(msg.to,"➲ Protection Cancel Invite Already Off\n\n" + Timed) #------------------------------------------------------------------------------- elif cmd.startswith('#setpro on'): if msg._from in Owner: tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] Timed = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to not in read['readPoint']: dap.sendMessage(msg.to, "「 NOTIFIED ACTIVIED PROTECTION 」") settings["protect"] = True settings["qrprotect"] = True settings["inviteprotect"] = True settings["cancelprotect"] = True dap.sendMessage(msg.to,"All Protection Set To On\n\n" + Timed) else: dap.sendMessage(msg.to,"This Command only Applies to Owner\n\n" + Timed) elif cmd.startswith('#setpro off'): if msg._from in Owner: tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] Timed = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to not in read['readPoint']: dap.sendMessage(msg.to, "「 NOTIFIED UNACTIVIED PROTECTION 」") settings["protect"] = False settings["qrprotect"] = False settings["inviteprotect"] = False settings["cancelprotect"] = False dap.sendMessage(msg.to,"All Protection Set To Of\n\nf" + Timed) else: dap.sendMessage(msg.to,"This Command only Applies to Owner\n\n" + Timed) #------------------------------------------------------------------------------- elif cmd.startswith("#pi:join"): if msg._from in Owner: G = dap.getGroup(msg.to) ginfo = dap.getGroup(msg.to) G.preventedJoinByTicket = False dap.updateGroup(G) invsend = 0 Ticket = dap.reissueGroupTicket(msg.to) tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] Timed = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" pi.acceptGroupInvitationByTicket(msg.to,Ticket) pi.sendMessage(to,"Hii Everyone!\n\n" + Timed) if msg.to not in read['readPoint']: sendMention(msg.to, "「 NOTIFIED INVITED TO ROOM 」\nStatus - Successed\n@!\n\n" + Timed, [sender]) G = dap.getGroup(msg.to) G.preventedJoinByTicket = True dap.updateGroup(G) G.preventedJoinByTicket(G) dap.updateGroup(G) elif cmd == "autoadd on": if msg._from in Owner: settings["autoAdd"] = True sendMessageWithMentionAndFooter(to, "@! \n\n[ Notified Auto Add ]\nBerhasil mengaktifkan Auto add", [sender]) elif cmd == "inroom on": if msg._from in Owner: settings["Inroom"] == True sendMention(to, "[ Notified Inroom ]\nBerhasil mengaktifkan Sambutan @!", [sender]) elif cmd == "inroom off": if msg._from in Owner: settings["Inroom"] == False sendMention(to, "[ Notified Inroom ]\nBerhasil menonaktifkan Sambutan @!", [sender]) elif cmd == "outroom on": if msg._from in Owner: settings["Outroom"] == True sendMention(to, "[ Notified Outroom ]\nBerhasil mengaktifkan Sambutan @!", [sender]) elif cmd == "outroom off": if msg._from in Owner: settings["Outroom"] == False sendMention(to, "[ Notified Outroom ]\nBerhasil menonaktifkan Sambutan @!", [sender]) elif cmd == "autoadd off": if msg._from in Owner: settings["autoAdd"] = False sendMention(to, "[ Notified Auto Add ]\nBerhasil menonaktifkan Auto add @!", [sender]) elif cmd == "autojoin on": if msg._from in Owner: settings["autoJoin"] = True sendMention(to, "[ Notified Auto Join ]\nBerhasil mengaktifkan Auto Join @!", [sender]) elif cmd == "autojoin off": if msg._from in Owner: settings["autoJoin"] = False sendMention(to, "[ Notified Auto Join ]\nBerhasil menonaktifkan Auto Join @!", [sender]) elif cmd == "changedp on": if msg._from in Owner: settings["changeDisplayPicture"] = True sendMention(to, "[ Notified Dp Changer ]\nBerhasil mengaktifkan DP changer @!", [sender]) elif cmd == "changedp off": if msg._from in Owner: settings["changeDisplayPicture"] = False sendMention(to, "[ Notified Dp Changer ]\nBerhasil menonaktifkan DP changer @!", [sender]) elif cmd == "lurkingset on": if msg._from in Owner: settings["lurk"] = True dap.sendMessage(to, "Lurking is Actived!") elif cmd == "lurkingset off": if msg._from in Owner: settings["lurk"] = False dap.sendMessage(to, "Lurking is Nonactived!") elif cmd == "autoleave on": if msg._from in Owner: settings["autoLeave"] = True sendMention(to, "[ Notified Auto Leave ]\nBerhasil mengaktifkan Auto leave @!", [sender]) elif cmd == "autoleave off": if msg._from in Owner: settings["autoLeave"] = False sendMention(to, "[ Notified Auto Leave ]\nBerhasil menonaktifkan Auto leave @!", [sender]) elif cmd == "autorespon on": if msg._from in Owner: settings["autoRespon"] = True sendMention(to, "[ Notified Auto Respon ]\nBerhasil mengaktifkan Auto Respon @!", [sender]) elif cmd == "autorespon off": if msg._from in Owner: settings["autoRespon"] = False sendMention(to, "[ Notified Auto Respon ]\nBerhasil menonaktifkan Auto Respon @!", [sender]) elif cmd == "autoread on": if msg._from in Owner: settings["autoRead"] = True sendMention(to, "[ Notified Auto Read ]\nBerhasil mengaktifkan Auto Read @!", [sender]) elif cmd == "autoread off": if msg._from in Owner: settings["autoRead"] = False sendMention(to, "[ Notified Auto Read ]\nBerhasil menonaktifkan Auto Read @!", [sender]) elif cmd == "autojointicket on": if msg._from in Owner: settings["autoJoinTicket"] = True sendMention(to, "[ Notified Auto Join Ticket ]\nBerhasil mengaktifkan Auto join ticket @!", [sender]) elif cmd == "autoJoinTicket off": if msg._from in Owner: settings["autoJoin"] = False sendMention(to, "[ Notified Auto Join Ticket ]\nBerhasil menonaktifkan Auto join ticket @!", [sender]) elif cmd == "checkcontact on": if msg._from in Owner: settings["checkContact"] = True sendMention(to, "[ Notified Check Contact ]\nBerhasil mengaktifkan Check contact @!", [sender]) elif cmd == "checkcontact off": if msg._from in Owner: settings["checkContact"] = False sendMention(to, "[ Notified Check Contact ]\nBerhasil menonaktifkan Check contact @!", [sender]) elif cmd == "checkpost on": if msg._from in Owner: settings["checkPost"] = True sendMention(to, "[ Notified Check Post ]\nBerhasil mengaktifkan Check Post @!", [sender]) elif cmd == "checkpost off": if msg._from in Owner: settings["checkPost"] = False sendMention(to, "[ Notified Check Post ]\nBerhasil menonaktifkan Check Post @!", [sender]) elif cmd == "checksticker on": if msg._from in Owner: settings["checkSticker"] = True sendMention(to, "[ Notified Check Sticker ]\nBerhasil mengaktifkan Check Sticker @!", [sender]) elif cmd == "checksticker off": if msg._from in Owner: settings["checkSticker"] = False sendMention(to, "[ Notified Check Sticker ]\nBerhasil menonaktifkan Check Sticker @!", [sender]) elif cmd == "unsendchat on": if msg._from in Owner: settings["unsendMessage"] = True sendMention(to, "[ Notified UnsendMsg Detect ]\nBerhasil mengaktifkan Unsend Detect @!", [sender]) elif cmd == "unsendchat off": if msg._from in Owner: settings["unsendMessage"] = False sendMention(to, "[ Notified UnsendMsg Detect ]\nBerhasil menonaktifkan Unsend Detect @!", [sender]) elif cmd == "protect on": if msg._from in Owner: settings["protect"] = True sendMention(to, "[ Notified ProtectGroup ]\nBerhasil mengaktifkan protect\n@!", [sender]) elif cmd == "protect off": if msg._from in Owner: settings["protect"] = False sendMention(to, "[ Notified ProtectGroup ]\nBerhasil menonaktifkan protect\n@!", [sender]) elif cmd == "qrprotect on": if msg._from in Owner: settings["qrprotect"] = True sendMention(to, "[ Notified ProtectGroup ]\nBerhasil mengaktifkan qrprotect\n@!", [sender]) elif cmd == "qrprotect off": if msg._from in Owner: settings["qrprotect"] = False sendMention(to, "[ Notified ProtectGroup ]\nBerhasil menonaktifkan qrprotect\n@!", [sender]) elif cmd == "invcancel on": if msg._from in Owner: settings["inviteprotect"] = True sendMention(to, "[ Notified ProtectGroup ]\nBerhasil mengaktifkan InviteCancel\n@!", [sender]) elif cmd == "invcancel off": if msg._from in Owner: settings["inviteprotect"] = False sendMention(to, "[ Notified ProtectGroup ]\nBerhasil mengaktifkan InviteCancel\n@!", [sender]) elif cmd == "cancel on": if msg._from in Owner: settings["cancelprotect"] = True sendMention(to, "[ Notified ProtectGroup ]\nBerhasil mengaktifkan Cancelprotect\n@!", [sender]) elif cmd == "cancel off": if msg._from in Owner: settings["cancelprotect"] = False sendMention(to, "[ Notified ProtectGroup ]\nBerhasil mengaktifkan Cancelprotect\n@!", [sender]) elif cmd == "status": if msg._from in Admin: try: ret_ = "\n [ BOT STATUS ]\n" if settings["autoAdd"] == True: ret_ += "\n [ ON ] Auto Add" else: ret_ += "\n [ OFF ] Auto Add" if settings["autoJoin"] == True: ret_ += "\n [ ON ] Auto Join" else: ret_ += "\n [ OFF ] Auto Join" if settings["autoLeave"] == True: ret_ += "\n [ ON ] Auto Leave Room" else: ret_ += "\n [ OFF ] Auto Leave Room" if settings["autoJoinTicket"] == True: ret_ += "\n [ ON ] Auto Join Ticket" else: ret_ += "\n [ OFF ] Auto Join Ticket" if settings["autoRead"] == True: ret_ += "\n [ ON ] Auto Read" else: ret_ += "\n [ OFF ] Auto Read" if settings["protect"] == True: ret_ += "\n [ ON ] Protect" else: ret_ += "\n [ OFF ] Protect" if settings["qrprotect"] == True: ret_ += "\n [ ON ] Qr Protect" else: ret_ += "\n [ OFF ] Qr Protect" if settings["inviteprotect"] == True: ret_ += "\n [ ON ] Invite Protect" else: ret_ += "\n [ OFF ] Invite Protect" if settings["cancelprotect"] == True: ret_ += "\n [ ON ] Cancel Protect" else: ret_ += "\n [ OFF ] Cancel Protect" if settings["autoRespon"] == True: ret_ += "\n [ ON ] Detect Mention" else: ret_ += "\n [ OFF ] Detect Mention" if settings["checkContact"] == True: ret_ += "\n [ ON ] Check Contact" else: ret_ += "\n [ OFF ] Check Contact" if settings["checkPost"] == True: ret_ += "\n [ ON ] Check Post" else: ret_ += "\n [ OFF ] Check Post" if settings["checkSticker"] == True: ret_ += "\n [ ON ] Check Sticker" else: ret_ += "\n [ OFF ] Check Sticker" if settings["lurk"] == True: ret_ += "\n [ ON ] Lurkset" else: ret_ += "\n [ OFF ] Lurkset" if settings["setKey"] == True: ret_ += "\n [ ON ] Set Key" else: ret_ += "\n [ OFF ] Set Key" if settings["Inroom"] == True: ret_ += "\n [ ON ] Inroom Detect" else: ret_ += "\n [ OFF ] Inroom Detect" if settings["Outroom"] == True: ret_ += "\n [ ON ] Outroom Detect" else: ret_ += "\n [ OFF ] Outroom detect" if settings["unsendMessage"] == True: ret_ += "\n [ ON ] Unsend Message" else: ret_ += "\n [ OFF ] Unsend Message\n" ret_ += "" dap.sendMessage(to, str(ret_)) except Exception as e: dap.sendMessage(to, str(e)) # Pembatas Script # elif cmd.startswith("respon"): dap.sendMessage(to,responsename) pi.sendMessage(to,responsename2) elif cmd.startswith('absen'): if msg._from in Admin: dap.sendContact(to, dapMID) pi.sendContact(to, piMID) elif cmd == "crash": if msg._from in Owner: dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") elif cmd == "spamcrash": if msg._from in Owner: dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") dap.sendContact(to, "u1f41296217e740650e0448b96851a3e2',") elif cmd.startswith("##changename:"): if msg._from in Owner: sep = text.split(" ") string = text.replace(sep[0] + " ","") if len(string) <= 20: profile = dap.getProfile() profile.displayName = string dap.updateProfile(profile) dap.sendMessage(to,"Successfully changed display name to {}".format(str(string))) elif cmd.startswith("##changebio:"): if msg._from in Owner: sep = text.split(" ") string = text.replace(sep[0] + " ","") if len(string) <= 500: profile = dap.getProfile() profile.statusMessage = string dap.updateProfile(profile) dap.sendMessage(to,"Successfully changed status message to {}".format(str(string))) elif cmd == "#me": #sendMention(to, "@!", [sender]) #tgb = dap.getGroup(op.param1) #dan = dap.getContact(op.param2) contact = dap.getContact(sender) sendMentionFooter(to, "At here @!", [sender]) dap.sendContact(to, sender) dap.sendImageWithURL(to,"http://dl.profile.line-cdn.net/{}".format(contact.pictureStatus)) elif cmd == "#mymid": contact = dap.getContact(sender) dap.sendMessage(to, "[ MID ]\n{}".format(sender)) dap.sendImageWithURL(to,"http://dl.profile.line-cdn.net/{}".format(contact.pictureStatus)) elif cmd == "#myname": contact = dap.getContact(sender) dap.sendImageWithURL(to,"http://dl.profile.line-cdn.net/{}".format(contact.pictureStatus)) dap.sendMessage(to, "[ Display Name ]\n{}".format(contact.displayName)) elif cmd == "#mybio": contact = dap.getContact(sender) dap.sendMessage(to, "[ Status Message ]\n{}".format(contact.statusMessage)) dap.sendImageWithURL(to,"http://dl.profile.line-cdn.net/{}".format(contact.pictureStatus)) elif cmd == "#mypicture": contact = dap.getContact(sender) dap.sendImageWithURL(to,"http://dl.profile.line-cdn.net/{}".format(contact.pictureStatus)) elif cmd == "#myvideoprofile": contact = dap.getContact(sender) dap.sendVideoWithURL(to,"http://dl.profile.line-cdn.net/{}/vp".format(contact.pictureStatus)) elif cmd == "#mycover": channel = dap.getProfileCoverURL(sender) path = str(channel) dap.sendImageWithURL(to, path) elif cmd.startswith("#cloneprofile "): if msg._from in Owner: if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) for ls in lists: contact = dap.getContact(ls) dap.cloneContactProfile(ls) dap.sendMessage(to, "Successfully clone profile {}".format(contact.displayName)) elif cmd == "#restoreprofile": if msg._from in Owner: try: clientProfile = dap.getProfile() clientProfile.displayName = str(settings["myProfile"]["displayName"]) clientProfile.statusMessage = str(settings["myProfile"]["statusMessage"]) clientProfile.pictureStatus = str(settings["myProfile"]["pictureStatus"]) dap.updateProfileAttribute(8, clientProfile.pictureStatus) dap.updateProfile(clientProfile) coverId = str(settings["myProfile"]["coverId"]) dap.updateProfileCoverById(coverId) dap.sendMessage(to, "Successfully restore profile wait a while until profile change") except Exception as e: dap.sendMessage(to, "Failed restore profile") logError(error) elif cmd == "#backupprofile": if msg._from in Owner: try: profile = dap.getProfile() settings["myProfile"]["displayName"] = str(profile.displayName) settings["myProfile"]["statusMessage"] = str(profile.statusMessage) settings["myProfile"]["pictureStatus"] = str(profile.pictureStatus) coverId = dap.getProfileDetail()["result"]["objectId"] settings["myProfile"]["coverId"] = str(coverId) dap.sendMessage(to, "Successfully backup profile") except Exception as e: dap.sendMessage(to, "Failed backup profile") logError(error) elif cmd.startswith("#stealmid "): if msg._from in Owner: if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) ret_ = "[ Mid User ]" for ls in lists: ret_ += "\n{}".format(str(ls)) dap.sendMessage(to, str(ret_)) elif cmd.startswith("stealname "): if msg._from in Owner: if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) for ls in lists: contact = dap.getContact(ls) dap.sendMessage(to, "[ Display Name ]\n{}".format(str(contact.displayName))) elif cmd.startswith("#stealbio "): if msg._from in Owner: if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) for ls in lists: contact = dap.getContact(ls) dap.sendMessage(to, "[ Status Message ]\n{}".format(str(contact.statusMessage))) elif cmd.startswith("#stealpicture"): if msg._from in Owner: if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) for ls in lists: contact = dap.getContact(ls) path = "http://dl.profile.line.naver.jp/{}".format(contact.pictureStatus) dap.sendImageWithURL(to, str(path)) elif cmd.startswith("#stealvideoprofile "): if msg._from in Owner: if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) for ls in lists: contact = dap.getContact(ls) path = "http://dl.profile.line.naver.jp/{}/vp".format(contact.pictureStatus) dap.sendVideoWithURL(to, str(path)) elif cmd.startswith("#stealcover "): if msg._from in Owner: if dap != None: if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) for ls in lists: channel = dap.getProfileCoverURL(ls) path = str(channel) dap.sendImageWithURL(to, str(path)) # Pembatas Script # elif cmd == '#groupcreator': group = dap.getGroup(to) GS = group.creator.mid dap.sendContact(to, GS) elif cmd == '#groupid': gid = dap.getGroup(to) dap.sendMessage(to, "[ ID Group ]\n" + gid.id) elif cmd == '#grouppicture': group = dap.getGroup(to) path = "http://dl.profile.line-cdn.net/" + group.pictureStatus dap.sendImageWithURL(to, path) elif cmd == '#groupname': gid = dap.getGroup(to) dap.sendMessage(to, "[ Nama Group ]\n" + gid.name) elif cmd == '#groupticket': if msg.toType == 2: group = dap.getGroup(to) if group.preventedJoinByTicket == False: ticket = dap.reissueGroupTicket(to) dap.sendMessage(to, "[ Group Ticket ]\nhttps://line.me/R/ti/g/{}".format(str(ticket))) else: dap.sendMessage(to, "Group Qr not has been Set\nPlease type #groupticket on for opened a groupqr{}openqr".format(str(settings["keyCommand"]))) elif cmd == '#groupticket on': if msg.toType == 2: group = dap.getGroup(to) if group.preventedJoinByTicket == False: sendMentionFooter(to, "[ Group Ticket ]\n Status - GROUP TICKET HAS BEEN ENABLED!\n@!", [sender]) else: group.preventedJoinByTicket = False dap.updateGroup(group) sendMentionFooter(to, "[ Group Ticket ]\n Status - GROUP TICKET HAS BEEN ENABLED!\n@!", [sender]) elif cmd == '#groupticket off': if msg.toType == 2: group = dap.getGroup(to) if group.preventedJoinByTicket == True: sendMentionFooter(to, "[ Group Ticket ]\n Status - GROUP TICKET HAS BEEN DISABLED!\n@!", [sender]) #dap.sendMessage(to, "The qr group is already closed") else: group.preventedJoinByTicket = True dap.updateGroup(group) sendMentionFooter(to, "[ Group Ticket ]\n Status - GROUP TICKET HAS BEEN DISABLED!\n@!", [sender]) #sendMessage(to, "Failed menutup grup qr") elif cmd == '#groupinfo': group = dap.getGroup(to) try: gCreator = group.creator.displayName except: gCreator = "Tidak ditemukan" if group.invitee is None: gPending = "0" else: gPending = str(len(group.invitee)) if group.preventedJoinByTicket == True: gQr = "Mati" gTicket = "Tidak ada" else: gQr = "Hidup" gTicket = "https://line.me/R/ti/g/{}".format(str(dap.reissueGroupTicket(group.id))) path = "http://dl.profile.line-cdn.net/" + group.pictureStatus ret_ = "\n [ Group Info ]" ret_ += "\n Nama Grup : {}".format(str(group.name)) ret_ += "\n ID Grup : {}".format(group.id) ret_ += "\n Pembuat Grup : {}".format(str(gCreator)) ret_ += "\n Anggota : {}".format(str(len(group.members))) ret_ += "\n Anggota yang pending : {}".format(gPending) ret_ += "\n Qr Grup : {}".format(gQr) ret_ += "\n Qr : {}".format(gTicket) ret_ += "" dap.sendMessage(to, str(ret_)) dap.sendImageWithURL(to, path) elif cmd == '#groupmemberlist': if msg.toType == 2: group = dap.getGroup(to) ret_ = "\n [ Member List ] " no = 0 + 1 for mem in group.members: ret_ += "\n {}. {}".format(str(no), str(mem.displayName)) no += 1 ret_ += "\n[ Ada {} ]\n".format(str(len(group.members))) dap.sendMessage(to, str(ret_)) elif cmd == '#grouplist': if msg._from in Owner: groups = dap.groups ret_ = "\n [ Group List ]\n " no = 0 + 1 for gid in groups: group = dap.getGroup(gid) ret_ += "\n {}. {} | {}".format(str(no), str(group.name), str(len(group.members))) no += 1 ret_ += "\n\n[ Ada {} Groups ]\n".format(str(len(groups))) dap.sendMessage(to, str(ret_)) # Pembatas Script # elif cmd == "#changedp": if msg._from in Owner: settings["changeDisplayPicture"] = True dap.sendMessage(to, "\n[ Change Display Picture ]\n\nUsage : send 1 pict what u want and, DisplayPicture has been Changed\n") elif cmd.startswith("#fbroadcast: "): if msg._from in Owner: sep = text.split(" ") txt = text.replace(sep[0] + " ","") friends = dap.friends for friend in friends: sendMention(friend, "[ Broadcast ]\n@!\n\n{}".format(str(txt), [sender])) dap.sendMessage(to, "Berhasil broadcast ke {} teman".format(str(len(friends)))) elif cmd == "#changegp": if msg._from in Admin: if msg.toType == 2: if to not in settings["changeGroupPicture"]: settings["changeGroupPicture"].append(to) dap.sendMessage(to, "\n[Change Group Picture]\n\nUsage : send 1 pict what u want and, GroupPicture has been Changed\n") elif cmd == '#mentioning': group = dap.getGroup(msg.to) nama = [contact.mid for contact in group.members] k = len(nama)//100 for a in range(k+1): txt = u'' s=0 b=[] for i in group.members[a*100 : (a+1)*100]: b.append({"S":str(s), "E" :str(s+6), "M":i.mid}) s += 7 txt += u'@Zero \n' dap.sendMessage(to, text=txt, contentMetadata={u'MENTION': json.dumps({'MENTIONEES':b})}, contentType=0) dap.sendMessage(to, "All Mentioned : {} ".format(str(len(nama)))) #sendMention(to, "@!\n\nAll Mentioned : {} ".format(str(len(nama)), [sender]) elif text.lower() == '#ceksider on': tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to in read['readPoint']: try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to] except: pass read['readPoint'][msg.to] = msg.id read['readMember'][msg.to] = "" read['readTime'][msg.to] = datetime.now().strftime('%H:%M:%S') read['ROM'][msg.to] = {} with open('read.json', 'w') as fp: json.dump(read, fp, sort_keys=True, indent=4) #sendMention(to, "@!\n「 Ceksider Diaktifkan 」\n\n" + readTime, [sender]) dap.sendMessage(to, "「 Ceksider Diaktifkan 」\n\n" + readTime) else: try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to] except: pass read['readPoint'][msg.to] = msg.id read['readMember'][msg.to] = "" read['readTime'][msg.to] = datetime.now().strftime('%H:%M:%S') read['ROM'][msg.to] = {} with open('read.json', 'w') as fp: json.dump(read, fp, sort_keys=True, indent=4) #sendMention(to, "@!\n「 Ceksider Diaktifkan 」\n" + readTime, [sender]) dap.sendMessage(to, "「 Ceksider Diaktifkan 」\n\n" + readTime) elif text.lower() == '#ceksider off': tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to not in read['readPoint']: #sendMention(to, "「 Ceksider telah dimatikan 」\n@!\nWaktu :\n" + readTime, [sender]) dap.sendMessage(to, "「 Ceksider telah dimatikan 」\n\n" + readTime) else: try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to] except: pass #sendMention(to, "「 Ceksider telah dimatikan 」\n@!\nWaktu :\n" + readTime, [sender]) dap.sendMessage(to, "「 Ceksider telah dimatikan 」\n\n" + readTime) elif text.lower() == '#ceksider reset': tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to in read["readPoint"]: try: del read["readPoint"][msg.to] del read["readMember"][msg.to] del read["readTime"][msg.to] except: pass #sendMention(to, "「 Mengulangi riwayat pembaca 」\n@!\n" + readTime, [sender]) dap.sendMessage(to, "「 Ceksider telah direset 」\n\n" + readTime) else: #sendMention(to, "「 Ceksider belum diaktifkan 」\n@!", [sender]) dap.sendMessage(to, "「 Ceksider telah direset 」\n\n" + readTime) elif text.lower() == '#ceksider': tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if receiver in read['readPoint']: if read["ROM"][receiver].items() == []: dap.sendMessage(receiver," 「 Daftar Pembaca 」\nNone") else: chiya = [] for rom in read["ROM"][receiver].items(): chiya.append(rom[1]) cmem = dap.getContacts(chiya) zx = "" zxc = "" zx2 = [] xpesan = ' 「 Daftar Pembaca 」\n\n' for x in range(len(cmem)): xname = str(cmem[x].displayName) pesan = '' pesan2 = pesan+"@c\n" xlen = str(len(zxc)+len(xpesan)) xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1) zx = {'S':xlen, 'E':xlen2, 'M':cmem[x].mid} zx2.append(zx) zxc += pesan2 text = xpesan+ zxc + "\n[ Waktu ] : \n" + readTime try: dap.sendMessage(receiver, text, contentMetadata={'MENTION':str('{"MENTIONEES":'+json.dumps(zx2).replace(' ','')+'}')}, contentType=0) except Exception as error: print (error) pass else: dap.sendMessage(receiver,"*Ceksider belum diaktifkan\nKetik 「 #ceksider on 」 untuk mengaktifkan.") elif text.lower() == '#lurking': tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if receiver in read['readPoint']: if read["ROM"][receiver].items() == []: dap.sendMessage(receiver,"[ Reader ]:\nNone") else: chiya = [] for rom in read["ROM"][receiver].items(): chiya.append(rom[1]) cmem = dap.getContacts(chiya) zx = "" zxc = "" zx2 = [] xpesan = ' 「 Daftar Pembaca 」\n\n' for x in range(len(cmem)): xname = str(cmem[x].displayName) pesan = '' pesan2 = pesan+"@c\n" xlen = str(len(zxc)+len(xpesan)) xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1) zx = {'S':xlen, 'E':xlen2, 'M':cmem[x].mid} zx2.append(zx) zxc += pesan2 text = xpesan+ zxc + "\n[ Waktu ] : \n" + readTime try: dap.sendMessage(receiver, text, contentMetadata={'MENTION':str('{"MENTIONEES":'+json.dumps(zx2).replace(' ','')+'}')}, contentType=0) except Exception as error: print (error) pass else: #sendMention(receiver,"*Ceksider belum diaktifkan\nKetik 「 #ceksider on 」 untuk mengaktifkan\n@!") dap.sendMessage(receiver,"*Ceksider belum diaktifkan\nKetik 「 #ceksider on 」 untuk mengaktifkan.") elif text.lower() == '###spamcall': if msg.toType == 2: group = dap.getGroup(to) members = [mem.mid for mem in group.members] call.acquireGroupCallRoute(to) call.inviteIntoGroupCall(to, contactIds=members) dap.sendMessage(to, "Berhasil mengundang kedalam telponan group") elif cmd.startswith('##clearallmessage'): if msg._from in Owner: dap.removeAllMessages(op.param2) dap.sendMessage(to, "Success deleted allMessage for this room") elif cmd.startswith('##youtubemp3 '): if msg._from in Owner: try: dap.sendMessage(to,"hm wait") textToSearch = text.replace('##youtubemp3 ', "").strip() query = urllib.parse.quote(textToSearch) url = "https://www.youtube.com/results?search_query=" + query response = urllib.request.urlopen(url) html = response.read() soup = BeautifulSoup(html, "html.parser") results = soup.find(attrs={'class':'yt-uix-tile-link'}) dl = 'https://www.youtube.com' + results['href'] vid = pafy.new(dl) stream = vid.audiostreams for s in stream: start = timeit.timeit() vin = s.url img = vid.bigthumbhd hasil = vid.title hasil += '\n\nDi upload oleh ✍️ ' +str(vid.author) hasil += '\nDurasi ⏱️ ' +str(vid.duration)+ ' (' +s.quality+ ') ' hasil += '\nDi Like sebanyak👍 ' +str(vid.rating) hasil += '\nDi tonton sebanyak 👬 ' +str(vid.viewcount)+ 'x ' hasil += '\nDi upload pada 📆 ' +vid.published hasil += '\n\nWaktunya⏲️ %s' % (start) hasil += '\n\n Waitting proses mp3....' dap.sendAudioWithURL(to, vin) dap.sendImageWithURL(to, img) dap.sendMessage(to, hasil) except: dap.sendMessage(to, "Fail") elif cmd.startswith('##pimention'): if msg._from in Owner: group = dap.getGroup(msg.to) k = len(group.members)//100 for j in range(k+1): aa = [] for x in group.members: aa.append(x.mid) try: arrData = "" textx = " [ Mention {} Members ] \n1 - ".format(str(len(aa))) arr = [] no = 1 b = 1 for i in aa: b = b + 1 end = "\n" mention = "@x\n" slen = str(len(textx)) elen = str(len(textx) + len(mention) - 1) arrData = {'S':slen, 'E':elen, 'M':i} arr.append(arrData) textx += mention if no < len(aa): no += 1 textx += str(b) + " - " else: try: no = "[ {} ]".format(str(dap.getGroup(msg.to).name)) except: no = "[ Success ]" msg.to = msg.to msg.text = textx msg.contentMetadata = {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')} msg.contentType = 0 dap.sendMessage(msg) except Exception as e: dap.sendMessage(to, str(e)) elif cmd.startswith("##Gbcpict "): if msg._from in Owner: txt = msg.text.split(" ") bcteks = msg.text.replace("Gbcpict "+txt[1]+" "+txt[2]+" ","") n = dap.getGroupIdsJoined() for people in n: dap.sendImageWithURL(people, txt[2]) dap.sendMessage(people, bcteks) dap.sendContact(people, txt[1]) elif cmd.startswith("##botproblem "): if msg._from in Owner: at = text.replace("##botproblem ","") aa = dap.getContact(sender).displayName ab = dap.getGroup(msg.to).name ac = dap.getContact(sender).mid dap.sendMessage(to,"Your message has been added to the que") dap.sendMessage(to,"「 List Problem 」\nName: "+aa+"\nFrom Group: "+ab+"\nProblem: "+at+"\nMid User: "+ac) dap.sendContact(ac) elif cmd.startswith("#murottal"): try: sep = msg.text.split(" ") surah = int(text.replace(sep[0] + " ","")) if 0 < surah < 115: if surah not in [2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 16, 17, 18, 20, 21, 23, 26, 37]: if len(str(surah)) == 1: audionya = "https://audio5.qurancentral.com/mishary-rashid-alafasy/mishary-rashid-alafasy-00" + str(surah) + "-muslimcentral.com.mp3" dap.sendAudioWithURL(to, audionya) elif len(str(surah)) == 2: audionya = "https://audio5.qurancentral.com/mishary-rashid-alafasy/mishary-rashid-alafasy-0" + str(surah) + "-muslimcentral.com.mp3" dap.sendAudioWithURL(to, audionya) else: audionya = "https://audio5.qurancentral.com/mishary-rashid-alafasy/mishary-rashid-alafasy-" + str(surah) + "-muslimcentral.com.mp3" dap.sendAudioWithURL(to, audionya) else: dap.sendMessage(to, "Surah terlalu panjang") else: dap.sendMessage(to, "Quran hanya 114 surah") except Exception as error: dap.sendMessage(to, "error\n"+str(error)) logError(error) elif cmd.startswith("#screenshot "): type_ = msg.text.lower()[11:12] params = {'url':msg.text.lower()[13:]} if type_ == '1': url = 'https://dzin.xyz/api/screenshot/phone.php?url=instagram.com' elif type_ == '2': url = 'https://dzin.xyz/api/screenshot/desktop.php?' elif type_ == '3': url = 'https://dzin.xyz/api/screenshot/tablet.php?' data = requests.get(url, params=params).json() dap.sendImageWithURL(msg.to, data['image']) elif cmd == "#siderrr": tz = pytz.timezone("Asia/Makassar") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if receiver in read['readPoint']: if read["ROM"][receiver].items() == []: dap.sendMessage(receiver,"Tidak Ada Sider") else: chiya = [] for rom in read["ROM"][receiver].items(): chiya.append(rom[1]) cmem = dap.getContacts(chiya) zx = "" zxc = "" zx2 = [] xpesan = '[R E A D E R ]\n' for x in range(len(cmem)): xname = str(cmem[x].displayName) pesan = '' pesan2 = pesan+"@c\n" xlen = str(len(zxc)+len(xpesan)) xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1) zx = {'S':xlen, 'E':xlen2, 'M':cmem[x].mid} zx2.append(zx) zxc += pesan2 text = xpesan+ zxc + "\n" + readTime try: dap.sendMessage(receiver, text, contentMetadata={'MENTION':str('{"MENTIONEES":'+json.dumps(zx2).replace(' ','')+'}')}, contentType=0) except Exception as error: print (error) pass else: dap.sendMessage(receiver,"Lurking belum diaktifkan") elif cmd.startswith("#mimicadd"): if msg._from in Owner: targets = [] key = eval(msg.contentMetadata["MENTION"]) key["MENTIONEES"][0]["M"] for x in key["MENTIONEES"]: targets.append(x["M"]) for target in targets: try: settings["mimic"]["target"][target] = True dap.sendMessage(msg.to,"\nTarget ditambahkan!\n") break except: dap.sendMessage(msg.to,"\ Gagal menambahkan target\n") break elif cmd.startswith("#mimicdel"): if msg._from in Owner: targets = [] key = eval(msg.contentMetadata["MENTION"]) key["MENTIONEES"][0]["M"] for x in key["MENTIONEES"]: targets.append(x["M"]) for target in targets: try: del settings["mimic"]["target"][target] dap.sendMessage(msg.to,"\n Target dihapuskan!\n") break except: dap.sendMessage(msg.to,"\n Gagal menghapus target\n") break elif cmd == "#mimiclist": if msg._from in Owner: if settings["mimic"]["target"] == {}: dap.sendMessage(msg.to,"\n Tidak Ada Target\n") else: mc = " [ Mimic List ] " for mi_d in settings["mimic"]["target"]: mc += "\n "+dap.getContact(mi_d).displayName mc += "\n [ MIMIC CMD] " dap.sendMessage(msg.to,mc) elif cmd.startswith("#wordbanlist"): if msg._from in Owner: if wordban not in [[]]: no = 1 wordbans = "[ WordBan List ]\n" for word in wordban: wordbans+="\n{}. {}".format(str(no),str(word)) no+=1 wordbans+="\n" #dap.sendMessage(to, str(wordbans)) dap.sendMessage(to, str(wordbans),{'AGENT_ICON':'http://dl.profile.line-cdn.net/0hkY3juiptNHYOExk5wsdLITJWOht5PTI-diUpGX8RPhZ0IydzMSV_FC0VaxV0I3JyMCZ4Ei8VOEQh','AGENT_LINK':'https://line.me/ti/p/~yapuy','AGENT_NAME':'WordBan List'}) if wordban == []: dap.sendMessage(to, "[ Notified Word Ban ]\nNo WordBan yet") elif cmd.startswith("#addwordban: "): #if msg._from in Owner: word = text.replace("addwordban: ","") if word not in wordban: wordban.append(word) dap.sendMessage(to, "[ Notified Word Ban ]\nSuccess Added {} From WordBan".format(str(word))) else: dap.sendMessage(to, "[ Notified Word Ban ]\n{} Already added".format(str(word))) elif cmd.startswith("#delwordban: "): #if msg._from in Owner: word = text.replace("delwordban: ","") if word in wordban: wordban.remove(word) dap.sendMessage(to, "[ Notified Word Ban ]\nSuccess Deleted {} From WordBan".format(str(word))) else: dap.sendMessage(to, "[ Notified Word Ban ]\n{} Notfound".format(str(word))) elif text.lower() == "#wordban": #if msg._from in Owner: dap.sendMessage(to, "[ Notified Word Ban ]\n{} Registered to WordBan\nSorry".format(str(text))) dap.kickoutFromGroup(to, [sender]) elif cmd.startswith("#mimic"): if msg._from in Owner: sep = text.split(" ") mic = text.replace(sep[0] + " ","") if mic == "on": if settings["mimic"]["status"] == False: settings["mimic"]["status"] = True dap.sendMessage(msg.to,"\n Reply Message on\n") elif mic == "off": if settings["mimic"]["status"] == True: settings["mimic"]["status"] = False dap.sendMessage(msg.to,"\n Reply Message off\n") # Pembatas Script # elif cmd.startswith("#checkwebsite"): if msg._from in Owner: try: sep = text.split(" ") query = text.replace(sep[0] + " ","") r = requests.get("http://rahandiapi.herokuapp.com/sswebAPI?key=betakey&link={}".format(urllib.parse.quote(query))) data = r.text data = json.loads(data) dap.sendImageWithURL(to, data["result"]) except Exception as error: logError(error) elif cmd.startswith("#checkdate"): if msg._from in Owner: try: sep = msg.text.split(" ") tanggal = msg.text.replace(sep[0] + " ","") r = requests.get('https://script.google.com/macros/exec?service=AKfycbw7gKzP-WYV2F5mc9RaR7yE3Ve1yN91Tjs91hp_jHSE02dSv9w&nama=ervan&tanggal='+tanggal) data=r.text data=json.loads(data) ret_ = "[ D A T E ]" ret_ += "\nDate Of Birth : {}".format(str(data["data"]["lahir"])) ret_ += "\nAge : {}".format(str(data["data"]["usia"])) ret_ += "\nBirthday : {}".format(str(data["data"]["ultah"])) ret_ += "\nZodiak : {}".format(str(data["data"]["zodiak"])) dap.sendMessage(to, str(ret_)) except Exception as error: logError(error) elif text.lower().startswith("#spam "): syd=text.split(" ") syd=text.replace(syd[0]+" ","") syd=syd.split('*') txt=str(syd[0]) num=int(syd[1]) if num <=100: for spammer in range(0,num): dap.sendMessage(to,txt) else: dap.sendMessage(to,'?') elif cmd.startswith("#checkpraytime "): if msg._from in Owner: separate = msg.text.split(" ") location = msg.text.replace(separate[0] + " ","") r = requests.get("http://api.corrykalam.net/apisholat.php?lokasi={}".format(location)) data = r.text data = json.loads(data) tz = pytz.timezone("Asia/Makassar") timeNow = datetime.now(tz=tz) if data[1] != "Subuh : " and data[2] != "Dzuhur : " and data[3] != "Ashar : " and data[4] != "Maghrib : " and data[5] != "Isya : ": ret_ = "* Jadwal Sholat Sekitar *" + data[0] + " ]" ret_ += "\n* Tanggal : " + datetime.strftime(timeNow,'%Y-%m-%d') ret_ += "\n* Jam : " + datetime.strftime(timeNow,'%H:%M:%S') ret_ += "\n* " + data[1] ret_ += "\n* " + data[2] ret_ += "\n* " + data[3] ret_ += "\n* " + data[4] ret_ += "\n* " + data[5] ret_ += "" dap.sendMessage(msg.to, str(ret_)) elif cmd.startswith("#jadwalsholat"): if msg._from in Owner: anunya = text.replace("jadwalsholat ","") r = requests.get("http://leert.corrykalam.gq/praytime.php?location={}".format(str(anunya))) data = r.text data = json.loads(data) try: fine = " [ Jadwal Sholat ] \n\n" fine += "Subuh : {}".format(str(data["pray_time"]["subuh"])) fine += "\nDhuhur : {}".format(str(data["pray_time"]["dzuhur"])) fine += "\nAshar : {}".format(str(data["pray_time"]["ashar"])) fine += "\nMaghrib : {}".format(str(data["pray_time"]["maghrib"])) fine += "\nIsya : {}".format(str(data["pray_time"]["isha"])) fine += "\nImsak : {}".format(str(data["pray_time"]["imsak"])) fine += "\n\nTimezone : {}".format(str(data["info"]["timezone"])) fine += "\nDate : {}".format(str(data["info"]["date"])) fine += "\nLatitude : {}".format(str(data["info"]["latitude"])) fine += "\nLongitude : {}".format(str(data["info"]["longitude"])) fine += "\nSource : {}".format(str(data["info"]["source"])) dap.sendMessage(to, str(fine)) except Exception as error: dap.sendMessage(to,str(error)) elif cmd.startswith("kintil"): dap.sendImageWithURL(to, "https://stickershop.line-scdn.net/stickershop/v1/sticker/26911499/ANDROID/sticker.png") dap.sendMessage(to, "kerad") #elif cmd.startswith("unsend ") and sender == "uac8e3eaf1eb2a55770bf10c3b2357c33": # args = text.replace('unsend','') # mes = 0 # try: # mes = int(args[1]) # except: # mes = 1 # M = cliet.getRecentMessagesV2(to, 101) # MId = [] # for ind,i in enumerate(M): # if ind == 0: # pass # else: # if i._from == dap.profile.mid: # MId.append(i.id) # if len(MId) == mes: # break # def unsMes(id): # dap.unsendMessage(id) # for i in MId: # thread1 = threading.Thread(target=unsMes, args=(i,)) # thread1.start() # thread1.join() # dap.sendMessage(to, '[ Unsend {} message ]'.format(len(MId))) #################PUY############## elif text.lower() == "#acaratv": result = requests.get("http://ari-api.herokuapp.com/jadwaltv").json()["result"];no=1;tv=" [ Jadwal Acara TV ] \n\n" for wildan in result: tv+="{}. {} - {} ({})\n".format(str(no), str(wildan["channelName"]), str(wildan["acara"]), str(wildan["jam"])) no+=1 tv+="\n";dap.sendMessage(to, str(tv)) elif cmd.startswith("keluar"): tgb = dap.getGroup(op.param1) dan = dap.getContact(op.param2) sendMentionFooter(op.param1, "@!, Gbye", [op.param2]) pi.leaveGroup(to) dap.leaveGroup(to) elif cmd.startswith("#keluar"): #tgb = dap.getGroup(op.param1) #dan = dap.getContact(op.param2) #gid = dap.getGroup(to) dap.sendMessage(to, "Gbye") #sendMentionFooter(op.param1, "@!, Gbye", [op.param2]) dap.getGroupIdsJoined() pi.leaveGroup(to) dap.leaveGroup(to) elif cmd.startswith("#pi:keluar"): #tgb = dap.getGroup(op.param1) #dan = dap.getContact(op.param2) #gid = dap.getGroup(to) pi.sendMessage(to, "Gbye") #sendMentionFooter(op.param1, "@!, Gbye", [op.param2]) pi.getGroupIdsJoined() pi.leaveGroup(to) elif cmd.startswith("#pm"): sep = msg.text.split(" ") name = msg.text.replace(sep[0] + " ","") mention = eval(msg.contentMetadata["MENTION"]) mention1 = mention["MENTIONEES"][0]["M"] contact = dap.getContact(mention1) pisah = name.replace("@"+contact.displayName,"") ginfo = dap.getGroup(receiver).name pengirim = dap.getContact(sender).displayName result = "Sender : "+ pengirim +"\nFrom group : "+ ginfo +"\n\nMessage : "+pisah try: dap.sendMessage(contact.mid, result) sendMentionFooter(to, "[ SendMessage to Member ]\n Status - Message has been Sent!\n@!", [sender]) except Exception as e: dap.sendMessage(to, str(e)) elif cmd.startswith("#pc"): sep = msg.text.split(" ") name = msg.text.replace(sep[0] + " ","") mention = eval(msg.contentMetadata["MENTION"]) mention1 = mention["MENTIONEES"][0]["M"] contact = dap.getContact(mention1) pisah = name.replace("@"+contact.displayName,"") #ginfo = dap.getGroup(receiver).name #pengirim = dap.getContact(sender).displayName result = ""+pisah try: dap.sendMessage(contact.mid, result) sendMentionFooter(to, "[ SendMessage to Member ]\n Status - Message has been Sent!\n@!", [sender]) except Exception as e: dap.sendMessage(to, str(e)) elif cmd.startswith('#pcallmember '): try: sendMentionFooter(to, "[ SendMessage to AllMember ]\n Status - Sending Message...\n@!", [sender]) sep = msg.text.split(" ") text = msg.text.replace(sep[0] + " ","") pengirim = dap.getContact(sender).displayName gpinfo = dap.getGroup(msg.to).name kontak = dap.getGroup(msg.to) grup = kontak.members for ids in grup: mids = dap.getProfile().mid midd = ids.mid if midd == mids: pass else: #result = "Isi Pesan :"+text+"\nPesan Dari : "+ pengirim +"\nDari Grup : "+ gpinfo result = "Sender : "+ pengirim +"\nFrom Group : "+ gpinfo +"\n\nMessage : "+ text dap.sendMessage(ids.mid, str(result)) sendMentionFooter(to, "[ SendMessage to All Member ]\n Status - Message has been Sent!\n@!", [sender]) except Exception as e: dap.sendMessage(to, str(e)) elif cmd.startswith("pcid"): dan = text.split("|") x = dap.findContactsByUserid(dan[1]) a = dap.getContact(sender) dap.sendMessage(x.mid,"Anda mendapatkan pesan dari "+a.displayName+"\n\n"+dan[2]) dap.sendMessage(to,"Sukses mengirim pesan ke "+x.displayName+"\nDari: "+a.displayName+"\nPesan: "+dan[2]) elif cmd.startswith("sholatttt"): #if msg._from in Owner: try: sep = msg.text.split(" ") search = msg.text.replace(sep[0] + " ","") api = requests.get("https://farzain.xyz/api/shalat.php?apikey={}&id={}".format(str(search))) data = api.text data = json.loads(data) if data["status"] == "success": hasil = "Subuh : {}".format(str(data["respon"]["shubuh"])) hasil += "\nDzuhur : {}".format(str(data["respon"]["dzuhur"])) hasil += "\nAshar : {}".format(str(data["respon"]["ashar"])) hasil += "\nMaghrib : {}".format(str(data["respon"]["maghrib"])) hasil += "\nIsya : {}".format(str(data["respon"]["isya"])) path = str(data["peta_gambar"]) dap.sendImageWithURL(msg.to, str(path)) dap.sendMessage(msg.to, str(hasil)) else: sendMentionFooter(msg.to, "Maaf @!,lokasi tidak ditemukan", [sender]) except Exception as error: dap.sendMessage(msg.to, str(error)) elif cmd.startswith("filmmmm"): try: sep = msg.text.split(" ") search = msg.text.replace(sep[0] + " ","") api = requests.get("https://farzain.xyz/api/film.php?apikey={}&id={}".format(str(search))) data = api.text data = json.loads(data) if data["status"] == "success": hasil = "[ Result Film ]" hasil += "\nTitle : {}".format(str(data["Title"])) hasil += "\nYear : {}".format(str(data["Year"])) hasil += "\nRated : {}".format(str(data["Rated"])) hasil += "\nReleased : {}".format(str(data["Released"])) hasil += "\nDuration : {}".format(str(data["Runtime"])) hasil += "\nGenre : {}".format(str(data["Genre"])) path = str(data["Poster"]) dap.sendImageWithURL(msg.to, str(path)) dap.sendMessage(msg.to, str(hasil)) else: sendMentionV2(msg.to, "Maaf @!,hasil pencarin tidak ditemukan", [sender]) except Exception as error: dap.sendMessage(msg.to, str(error)) elif cmd.startswith("spmid: "): #if msg.from_ in Admin or msg.from_ in staff or msg.from_ in creator or msg.from_ in penyewa: korban2 = msg.text.split(" ") gs = dap.getGroup(msg.to) jmlh = int(korban2[4]) txt = msg.text.split(" ") text = msg.text.replace(cmd+ "spmid: "+str(korban2[3])+" "+ str(jmlh)+ " ","") x = dap.findContactsByUserid(korban2[3]) dap.sendMessage(msg.to,"Dimulai ya") if jmlh <= 1000: for baba in range(jmlh): try: dap.sendMessage(x.mid, text) except: pass dap.sendMessage(msg.to, "Sudah di spamin XD") else: dap.sendMessage(msg.to,"Jumlah melebihi batas") elif cmd.startswith ("invitegroupcall "): if msg._from in Owner: if msg.toType == 2: sep = text.split(" ") strnum = text.replace(sep[0] + " ","") num = int(strnum) dap.sendMessage(to, "Berhasil mengundang kedalam telponan group") for var in range(0,num): group = dap.getGroup(to) members = [mem.mid for mem in group.members] dap.acquireGroupCallRoute(to) dap.inviteIntoGroupCall(to, contactIds=members) elif cmd == "#delannounce": a = dap.getChatRoomAnnouncements(to) anu = [] for b in a: c = b.announcementSeq anu.append(c) dap.removeChatRoomAnnouncement(to, c) sendMentionFooter(to, "[Notified Announcement]\n - Success Removed Announce @!", [sender]) elif text.lower() == 'limitlist': if msg._from not in creator: if settings["limituser"] == {}: dap.sendMessage(to, "Kosong") else: mc = "Daftar Limit:" for mi_d in settings["limituser"]: if settings["limituser"][mi_d]["count"] == 5: mc += "\n\n• Nama : " + dap.getContact(mi_d).displayName + "\n• Count : "+settings['limituser'][mi_d]['count'] + "\n• Limit : "+settings['limituser'][mi_d]['limit'] dap.sendMessage(to, mc) elif cmd.startswith("#announce "): sep = text.split(" ") a = text.replace(sep[0] + " ","") z = dap.getGroupIdsJoined() b = dap.getContact(sender) c = ChatRoomAnnouncementContents() c.displayFields = 5 c.text = a c.link = "https://line.me/ti/p/~yapuy" c.thumbnail = "http://dl.profile.line-cdn.net/0hkY3juiptNHYOExk5wsdLITJWOht5PTI-diUpGX8RPhZ0IydzMSV_FC0VaxV0I3JyMCZ4Ei8VOEQ" c.iconlink = "http://dl.profile.line-cdn.net/0hkY3juiptNHYOExk5wsdLITJWOht5PTI-diUpGX8RPhZ0IydzMSV_FC0VaxV0I3JyMCZ4Ei8VOEQh" try: dap.createChatRoomAnnouncement(to, 1, c) sendMentionFooter(to, "[Notified Announcement]\n - Success Added Announce @!", [sender]) except Exception as e: dap.sendMessage(to, str(e)) elif cmd.startswith("#retrowavetextlist"): dap.sendMessage(to, "Retrowave Text List\n\n- Text 1\n- Text 2\n- Text 3\n- Text 4\n\nUntuk melihat gambar text, silahkan ketik retrowavetext-num") elif text.lower() == "#retrowavebglist": dap.sendMessage(to, "Retrowave Background List\n\n- Background 1\n- Background 2\n- Background 3\n- Background 4\n- Background 5\n\nUntuk melihat gambar background, silahkan ketik retrowavebg-num") elif cmd.startswith("#retrowavebg-"): num = text.replace("#retrowavebg-","") if num not in ["1","2","3","4","5"]:dap.sendMessage(to,"maaf jenis retrowavebg {} tidak ada\n\nuntuk melihat daftar retrowavebg silahkan ketik retrowavebglist.".format(num)) else: if num == "1": dap.sendImageWithURL(to, "https://cdn.photofunia.com/effects/retro-wave/resources/1txxjga.jpg") elif num == "2": dap.sendImageWithURL(to, "https://cdn.photofunia.com/effects/retro-wave/resources/ign25g.jpg") elif num == "3": dap.sendImageWithURL(to, "https://cdn.photofunia.com/effects/retro-wave/resources/vtejls.jpg") elif num == "4": dap.sendImageWithURL(to, "https://cdn.photofunia.com/effects/retro-wave/resources/2t537o.jpg") elif num == "5": dap.sendImageWithURL(to, "https://cdn.photofunia.com/effects/retro-wave/resources/11rfhkj.jpg") elif cmd.startswith("#retrowavetext-"): num = text.replace("#retrowavetext-","") if num not in ["1","2","3","4"]:dap.sendMessage(to,"maaf jenis retrowavetext {} tidak ada\n\nuntuk melihat daftar retrowavetext silahkan ketik retrowavetextlist.".format(num)) else: if num == "1": dap.sendImageWithURL(to, "https://cdn.photofunia.com/effects/retro-wave/resources/eye191.jpg") elif num == "2": dap.sendImageWithURL(to, "https://cdn.photofunia.com/effects/retro-wave/resources/1xxre9n.jpg") elif num == "3": dap.sendImageWithURL(to, "https://cdn.photofunia.com/effects/retro-wave/resources/9ddnhx.jpg") elif num == "4": dap.sendImageWithURL(to, "https://cdn.photofunia.com/effects/retro-wave/resources/dlxine.jpg") elif cmd.startswith("#retrowave"): dan = text.split("|") text1 = dan[1] text2 = dan[2] text3 = dan[3] btype = dan[4] ttype = dan[5] if btype in ["1","2","3","4","5"] and ttype in ["1","2","3","4"]: data = requests.get("http://corrykalam.gq/retrowave.php?text1={}&text2={}&text3={}&btype={}&ttype={}".format(text1,text2,text3,btype,ttype)).json() dap.sendImageWithURL(to, data["image"]) else: dap.sendMessage(to, "Background Type atau Text Type salah, silahkan cek :\n- retrowavetextlist\n- retrowavebglist") elif cmd.startswith("#changedual"): if msg._from in Owner: if msg.contentType == 0: settings["ChangeVideoProfilevid"] = True #dap.sendMessage(to, "Send 1 Video") sendMentionFooter(to, "[ Notified ChangeDual ]\nChangeDual Started!\n\nSend 1 Video what u want\n@!", [sender]) if msg.contentType == 2: path = dap.downloadObjectMsg(msg_id,saveAs="tmp/vid.bin") settings["ChangeVideoProfilevid"] = False settings["ChangeVideoProfilePicture"] = True #dap.sendMessage(to, "Send 1 Picture") sendMentionFooter(to, "[ Notified ChangeDual ]\nChangeDual Started!\n\nSend 1 Picture what u want\n@!", [sender]) if msg.contentType == 1: path = dap.downloadObjectMsg(msg_id) settings["ChangeVideoProfilePicture"] = False dap.updateProfileVideoPicture(path) #dap.sendMessage(to, "success") sendMentionFooter(to, "[ Notified ChangeDual ]\nSuccessed Changedual\n @!", [sender]) elif cmd.startswith("#gitlabprofile "): if msg._from in Owner: dan = "[ GitLab Profile ]\n\n" user = text.replace("gitlabprofile ","") data = requests.get("http://moeapi.panel.moe/api/gitlab/profile/?apikey=beta&username="+user).json() if "message" not in data: dan+="Name: "+str(data["result"]["name"]) dan+="\nUsername: "+str(data["result"]["username"]) dan+="\nBio: "+str(data["result"]["bio"]) dan+="\nSince: "+str(data["result"]["since"]) dap.sendImageWithURL(to, data["result"]["image"]) dan+="\n\n[ Finish ]" dap.sendMessage(to, str(dan)) elif cmd.startswith("#clonegroup "): if msg._from in Owner: gname = msg.text.replace("clonegroup ", "") group = dap.getGroup(msg.to) members = [mem.mid for mem in group.members] + [pen.mid for pen in group.invitee] if group.invitee else [mem.mid for mem in group.members] members.remove(dap.profile.mid) for mem in members: dap.findAndAddContactsByMid(mem) dap.createGroup(gname, members) elif cmd.startswith("#unsend "): if msg._from in Owner: args = text.replace("unsend","") #args = removeCmd("unsend", text) mes = 0 try: mes = int(args[1]) except: mes = 1 M = dap.getRecentMessages(to, 101) MId = [] for ind,i in enumerate(M): if ind == 0: pass else: if i._from == dap.profile.mid: MId.append(i.id) if len(MId) == mes: break def unsMes(id): dap.unsendMessage(id) for i in MId: thread1 = threading.Thread(target=unsMes, args=(i,)) thread1.start() thread1.join() dap.sendMessage(to, '「 Unsend {} message 」'.format(len(MId))) elif cmd.startswith("mantap"): dap.sendImageWithURL(to, "https://stickershop.line-scdn.net/stickershop/v1/sticker/47751647/ANDROID/sticker.png") sendMention(to, "@!", [sender]) elif cmd.startswith("logout"): dap.sendImageWithURL(to, "https://stickershop.line-scdn.net/stickershop/v1/sticker/16365599/ANDROID/sticker.png") elif cmd.startswith("hmm"): dap.sendImageWithURL(to, "https://stickershop.line-scdn.net/stickershop/v1/sticker/31093005/ANDROID/sticker.png") elif cmd.startswith("#bc"): wildan = cmd.split("*") bc["txt"] = wildan[1];bc["mid"] = wildan[2];bc["img"] = True dap.sendMessage(to, "Send 1 image") elif cmd.startswith("bc: "): if msg._from in Owner: sep = text.split(" ") pesan = text.replace(sep[0] + " ","") saya = dap.getGroupIdsJoined() for group in saya: dap.sendMessage(group,"" + str(pesan)) elif cmd.startswith("#Bc*Usage"): #sendMentionFooter(to, "[ Broadcast ]\n\nUsage : dap-bc*bctext*yourmid.") sendMentionFooter(to, "[ Broadcast Usage ]\n\nUsage : dap-bc*bctext*yourmid\n @!", [sender]) elif cmd.startswith("#Profile Changer*Usage"): #sendMentionFooter(to, "[ Profile Changer ]\n\n - Change Group Picture\nUsage : type Changegp and send 1 pict what u want.\n\n - Change Display Picture\nUsage : type Changedp and Send 1 pict what u want.") sendMentionFooter(to, "[ Profile Changer ]\n\n - Change Group Picture\nUsage : type Changegp and send 1 pict what u want.\n\n - Change Display Picture\nUsage : type Changedp and Send 1 pict what u want\n @!", [sender]) elif cmd.startswith("#Announcement*Usage"): #dap.dap.sendMessage(to, "[ Announcement Usage ]\n\n - Add Announcement\nUsage : Announce (text)\n\n - Remove Announcement\nUsage : Delannounce") sendMentionFooter(to, "[ Announcement Usage ]\n\n - Add Announcement\nUsage : Announce (text)\n\n - Remove Announcement\nUsage : Delannounce\n @!", [sender]) elif cmd.startswith("#checkweather "): try: sep = text.split(" ") location = text.replace(sep[0] + " ","") r = requests.get("http://api.corrykalam.net/apicuaca.php?kota={}".format(location)) data = r.text data = json.loads(data) tz = pytz.timezone("Asia/Makassar") timeNow = datetime.now(tz=tz) if "result" not in data: ret_ = "* Weather Status *" ret_ += "\n* Location : " + data[0].replace("Temperatur di kota ","") ret_ += "\n* Suhu : " + data[1].replace("Suhu : ","") + "°C" ret_ += "\n* Kelembaban : " + data[2].replace("Kelembaban : ","") + "%" ret_ += "\n* Tekanan udara : " + data[3].replace("Tekanan udara : ","") + "HPa" ret_ += "\n* Kecepatan angin : " + data[4].replace("Kecepatan angin : ","") + "m/s" ret_ += "\n* Time Status *" ret_ += "\n* Tanggal : " + datetime.strftime(timeNow,'%Y-%m-%d') ret_ += "\n* Jam : " + datetime.strftime(timeNow,'%H:%M:%S') + " WIB" ret_ += "" dap.sendMessage(to, str(ret_)) except Exception as error: logError(error) elif cmd.startswith("#checklocation "): sep = text.split(" ") location = text.replace(sep[0] + " ","") with requests.session() as web: web.headers["user-agent"] = random.choice(settings["userAgent"]) r = web.get("http://api.corrykalam.net/apiloc.php?lokasi={}".format(urllib.parse.quote(location))) data = r.text data = json.loads(data) if data[0] != "" and data[1] != "" and data[2] != "": link = "https://www.google.co.id/maps/@{},{},15z".format(str(data[1]), str(data[2])) ret_ = "╔══[ Details Location ]" ret_ += "\n╠ Lokasi : " + data[0] ret_ += "\n╠ Google Maps : " + link ret_ += "\n╚══[ Complete ]" else: ret_ = "[ Details Location ] Error : Lokasi tidak ditemukan" dap.sendMessage(to,str(ret_)) #elif cmd.startswith('Quran '): # try: # query = txt.replace('Quran ','') # text = query.split("|") # surah = int(text[0]) # ayat1 = int(text[1]) # ayat2 = int(text[2]) # result = requests.get("https://farzain.xyz/api/alquran.php?id={}&from={}&to={}".format(surah, ayat1, ayat2)) # data = result.text # data = json.loads(data) # if data["status"] == "done": # hasil = "[ Al-Qur'an ]\n" # hasil += "\n Name : {}".format(str(data["nama_surat"])) # hasil += "\n Meaning : {}".format(str(data["arti_surat"])) # hasil += "\n Ayat :" # for ayat in data["ayat"]: # hasil += "\n{}".format(str(ayat)) # hasil += "\n Meaning Ayat :" # for arti in data["arti"]: # hasil += "\n{}".format(str(arti)) # dap.sendMessage(to, str(hasil)) elif cmd.startswith("#spamcall"): if msg._from in Owner: if msg.toType == 2: group = dap.getGroup(to) members = [mem.mid for mem in group.members] jmlh = int(settings["limit"]) dap.sendMessage(msg.to, "Invitation Call Groups {} In Progress ".format(str(settings["limit"]))) if jmlh <= 9999: for x in range(jmlh): try: dap.inviteIntoGroupCall(to, contactIds=members) except Exception as e: dap.sendMessage(msg.to,str(e)) else: dap.sendMessage(msg.to,"Invitation Call Groups Successed") elif cmd.startswith('invgroupcall'): if msg.toType == 2: group = dap.getGroup(to) members = [mem.mid for mem in group.members] call.acquireGroupCallRoute(to) call.inviteIntoGroupCall(to, contactIds=members) dap.sendMention(to, "[ Notified GroupCall ]\nInvited Groupcall Status - Successed\n@!", [sender]) elif cmd.startswith("#tagid: "): try: id = text.replace("tagid: ","") dan = line.findContactsByUserid(id) sM2(to, "Hai @!", [dan.mid]) except Exception as wk: #line.sendMessage(to, "Tidak ada id {}".format(str(id))) line.sendMessage(to, str(wk)) elif cmd.startswith('tes'): dap.sendMessage(to, 'tis') elif cmd.startswith('#call '): try: call = text.replace('#call ','') r = requests.get('https://farzain.xyz/api/prank().php?apikey=&id='+call+'&type=2') sendMention(receiver, "@! Sukses melakukan panggilan ke nomor "+call,[sender]) except Exception as e: dap.sendMessage(receiver, str(e)) logError(e) elif cmd.startswith('#sms '): try: sms = text.replace('#sms ','') r = requests.get('https://farzain.xyz/api/prank().php?apikey=&id='+sms+'&type=1') sendMention(receiver, "@! Sukses mengirim pesan ke nomor "+sms,[sender]) except Exception as e: dap.sendMessage(receiver, str(e)) logError(e) elif cmd.startswith("#instainfo"): try: sep = text.split(" ") search = text.replace(sep[0] + " ","") r = requests.get("http://api.farzain.com/ig_post.php".format(search)) data = r.text data = json.loads(data) if data != []: ret_ = " [ Profile Instagram ] " ret_ += "\n Nama : {}".format(str(data["graphql"]["user"]["full_name"])) ret_ += "\n Username : {}".format(str(data["graphql"]["user"]["username"])) ret_ += "\n Bio : {}".format(str(data["graphql"]["user"]["biography"])) ret_ += "\n Followers : {}".format(str(data["graphql"]["user"]["edge_followed_by"]["count"])) ret_ += "\n Following : {}".format(str(data["graphql"]["user"]["edge_follow"]["count"])) if data["graphql"]["user"]["is_verified"] == True: ret_ += "\n Verified : Verified" else: ret_ += "\n Verified : Not" if data["graphql"]["user"]["is_private"] == True: ret_ += "\n Private Account : Ya" else: ret_ += "\n Private Account : Not" ret_ += "\n Total Post : {}".format(str(data["graphql"]["user"]["edge_owner_to_timeline_media"]["count"])) ret_ += "\n [ https://www.instagram.com/{} ]".format(search) path = data["graphql"]["user"]["profile_pic_url_hd"] dap.sendImageWithURL(to, str(path)) dap.sendMessage(to, str(ret_)) except Exception as error: logError(error) elif cmd.startswith("#alqur'an "): query = text.replace("#alqur'an ","") text = query.split("|") surah = int(text[0]) ayat1 = int(text[1]) ayat2 = int(text[2]) result = requests.get("https://farzain.xyz/api/alquran.php?id={}&from={}&to={}".format(surah, ayat1, ayat2)) data = result.text data = json.loads(data) if data["status"] == "success": hasil = "「 Al-Qur'an 」\n" hasil += "\nName : {}".format(str(data["nama_surat"])) hasil += "\nMeaning : {}".format(str(data["arti_surat"])) hasil += "\nAyat :" for ayat in data["ayat"]: hasil += "\n{}".format(str(ayat)) hasil += "\nMeaning Ayat :" for arti in data["arti"]: hasil += "\n{}".format(str(arti)) dap.sendMessage(to, str(hasil)) elif cmd.startswith("#instapost"): try: sep = text.split(" ") text = text.replace(sep[0] + " ","") cond = text.split("|") username = cond[0] no = cond[1] r = requests.get("http://api.farzain.com/ig_post.php?id=https://www.instagram.com/p/URgHXv1R5zqVz4v9BLE8tb9r5/?_a=1&apikey=beta".format(str(username), str(no))) data = r.text data = json.loads(data) if data["find"] == True: if data["media"]["mediatype"] == 1: dap.sendImageWithURL(msg.to, str(data["media"]["url"])) if data["media"]["mediatype"] == 2: dap.sendVideoWithURL(msg.to, str(data["media"]["url"])) ret_ = " [ Info Post ] " ret_ += "\n Number of Like : {}".format(str(data["media"]["like_count"])) ret_ += "\n Number of Comment : {}".format(str(data["media"]["comment_count"])) ret_ += "\n [ Caption ]\n{}".format(str(data["media"]["caption"])) dap.sendMessage(to, str(ret_)) except Exception as error: logError(error) elif cmd.startswith("#instastory"): try: sep = text.split(" ") text = text.replace(sep[0] + " ","") cond = text.split("*") search = str(cond[0]) if len(cond) == 2: r = requests.get("http://rahandiapi.herokuapp.com/instastory/{}?key=betakey".format(search)) data = r.text data = json.loads(data) if data["url"] != []: num = int(cond[1]) if num <= len(data["url"]): search = data["url"][num - 1] if search["tipe"] == 1: dap.sendImageWithURL(to, str(search["link"])) if search["tipe"] == 2: dap.sendVideoWithURL(to, str(search["link"])) except Exception as error: logError(error) elif cmd.startswith("#say-"): sep = text.split("-") sep = sep[1].split(" ") lang = sep[0] say = text.replace("#say-" + lang + " ","") if lang not in list_language["list_textToSpeech"]: return dap.sendMessage(to, "\nLanguage not found\n") tts = gTTS(text=say, lang=lang) tts.save("hasil.mp3") dap.sendAudio(to,"hasil.mp3") elif cmd.startswith("#carigambar"): try: separate = msg.text.split(" ") search = msg.text.replace(separate[0] + " ","") r = requests.get("http://rahandiapi.herokuapp.com/imageapi?key=betakey&q={}".format(search)) data = r.text data = json.loads(data) if data["result"] != []: items = data["result"] path = random.choice(items) a = items.index(path) b = len(items) dap.sendImageWithURL(to, str(path)) except Exception as error: logError(error) elif cmd.startswith("#carimusik "): sep = msg.text.split(" ") query = msg.text.replace(sep[0] + " ","") cond = query.split("|") search = str(cond[0]) result = requests.get("http://api.ntcorp.us/joox/search?q={}".format(str(search))) data = result.text data = json.loads(data) if len(cond) == 1: num = 0 ret_ = "\n [ Result Music ] " for music in data["result"]: num += 1 ret_ += "\n* {}. {}".format(str(num), str(music["single"])) ret_ += "\n [ Total {} Music ]\n".format(str(len(data["result"]))) ret_ += "\n\nUntuk Melihat Details Music, silahkan gunakan command {}SearchMusic {}|「number」\n".format(str(setKey), str(search)) dap.sendMessage(to, str(ret_)) elif len(cond) == 2: num = int(cond[1]) if num <= len(data["result"]): music = data["result"][num - 1] result = requests.get("http://api.ntcorp.us/joox/song_info?sid={}".format(str(music["sid"]))) data = result.text data = json.loads(data) if data["result"] != []: ret_ = " [ Music ] " ret_ += "\n Title : {}".format(str(data["result"]["song"])) ret_ += "\n Album : {}".format(str(data["result"]["album"])) ret_ += "\n Size : {}".format(str(data["result"]["size"])) ret_ += "\n Link : {}".format(str(data["result"]["mp3"][0])) ret_ += "\n" dap.sendImageWithURL(to, str(data["result"]["img"])) dap.sendMessage(to, str(ret_)) dap.sendAudioWithURL(to, str(data["result"]["mp3"][0])) elif cmd.startswith("#carilirik"): sep = msg.text.split(" ") query = msg.text.replace(sep[0] + " ","") cond = query.split("|") search = cond[0] api = requests.get("http://api.secold.com/joox/cari/{}".format(str(search))) data = api.text data = json.loads(data) if len(cond) == 1: num = 0 ret_ = "\n [ Result Lyric ] " for lyric in data["results"]: num += 1 ret_ += "\n {}. {}".format(str(num), str(lyric["single"])) ret_ += "\n [ Total {} Music ]".format(str(len(data["results"]))) ret_ += "\n\nUntuk Melihat Details Lyric, silahkan gunakan command {}SearchLyric {}|「number」\n".format(str(setKey), str(search)) dap.sendMessage(to, str(ret_)) elif len(cond) == 2: num = int(cond[1]) if num <= len(data["results"]): lyric = data["results"][num - 1] api = requests.get("http://api.secold.com/joox/sid/{}".format(str(lyric["songid"]))) data = api.text data = json.loads(data) lyrics = data["results"]["lyric"] lyric = lyrics.replace('ti:','Title - ') lyric = lyric.replace('ar:','Artist - ') lyric = lyric.replace('al:','Album - ') removeString = "[1234567890.:]" for char in removeString: lyric = lyric.replace(char,'') dap.sendMessage(msg.to, str(lyric)) elif cmd.startswith("#cariyoutube"): sep = text.split(" ") search = text.replace(sep[0] + " ","") params = {"search_query": search} r = requests.get("https://www.youtube.com/results", params = params) soup = BeautifulSoup(r.content, "html5lib") ret_ = "* Youtube Result *" datas = [] for data in soup.select(".yt-lockup-title > a[title]"): if "&lists" not in data["href"]: datas.append(data) for data in datas: ret_ += "\n [ {} ]".format(str(data["title"])) ret_ += "\n https://www.youtube.com{}".format(str(data["href"])) ret_ += "\n [ Total {} ]".format(len(datas)) dap.sendMessage(to, str(ret_)) elif cmd.startswith("#tr-"): sep = text.split("-") sep = sep[1].split(" ") lang = sep[0] say = text.replace("#tr-" + lang + " ","") if lang not in list_language["list_translate"]: return dap.sendMessage(to, "Language not found") translator = Translator() hasil = translator.translate(say, dest=lang) A = hasil.text dap.sendMessage(to, str(A)) # Pembatas Script # # Pembatas Script # if text.lower() == "##prefix": dap.sendMessage(to, "\nPrefix Saat ini adalah [ {} ]\n".format(str(settings["keyCommand"]))) #elif text.lower() == "token done": # tknop= codecs.open("tkn.json","r","utf-8") # tkn = json.load(tknop) # a = tkn['{}'.format(msg._from)][0]['tkn'] # req = requests.get(url = '{}'.format(a)) # b = req.text # dap.sendMessage(msg.to, 'Your token : \n{}'.format(b)) if text.lower() == '#login win10': req = requests.get('https://api.eater.tech/WIN10') #contact = dap.getContact(mid) #dap.sendMessage(to, "[ MID ]\n{}".format(sender)) a = req.text b = json.loads(a) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) tkn['{}'.format(msg._from)] = [] tkn['{}'.format(msg._from)].append({ 'qr': b['result'][0]['linkqr'], 'tkn': b['result'][0]['linktkn'] }) qrz = b['result'][0]['linkqr'] dap.sendMessage(to, 'Buka Link dibawah dan Tekan Login\n\n{}'.format(qrz)) #dap.sendMessage(msg.to, 'Buka Link dibawah dan Tekan Login\n{}'.format(qrz)) with open('tkn.json', 'w') as outfile: json.dump(tkn, outfile) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) a = tkn['{}'.format(msg._from)][0]['tkn'] req = requests.get(url = '{}'.format(a)) b = req.text aa = dap.getContact(sender).displayName ab = dap.getGroup(msg.to).name ac = dap.getContact(sender).mid #sendMention(to, '- TIPE TOKEN : WIN10\n- For : @!\n\n- TOKEN : \n{}'.format(b), [sender]) sendMention(to,'「 WIN 10 」\nUntuk : @!\nDari Grup : '+ab+'\nMid Kamu : '+ac+'\n\n-「 TOKEN 」 : \n{}\n\n- UA : Line/8.3.2\n- LA : WIN10 8.8.3 NADYA-TJ x64\n\n*「 From NadyaTJ & BotEater / Edited By PUY 」'.format(b), [sender]) if text.lower() == '#login chrome': req = requests.get('https://api.eater.tech/CHROMEOS') a = req.text b = json.loads(a) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) tkn['{}'.format(msg._from)] = [] tkn['{}'.format(msg._from)].append({ 'qr': b['result'][0]['linkqr'], 'tkn': b['result'][0]['linktkn'] }) qrz = b['result'][0]['linkqr'] dap.sendMessage(to, 'Buka Link dibawah dan Tekan Login\n\n{}'.format(qrz)) #dap.sendMessage(msg.to, 'Buka Link dibawah dan Tekan Login\n{}'.format(qrz)) with open('tkn.json', 'w') as outfile: json.dump(tkn, outfile) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) a = tkn['{}'.format(msg._from)][0]['tkn'] req = requests.get(url = '{}'.format(a)) b = req.text aa = dap.getContact(sender).displayName ab = dap.getGroup(msg.to).name ac = dap.getContact(sender).mid #sendMention(to, '- TIPE TOKEN : WIN10\n- For : @!\n\n- TOKEN : \n{}'.format(b), [sender]) #dap.sendMessage(to,'「 CHROMEOS 」\nUntuk: '+aa+'\nFrom Group: '+ab+'\nMid User: '+ac+'\n\n- TOKEN : \n{}'.format(b)) sendMention(to,'「 CHROME 」\nUntuk : @!\nDari Grup : '+ab+'\nMid Kamu : '+ac+'\n\n-「 TOKEN 」 : \n{}\n\n- UA : Line/8.3.2\n- LA : CHROMEOS 8.8.3 NADYA-TJ x64\n\n*「 From NadyaTJ & BotEater / Edited By PUY 」'.format(b), [sender]) if text.lower() == '#login iospad': req = requests.get('https://api.eater.tech/IOSPAD') a = req.text b = json.loads(a) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) tkn['{}'.format(msg._from)] = [] tkn['{}'.format(msg._from)].append({ 'qr': b['result'][0]['linkqr'], 'tkn': b['result'][0]['linktkn'] }) qrz = b['result'][0]['linkqr'] dap.sendMessage(to, 'Buka Link dibawah dan Tekan Login\n\n{}'.format(qrz)) #dap.sendMessage(msg.to, 'Buka Link dibawah dan Tekan Login\n{}'.format(qrz)) with open('tkn.json', 'w') as outfile: json.dump(tkn, outfile) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) a = tkn['{}'.format(msg._from)][0]['tkn'] req = requests.get(url = '{}'.format(a)) b = req.text aa = dap.getContact(sender).displayName ab = dap.getGroup(msg.to).name ac = dap.getContact(sender).mid #sendMention(to, '- TIPE TOKEN : WIN10\n- For : @!\n\n- TOKEN : \n{}'.format(b), [sender]) #dap.sendMessage(to,'「 CHROMEOS 」\nUntuk: '+aa+'\nFrom Group: '+ab+'\nMid User: '+ac+'\n\n- TOKEN : \n{}'.format(b)) sendMention(to,'「 IOSPAD 」\nUntuk : @!\nDari Grup : '+ab+'\nMid Kamu : '+ac+'\n\n-「 TOKEN 」 : \n{}\n\n- UA : Line/8.3.2\n- LA : IOSPAD 8.8.3 NADYA-TJ x64\n\n*「 From NadyaTJ & BotEater / Edited By PUY 」'.format(b), [sender]) if text.lower() == '#login desktopwin': req = requests.get('https://api.eater.tech/DESKTOPWIN') a = req.text b = json.loads(a) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) tkn['{}'.format(msg._from)] = [] tkn['{}'.format(msg._from)].append({ 'qr': b['result'][0]['linkqr'], 'tkn': b['result'][0]['linktkn'] }) qrz = b['result'][0]['linkqr'] dap.sendMessage(to, 'Buka Link dibawah dan Tekan Login\n\n{}'.format(qrz)) #dap.sendMessage(msg.to, 'Buka Link dibawah dan Tekan Login\n{}'.format(qrz)) with open('tkn.json', 'w') as outfile: json.dump(tkn, outfile) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) a = tkn['{}'.format(msg._from)][0]['tkn'] req = requests.get(url = '{}'.format(a)) b = req.text aa = dap.getContact(sender).displayName ab = dap.getGroup(msg.to).name ac = dap.getContact(sender).mid #sendMention(to, '- TIPE TOKEN : WIN10\n- For : @!\n\n- TOKEN : \n{}'.format(b), [sender]) #dap.sendMessage(to,'「 CHROMEOS 」\nUntuk: '+aa+'\nFrom Group: '+ab+'\nMid User: '+ac+'\n\n- TOKEN : \n{}'.format(b)) sendMention(to,'「 DESKTOPWIN 」\nUntuk : @!\nDari Grup : '+ab+'\nMid Kamu : '+ac+'\n\n-「 TOKEN 」 : \n{}\n\n- UA : DESKTOPWIN 8.8.3 NADYA-TJ x64\n\n*「 From NadyaTJ & BotEater / Edited By PUY 」'.format(b), [sender]) if text.lower() == '#login desktopmac': req = requests.get('https://api.eater.tech/DESKTOPMAC') a = req.text b = json.loads(a) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) tkn['{}'.format(msg._from)] = [] tkn['{}'.format(msg._from)].append({ 'qr': b['result'][0]['linkqr'], 'tkn': b['result'][0]['linktkn'] }) qrz = b['result'][0]['linkqr'] dap.sendMessage(to, 'Buka Link dibawah dan Tekan Login\n\n{}'.format(qrz)) #dap.sendMessage(msg.to, 'Buka Link dibawah dan Tekan Login\n{}'.format(qrz)) with open('tkn.json', 'w') as outfile: json.dump(tkn, outfile) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) a = tkn['{}'.format(msg._from)][0]['tkn'] req = requests.get(url = '{}'.format(a)) b = req.text aa = dap.getContact(sender).displayName ab = dap.getGroup(msg.to).name ac = dap.getContact(sender).mid #sendMention(to, '- TIPE TOKEN : WIN10\n- For : @!\n\n- TOKEN : \n{}'.format(b), [sender]) #dap.sendMessage(to,'「 CHROMEOS 」\nUntuk: '+aa+'\nFrom Group: '+ab+'\nMid User: '+ac+'\n\n- TOKEN : \n{}'.format(b)) sendMention(to,'「 DESKTOPMAC 」\nUntuk : @!\nDari Grup : '+ab+'\nMid Kamu : '+ac+'\n\n-「 TOKEN 」 : \n{}\n\n- UA : Line/8.3.2\n- LA : DESKTOPMAC 8.8.3 NADYA-TJ x64\n\n*「 From NadyaTJ & BotEater / Edited By PUY 」'.format(b), [sender]) #elif cmd.startswith("Meme:"): # try: # txt = msg.text.split(" ") # teks = msg.text.replace("Meme: "+txt[1]+" ","") # data = [] # r = requests.get("http://captaintools.tk/bot.php") # r = eval(r.text) # for a in r: # data.append(a) # c = random.choice(data) # foto = "https://memegen.link/"+c+"/"+txt[1]+"/"+teks+".jpg" # puy.sendImageWithURL(msg.to, foto) # except: # puy.sendMessage(to, str(e)) ###PREFIX### elif text.lower() == "##prefix on": settings["setKey"] = True dap.sendMention(to, "@! \n\n[ Notified Prefix Key ]\nBerhasil mengaktifkan Prefix", [sender]) elif text.lower() == "##prefix off": settings["setKey"] = False dap.sendMention(to, "@! \n\n[ Notified Prefix Key ]\nBerhasil menonaktifkan Prefix", [sender]) elif msg.contentType == 1: if settings["changeDisplayPicture"] == True: path = dap.downloadObjectMsg(msg_id) settings["changeDisplayProfile"] = False dap.updateProfilePicture(path) dap.sendMessage(to, "\nDisplay Picture has been Changed\n") if msg.toType == 2: if to in settings["changeGroupPicture"]: path = dap.downloadObjectMsg(msg_id) settings["changeGroupPicture"].remove(to) dap.updateGroupPicture(to, path) dap.sendMessage(to, "\nGroup picture has been Changed\n") elif msg.contentType == 1 and sender == dapMID: if bc["img"] == True: path = dap.downloadObjectMsg(msg_id) for gc in dap.groups: dap.sendMessage(gc, bc["txt"]) dap.sendContact(gc, bc["mid"]) dap.sendImage(gc, path) bc["img"] = False dap.sendMessage(to, "Sukses broadcast ke {} grup.".format(str(len(dap.groups)))) elif msg.contentType == 7: if settings["checkSticker"] == True: stk_id = msg.contentMetadata['STKID'] stk_ver = msg.contentMetadata['STKVER'] pkg_id = msg.contentMetadata['STKPKGID'] ret_ = "\n [ Sticker Info ] " ret_ += "\n STICKER ID : {}".format(stk_id) ret_ += "\n STICKER PACKAGES ID : {}".format(pkg_id) ret_ += "\n STICKER VERSION : {}".format(stk_ver) ret_ += "\n STICKER URL : line://shop/detail/{}\n".format(pkg_id) ret_ += "" dap.sendMessage(to, str(ret_)) elif msg.contentType == 13: if settings["checkContact"] == True: try: contact = dap.getContact(msg.contentMetadata["mid"]) if dap != None: cover = dap.getProfileCoverURL(msg.contentMetadata["mid"]) else: cover = "Tidak dapat masuk di line channel" path = "http://dl.profile.line-cdn.net/{}".format(str(contact.pictureStatus)) try: dap.sendImageWithURL(to, str(path)) except: pass ret_ = "\n[ Details Contact ] " ret_ += "\n Name : {}".format(str(contact.displayName)) ret_ += "\n MID : {}".format(str(msg.contentMetadata["mid"])) ret_ += "\n Bio : {}".format(str(contact.statusMessage)) ret_ += "\n Profile Picture : http://dl.profile.line-cdn.net/{}".format(str(contact.pictureStatus)) ret_ += "\n Cover Picture : {}\n".format(str(cover)) ret_ += "" dap.sendMessage(to, str(ret_)) except: dap.sendMessage(to, "\nInvalid contact\n") elif msg.contentType == 16: if settings["checkPost"] == True: try: ret_ = "\n [ Details Post ] " if msg.contentMetadata["serviceType"] == "GB": contact = dap.getContact(sender) auth = "\n Author : {}".format(str(contact.displayName)) else: auth = "\n Author : {}".format(str(msg.contentMetadata["serviceName"])) purl = "\n URL : {}".format(str(msg.contentMetadata["postEndUrl"]).replace("line://","https://line.me/R/")) ret_ += auth ret_ += purl if "mediaOid" in msg.contentMetadata: object_ = msg.contentMetadata["mediaOid"].replace("svc=myhome|sid=h|","") if msg.contentMetadata["mediaType"] == "V": if msg.contentMetadata["serviceType"] == "GB": ourl = "\n Object URL : https://obs-us.line-apps.com/myhome/h/download.nhn?tid=612w&{}".format(str(msg.contentMetadata["mediaOid"])) murl = "\n Media URL : https://obs-us.line-apps.com/myhome/h/download.nhn?{}".format(str(msg.contentMetadata["mediaOid"])) else: ourl = "\n Object URL : https://obs-us.line-apps.com/myhome/h/download.nhn?tid=612w&{}".format(str(object_)) murl = "\n Media URL : https://obs-us.line-apps.com/myhome/h/download.nhn?{}".format(str(object_)) ret_ += murl else: if msg.contentMetadata["serviceType"] == "GB": ourl = "\n Object URL : https://obs-us.line-apps.com/myhome/h/download.nhn?tid=612w&{}".format(str(msg.contentMetadata["mediaOid"])) else: ourl = "\n Object URL : https://obs-us.line-apps.com/myhome/h/download.nhn?tid=612w&{}".format(str(object_)) ret_ += ourl if "stickerId" in msg.contentMetadata: stck = "\n Sticker : https://line.me/R/shop/detail/{}".format(str(msg.contentMetadata["packageId"])) ret_ += stck if "text" in msg.contentMetadata: text = "\n the contents of writing : {}".format(str(msg.contentMetadata["text"])) ret_ += text ret_ += "\n" dap.sendMessage(to, str(ret_)) except: dap.sendMessage(to, "\nInvalid post\n") except Exception as error: logError(error) traceback.print_tb(error.__traceback__) #if op.type == 26: # msg = op.message # text = msg.text # msg_id = msg.id # receiver = msg.to # sender = msg.from_ # sender = msg._from # if msg.toType == 0 or msg.toType == 1 or msg.toType == 2: # if msg.toType == 0: # if msg._from != mid: # to = msg._from # else: # to = msg.to # elif msg.toType == 1: # to = receiver # elif msg.toType == 2: # to = receiver # elif msg.contentType==0: if op.type == 26: print ("[ 26 ] RECEIVE MESSAGE") msg = op.message text = msg.text msg_id = msg.id receiver = msg.to sender = msg._from if msg.toType == 0: if sender != dap.profile.mid: to = sender else: to = receiver else: to = receiver if settings["autoRead"] == True: dap.sendChatChecked(to, msg_id) if to in read["readPoint"]: if sender not in read["ROM"][to]: read["ROM"][to][sender] = True if sender in settings["mimic"]["target"] and settings["mimic"]["status"] == True and settings["mimic"]["target"][sender] == True: text = msg.text if text is not None: dap.sendMessage(msg.to,text) #if msg.contentType == 0 and sender not in dapMID and msg.toType == 2: # if 'MENTION' in msg.contentMetadata.keys()!= None: # names = re.findall(r'@(\w+)', text) # mention = ast.literal_eval(msg.contentMetadata['MENTION']) # mentionees = mention['MENTIONEES'] # lists = [] # for mention in mentionees: # if dapMID in mention["M"]: # if settings["detectMention"] == True: # contact = dap.getContact(sender) # dap.sendMessage(to, "????") # sendMessageWithMention(to, contact.mid) #if settings["unsendMessage"] == True: # try: # msg = op.message # if msg.toType == 0: # dap.log("[{} : {}]".format(str(msg._from), str(msg.text))) # else: # dap.log("[{} : {}]".format(str(msg.to), str(msg.text))) # msg_dict[msg.id] = {"text": msg.text, "from": msg._from, "createdTime": msg.createdTime, "contentType": msg.contentType, "contentMetadata": msg.contentMetadata} # except Exception as error: # logError(error) if msg.contentType == 0: if text is None: return if "/ti/g/" in msg.text.lower(): if settings["autoJoinTicket"] == True: link_re = re.compile('(?:line\:\/|line\.me\/R)\/ti\/g\/([a-zA-Z0-9_-]+)?') links = link_re.findall(text) n_links = [] for l in links: if l not in n_links: n_links.append(l) for ticket_id in n_links: group = dap.findGroupByTicket(ticket_id) dap.acceptGroupInvitationByTicket(group.id,ticket_id) pi.acceptGroupInvitationByTicket(group.id,ticket_id) dap.sendMessage(to, "Berhasil masuk ke group %s" % str(group.name)) if 'MENTION' in msg.contentMetadata.keys() != None: if msg.to in mentionKick: name = re.findall(r'@(\w+)', msg.text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] for mention in mentionees: if mention ['M'] in Xmid: dap.sendMessage(msg.to, "Don't Tag") #cl.kickoutFromGroup(msg.to, [msg._from]) if 'MENTION' in msg.contentMetadata.keys() != None: if wait["CrashMention"] == True: contact = dap.getContact(msg.from_) cName = contact.displayName balas = ["??? " + cName + "\n"] ret_ = dap.choice(balas) name = re.findall(r'@(\w+)', msg.text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] for mention in mentionees: if mention['M'] in Bots: dap.sendMessage(msg.to,ret_) break msg.contentType = 13 msg.contentMetadata = {'mid': "00000000000000000000000000000000',"} dap.sendMessage(msg) if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if dapMid in mention["M"]: if settings["autoRespon"] == True: sendMention(sender, " @!, don't tag", [sender]) # break # except Exception as error: # logError(error) # traceback.print_tb(error.__traceback__) if op.type == 65: print ("[ 65 ] NOTIFIED DESTROY MESSAGE") if settings["unsendMessage"] == True: try: at = op.param1 msg_id = op.param2 if msg_id in msg_dict: if msg_dict[msg_id]["from"]: contact = dap.getContact(msg_dict[msg_id]["from"]) ginfo = dap.getGroup(at) if contact.displayNameOverridden != None: name_ = contact.displayNameOverridden else: name_ = contact.displayName ret_ = "[ Pesan Ditarik ]\n" ret_ += "\nPengirim : @!" #ret_ += "\nMengirim pada : {}".format(str(dt_to_str(cTime_to_datetime(msg_dict[msg_id]["createdTime"])))) #ret_ += "\nMengirim pada : {}".format(str(inihari.strftime('%d')), str(bln), str(inihari.strftime('%Y')), str(inihari.strftime('%H:%M:%S'))) #ret_ += "\nTipe pesan : {}".format(str(Type._VALUES_TO_NAMES[msg_dict[msg_id]["contentType"]])) ret_ += "\nDari grup : {}".format(str(ginfo.name)) ret_ += "\nIsi : {}".format(str(msg_dict[msg_id]["text"])) sendMentionFooter(at, str(ret_), [contact.mid]) dap.sendImageWithURL(receiver, "https://stickershop.line-scdn.net/stickershop/v1/sticker/16365599/ANDROID/sticker.png") del msg_dict[msg_id] else: dap.sendMessage(at,"SentMessage cancelled,But I didn't have log data.\nSorry > <") except Exception as error: logError(error) traceback.print_tb(error.__traceback__) if op.type == 65: if settings["unsendMessage"] == True: try: at = op.param1 msg_id = op.param2 if msg_id in msg_dict: if msg_dict[msg_id]["from"]: if msg_dict[msg_id]["text"] == 'Gambarnya': ginfo = dap.getGroup(at) contact = dap.getContact(msg_dict[msg_id]["from"]) zx = "" zxc = "" zx2 = [] xpesan = "「 Gambar Dihapus 」\n◤ Pengirim : " ret_ = "◤ Nama Grup : {}".format(str(ginfo.name)) ret_ += "\n◤ Waktu Ngirim : {}".format(dt_to_str(cTime_to_datetime(msg_dict[msg_id]["createdTime"]))) ry = str(contact.displayName) pesan = '' pesan2 = pesan+"@x \n" xlen = str(len(zxc)+len(xpesan)) xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1) zx = {'S':xlen, 'E':xlen2, 'M':contact.mid} zx2.append(zx) zxc += pesan2 text = xpesan + zxc + ret_ + "" dap.sendMessage(at, text, contentMetadata={'MENTION':str('{"MENTIONEES":'+json.dumps(zx2).replace(' ','')+'}')}, contentType=0) dap.sendImage(at, msg_dict[msg_id]["data"]) else: ginfo = dap.getGroup(at) contact = dap.getContact(msg_dict[msg_id]["from"]) ret_ = "「 Pesan Dihapus 」\n" ret_ += "◤ Pengirim : {}".format(str(contact.displayName)) ret_ += "\n◤ Nama Grup : {}".format(str(ginfo.name)) ret_ += "\n◤ Waktu Ngirim : {}".format(dt_to_str(cTime_to_datetime(msg_dict[msg_id]["createdTime"]))) ret_ += "\n◤ Pesannya : {}".format(str(msg_dict[msg_id]["text"])) dap.sendMessage(at, str(ret_)) del msg_dict[msg_id] except Exception as e: print(e) if op.type == 17: if settings["Inroom"] == True: dapii = dap.getGroup(op.param1) dancuk = dap.getContact(op.param2) #image = "http://dl.profile.line.naver.jp/" + contact.pictureStatus sendMentionFooter(op.param1, "@!, Welcome".format(str(dapii.name)),[op.param2]) dap.sendContact(op.param1, op.param2) if op.type == 15: if settings["Outroom"] == True: tgb = dap.getGroup(op.param1) dan = dap.getContact(op.param2) #dap.sendContact(op.param1, op.param2) sendMentionFooter(op.param1, "@!, Gbye", [op.param2]) dap.sendImageWithURL(op.param1, "http://dl.profile.line-cdn.net"+dap.getContact(op.param2).picturePath) #dap.sendContact(op.param1, op.param2) if op.type == 55: try: if op.param1 in read['readPoint']: if op.param2 in read['readMember'][op.param1]: pass else: read['readMember'][op.param1] += op.param2 read['ROM'][op.param1][op.param2] = op.param2 with open('sider.json', 'w') as fp: json.dump(read, fp, sort_keys=True, indent=4) else: pass except: pass if op.type == 55: print ("[ 55 ] NOTIFIED READ MESSAGE") try: if op.param1 in read['readPoint']: if op.param2 in read['readMember'][op.param1]: pass else: read['readMember'][op.param1] += op.param2 read['ROM'][op.param1][op.param2] = op.param2 else: pass except Exception as error: logError(error) traceback.print_tb(error.__traceback__) except Exception as error: logError(error) traceback.print_tb(error.__traceback__) #=============================================================================== # if op.type == 19: # print ("[ 19 ] KICKOUT DAP MESSAGE") # try: # if op.param3 in dapMID: # if op.param2 in kiMID: # G = pi.getGroup(op.param1) # ginfo = pi.getGroup(op.param1) # G.preventedJoinByTicket = False # pi.updateGroup(G) # invsend = 0 # Ticket = pi.reissueGroupTicket(op.param1) # dap.acceptGroupInvitationByTicket(op.param1,Ticket) # pi.acceptGroupInvitationByTicket(op.param1,Ticket) # #ki2.acceptGroupInvitationByTicket(op.param1,Ticket) # #ki3.acceptGroupInvitationByTicket(op.param1,Ticket) # #ki4.acceptGroupInvitationByTicket(op.param1,Ticket) # G = pi.getGroup(op.param1) # G.preventedJoinByTicket = True # pi.updateGroup(G) # G.preventedJoinByTicket(G) # pi.updateGroup(G) # else: # G = pi.getGroup(op.param1) # ginfo = pi.getGroup(op.param1) # pi.kickoutFromGroup(op.param1,[op.param2]) # G.preventedJoinByTicket = False # pi.updateGroup(G) # invsend = 0 # Ticket = pi.reissueGroupTicket(op.param1) # dap.acceptGroupInvitationByTicket(op.param1,Ticket) # pi.acceptGroupInvitationByTicket(op.param1,Ticket) # #ki2.acceptGroupInvitationByTicket(op.param1,Ticket) # #ki3.acceptGroupInvitationByTicket(op.param1,Ticket) # #ki4.acceptGroupInvitationByTicket(op.param1,Ticket) # G = pi.getGroup(op.param1) # G.preventedJoinByTicket = True # pi.updateGroup(G) # G.preventedJoinByTicket(G) # pi.updateGroup(G) # #settings["blacklist"][op.param2] = True #------------------------------------------------------------------------------- def NOTIFIED_INVITE_INTO_GROUP(op): try: dap.acceptGroupInvitation(op.param1) ki.acceptGroupInvitation(op.param1) #ki2.acceptGroupInvitation(op.param1) #ki3.acceptGroupInvitation(op.param1) #ki4.acceptGroupInvitation(op.param1) except Exception as e: dap.log("[NOTIFIED_INVITE_INTO_GROUP] ERROR : " + str(e)) #================================= while True: try: delete_log() ops = dapPoll.singleTrace(count=50) if ops is not None: for op in ops: dapBot(op) dapPoll.setRevision(op.revision) except Exception as error: logError(error) def atend(): print("Saving") with open("Log_data.json","w",encoding='utf8') as f: json.dump(msg_dict, f, ensure_ascii=False, indent=4,separators=(',', ': ')) print("BYE") atexit.register(atend) <file_sep>/puck.py.py # -*- coding: utf-8 -*- # 「 From Helloworldd / Edited by Puy 」 " # ID : yapuy from PUY.linepy import * from PUY.akad.ttypes import Message from PUY.akad.ttypes import ContentType as Type from time import sleep from datetime import datetime, timedelta from googletrans import Translator from humanfriendly import format_timespan, format_size, format_number, format_length import time, random, sys, json, codecs, subprocess, threading, glob, re, string, os, requests, six, ast, pytz, urllib, urllib3, urllib.parse, traceback, atexit #puy = LINE() #puy = LINE("<KEY> # UNTUK LOGIN TOKEN # puy = LINE("<KEY> #puy = LINE('','') # UNTUK LOGIN MAIL LINE # puyMid = puy.profile.mid puyProfile = puy.getProfile() puySettings = puy.getSettings() puyPoll = OEPoll(puy) botStart = time.time() msg_dict = {} Owner = ["u<KEY>"] Admin =["<KEY>"] settings = { "autoJoin": True, "autoLeave": False, "Inroom": True, "Outroom": True, "timeRestart": "18000", "changeGroupPicture": [], "limit": 50, "limits": 50, "wordban": [], "keyCommand": "", "myProfile": { "displayName": "", "coverId": "", "pictureStatus": "", "statusMessage": "" }, "setKey": False, "unsendMessage": True } read = { "ROM": {}, "readPoint": {}, "readMember": {}, "readTime": {} } try: with open("Log_data.json","r",encoding="utf_8_sig") as f: msg_dict = json.loads(f.read()) except: print("PUY") settings["myProfile"]["displayName"] = puyProfile.displayName settings["myProfile"]["statusMessage"] = puyProfile.statusMessage settings["myProfile"]["pictureStatus"] = puyProfile.pictureStatus coverId = puy.getProfileDetail()["result"]["objectId"] settings["myProfile"]["coverId"] = coverId def restartBot(): print ("[ INFO ] BOT RESTART") python = sys.executable os.execl(python, python, *sys.argv) def autoRestart(): if time.time() - botStart > int(settings["timeRestart"]): time.sleep(5) restartBot() def sendMentionFooter(to, text="", mids=[]): arrData = "" arr = [] mention = "@Meka Finee " if mids == []: raise Exception("Invalid mids") if "@!" in text: if text.count("@!") != len(mids): raise Exception("Invalid mids") texts = text.split("@!") textx = "" for mid in mids: textx += str(texts[mids.index(mid)]) slen = len(textx) elen = len(textx) + 15 arrData = {'S':str(slen), 'E':str(elen - 4), 'M':mid} arr.append(arrData) textx += mention textx += str(texts[len(mids)]) else: textx = "" slen = len(textx) elen = len(textx) + 15 arrData = {'S':str(slen), 'E':str(elen - 4), 'M':mids[0]} arr.append(arrData) textx += mention + str(text) puy.sendMessage(to, textx, {'AGENT_NAME':'@Muh.khadaffy on Instagram', 'AGENT_LINK': 'https://www.instagram.com/muh.khadaffy', 'AGENT_ICON': "http://dl.profile.line-cdn.net/" + puy.getProfile().picturePath, 'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0) #'AGENT_LINK': 'line://ti/p/~{}'.format(puy.getProfile().userid), def sendMessageWithFooter(to, text, name, url, iconlink): contentMetadata = { 'AGENT_NAME': name, 'AGENT_LINK': url, 'AGENT_ICON': iconlink } return puy.sendMessage(to, text, contentMetadata, 0) def sendMessageWithFooter(to, text): puy.reissueUserTicket() dap = puy.getProfile() ticket = "http://line.me/ti/p/"+puy.getUserTicket().id pict = "http://dl.profile.line-cdn.net/"+dap.pictureStatus name = dap.displayName dapi = {"AGENT_ICON": pict, "AGENT_NAME": name, "AGENT_LINK": ticket } puy.sendMessage(to, text, contentMetadata=dapi) def sendMessageWithContent(to, name, link, url, iconlink): contentMetadata = { 'AGENT_NAME': name, 'AGENT_LINK': url, 'AGENT_ICON': iconlink } return self.sendMessage(to, text, contentMetadata, 0) def logError(text): puy.log("[ ERROR ] {}".format(str(text))) tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) timeHours = datetime.strftime(timeNow,"(%H:%M)") day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] inihari = datetime.now(tz=tz) hr = inihari.strftime('%A') bln = inihari.strftime('%m') for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] time = "{}, {} - {} - {} | {}".format(str(hasil), str(inihari.strftime('%d')), str(bln), str(inihari.strftime('%Y')), str(inihari.strftime('%H:%M:%S'))) with open("logError.txt","a") as error: error.write("\n[ {} ] {}".format(str(time), text)) def cTime_to_datetime(unixtime): return datetime.fromtimestamp(int(str(unixtime)[:len(str(unixtime))-3])) def dt_to_str(dt): return dt.strftime('%H:%M:%S') def delete_log(): ndt = datetime.now() for data in msg_dict: if (datetime.utcnow() - cTime_to_datetime(msg_dict[data]["createdTime"])) > timedelta(1): if "path" in msg_dict[data]: puy.deleteFile(msg_dict[data]["path"]) del msg_dict[data] def sendMention(to, text="", mids=[]): arrData = "" arr = [] mention = "@zeroxyuuki " if mids == []: raise Exception("Invalid mids") if "@!" in text: if text.count("@!") != len(mids): raise Exception("Invalid mids") texts = text.split("@!") textx = "" for mid in mids: textx += str(texts[mids.index(mid)]) slen = len(textx) elen = len(textx) + 15 arrData = {'S':str(slen), 'E':str(elen - 4), 'M':mid} arr.append(arrData) textx += mention textx += str(texts[len(mids)]) else: textx = "" slen = len(textx) elen = len(textx) + 15 arrData = {'S':str(slen), 'E':str(elen - 4), 'M':mids[0]} arr.append(arrData) textx += mention + str(text) puy.sendMessage(to, textx, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0) def command(text): pesan = text.lower() if settings["setKey"] == True: if pesan.startswith(settings["keyCommand"]): cmd = pesan.replace(settings["keyCommand"],"") else: cmd = "Undefined command" else: cmd = text.lower() return cmd def helpmessage(): if settings['setKey'] == True: key = settings['keyCommand'] else: key = '' helpMessage = "\n 「 HELPER 」 " + "\n" + \ " " + key + "1) #Token" + "\n" + \ " " + key + "2) #Keluar" + "\n\n" + \ " " + key + " 「 CEKSIDER 」" + "\n" + \ " " + key + "3) #Ceksider On/Off - [For SetRead]" + "\n" + \ " " + key + "4) #Ceksider reset - [For Reset reader point]" + "\n" + \ " " + key + "5) #Ceksider - [For Ceksider]" + "\n\n" + \ " " + key + " 「 Use # For the Prefix 」" + "\n" + \ " 「 From Helloworld / Edited by Puy 」" return helpMessage def puyBot(op): try: if op.type == 0: print ("[ 0 ] END OF OPERATION") return if op.type == 5: print ("[ 5 ] NOTIFIED ADD CONTACT") if settings["autoAdd"] == True: puy.findAndAddContactsByMid(op.param2) sendMessageWithFooter(op.param1, "Thx for add") if op.type == 13: print ("[ 13 ] Invite Into Group") if cvMid in op.param3: if settings["autoJoin"] == True: puy.acceptGroupInvitation(op.param1) dan = puy.getContact(op.param2) tgb = puy.getGroup(op.param1) sendMention(op.param1, "@!, Thx for invited Me".format(str(tgb.name)),[op.param2]) puy.sendImageWithURL(op.param1, "http://dl.profile.line-cdn.net{}".format(dan.picturePath)) puy.sendContact(op.param1, op.param2) if op.type in [22, 24]: print ("[ 22 And 24 ] NOTIFIED INVITE INTO ROOM & NOTIFIED LEAVE ROOM") if settings["autoLeave"] == True: sendMention(op.param2, "@! hmm?") puy.leaveRoom(op.param1) if op.type == 26: try: print ("[ 26 ] SEND MESSAGE") msg = op.message text = msg.text msg_id = msg.id receiver = msg.to sender = msg._from setKey = settings["keyCommand"].title() if settings["setKey"] == False: setKey = '' if msg.toType == 0 or msg.toType == 1 or msg.toType == 2: if msg.toType == 0: if sender != puy.profile.mid: to = sender else: to = receiver elif msg.toType == 1: to = receiver elif msg.toType == 2: to = receiver if msg.contentType == 0: if text is None: return else: cmd = command(text) if cmd == "help": helpMessage = helpmessage() puy.sendMessage(to, str(helpMessage),{'AGENT_ICON':'http://dl.profile.line-cdn.net/0hkY3juiptNHYOExk5wsdLITJWOht5PTI-diUpGX8RPhZ0IydzMSV_FC0VaxV0I3JyMCZ4Ei8VOEQh','AGENT_LINK':'https://line.me/ti/p/~yapuy','AGENT_NAME':'Help Message'}) if cmd == "#help": helpMessage = helpmessage() puy.sendMessage(to, str(helpMessage),{'AGENT_ICON':'http://dl.profile.line-cdn.net/0hkY3juiptNHYOExk5wsdLITJWOht5PTI-diUpGX8RPhZ0IydzMSV_FC0VaxV0I3JyMCZ4Ei8VOEQh','AGENT_LINK':'https://line.me/ti/p/~yapuy','AGENT_NAME':'Help Message'}) elif cmd == "#token generator": sendMentionFooter(to, "「 TOKEN TIPE 」\n1* DESKTOPWIN\n2* WIN10\n3* DESKTOPMAC\n4* IOSPAD\n5* CHROME\n\n*Usage : Type #login with Token Type\n\n*Example : #login chrome\n\n[ From BotEater / Edited by Puy ]\n@! - Selamat Mencoba.", [sender]) elif cmd == "#token": sendMentionFooter(to, "「 TOKEN TIPE 」\n1* DESKTOPWIN\n2* WIN10\n3* DESKTOPMAC\n4* IOSPAD\n5* CHROME\n\n*Usage : Type #login with Token Type\n\n*Example : #login chrome\n\n[ From BotEater / Edited by Puy ]\n@! - Sel<NAME>.", [sender]) elif cmd == "#speed": if msg._from in Owner: start = time.time() puy.sendMessage(to, "...") elapsed_time = time.time() - start puy.sendMessage(to, "[ Speed ]\nKecepatan mengirim pesan {} detik puy".format(str(elapsed_time))) elif cmd == "#restart": if msg._from in Owner: puy.sendMessage(to, "I'll be Back") sendMention(to, "@! \nBot Restarted", [sender]) restartBot() else: puy.sendMessage("Permission Denied") elif cmd.startswith("spamcall"): if msg._from in Owner: if msg.toType == 2: group = puy.getGroup(to) members = [mem.mid for mem in group.members] jmlh = int(settings["limit"]) puy.sendMessage(msg.to, "Invitation Call Groups {} In Progress ".format(str(settings["limit"]))) if jmlh <= 9999: for x in range(jmlh): try: puy.inviteIntoGroupCall(to, contactIds=members) except Exception as e: puy.sendMessage(msg.to,str(e)) else: puy.sendMessage(msg.to,"Invitation Call Groups Successed") elif cmd == "#me": contact = puy.getContact(sender) sendMentionFooter(to, "At here @!", [sender]) puy.sendContact(to, sender) puy.sendImageWithURL(to,"http://dl.profile.line-cdn.net/{}".format(contact.pictureStatus)) elif cmd == "autojoin on": if msg._from in Owner: settings["autoJoin"] = True sendMention(to, "[ Notified Auto Join ]\nBerhasil mengaktifkan Auto Join @!", [sender]) elif cmd == "autojoin off": if msg._from in Owner: settings["autoJoin"] = False sendMention(to, "[ Notified Auto Join ]\nBerhasil menonaktifkan Auto Join @!", [sender]) elif cmd == "autoleave on": settings["autoLeave"] = True sendMention(to, "[ Notified Auto Leave ]\nBerhasil mengaktifkan Auto leave @!", [sender]) elif cmd == "autoleave off": if msg._from in Owner: settings["autoLeave"] = False sendMention(to, "[ Notified Auto Leave ]\nBerhasil menonaktifkan Auto leave @!", [sender]) elif cmd == "status": try: ret_ = "\n [ BOT STATUS ]\n" if settings["autoJoin"] == True: ret_ += "\n [ ON ] Auto Join" else: ret_ += "\n [ OFF ] Auto Join" if settings["autoLeave"] == True: ret_ += "\n [ ON ] Auto Leave Room" else: ret_ += "\n [ OFF ] Auto Leave Room" ret_ += "" sendMessageWithFooter(to, str(ret_)) except Exception as e: sendMessageWithFooter(to, str(e)) ## LURKING ## elif text.lower() == '#ceksider on': tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to in read['readPoint']: try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to] except: pass read['readPoint'][msg.to] = msg.id read['readMember'][msg.to] = "" read['readTime'][msg.to] = datetime.now().strftime('%H:%M:%S') read['ROM'][msg.to] = {} with open('read.json', 'w') as fp: json.dump(read, fp, sort_keys=True, indent=4) #sendMention(to, "@!\n「 Ceksider Diaktifkan 」\nWaktu :\n" + readTime, [sender]) puy.sendMessage(to, "「 Ceksider Diaktifkan 」\n\nWaktu :\n" + readTime) else: try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to] except: pass read['readPoint'][msg.to] = msg.id read['readMember'][msg.to] = "" read['readTime'][msg.to] = datetime.now().strftime('%H:%M:%S') read['ROM'][msg.to] = {} with open('read.json', 'w') as fp: json.dump(read, fp, sort_keys=True, indent=4) #sendMention(to, "@!\n「 Ceksider Diaktifkan 」\n" + readTime, [sender]) puy.sendMessage(to, "「 Ceksider Diaktifkan 」\n\n" + readTime) elif text.lower() == '#ceksider off': tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to not in read['readPoint']: #sendMention(to, "「 Ceksider telah dimatikan 」\n@!\nWaktu :\n" + readTime, [sender]) puy.sendMessage(to, "「 Ceksider telah dimatikan 」\n\nWaktu :\n" + readTime) else: try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to] except: pass #sendMention(to, "「 Ceksider telah dimatikan 」\n@!\n" + readTime, [sender]) puy.sendMessage(to, "「 Ceksider telah dimatikan 」\n\n" + readTime) elif text.lower() == '#ceksider reset': tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to in read["readPoint"]: try: del read["readPoint"][msg.to] del read["readMember"][msg.to] del read["readTime"][msg.to] except: pass #sendMention(to, "「 Mengulangi riwayat pembaca 」 :\n@!\n" + readTime, [sender]) puy.sendMessage(to, "「 Ceksider telah direset 」\n\n" + readTime) else: #sendMention(to, "「 Ceksider belum diaktifkan 」\n@!", [sender]) puy.sendMessage(to, "「 Ceksider telah direset 」\n\n" + readTime) elif text.lower() == '#ceksider': tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if receiver in read['readPoint']: if read["ROM"][receiver].items() == []: puy.sendMessage(receiver," 「 Daftar Pembaca 」\nNone") else: chiya = [] for rom in read["ROM"][receiver].items(): chiya.append(rom[1]) cmem = puy.getContacts(chiya) zx = "" zxc = "" zx2 = [] xpesan = '「 Daftar Pembaca 」\n\n' for x in range(len(cmem)): xname = str(cmem[x].displayName) pesan = '' pesan2 = pesan+"@c\n" xlen = str(len(zxc)+len(xpesan)) xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1) zx = {'S':xlen, 'E':xlen2, 'M':cmem[x].mid} zx2.append(zx) zxc += pesan2 text = xpesan+ zxc + "\n\n" + readTime try: puy.sendMessage(receiver, text, contentMetadata={'MENTION':str('{"MENTIONEES":'+json.dumps(zx2).replace(' ','')+'}')}, contentType=0) except Exception as error: print (error) pass else: puy.sendMessage(receiver,"*Ceksider belum diaktifkan\nKetik 「 #ceksider on 」 untuk mengaktifkan.") elif text.lower() == '#lurking': tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if receiver in read['readPoint']: if read["ROM"][receiver].items() == []: puy.sendMessage(receiver,"[ Reader ]:\nNone") else: chiya = [] for rom in read["ROM"][receiver].items(): chiya.append(rom[1]) cmem = puy.getContacts(chiya) zx = "" zxc = "" zx2 = [] xpesan = ' 「 Daftar Pembaca 」\n\n' for x in range(len(cmem)): xname = str(cmem[x].displayName) pesan = '' pesan2 = pesan+"@c\n" xlen = str(len(zxc)+len(xpesan)) xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1) zx = {'S':xlen, 'E':xlen2, 'M':cmem[x].mid} zx2.append(zx) zxc += pesan2 text = xpesan+ zxc + "\n[ Waktu ] : \n" + readTime try: puy.sendMessage(receiver, text, contentMetadata={'MENTION':str('{"MENTIONEES":'+json.dumps(zx2).replace(' ','')+'}')}, contentType=0) except Exception as error: print (error) pass else: #sendMention(receiver,"*Ceksider belum diaktifkan\nKetik 「 #ceksider on 」 untuk mengaktifkan\n@!") client.sendMessage(receiver,"*Ceksider belum diaktifkan\nKetik 「 #ceksider on 」 untuk mengaktifkan.") elif cmd.startswith("#keluar"): #tgb = puy.getGroup(op.param1) #dan = puy.getContact(op.param2) #gid = puy.getGroup(to) puy.sendMessage(to, "Gbye") #sendMentionFooter(op.param1, "@!, Gbye", [op.param2]) puy.getGroupIdsJoined() puy.leaveGroup(to) elif cmd.startswith("bc: "): if msg._from in Owner: sep = text.split(" ") pesan = text.replace(sep[0] + " ","") saya = puy.getGroupIdsJoined() for group in saya: sendMessageWithFooter(group,"" + str(pesan)) if text.lower() == '#login win10': req = requests.get('https://api.eater.tech/WIN10') #contact = dap.getContact(mid) #dap.sendMessage(to, "[ MID ]\n{}".format(sender)) a = req.text b = json.loads(a) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) tkn['{}'.format(msg._from)] = [] tkn['{}'.format(msg._from)].append({ 'qr': b['result'][0]['linkqr'], 'tkn': b['result'][0]['linktkn'] }) qrz = b['result'][0]['linkqr'] dap.sendMessage(to, 'Buka Link dibawah dan Tekan Login\n\n{}'.format(qrz)) #dap.sendMessage(msg.to, 'Buka Link dibawah dan Tekan Login\n{}'.format(qrz)) with open('tkn.json', 'w') as outfile: json.dump(tkn, outfile) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) a = tkn['{}'.format(msg._from)][0]['tkn'] req = requests.get(url = '{}'.format(a)) b = req.text aa = dap.getContact(sender).displayName ab = dap.getGroup(msg.to).name ac = dap.getContact(sender).mid #sendMention(to, '- TIPE TOKEN : WIN10\n- For : @!\n\n- TOKEN : \n{}'.format(b), [sender]) sendMention(to,'「 WIN 10 」\nUntuk : @!\nDari Grup : '+ab+'\nMid Kamu : '+ac+'\n\n-「 TOKEN 」 : \n{}\n\n- UA : Line/8.3.2\n- LA : WIN10 8.8.3 NADYA-TJ x64\n\n*「 From NadyaTJ & BotEater / Edited By PUY 」'.format(b), [sender]) if text.lower() == '#login chrome': req = requests.get('https://api.eater.tech/CHROMEOS') a = req.text b = json.loads(a) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) tkn['{}'.format(msg._from)] = [] tkn['{}'.format(msg._from)].append({ 'qr': b['result'][0]['linkqr'], 'tkn': b['result'][0]['linktkn'] }) qrz = b['result'][0]['linkqr'] dap.sendMessage(to, 'Buka Link dibawah dan Tekan Login\n\n{}'.format(qrz)) #dap.sendMessage(msg.to, 'Buka Link dibawah dan Tekan Login\n{}'.format(qrz)) with open('tkn.json', 'w') as outfile: json.dump(tkn, outfile) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) a = tkn['{}'.format(msg._from)][0]['tkn'] req = requests.get(url = '{}'.format(a)) b = req.text aa = dap.getContact(sender).displayName ab = dap.getGroup(msg.to).name ac = dap.getContact(sender).mid #sendMention(to, '- TIPE TOKEN : WIN10\n- For : @!\n\n- TOKEN : \n{}'.format(b), [sender]) #dap.sendMessage(to,'「 CHROMEOS 」\nUntuk: '+aa+'\nFrom Group: '+ab+'\nMid User: '+ac+'\n\n- TOKEN : \n{}'.format(b)) sendMention(to,'「 CHROME 」\nUntuk : @!\nDari Grup : '+ab+'\nMid Kamu : '+ac+'\n\n-「 TOKEN 」 : \n{}\n\n- UA : Line/8.3.2\n- LA : CHROMEOS 8.8.3 NADYA-TJ x64\n\n*「 From NadyaTJ & BotEater / Edited By PUY 」'.format(b), [sender]) if text.lower() == '#login iospad': req = requests.get('https://api.eater.tech/IOSPAD') a = req.text b = json.loads(a) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) tkn['{}'.format(msg._from)] = [] tkn['{}'.format(msg._from)].append({ 'qr': b['result'][0]['linkqr'], 'tkn': b['result'][0]['linktkn'] }) qrz = b['result'][0]['linkqr'] dap.sendMessage(to, 'Buka Link dibawah dan Tekan Login\n\n{}'.format(qrz)) #dap.sendMessage(msg.to, 'Buka Link dibawah dan Tekan Login\n{}'.format(qrz)) with open('tkn.json', 'w') as outfile: json.dump(tkn, outfile) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) a = tkn['{}'.format(msg._from)][0]['tkn'] req = requests.get(url = '{}'.format(a)) b = req.text aa = dap.getContact(sender).displayName ab = dap.getGroup(msg.to).name ac = dap.getContact(sender).mid #sendMention(to, '- TIPE TOKEN : WIN10\n- For : @!\n\n- TOKEN : \n{}'.format(b), [sender]) #dap.sendMessage(to,'「 CHROMEOS 」\nUntuk: '+aa+'\nFrom Group: '+ab+'\nMid User: '+ac+'\n\n- TOKEN : \n{}'.format(b)) sendMention(to,'「 IOSPAD 」\nUntuk : @!\nDari Grup : '+ab+'\nMid Kamu : '+ac+'\n\n-「 TOKEN 」 : \n{}\n\n- UA : Line/8.3.2\n- LA : IOSPAD 8.8.3 NADYA-TJ x64\n\n*「 From NadyaTJ & BotEater / Edited By PUY 」'.format(b), [sender]) if text.lower() == '#login desktopwin': req = requests.get('https://api.eater.tech/DESKTOPWIN') a = req.text b = json.loads(a) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) tkn['{}'.format(msg._from)] = [] tkn['{}'.format(msg._from)].append({ 'qr': b['result'][0]['linkqr'], 'tkn': b['result'][0]['linktkn'] }) qrz = b['result'][0]['linkqr'] dap.sendMessage(to, 'Buka Link dibawah dan Tekan Login\n\n{}'.format(qrz)) #dap.sendMessage(msg.to, 'Buka Link dibawah dan Tekan Login\n{}'.format(qrz)) with open('tkn.json', 'w') as outfile: json.dump(tkn, outfile) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) a = tkn['{}'.format(msg._from)][0]['tkn'] req = requests.get(url = '{}'.format(a)) b = req.text aa = dap.getContact(sender).displayName ab = dap.getGroup(msg.to).name ac = dap.getContact(sender).mid #sendMention(to, '- TIPE TOKEN : WIN10\n- For : @!\n\n- TOKEN : \n{}'.format(b), [sender]) #dap.sendMessage(to,'「 CHROMEOS 」\nUntuk: '+aa+'\nFrom Group: '+ab+'\nMid User: '+ac+'\n\n- TOKEN : \n{}'.format(b)) sendMention(to,'「 DESKTOPWIN 」\nUntuk : @!\nDari Grup : '+ab+'\nMid Kamu : '+ac+'\n\n-「 TOKEN 」 : \n{}\n\n- UA : DESKTOPWIN 8.8.3 NADYA-TJ x64\n\n*「 From NadyaTJ & BotEater / Edited By PUY 」'.format(b), [sender]) if text.lower() == '#login desktopmac': req = requests.get('https://api.eater.tech/DESKTOPMAC') a = req.text b = json.loads(a) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) tkn['{}'.format(msg._from)] = [] tkn['{}'.format(msg._from)].append({ 'qr': b['result'][0]['linkqr'], 'tkn': b['result'][0]['linktkn'] }) qrz = b['result'][0]['linkqr'] dap.sendMessage(to, 'Buka Link dibawah dan Tekan Login\n\n{}'.format(qrz)) #dap.sendMessage(msg.to, 'Buka Link dibawah dan Tekan Login\n{}'.format(qrz)) with open('tkn.json', 'w') as outfile: json.dump(tkn, outfile) tknop= codecs.open("tkn.json","r","utf-8") tkn = json.load(tknop) a = tkn['{}'.format(msg._from)][0]['tkn'] req = requests.get(url = '{}'.format(a)) b = req.text aa = dap.getContact(sender).displayName ab = dap.getGroup(msg.to).name ac = dap.getContact(sender).mid #sendMention(to, '- TIPE TOKEN : WIN10\n- For : @!\n\n- TOKEN : \n{}'.format(b), [sender]) #dap.sendMessage(to,'「 CHROMEOS 」\nUntuk: '+aa+'\nFrom Group: '+ab+'\nMid User: '+ac+'\n\n- TOKEN : \n{}'.format(b)) sendMention(to,'「 DESKTOPMAC 」\nUntuk : @!\nDari Grup : '+ab+'\nMid Kamu : '+ac+'\n\n-「 TOKEN 」 : \n{}\n\n- UA : Line/8.3.2\n- LA : DESKTOPMAC 8.8.3 NADYA-TJ x64\n\n*「 From NadyaTJ & BotEater / Edited By PUY 」'.format(b), [sender]) ## PREFIX ## elif cmd.startswith("changeprefix:"): if msg._from in Owner: sep = text.split(" ") key = text.replace(sep[0] + " ","") if " " in key: puy.sendMessage(to, "\nTanpa spasi.\n") else: settings["keyCommand"] = str(key).lower() sendMessageWithFooter(to, "text [ {} ]".format(str(key).lower())) if text.lower() == "#prefix": puy.sendMessage(to, "\nPrefix Saat ini adalah [ {} ]\n".format(str(settings["keyCommand"]))) elif text.lower() == "#prefix on": settings["setKey"] = True puy.sendMention(to, "@! \n\n[ Notified Prefix Key ]\nBerhasil mengaktifkan Prefix", [sender]) elif text.lower() == "#prefix off": settings["setKey"] = False puy.sendMention(to, "@! \n\n[ Notified Prefix Key ]\nBerhasil menonaktifkan Prefix", [sender]) if msg.contentType == 0: if text is None: return if "/ti/g/" in msg.text.lower(): if settings["autoJoinTicket"] == True: link_re = re.compile('(?:line\:\/|line\.me\/R)\/ti\/g\/([a-zA-Z0-9_-]+)?') links = link_re.findall(text) n_links = [] for l in links: if l not in n_links: n_links.append(l) for ticket_id in n_links: group = puy.findGroupByTicket(ticket_id) puy.acceptGroupInvitationByTicket(group.id,ticket_id) puy.sendMessage(to, "Berhasil masuk ke group %s" % str(group.name)) #if 'MENTION' in msg.contentMetadata.keys() != None: # if msg.to in mentionKick: # name = re.findall(r'@(\w+)', msg.text) # mention = ast.literal_eval(msg.contentMetadata['MENTION']) # mentionees = mention['MENTIONEES'] # for mention in mentionees: # if mention ['M'] in Xmid: # puy.sendMessage(msg.to, "Don't Tag") #puy.kickoutFromGroup(msg.to, [msg._from]) if 'MENTION' in msg.contentMetadata.keys() != None: if wait["CrashMention"] == True: contact = puy.getContact(msg.from_) cName = contact.displayName balas = ["??? " + cName + "\n"] ret_ = puy.choice(balas) name = re.findall(r'@(\w+)', msg.text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] for mention in mentionees: if mention['M'] in Bots: puy.sendMessage(msg.to,ret_) break msg.contentType = 13 msg.contentMetadata = {'mid': "00000000000000000000000000000000',"} puy.sendMessage(msg) if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if puyMid in mention["M"]: if settings["autoRespon"] == True: sendMention(sender, " @!, don't tag", [sender]) break except Exception as error: logError(error) traceback.print_tb(error.__traceback__) if op.type == 26: try: print ("[ 26 ] RECIEVE MESSAGE") msg = op.message text = msg.text msg_id = msg.id receiver = msg.to sender = msg._from if msg.toType == 0 or msg.toType == 1 or msg.toType == 2: if msg.toType == 0: #if text =='mute': if sender != puy.profile.mid: to = sender else: to = receiver elif msg.toType == 1: to = receiver elif msg.toType == 2: to = receiver #if settings["autoRead"] == True: #puy.sendChatChecked(to, msg_id) if to in read["readPoint"]: if sender not in read["ROM"][to]: read["ROM"][to][sender] = True #if sender in settings["mimic"]["target"] and settings["mimic"]["status"] == True and settings["mimic"]["target"][sender] == True: # text = msg.text # if text is not None: # puy.sendMessage(msg.to,text) ## INI KALAU MAU DI HAPUS SILAHKAN ## #elif msg.contentType == 1: # if settings["changeDisplayPicture"] == True: # path = puy.downloadObjectMsg(msg_id) # settings["changeDisplayProfile"] = False # puy.updateProfilePicture(path) # puy.sendMessage(to, "\nDisplay Picture has been Changed\n") # if msg.toType == 2: # if to in settings["changeGroupPicture"]: # path = puy.downloadObjectMsg(msg_id) # settings["changeGroupPicture"].remove(to) # puy.updateGroupPicture(to, path) # puy.sendMessage(to, "\nGroup picture has been Changed\n") #elif msg.contentType == 1 and sender == puyMID: # if bc["img"] == True: # path = puy.downloadObjectMsg(msg_id) # for gc in puy.groups: # sendMessageWithFooter(gc, bc["txt"]) # puy.sendContact(gc, bc["mid"]) # puy.sendImage(gc, path) # bc["img"] = False # sendMessageWithFooter(to, "Sukses broadcast ke {} grup.".format(str(len(puy.groups)))) #elif msg.contentType == 7: # if settings["checkSticker"] == True: # stk_id = msg.contentMetadata['STKID'] # stk_ver = msg.contentMetadata['STKVER'] # pkg_id = msg.contentMetadata['STKPKGID'] # ret_ = "\n [ Sticker Info ] " # ret_ += "\n STICKER ID : {}".format(stk_id) # ret_ += "\n STICKER PACKAGES ID : {}".format(pkg_id) # ret_ += "\n STICKER VERSION : {}".format(stk_ver) # ret_ += "\n STICKER URL : line://shop/detail/{}\n".format(pkg_id) # ret_ += "" # puy.sendMessage(to, str(ret_)) #elif msg.contentType == 13: # if settings["checkContact"] == True: # try: # contact = puy.getContact(msg.contentMetadata["mid"]) # if puy != None: # cover = puy.getProfileCoverURL(msg.contentMetadata["mid"]) # else: # cover = "Tidak dapat masuk di line channel" # path = "http://dl.profile.line-cdn.net/{}".format(str(contact.pictureStatus)) # try: # puy.sendImageWithURL(to, str(path)) # except: # pass # ret_ = "\n[ Details Contact ] " # ret_ += "\n Name : {}".format(str(contact.displayName)) # ret_ += "\n MID : {}".format(str(msg.contentMetadata["mid"])) # ret_ += "\n Bio : {}".format(str(contact.statusMessage)) # ret_ += "\n Profile Picture : http://dl.profile.line-cdn.net/{}".format(str(contact.pictureStatus)) # ret_ += "\n Cover Picture : {}\n".format(str(cover)) # ret_ += "" # puy.sendMessage(to, str(ret_)) # except: # puy.sendMessage(to, "\nInvalid contact\n") elif msg.contentType == 16: if settings["checkPost"] == True: try: ret_ = "\n [ Details Post ] " if msg.contentMetadata["serviceType"] == "GB": contact = puy.getContact(sender) auth = "\n Author : {}".format(str(contact.displayName)) else: auth = "\n Author : {}".format(str(msg.contentMetadata["serviceName"])) purl = "\n URL : {}".format(str(msg.contentMetadata["postEndUrl"]).replace("line://","https://line.me/R/")) ret_ += auth ret_ += purl if "mediaOid" in msg.contentMetadata: object_ = msg.contentMetadata["mediaOid"].replace("svc=myhome|sid=h|","") if msg.contentMetadata["mediaType"] == "V": if msg.contentMetadata["serviceType"] == "GB": ourl = "\n Object URL : https://obs-us.line-apps.com/myhome/h/download.nhn?tid=612w&{}".format(str(msg.contentMetadata["mediaOid"])) murl = "\n Media URL : https://obs-us.line-apps.com/myhome/h/download.nhn?{}".format(str(msg.contentMetadata["mediaOid"])) else: ourl = "\n Object URL : https://obs-us.line-apps.com/myhome/h/download.nhn?tid=612w&{}".format(str(object_)) murl = "\n Media URL : https://obs-us.line-apps.com/myhome/h/download.nhn?{}".format(str(object_)) ret_ += murl else: if msg.contentMetadata["serviceType"] == "GB": ourl = "\n Object URL : https://obs-us.line-apps.com/myhome/h/download.nhn?tid=612w&{}".format(str(msg.contentMetadata["mediaOid"])) else: ourl = "\n Object URL : https://obs-us.line-apps.com/myhome/h/download.nhn?tid=612w&{}".format(str(object_)) ret_ += ourl if "stickerId" in msg.contentMetadata: stck = "\n Sticker : https://line.me/R/shop/detail/{}".format(str(msg.contentMetadata["packageId"])) ret_ += stck if "text" in msg.contentMetadata: text = "\n the contents of writing : {}".format(str(msg.contentMetadata["text"])) ret_ += text ret_ += "\n" puy.sendMessage(to, str(ret_)) except: puy.sendMessage(to, "\nInvalid post\n") except Exception as error: logError(error) traceback.print_tb(error.__traceback__) if op.type == 55: print ("[ 55 ] NOTIFIED READ MESSAGE") try: if op.param1 in read['readPoint']: if op.param2 in read['readMember'][op.param1]: pass else: read['readMember'][op.param1] += op.param2 read['ROM'][op.param1][op.param2] = op.param2 else: pass except Exception as error: logError(error) traceback.print_tb(error.__traceback__) except Exception as error: logError(error) traceback.print_tb(error.__traceback__) while True: try: delete_log() ops = puyPoll.singleTrace(count=50) if ops is not None: for op in ops: puyBot(op) puyPoll.setRevision(op.revision) except Exception as error: logError(error) def atend(): print("Saving") with open("Log_data.json","w",encoding='utf8') as f: json.dump(msg_dict, f, ensure_ascii=False, indent=4,separators=(',', ': ')) print("BYE") atexit.register(atend)
fddfe75c56493ddf4fd91be6057513549492f0b6
[ "Markdown", "Python" ]
4
Markdown
Kaneki711/haa
d8e838357b38a49b9d3deda82681fa71afeac657
e36167a410079caa5b840d98f5f07651ed8146c6
refs/heads/master
<file_sep>""" Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. """ class Solution: def searchInsert(self, nums: list, target: int) -> int: if target > nums[-1]: return len(nums) if target <= nums[0]: return 0 low_pointer = 0 high_pointer = len(nums) - 1 while high_pointer - low_pointer > 1: middle_point = (low_pointer + high_pointer) // 2 middle_value = nums[middle_point] if target == middle_value: return middle_point elif target < middle_value: high_pointer = middle_point else: low_pointer = middle_point return high_pointer <file_sep>def partition(arr: list, low: int, high: int) -> int: divider = low - 1 pivot = high for search in range(low, high): if arr[search] <= arr[pivot]: divider += 1 arr[divider], arr[search] = arr[search], arr[divider] divider += 1 arr[divider], arr[pivot] = arr[pivot], arr[divider] return divider def quick_sort(arr: list, low: int, high: int): if low < high: pivot = partition(arr, low, high) quick_sort(arr, low, pivot - 1) quick_sort(arr, pivot + 1, high) return a = [1, 34, 23, 1445, 4, 12, 33, -11, 3, 11, 555, 1000, -1212] quick_sort(a, 0, len(a) - 1) print(a) <file_sep>""" You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note: Given n will be a positive integer. """ class Solution: def climbStairs(self, n: int) -> int: memo = [0, 1, 2] if n < 3: return memo[n] for i in range(3, n + 1): memo.append(memo[i - 1] + memo[i - 2]) return memo[n] <file_sep>""" Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children. """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def minDepth(self, root: TreeNode) -> int: if not root: return 0 level = 1 queue_list = [root] while len(queue_list) != 0: new_queue_list = [] for item in queue_list: if not item.left and not item.right: return level if item.left: new_queue_list.append(item.left) if item.right: new_queue_list.append(item.right) level += 1 queue_list = new_queue_list <file_sep>""" Given a non-empty, singly linked list with head node head, return a middle node of linked list. If there are two middle nodes, return the second middle node. """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def middleNode(self, head: ListNode) -> ListNode: slow_pointer = head fast_pointer = head while fast_pointer.next is not None: slow_pointer = slow_pointer.next fast_pointer = fast_pointer.next.next if fast_pointer is None: return slow_pointer return slow_pointer node_list = [] for i in range(6): node_list.append(ListNode(i + 1)) for i in range(6): if i == 5: node_list[i].next = None else: node_list[i].next = node_list[i + 1] s = Solution() result = s.middleNode(node_list[0]) print(result.val) <file_sep>""" Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. """ class Solution: def trap(self, height: list) -> int: max_left = 0 max_right = 0 left = 0 right = len(height) - 1 water = 0 while left < right: if height[left] < height[right]: max_left = max(height[left], max_left) water += max_left - height[left] left += 1 else: max_right = max(height[right], max_right) water += max_right - height[right] right -= 1 return water a = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] s = Solution() print(s.trap(a)) <file_sep>""" You're now a baseball game point recorder. Given a list of strings, each string can be one of the 4 following types: Integer (one round's score): Directly represents the number of points you get in this round. "+" (one round's score): Represents that the points you get in this round are the sum of the last two valid round's points. "D" (one round's score): Represents that the points you get in this round are the doubled data of the last valid round's points. "C" (an operation, which isn't a round's score): Represents the last valid round's points you get were invalid and should be removed. Each round's operation is permanent and could have an impact on the round before and the round after. You need to return the sum of the points you could get in all the rounds. """ class Solution: def calPoints(self, ops: list) -> int: temp_stack = [] for item in ops: if item == '+': temp_stack.append(temp_stack[-2] + temp_stack[-1]) elif item == 'D': temp_stack.append(temp_stack[-1] * 2) elif item == 'C': temp_stack.pop() else: temp_stack.append(int(item)) return sum(temp_stack) <file_sep>""" Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: """ recursive """ def levelOrderBottomRecursive(self, root: TreeNode) -> list: if not root: return [] output_list = [] output_list_left = self.levelOrderBottomRecursive(root.left) output_list_right = self.levelOrderBottomRecursive(root.right) while len(output_list_left) != 0 or len(output_list_right) != 0: if len(output_list_left) == 0: output_list.insert(0, output_list_right.pop()) elif len(output_list_right) == 0: output_list.insert(0, output_list_left.pop()) else: output_list.insert(0, output_list_left.pop() + output_list_right.pop()) output_list.append([root.val]) return output_list """ iterative """ def levelOrderBottom(self, root: TreeNode) -> list: if not root: return [] output_list = [] temp_list1 = [root] temp_list2 = [] while len(temp_list1) != 0 or len(temp_list2) != 0: level_list = [] while len(temp_list1) != 0: current_node = temp_list1.pop(0) level_list.append(current_node.val) if current_node.left is not None: temp_list2.append(current_node.left) if current_node.right is not None: temp_list2.append(current_node.right) if len(level_list) != 0: output_list.insert(0, level_list) level_list = [] while len(temp_list2) != 0: current_node = temp_list2.pop(0) level_list.append(current_node.val) if current_node.left is not None: temp_list1.append(current_node.left) if current_node.right is not None: temp_list1.append(current_node.right) if len(level_list) != 0: output_list.insert(0, level_list) return output_list <file_sep>def LongestPalindromicSubstring(inputStream): def helper(input_string, left_pointer, right_pointer): while left_pointer >= 0 and right_pointer < len(input_string) and input_string[left_pointer] == input_string[right_pointer]: left_pointer -= 1 right_pointer += 1 return input_string[left_pointer + 1:right_pointer] longest_substring = '' for i in range(len(inputStream)): even_substring = helper(inputStream, i, i + 1) odd_substring = helper(inputStream, i, i) if len(longest_substring) < len(even_substring): longest_substring = even_substring if len(longest_substring) < len(odd_substring): longest_substring = odd_substring return longest_substring <file_sep>""" Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Each row must contain the digits 1-9 without repetition. Each column must contain the digits 1-9 without repetition. Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition. A partially filled sudoku which is valid. The Sudoku board could be partially filled, where empty cells are filled with the character '.'. """ class Solution: def isValidSudoku(self, board: list) -> bool: for item in board: if not self.checkUnit(item): return False for item in zip(*board): if not self.checkUnit(item): return False for row in [0, 3, 6]: for col in [0, 3, 6]: item = [] for i in range(3): for j in range(3): item.append(board[row + i][col + j]) if not self.checkUnit(item): return False return True def checkUnit(self, input_list): check_list = [] for item in input_list: if item is not '.': check_list.append(item) return len(check_list) == len(set(check_list)) def isValidSodukuFast(self, board: list) -> bool: hash_list = [] for row in range(len(board)): for col in range(len(board)): num_val = board[row][col] if num_val is '.': continue row_index = str(row) + '(' + str(num_val) + ')' col_index = '(' + str(num_val) + ')' + str(col) sec_index = str(row // 3) + '(' + str(num_val) + ')' + str(col // 3) if row_index in hash_list or col_index in hash_list or sec_index in hash_list: return False else: hash_list.append(row_index) hash_list.append(col_index) hash_list.append(sec_index) return True <file_sep>""" This is a relatively easy question. But there are still two points need to be remembered. 1. enumerate(seq): returns the location and values. 2. In the dictionary in Python: the int and float can also be the key. """ class Solution: def twoSum(self, nums: list, target: int) -> list: hash_table = {} for i, num in enumerate(nums): if num in hash_table: return [hash_table[num], i] hash_table[target - num] = i <file_sep>""" Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. """ class Solution: def maxSubArray(self, nums: list) -> int: if not nums: return float("-inf") middle_point = len(nums) // 2 max_left = self.maxSubArray(nums[:middle_point]) max_right = self.maxSubArray(nums[middle_point + 1:]) left_max_cross = nums[middle_point] right_max_cross = nums[middle_point] left_sum = 0 right_sum = 0 for i in range(middle_point, -1, -1): left_sum += nums[i] if left_max_cross <= left_sum: left_max_cross = left_sum for i in range(middle_point, len(nums)): right_sum += nums[i] if right_max_cross <= right_sum: right_max_cross = right_sum max_cross = left_max_cross + right_max_cross - nums[middle_point] return max(max_left, max_cross, max_right) def maxSubArrayDP(self, nums: list) -> int: if not nums: return 0 max_current = 0 max_sum = nums[0] for item in nums: max_current = max(max_current + item, item) max_sum = max(max_sum, max_current) return max_sum def maxSubArrayDPEasyUnderstand(self, nums: list) -> int: if not nums: return 0 max_list = [nums[0]] for i in range(1, len(nums)): max_list.append(max(max_list[i - 1] + nums[i], nums[i])) return max(max_list) <file_sep>""" Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle. Note that the row index starts from 0. """ class Solution: def getRow(self, rowIndex: int) -> list: if rowIndex == 0: return [1] if rowIndex == 1: return [1, 1] res = self.getRow(rowIndex - 1) new_list = [1] for i in range(len(res) - 1): new_list.append(res[i] + res[i + 1]) new_list.append(1) return new_list <file_sep>""" Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if not l1 and not l2: return None elif not l1: return l2 elif not l2: return l1 if l1.val <= l2.val: root = l1 cur = l1 l1 = l1.next else: root = l2 cur = l2 l2 = l2.next while l1 and l2: if l1.val <= l2.val: cur.next = l1 cur = l1 l1 = l1.next else: cur.next = l2 cur = l2 l2 = l2.next if not l1: cur.next = l2 else: cur.next = l1 return root def mergeTwoListsRecursive(self, l1: ListNode, l2: ListNode) -> ListNode: if not l1: return l2 if not l2: return l1 while l1 and l2: if l1.val <= l2.val: l1.next = self.mergeTwoLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists(l1, l2.next) return l2 <file_sep>""" Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). """ class Solution: def maxProfit(self, prices: list) -> int: if len(prices) < 2: return 0 first_point = 0 second_point = 1 profit = 0 while second_point < len(prices): if prices[second_point] >= prices[first_point]: profit += prices[second_point] - prices[first_point] first_point += 1 second_point += 1 return profit <file_sep>""" Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. """ class Solution: def generate(self, numRows: int) -> list: if numRows == 0: return [] if numRows == 1: return [[1]] if numRows == 2: return [[1], [1, 1]] res = self.generate(numRows - 1) last_list = res[-1] new_list = [1] for i in range(len(last_list) - 1): new_list.append(last_list[i] + last_list[i + 1]) new_list.append(1) res.append(new_list) return res <file_sep>""" Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. """ class Solution: def isValid(self, s: str) -> bool: if len(s) == 0: return True stack_list = [] for item in s: if item in ['(', '[', '{']: stack_list.append(item) else: if len(stack_list) == 0: return False out_stack = stack_list.pop() if (item == ')' and out_stack == '(') or (item == '}' and out_stack == '{') or (item == ']' and out_stack == '['): continue else: return False if len(stack_list) == 0: return True else: return False a = "]" s = Solution() b = s.isValid(a) print(b) <file_sep>""" This is a very wise method. We use the pre-order tree iteration. In this method, a very important characteristic of Python is included. Iteration. a = iter(list): return a iteration structure. b = next(a): return each item in a. """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Codec: def serialize1(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ def DFS(res, node): if node: res.append(str(node.val)) DFS(res, node.left) DFS(res, node.right) else: res.append('#') res = [] DFS(res, root) return ' '.join(res) def deserialize1(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ def DFS(): pointer = next(data_list) if pointer != '#': node = TreeNode(pointer) node.left = DFS() node.right = DFS() return node else: return None data_list = iter(data.split()) return DFS() def serialize2(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ if not root: return '#' return root.val, self.serialize2(root.left), self.serialize2(root.right) def deserialize2(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ if data[0] == '#': return None node = TreeNode(data[0]) node.left = self.deserialize2(data[1]) node.right = self.deserialize2(data[2]) return node # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.deserialize(codec.serialize(root)) <file_sep>class Solution: def __init__(self, num_string): self.string = num_string def decode_num(self): return self.helper(self.string) def helper(self, num): if not len(num): return [''] if len(num) == 1: return [self.num_to_alpha(int(num))] num1 = num[1:] list1 = [self.num_to_alpha(int(num[0])) + x for x in self.helper(num1)] num2 = num[2:] list2 = [self.num_to_alpha(int(num[0:2])) + x for x in self.helper(num2)] if int(num[0:2]) <= 26 else [] return list1 + list2 @staticmethod def num_to_alpha(num): return chr(num + 96) a = Solution('123') print(a.decode_num())<file_sep>""" Given a 32-bit signed integer, reverse digits of an integer. """ class Solution: def reverse(self, x: int) -> int: if x < 0: result = - int(str(x)[:0:-1]) else: result = int(str(x)[::-1]) if 2**31 > result >= - 2**31: return result else: return 0 <file_sep>""" Given a binary tree, determine if it is height-balanced. """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isBalanced(self, root: TreeNode) -> bool: if not root: return True return abs(self.calculateLevel(root.left) - self.calculateLevel(root.right)) <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right) def calculateLevel(self, tree_node: TreeNode) -> int: if not tree_node: return 0 level_num = [] level = 0 queue_list = [tree_node] while len(queue_list) != 0: level += 1 new_queue_list = [] for item in queue_list: if not item.left or not item.right: level_num.append(level) if item.left: new_queue_list.append(item.left) if item.right: new_queue_list.append(item.right) queue_list = new_queue_list return max(level_num) <file_sep>""" This question is using DFS to iterate the tree. By adding a variable called level to judge if we run from left to right or right to left. """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def zigzagLevelOrder(self, root: TreeNode) -> list: res = [] level = 0 self.DFS(res, level, root) return res def DFS(self, res, level, node): if not node: return if len(res) < level + 1: res.append([]) if level % 2 == 0: res[level].append(node.val) else: res[level].insert(0, node.val) level += 1 self.DFS(res, level, node.left) self.DFS(res, level, node.right) <file_sep>""" Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. Note: You may not slant the container and n is at least 2. """ class Solution: def maxArea(self, height: list) -> int: length = len(height) - 1 left_pointer = 0 right_pointer = length max_area = length * min(height[left_pointer], height[right_pointer]) while right_pointer > left_pointer: if height[left_pointer] > height[right_pointer]: right_pointer -= 1 else: left_pointer += 1 max_area = max(max_area, (right_pointer - left_pointer) * min(height[left_pointer], height[right_pointer])) return max_area <file_sep>""" Given a positive integer, return its corresponding column title as appear in an Excel sheet. """ class Solution: def convertToTitle(self, n: int) -> str: res = [] while n > 0: if n == 26: res.append('Z') break res.append(chr(n % 26 + 64)) n = n // 26 return ''.join(res[::-1]) <file_sep>""" This question is really confusing. From the questions, we don't need to consider the identifier order during the sorting. BUT, the test case need us to order the identifier when the contents are exactly the same. This is why I add a alpha.sort(). """ class Solution: def reorderLogFiles(self, logs: list) -> list: alpha = [] digit = [] for item in logs: item_list = item.split() if item_list[1].isdigit(): digit.append(item) else: alpha.append(item.split()) alpha.sort() alpha = [' '.join(x) for x in sorted(alpha, key=lambda input: input[1:])] return alpha + digit <file_sep>""" Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. """ class Solution: def merge(self, nums1: list, m: int, nums2: list, n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ point1_t = n + m - 1 point1_h = m - 1 point2_h = n - 1 while point2_h >= 0: if point1_h >= 0: if nums2[point2_h] >= nums1[point1_h]: nums1[point1_t] = nums2[point2_h] point2_h -= 1 else: nums1[point1_t] = nums1[point1_h] point1_h -= 1 point1_t -= 1 else: nums1[point1_t] = nums2[point2_h] point2_h -= 1 point1_t -= 1 <file_sep>""" RECURSIVE METHOD!!!! """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if not l1: return l2 if not l2: return l1 if l1 and l2: head = l1 if l1.val < l2.val else l2 if head == l1: head.next = self.mergeTwoLists(l1.next, l2) else: head.next = self.mergeTwoLists(l1, l2.next) return head else: return None <file_sep>""" 1. This question broadens my horizon, I haven't known that the type of key in the dictionary can be a CLASS! 2. collections.defaultdict() can accept: - a type: such as int, list... - a function without parameters: such as lambda: x ** 2 """ from collections import defaultdict # Definition for a Node. class Node: def __init__(self, val, next, random): self.val = val self.next = next self.random = random class Solution: def copyRandomList(self, head: 'Node') -> 'Node': new_list_dict = defaultdict(lambda: Node(0, None, None)) new_list_dict[None] = None pointer = head while pointer: new_list_dict[pointer].val = pointer.val new_list_dict[pointer].next = new_list_dict[pointer.next] new_list_dict[pointer].random = new_list_dict[pointer.random] pointer = pointer.next return new_list_dict[head]<file_sep>""" There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume nums1 and nums2 cannot be both empty. """ class Solution: def findMedianSortedArrays(self, nums1: list, nums2: list) -> float: if len(nums1) >= len(nums2): nums1, nums2 = nums2, nums1 n = len(nums1) m = len(nums2) total = (n + m + 1) // 2 left_start = 0 left_end = n while left_end >= left_start: n_p = (left_start + left_end) // 2 m_p = total - n_p n_left = float("-inf") if n_p == 0 else nums1[n_p - 1] n_right = float("inf") if n_p == n else nums1[n_p] m_left = float("-inf") if m_p == 0 else nums2[m_p - 1] m_right = float("inf") if m_p == m else nums2[m_p] if n_left > m_right: left_end = n_p - 1 if n_right < m_left: left_start = n_p + 1 if n_left <= m_right and n_right >= m_left: if (n + m) % 2 == 0: return (max(n_left, m_left) + min(n_right, m_right)) / 2 else: return max(n_left, m_left) <file_sep>""" Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. """ class Solution: def strStr(self, haystack: str, needle: str) -> int: if needle == '': return 0 elif needle not in haystack: return -1 else: num = 0 while needle in haystack: haystack = haystack[:-1] num += 1 return len(haystack) - len(needle) + 1 haystack = "sfasdfasdf" needle = "asd" s = Solution() b = s.strStr(haystack, needle) print(b) <file_sep>class Solution: def convert(self, s: str, numRows: int) -> str: if not s: return '' if numRows == 1 or len(s) <= numRows: return s res = '' total = 2 * (numRows - 1) for i in range(numRows): first_round = total - 2 * i second_round = 2 * i j = i sig = True while j < len(s): if first_round * second_round: res += s[j] j = j + first_round if sig else j + second_round sig = not sig else: res += s[j] j = j + first_round + second_round return res<file_sep>""" Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSymmetric(self, root: TreeNode) -> bool: if root is None: return True else: return self.symmeticHelp(root.left, root.right) def symmeticHelp(self, left, right): if left is None and right is None: return True elif left is None or right is None or left.val != right.val: return False else: return self.symmeticHelp(left.left, right.right) and self.symmeticHelp(left.right, right.left) <file_sep>""" Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. """ import heapq as hq class Solution: def findKthLargest(self, nums: list, k: int) -> int: nums.sort() return nums[-k] def findKthLargestHeap(self, nums: list, k: int) -> int: nums = [-num for num in nums] hq.heapify(nums) res = 0 for _ in range(k): res = hq.heappop(nums) return -res def findKthLargestQuick(self, nums: list, k: int) -> int: low = 0 high = len(nums) - 1 res = self.quickFind(nums, low, high, k) return res def quickFind(self, nums: list, low: int, high: int, k: int) -> int: pivot = self.partition(nums, low, high) if pivot == k - 1: res = nums[pivot] elif pivot < k - 1: res = self.quickFind(nums, pivot + 1, high, k) else: res = self.quickFind(nums, low, pivot - 1, k) return res def partition(self, arr: list, low: int, high: int) -> int: divider = low - 1 pivot = high for search in range(low, high): if arr[search] >= arr[pivot]: divider += 1 arr[divider], arr[search] = arr[search], arr[divider] divider += 1 arr[divider], arr[pivot] = arr[pivot], arr[divider] return divider <file_sep>""" This question is very very tricky. We can brute force search. But we will meet the problem of TLE. So we can find that the frequency of the cells - 14. """ class Solution: def prisonAfterNDays(self, cells: list, N: int) -> list: if N == 0: return cells days = 1 res = [] time_limit = 14 if not N % 14 else N % 14 while days <= time_limit: res.append(0) for row in range(1, len(cells) - 1): res.append(1 if cells[row - 1] == cells[row + 1] else 0) res.append(0) cells = res res = [] days += 1 return cells <file_sep>""" Given a collection of numbers that might contain duplicates, return all possible unique permutations. """ class Solution: def permuteUnique(self, nums: list) -> list: nums.sort() res = [] self.helper(nums, res, []) return res def helper(self, nums, res, path): if not nums: res.append(path) return for i in range(len(nums)): if i > 0 and nums[i] == nums[i - 1]: continue else: self.helper(nums[:i] + nums[i + 1:], res, path + [nums[i]]) <file_sep>""" Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. """ class Solution: def longestPalindrome(self, s: str) -> str: def helper(str, l, r): while l >= 0 and r < len(str) and str[l] == str[r]: l -= 1 r += 1 return str[l + 1: r] res = '' for i in range(len(s)): even_s = helper(s, i, i + 1) odd_s = helper(s, i, i) if len(res) < len(even_s): res = even_s if len(res) < len(odd_s): res = odd_s return res <file_sep>""" You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: value_l1 = 0 num_l1 = 0 value_l2 = 0 num_l2 = 0 move_l1 = l1 move_l2 = l2 while move_l1: value_l1 += move_l1.val * (10 ** num_l1) num_l1 += 1 move_l1 = move_l1.next while move_l2: value_l2 += move_l2.val * (10 ** num_l2) num_l2 += 1 move_l2 = move_l2.next sum_result = str(value_l1 + value_l2)[::-1] head_node = ListNode(int(sum_result[0])) move_node = head_node for i in range(1, len(sum_result)): move_node.next = ListNode(int(sum_result[i])) move_node = move_node.next return head_node <file_sep>""" 1. if s == None and t == None, return True 2. if s == None or t == None, return False 3. if s != None and t != None, check if s == t 4. if s != t, check s.left == t or s.right == t. """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSubtree(self, s: TreeNode, t: TreeNode) -> bool: if not s and not t: return True if not s or not t: return False if s.val == t.val and self.isSametree(s, t): return True return self.isSubtree(s.left, t) or self.isSubtree(s.right, t) def isSametree(self, s, t): if not s and not t: return True elif not s or not t: return False return s.val == t.val and self.isSametree(s.left, t.left) and self.isSametree(s.right, t.right) <file_sep>""" This question is very hard for me. There are two ways to complete this question. 1. Dynamic programming 2. Center searching """ class Solution: def longestPalindromeDP(self, s: str) -> str: dp = [[False] * len(s) for _ in range(len(s))] start_lpd = 0 end_lpd = 0 for i in range(len(s)): start = i end = i while start >= 0: if start == end: dp[start][end] = True elif start + 1 == end: dp[start][end] = s[start] == s[end] else: dp[start][end] = dp[start + 1][end - 1] and (s[start] == s[end]) if dp[start][end] and (end - start + 1) > (end_lpd - start_lpd + 1): start_lpd = start end_lpd = end start = start - 1 return s[start_lpd:end_lpd + 1] def longestPalindrome(self, s: str) -> str: def helper(str, l, r): while l >= 0 and r < len(str) and str[l] == str[r]: l -= 1 r += 1 return str[l + 1: r] res = '' for i in range(len(s)): even_s = helper(s, i, i + 1) odd_s = helper(s, i, i) if len(res) < len(even_s): res = even_s if len(res) < len(odd_s): res = odd_s return res<file_sep>""" Given a string, find the length of the longest substring without repeating characters. """ class Solution: def lengthOfLongestSubstring(self, s: str) -> int: hashed = {} start = 0 max_length = 0 for i, item in enumerate(s): if item in hashed and hashed[item] >= start: start = hashed[item] + 1 else: max_length = max(max_length, i - start + 1) hashed[item] = i return max_length <file_sep>""" This question has two method. 1. This method is relatively tricky. We use collections.Counter. It can calculate the counter of each value automatically. The input of Counter is a list/dictionary/void. Using for loop will automatically return the most counted items. 2. The second method is using collections.defaultdict. """ from collections import Counter, defaultdict class Solution: def mostCommonWord(self, paragraph: str, banned: list) -> str: for punc in "!?',;.": paragraph = paragraph.replace(punc, ' ') counter_para = Counter(paragraph.lower().split()) for item, _ in counter_para.most_common(): if item not in banned: return item return '' def mostComonWord2(self, paragraph, banned): for punc in "!?',;.": paragraph = paragraph.replace(punc, ' ') dict = defaultdict(lambda: 0) max_count = 0 res = "" for item in paragraph.lower().split(): if item not in banned: dict[item] += 1 if dict[item] >= max_count: max_count = dict[item] res = item return res <file_sep>""" Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array. """ class Solution: def majorityElement(self, nums: list) -> int: maj = nums[0] count = 1 for item in nums[1:]: if item != maj and count == 0: maj = item count += 1 elif item == maj: count += 1 else: count -= 1 return maj <file_sep>""" Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The replacement must be in-place and use only constant extra memory. Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. """ class Solution: def nextPermutation(self, nums: list) -> None: """ Do not return anything, modify nums in-place instead. """ if len(nums) < 2: return pointer = len(nums) - 2 while pointer >= 0: if nums[pointer] >= nums[-1]: for j in range(pointer + 1, len(nums)): temp = nums[j] nums[j] = nums[j - 1] nums[j - 1] = temp else: for j in range(pointer + 1, len(nums)): if nums[j] > nums[pointer]: temp = nums[j] nums[j] = nums[pointer] nums[pointer] = temp return pointer -= 1 return <file_sep>""" Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. """ class Solution: def threeSumClosest(self, nums: list, target: int) -> int: nums.sort() res = nums[0] + nums[1] + nums[2] for i in range(len(nums) - 1): if i > 0 and nums[i] == nums[i - 1]: continue left_p = i + 1 right_p = len(nums) - 1 while right_p > left_p: if left_p > i + 1 and nums[left_p] == nums[left_p - 1]: left_p += 1 continue if right_p < len(nums) - 1 and nums[right_p] == nums[right_p + 1]: right_p -= 1 continue sum = nums[left_p] + nums[right_p] + nums[i] if sum == target: return target if sum < target: left_p += 1 if sum > target: right_p -= 1 if abs(sum - target) < abs(res - target): res = sum return res <file_sep>""" Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. """ class Solution: def multiply(self, num1: str, num2: str) -> str: res = 0 num1 = num1[::-1] num2 = num2[::-1] for i in range(len(num1)): temp = 0 for j in range(len(num2)): temp += num1[i] * num2[j] * 10 ** (i + j) res += temp return str(res) <file_sep>""" We divide this list into two group, group one is the small one, group two is the larger one. We use heapq to build the maximum heap for smaller one, and minimum heap for larger one. We need to make sure the larger one is equal to smaller one or 1 item longer than the smaller one. 1. the minimum heap is built directly by heappush. 2. the maximum heap is built by minus list by heappush """ import heapq class MedianFinder: def __init__(self): self.heaps = [], [] def addNum(self, num): small, large = self.heaps heapq.heappush(small, -heapq.heappushpop(large, num)) if len(large) < len(small): heapq.heappush(large, -heapq.heappop(small)) def findMedian(self): small, large = self.heaps if len(large) > len(small): return float(large[0]) return (large[0] - small[0]) / 2.0 # Your MedianFinder object will be instantiated and called as such: # obj = MedianFinder() # obj.addNum(num) # param_2 = obj.findMedian() <file_sep>""" Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 IV 4 IX 9 XL 40 XC 90 CD 400 CM 900 """ class Solution: def romanToInt(self, s: str) -> int: s2i = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000 } exp = ['I', 'X', 'C'] num = 0 for i in range(len(s) - 1): if s[i] not in exp: num += s2i[s[i]] elif s[i] == 'I' and s[i + 1] not in ['V', 'X']: num += s2i[s[i]] elif s[i] == 'X' and s[i + 1] not in ['L', 'C']: num += s2i[s[i]] elif s[i] == 'C' and s[i + 1] not in ['D', 'M']: num += s2i[s[i]] else: num -= s2i[s[i]] num += s2i[s[-1]] return num <file_sep>""" You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Note: You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. """ class Solution: def rotate(self, matrix: list) -> None: """ Do not return anything, modify matrix in-place instead. """ length = len(matrix) for row in range(length // 2): for col in range(row, length - row - 1): first = True row_pointer = row col_pointer = col cur = matrix[row_pointer][col_pointer] while not (row_pointer == row and col_pointer == col) or first: first = False row_pointer, col_pointer = col_pointer, length - row_pointer - 1 temp = matrix[row_pointer][col_pointer] matrix[row_pointer][col_pointer] = cur cur = temp return <file_sep>""" Given a sorted linked list, delete all duplicates such that each element appear only once. """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: if not head: return None a_list = [head.val] a_node = head while a_node: b_node = a_node.next while b_node and b_node.val in a_list: b_node = b_node.next a_list.append(b_node and b_node.val) a_node.next = b_node a_node = b_node return head <file_sep>""" You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2. The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number. """ class Solution: def nextGreaterElement(self, nums1: list, nums2: list) -> list: target_dic = {} temp_stack = [] for item in nums2: while temp_stack and item > temp_stack[-1]: target_dic[temp_stack.pop()] = item temp_stack.append(item) return [target_dic.get(j) for j in nums1] <file_sep>""" Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. The order of elements can be changed. It doesn't matter what you leave beyond the new length. """ class Solution: def removeElement(self, nums: list, val: int) -> int: num_total = len(nums) pointer_num = 0 pointer = 0 while pointer_num < len(nums): if nums[pointer] != val: pointer += 1 else: nums.append(nums.pop(pointer)) num_total -= 1 pointer_num += 1 return num_total <file_sep>""" Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. """ class Solution: def fourSum(self, nums: list, target: int) -> list: nums.sort() res = [] for i in range(len(nums) - 2): if i > 0 and nums[i] == nums[i - 1]: continue for j in range(i + 1, len(nums) - 1): if j > i + 1 and nums[j] == nums[j - 1]: continue p_1 = j + 1 p_2 = len(nums) - 1 while p_2 > p_1: sum = nums[i] + nums[j] + nums[p_1] + nums[p_2] if p_1 > j + 1 and nums[p_1] == nums[p_1 - 1]: p_1 += 1 continue if p_2 < len(nums) - 1 and nums[p_2] == nums[p_2 + 1]: p_2 -= 1 continue if sum < target: p_1 += 1 elif sum > target: p_2 -= 1 else: res.append([nums[i], nums[j], nums[p_1], nums[p_2]]) p_1 += 1 p_2 -= 1 return res <file_sep>""" Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. """ class Solution: def twoSum(self, nums: list, target: int) -> list: hashed = {} for i, item in enumerate(nums): if item in hashed: return [hashed[item], i] hashed[target - item] = i <file_sep>[TOC] ## Amazon ### [937] Reorder Data In Log Files 前提:字符串数组,有两种字符串: - 开头第一个词是标签,后面只含有单词用空格连接。 - 开头第一个词是标签,后面只含有数字用空格连接。 目的: 1. 所有数字按照原顺序放在最后。 2. 单词按照字母表顺序排列,只有在两个单词一样的时候才考虑标签。 思路: 1. 首先确定space complexity是O(n), 因为要建立保存数字和单词的list。 2. 然后遍历一下input数组,用split()把字符串转成数组,逐个判断第二个是不是数字, 是的话,就append到数字list里,不是的话就append到单词list里,注意放到单词list里的应该是 split之后的数组。其中判断是不是数字可以用isdigit()。 3. 随后,首先sort()一下单词数组,因为要考虑两个单词一样的情况。 4. 最后用list推导式来重新排列,用sorted()把key设置为匿名lambda函数,只包括排除标签之外的元素。 5. 最后返回alpha和digit连接之后数组。 复杂度: - time complexity: O(nlogn) - space complexity: O(n) --- ### [1192] Critical Connections in a Network 前提:一个无向图,vertex个数是n,input如下: - n:vertex的个数 - list:无向图的所有edge。list的list。 目的:找出所有的critical connection。去掉这个connection,连通分量会增加。 思路: 1. 首先,建立6个: - dfn: 每个vertex的时间戳,初始化为-1。 - low:每个vertex和它的子树不通过他parent能到达的最小点,初始化为-1。 - parent:每个vertex的父节点。 - graph:list的dictionary,使用了collections.defaultdic(list),记录了每个节点和它连接的节点。存储图。 - self.time:记录时间戳。 - res:输出。 2. 然后写Tarjan函数: - 给input节点的dfn和low赋值为self.time。 - self.time增加1. - 遍历和u(input)连接的节点v。 - 如果子节点v的dfn为-1,也就是没有遍历过。给parent[v]赋值为u。然后递归执行Tarjan(v). 然后,更新low[u] = min(low[u],low[v])。然后判断如果low[v]比dfn[u]大的话,就代表着[u,v]为critical cennection。append到res里。 - 如果子节点被遍历过,但是parent[u] != v,再更新一下low[u] = min(low[u],dfn[v])。 3. 最后对n个未遍历过的节点逐个执行Tarjan,如果dfn[i] != -1,则跳过。 4. 最后返回res。 --- ### [1] Two Sum 前提:一个数字的list,一个target数字。 目的:返回一个list,包含两个index,使得这两个index对应的input的和等于target。 思路: 1. 循环嵌套的time complexity是O(n^2),所以使用hash table,time complexity变为O(n)。 2. 创建一个dictionary。 3. 遍历list,每次给hashtable加入key为target - list[i],而value为i。 4. 这样子在遍历的过程中,如果list[i]在hashtalbe中有值,则返回[hashtable的value, i]。 复杂度: - space complexity: O(n) - time complexity: O(n) --- ### [200] Number of Islands 前提:2D数组,1代表陆地,0代表海水,只要是水平和垂直没有陆地相连,就是一个独立的岛屿。 目的:返回一个数字,代表2D地图的岛屿数量。 思路: 1. 遍历地图上所有的点,如果是1,岛屿个数就加一。 2. DFS来清洗一个岛屿,分别对四个方向递归的执行DFS,把1换成0. 3. DFS的终止条件是超出边界,或者当前的点不是陆地。所以每次判断完之后要把当前陆地换成海水,然后四个方向递归。 --- ### [138] Copy List with Random Pointer 前提:一个单向链表,每一个node会有一个随机指针,指向任意node或者None。 目的:返回一个deep copy的链表。 思路: - 深度拷贝使用一个dictionary,key和value都是node,key对应原来的node,value对应新的node。 - 这题也使用了collections.defaultdict(),默认的不是一个type,而是lambda返回一个node。 - 注意1:记得dictionary[None] = None - 注意2:记得新node的next和random要连接旧node的next和random对应的新node。 --- ### [5] Longest Palindromic Substring 前提:一个字符串。 目的:返回最长的回文。 思路: 1. 就是用中心扩散法,这个容易理解。 2. 首先写一个辅助函数,输入一个string,左指针,右指针。返回以指针为中心的回文。 3. 然后遍历一下输入的string,分别考虑偶数和奇数回文的情况,分别返回比较大小。 4. 奇数就是helper(string,i,i)。 5. 偶数就是helper(string,i,i+1)。 --- ### [973] K Closest Points to Origin 前提:输入一个(x,y)坐标的list和一个K值。 目的:返回K个距离(0, 0)最近的坐标list。 思路: 1. 最简单的就是用list推导式,配合上sorted(),里面的key用一个lambda函数。 2. 然后返回前K个元素的list。 --- ### [146] LRU Cache 前提:设计一个数据结构,满足一下: - get: 获取key对应的正数值,如果没有,返回-1 - put: 将key和value存储到数据库中,但是,不能超过它的容量,如果超过容量,则最久没有使用的删除,添加新的。 - get和put都属于一种使用,会把相关的元素自动放在最近使用过的。 目的:实现这个数据结构,构造__init__,put和get函数。 思路: 1. 使用collections.OrderedDict。 2. 在get时,为了使操作触发最近使用,先pop,再put。如果不在,就返回-1 3. 在put时,首先判断是不是存在了,因为不涉及增加新的值,不用考虑容量的问题。 4. 然后如果put的是新的值,在判断有没有超过容量,如果超过了,用popitem(last=False)去除第一个元素,再加入新的。如果没超过,则直接加入,同时让仓库容量+1。 重点: - collections.OrderedDict() - pop(key) 删除并且返回key对应的value。 - popitem(last=False) 删除并且返回最早进入的值。 --- ### [819] Most Common Word 前提:输入一个字符串,同时给定一个banned字符串list。返回除了banned里之外,最长出现在input字符串里的单词。 思路: 1. 暴力搜索吧,首先用replace(old, new)去掉标点。 2. 然后遍历一下 - 用lower()全部小写 - 用split()转换成list之后 3. 创建一个dictionary,记录每个不在banned里单词出现的频率。同时记录最长的长度,和最长的单词,每次遍历出来的item都和最长的长度比较,如果长,更新最长的长度和最长的单词。 4. 返回出现次数最多的。 重点: - 在定义dictionary的时候,注意使用defaultdict(lambda:0),这样子后来就可以直接用+=来增加单词出现的数量了。 --- ### [957] Prison Cells After N Days 前提:一排牢房,如果前一天左右两个监狱都有人或者都没人,则第二天,这个监狱有人,如果左右两边一个有人一个没人,则第二天,这个监狱没人。 目的:给定一个初始状态,再给定一个天数,返回那天的状态。 难点:天数可以超级多,如果常规做法,写一个while循环,必然TLE。 思路: 1. 对于一般问题,我们写一个while函数,按照规律逐天的计算每天的状态。 2. 但是这么做不行,因为有时候天数太多,超时了。 3. 所以找规律,14天一个周期,问题解决。 重点: 1. 周期为14,但是当N为14时,不能直接N = 0,因为0天的时候是不对的,当N除以14mode为0时, N应该为14。所以time_limit = 14 if not N % 14 else N % 14。 2. 我们做while循环的时候因为最左右两边的永远是0,所以可以在for外面直接给这两个赋值。 --- ### [572] Subtree of Another Tree 前提:给定两个树,判断s树是不是t树的子树。 思路: 1. 写一个辅助函数,用来traverse一遍树,然后返回一个遍历树的字符串。(先序遍历) 2. 然后分别对两个树执行这个函数,如果其中一个in另外一个,则说明他是子树。 3. 有一点需要注意,返回字符串前要加一个特殊符号,为了避免{12}和{2}这种情况。 --- ### [42] Trapping Rain Water 前提:雨水收集问题,一个list,每个item代表一个宽度为1的挡板,问这个list能接多少雨水。 思路: 1. 使用two-pointer方法来求解。 2. 首先定义左右最大值,全部初始化为0。然后定义左右指针。初始化雨水值为0。 3. 然后开始向中间移动指针,while循环为left<right。 4. 然后看左右指针的值,每次都处理数值小的那一侧指针。 5. 然后先更新这一侧的最大值,然后雨水的量为最大值和当前指针的差,然后指针移动。 6. 最后返回雨水值。 重点: - 处理左右两侧相对小的值是因为木桶原理。 - 然后在用更新后的max和当前指针做差,就是雨水值。 --- ### [21] Merge Two Sorted Lists 前提:两个排好序的链表,把他们合并为一个新的排序链表。 思路: 1. 直接用recrusive做,首先判断其中是否有None,如果有,返回非空的那个。 2. 然后比较两个链表第一个值,返回小的那个。其中返回之前,把小的那个的next和大的那个recursive一下,连接到小的那个的next。 --- ### [1000] Minimum Cost to Merge Stones 前提:一个list代表一横行的石堆,每个数字代表石堆的石头数量。同时给定一个K值。 目的:一次合并K个连读的石堆,问把这个横行的石堆合并为一堆,最小花费多少(花费是K个石堆包含石头的个数和)。如果不能合并,返回-1。 思路: 1. 这道题非常难,我们把过程分为两部分。 2. 在之前首先判断一下是否可以被k合并为1堆,如果(n - 1)%(K - 1)等于0,则可以。不然就返回-1。 3. 首先,先算出stone[i]和之前所有石头重量的和。定义一个数组prefix[n + 1],其中n是stone数组的长度,prefix[i]就是stone[i - 1]包含它和之前所有的和。这个在后面有用。 4. 然后开始写dp的核心,一个recursive函数。输入参数只有两个值,一个是i,一个是j,分别是stone的起点和终点。返回的是最小代价。 5. 第一步,先判断j - i + 1是否大于K,如果不是,直接返回0。 6. 第二部,把i~j不断分成2份,recursive的计算每小份儿的返回值,然后不断的寻找最小的情况。循环的步长是k-1。 7. 第三步,判断一下i~j是否可以被K正好合并,也就是看看(j - i)%(k - 1)是否为0,如果可以直接合并,返回值需要加上i~j的总石头数,也就是prefix[j + 1] - prefix[i]。 8. 最后,直接返回dp(0, n - 1)就可以了。 --- ### [297] Serialize and Deserialize Binary Tree 前提:把一个树字符化,然后在解字符化。 思路: 1. 这道题思路就是recursive,无论是字符化还是解字符化,都只要处理当前的node.val,然后recursive的处理左右子树。有一点需要注意的是对None的处理。None和“#”对应是个不错的选择。 2. 巧妙利用python中function的返回值如果是多个值用逗号连接,则返回一个tuple。 3. 这里我们选择先序遍历树的方式。 --- ### [103] Binary Tree Zigzag Level Order Traversal 前提:给一个树,按照偶数排从左到右,奇数排从右到左,输出一个list的list。 思路: 1. 首先明确这个题用DFS来做,当是偶数排的时候,node.val用append添加到最后,如果是奇数排,用insert(0, node.val)添加到开头。 2. 因为要记录深度,所以这个函数不返回数组,而是把result和level通过参数传递进去,直接在函数中修改。 3. 但是记住每当level加1的时候,记得给result添加一个新的list进去,放置新level的元素。(具体操作就是判断深度是不是比result数组里的元素大,当深度为0,数组的长度应该为1。如果深度增加了,数组长度应该也增加。) --- ### [295] Find Median from Data Stream 前提:设计一个数据结构,有两个基本操作,第一就是放进去一个整数,第二个就是返回当前数据库里的中间值。其中如果是奇数个,返回中间那个,如果是偶数个,返回中间两个的平均值。 思路: 1. 利用python的heapq最小堆的这个特性,建立两个堆,一个small,一个large。确保large的数量和small的数量相等或者比它大1。(相等时是偶数个,大于1时是奇数个) 2. heapq只能建立最小堆,那怎么弄出来一个small一个large呢?large就是正常建立一个heap,每次pop都是最小的值,但是我们要得到small里最大的值该怎么办?把small里所有数都取负,然后放进去,那么最小的pop值就是最大的相反数了。 3. 然后在add时,每次都往small里加,放入的是large的pushpop值,然后再平衡一下small和large的个数。 4. 在取中间值的时候,判断一下small和large的个数,然后返回相应的值。用large[0]来取最小值,- small[0]取最大值。 --- ### [2] Add Two Numbers 前提:两个链表,分别代表两个数,链表从低位到高位,也就是把这个数反过来存到链表里。 目的:设计一个算法,求出这两个链表代表数的值,然后返回一个链表。也是反过来存储的。 注意:两个数没有任何前置0,除非它本身就是0。 思路: 1. 这题因为输入和输出都是逆序的,也就是从低位开始,所以问题变得简单了,一次遍历就可以搞定。 2. 添加一个carry,初始为0,每次遍历的时候都加上两个链表的值,然后carry % 10为输出的node.val,carry自己更新为carry // 10。 3. 直到while条件l1, l2, carry都为None时,才停止。 4. 记得返回的是链表的head。 --- ### [866] Prime Palindrome 前提:给一个正整数,返回不小于它的最小质数回文。 思路: 1. 首先写一个判断是不是质数的方程,先判断是不是小于2或者被2整除,因为质数必须大于1,所以质数从2开始算起,任何这两种条件的情况,只要判断这个input是不是等于2就可以了。如果通过了,就开始常规的质数辨认了,从3开始到input**0.5+1,间隔2来查找,只要是有可以整除的,就不是质数。否则就是。 2. 然后开始判断是不是回文,有一点,如果回文的个数是偶数,则它一定被11整除,所以除了11,只考虑个数是奇数的回文。 3. 加入判断语句如果input大于等于8小于等于11,则返回11。 4. 然后判断是不是回文,因为一共最大是10**8,不可能是偶数,那么只能是10的7次方,然后我们取前5位,也就是10的5次方为最大值,初始值是10的input位数整除2。在循环判断里,首先组成回文的整数,然后判断是不是prime并且大于等于input,返回结果就行了。 --- ### [127] Word Ladder 前提:给定两个单词,和一个字典list,从list找出最短的使startword变为endword的路径,返回变换的次数。 - 变换只能一次变换一个字母。 - 如果没有符合的变换,返回0。包括endword不在list里和没有路径可以使startword到endword。 思路: 1. 首先写一个函数,用来算出一个set(front)和set(wordlist)可能衍生的子树。首先对front里面的每一个单词,单词里的每一位,用每一个字母(26个)代替,然后组成一个新的set,在求一下这个set和wordlist的交集。返回。返回的就是front里的每个单词有效的转换。 2. 然后开始bi-BFS,首先建立front和end两个set,里面放的是beginWord和endWord,然后把worList也转换成set。(因为速度快),然后判断一下endWord是否在wordList里,不在就直接返回0。 3. 开始常规的BFS,while判断front是否为空。 4. 如果front和end有交集(&),则返回depth。 5. 然后depth加一,从wordlist里减去front,再用1的方程更新front。 6. 判断一下front和end的长度,永远让长度短的成为front。(减少branching factor) 7. 如果不行,就返回0。 --- ### [23] Merge k Sorted Lists 前提:输入一个链表list,每个链表都是排序过的。要求输入一个把所有链表排序的node。 思路: 1. 这题用python2来做。 2. 首先用list推导式来建造一个tuple的list,第一个值是node.val,第二个是node。 3. 然后用heap.heapify来把这个list转换成一最小堆。 4. 然后dummy = pointer = ListNode(0) 5. 然后进行while循环。(因为每个元素都参与了循环,所以时间是n*k。 6. 每次用heap[0]去除val最小的一个,然后进行一些判断,如果取出的node.next是空的,则直接heappop这个最小堆。因为这个链表已经遍历完了。如果不是空,则用(node.next.val, node.next)替换。(因为每次进行heap操作时都是K个元素,所以时间是logK) 7. 最后给pointer新建一个ListNode(ndoe.val),pointer = pointer.next 8. 最后返回dummy.next。 --- ### [763] Partition Labels 前提:一个只包含字母的字符串,要求分割字符串,每个字母只能出现在一个分割部分里。 思路: 1. 首先,遍历一次字符串,用dictionary记录一下每个字母最后一次出现的index。 2. 然后定义两个指针,一个左指针,一个右指针,一个最大index值。右指针不停的走,写一个while循环,直到右指针到达最后。 3. 每次右指针走到一个字母,更新一下目前遍历过的单词的最大index。当最大index等于右指针的时候,所以右指针和左指针之间所有的字符都只在这里面出现。将这个区间放入结果中,然后更新右指针,和最大index。 --- ### [240] Search a 2D Matrix II 前提:一个n*m的数组,所有row和col都是按照升序排列,查询一个数字是否在这个数组里。 思路: 1. 首先从矩阵右上角开始搜索,开始判断,如果目标比这个数小,证明这个col都不可能了,而目标比这个数大,证明row都不可能了。 2. 写一个while函数,遍历一下就可以了。 重点: - time complexity: O(n + m). - 从右上角蛇形循环。 --- ### [139] Word Break 前提:给了一个单词和一个单词list,问这个单词是否可以分割成几个小单词,并且小单词都在list里。 思路: 1. 这题用DP来做,因为单词的长度是n,那么我们建立一个dp长度为n+1的list。并且设置dp[0]=True,其他的都为False。 2. 具体说说dp的含义,dp[i]就代表单词[0:i]是否符合条件。 3. 然后为了dp进行一次for循环,从1到n。 4. 然后嵌套一个子循环,从0一直到i-1。 5. 如果dp[j]为true同时单词[j:i]也在list里,说明dp[i]也是true,并且break。 6. 最后直接返回dp最后一个值。 --- ### [472] Concatenated Words 前提:给了一个list的字符串,返回所有由至少两个短单词组成的字符串的list。 思路: 1. 这道题本来是结合WordBreak来做,但是失败了。简单说一下方法,因为我们用DP可以算出某一个单词是不是一个list组成的,也就是上面那个。所以我们首先按照字符串长度把list排列一下。遍历i,每次都查看i单词是不是由前面的单词组组合成的。也就是wordbreak外面再来一个循环,但是超时了。 2. 所以我们用dfs来做。 3. 首先我们来写DFS函数,把这个某个单词input进去,循环处理,把单词分为prefix和suffix两部分,如果prefix和suffix分别都在list里,那么返回true,或者如果prefix在list里,recursive的做suffixDFS也是true,那么也返回True。循环完毕返回False。 4. 外面,我们遍历每一个单词,如果满足DFS,就添加到res。最后返回。 --- ### [341] Flatten Nested List Iterator 前提:一个多次嵌套的整数list,把它展开平整。 目的:建立一个class,要求有两个方法,next和hasNext,不断的循环使用这两个方法,然后输出一个展平后的list。其中有三个函数可以用: - isInteger:返回是否是个整数 - getInteger:如果是整数返回,如果是list,返回None - getList:如果是list返回,如果是整数,返回None 思路: 1. 不一定每次next都一定要返回一个整数,也可以返回None,然后等着hasNext帮忙更新list,下次再next输出。(这个真的很难想到) 2. 首先从init开始,我们翻转一下list,存储在self.stack里。 3. 然后next,我们直接返回self.stack.pop().getInteger(),如果最后是整数,则返回,如果不是返回None。 4. 最后是hasNext,我们写一个while循环,当self.stack不会空时,取stack最后面的值,如果isInteger,就返回True,如果不是,就把最后这个元素通过top.getList()[::-1]翻转后连接到self.stack后面,也就是展平了最后一个元素,然后while循环,直到最后一个元素是integer,返回True,这时候self.stack也更新了。如果self.stack为空,则返回False。 --- <file_sep>""" Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Note: Your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution and you may not use the same element twice. """ class Solution: def twoSum(self, numbers: list, target: int) -> list: left_pointer = 0 right_pointer = len(numbers) - 1 while right_pointer > left_pointer: if numbers[left_pointer] + numbers[right_pointer] < target: left_pointer += 1 elif numbers[left_pointer] + numbers[right_pointer] > target: right_pointer -= 1 else: return [left_pointer + 1, right_pointer + 1] return [] <file_sep>""" The count-and-say sequence is the sequence of integers with the first five terms as following: 1. 1 2. 11 3. 21 4. 1211 5. 111221 6. 312211 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. Note: Each term of the sequence of integers will be represented as a string. """ class Solution: def countAndSay(self, n: int) -> str: if n == 1: return '1' target = self.countAndSay(n - 1) result = '' temp = target[0] count = 0 for item in target: if item == temp: count += 1 else: result += str(count) + temp temp = item count = 1 result += str(count) + temp return result <file_sep>""" We need two loops to solve this problems: 1. finding the last index for each char in the string. 2. finding the index where all the char on the left has a smaller last index. """ class Solution: def partitionLabels(self, S: str) -> list: res = [] max_last_seen = 0 count = 0 last_seen = {char: i for i, char in enumerate(S)} for i, char in enumerate(S): max_last_seen = max(max_last_seen, last_seen[char]) count += 1 if i == max_last_seen: res.append(count) count = 0 return res <file_sep>""" A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation. For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings. A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings. Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings. Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S. """ class Solution: def removeOuterParentheses(self, S: str) -> str: num_string = 0 for i in range(len(S)): if S[i] == '(': num_string += 1 else: num_string -= 1 if num_string == 0: if i == len(S) - 1: return S[1:-1] else: return self.removeOuterParentheses(S[:i + 1]) + self.removeOuterParentheses(S[i + 1:]) a = "(()())(())" s = Solution() b = s.removeOuterParentheses(a) print(b) <file_sep>""" Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. """ class Solution: def removeDuplicates(self, nums: list) -> int: if len(nums) <= 2: return len(nums) left = 1 for right in range(2, len(nums)): if nums[left] != nums[right] or nums[left-1] != nums[right]: left += 1 nums[left] = nums[right] return left + 1 <file_sep>""" Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1]. """ class Solution: def searchRange(self, nums: list, target: int) -> list: res = [-1, -1] left_pointer = 0 right_pointer = len(nums) - 1 self.helper(nums, target, res, left_pointer, right_pointer) return res def helper(self, nums, target, result, left_pointer, right_pointer): while left_pointer <= right_pointer: mid_pointer = (left_pointer + right_pointer) >> 1 mid_value = nums[mid_pointer] if target < mid_value: right_pointer = mid_pointer - 1 elif target > mid_value: left_pointer = mid_pointer + 1 else: if mid_pointer == 0 or nums[mid_pointer - 1] != target: result[0] = mid_pointer left_pointer = mid_pointer + 1 if mid_pointer == len(nums) - 1 or nums[mid_pointer + 1] != target: result[1] = mid_pointer right_pointer = mid_pointer - 1 if mid_pointer != 0 and nums[mid_pointer - 1] == target and mid_pointer != len(nums) - 1 and nums[mid_pointer + 1] == target: self.helper(nums, target, result, left_pointer, mid_pointer - 1) self.helper(nums, target, result, mid_pointer + 1, right_pointer) return return <file_sep>""" Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. """ class Solution: def lengthOfLastWord(self, s: str) -> int: len_x = 0 for item in s[::-1].strip(): if item.isspace(): return len_x else: len_x += 1 return len_x <file_sep>""" Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. """ class Solution: def generateParenthesis(self, n: int) -> list: res = [] self.helper('', res, 0, 0, n) return res def helper(self, cur, res, left, right, n): if right == n: res.append(cur) elif left - right >= 0: self.helper(cur + "(", res, left + 1, right, n) self.helper(cur + ')', res, left, right + 1, n) else: return <file_sep>""" Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. """ class Solution: def backspaceCompare(self, S: str, T: str) -> bool: s_stack = [] t_stack = [] for item in S: if item == '#': if s_stack: s_stack.pop() else: continue else: s_stack.append(item) for item in T: if item == '#': if t_stack: t_stack.pop() else: continue else: t_stack.append(item) return s_stack == t_stack a = "y#fo##f" b = "y#f#o##f" s = Solution() print(s.backspaceCompare(a, b)) <file_sep>/** * @param {string[]} words * @param {string} order * @return {boolean} */ let isAlienSorted = function(words, order) { let alpha = {}; for (let i = 0; i < order.length; i ++) { alpha[order[i]] = i; } let res = true; for (let i = 1; i < words.length; i ++) { let preWord = words[i - 1]; let curWord = words[i]; let j = 0; while (preWord[j] && curWord[j]) { if (alpha[preWord[j]] > alpha[curWord[j]]) { res = false; } else if (alpha[preWord[j]] < alpha[curWord[j]]) { break; } j += 1; } if (preWord[j] && !curWord[j]){ res = false; } } return res; }; <file_sep>""" Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. Each number in candidates may only be used once in the combination. Note: All numbers (including target) will be positive integers. The solution set must not contain duplicate combinations. """ class Solution: def combinationSum2(self, candidates: list, target: int) -> list: candidates.sort() res = [] self.helper(candidates, target, res, []) return res def helper(self, candidates, target, result, path): if target < 0: return if target == 0: result.append(path) return for i in range(len(candidates)): if i > 0 and candidates[i] == candidates[i - 1]: continue if candidates[i] > target: return self.helper(candidates[i + 1:], target - candidates[i], result, path + [candidates[i]])<file_sep>""" This is a typical DFS problem, we increase the number of island every time we found a '1' in the grid. Then we applied DFS to this grid and transform every '1' to '0'. """ class Solution: def numIslands(self, grid: list) -> int: num_island = 0 for row in range(len(grid)): for col in range(len(grid[0])): if grid[row][col] == '0': continue else: num_island += 1 grid[row][col] = '0' dfs_list = [[row, col]] while dfs_list: cur_loc = dfs_list.pop() cur_row = cur_loc[0] cur_col = cur_loc[1] for i in range(-1, 2, 1): for j in range(-1, 2, 1): if i == j or i * j != 0: continue new_row = cur_row + i new_col = cur_col + j if 0 <= new_row < len(grid) and 0 <= new_col < len(grid[0]) and grid[new_row][new_col] == '1': dfs_list.append([new_row, new_col]) grid[new_row][new_col] = '0' return num_island <file_sep>""" Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. Your algorithm's runtime complexity must be in the order of O(log n). """ class Solution: def search(self, nums: list, target: int) -> int: left_pointer = 0 right_pointer = len(nums) - 1 while right_pointer > left_pointer: mid_pointer = (left_pointer + right_pointer) // 2 mid_value = nums[mid_pointer] if nums[left_pointer] < nums[right_pointer]: if target < mid_value: right_pointer = mid_pointer elif target > mid_value: left_pointer = mid_pointer else: return mid_pointer else: if target > nums[left_pointer]: if target > mid_value: if mid_value > nums[left_pointer]: left_pointer = mid_pointer else: right_pointer = mid_pointer elif target < mid_value: right_pointer = mid_pointer else: return mid_pointer elif target < nums[right_pointer]: if target > mid_value: left_pointer = mid_pointer elif target < mid_value: if mid_value < nums[right_pointer]: right_pointer = mid_pointer else: left_pointer = mid_pointer else: return mid_pointer elif target == nums[left_pointer]: return left_pointer else: return right_pointer return -1 <file_sep>""" Given two binary strings, return their sum (also a binary string). The input strings are both non-empty and contains only characters 1 or 0. """ class Solution: def addBinary(self, a: str, b: str) -> str: a_r = a[::-1] b_r = b[::-1] result = '' a_p = 0 b_p = 0 c = 0 while a_p < len(a) or b_p < len(b): a_int = int(a_r[a_p]) if a_p < len(a) else 0 b_int = int(b_r[b_p]) if b_p < len(b) else 0 temp = a_int + b_int + c if temp < 2: result += str(temp) c = 0 else: result += str(temp - 2) c = 1 a_p += 1 b_p += 1 result += str(c) if c == 1 else '' return result[::-1] <file_sep>""" Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. """ class Solution: def threeSum(self, nums: list) -> list: nums.sort() res = [] for i in range(len(nums)): if i > 0 and nums[i] == nums[i - 1]: continue if nums[i] > 0: break left_p = i + 1 right_p = len(nums) - 1 while right_p > left_p: if left_p > i + 1 and nums[left_p] == nums[left_p - 1]: left_p += 1 continue if right_p < len(nums) - 1 and nums[right_p] == nums[right_p + 1]: right_p -= 1 continue left_v = nums[left_p] right_v = nums[right_p] if left_v + right_v == - nums[i]: res.append([nums[i], left_v, right_v]) left_p += 1 right_p -= 1 if left_v + right_v < -nums[i]: left_p += 1 if left_v + right_v > -nums[i]: right_p -= 1 return res <file_sep>from collections import defaultdict class Graph: def __init__(self, num_vertex): self.graph = defaultdict(list) self.num_vertex = num_vertex def add_edge(self, v, u): self.graph[v].append(u) def topological_sort_helper(self, v, visited, stack): visited[v] = True for u in self.graph[v]: if not visited[u]: self.topological_sort_helper(u, visited, stack) stack.insert(0, v) def topological_sort(self): visited = [False] * self.num_vertex stack = [] for i in range(self.num_vertex): if not visited[i]: self.topological_sort_helper(i, visited, stack) print(stack) g = Graph(6) g.add_edge(5, 2) g.add_edge(5, 0) g.add_edge(4, 0) g.add_edge(4, 1) g.add_edge(2, 3) g.add_edge(3, 1) g.topological_sort() <file_sep>""" Given a column title as appear in an Excel sheet, return its corresponding column number. """ class Solution: def titleToNumber(self, s: str) -> int: res = 0 count = 0 for item in s[::-1]: res += (ord(item) - 64) * 26 ** count count += 1 return res <file_sep>""" Reverse a singly linked list. """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: if head is None or head.next is None: return head else: reverse_head = self.reverseList(head.next) head.next.next = head head.next = None return reverse_head node_list = [] for i in range(6): node_list.append(ListNode(i + 1)) for i in range(6): if i == 5: node_list[i].next = None else: node_list[i].next = node_list[i + 1] s = Solution() result = s.reverseList(node_list[0]) print(result.val) <file_sep>""" Given a non-empty array of integers, every element appears twice except for one. Find that single one. """ class Solution: def singleNumber(self, nums: list) -> int: hashed = {} for item in nums: if item in hashed: hashed[item] = False else: hashed[item] = True for key, value in hashed.items(): if value: return key <file_sep>""" The good application of sorted() and lambda! """ class Solution: def kClosest(self, points: list, K: int) -> list: points = [x for x in sorted(points, key=lambda input: input[0] ** 2 + input[1] ** 2)] return points[:K]<file_sep>""" Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". """ class Solution: def longestCommonPrefix(self, strs: list) -> str: if len(strs) == 0: return '' common = strs[0] while len(common) > 0: for i in range(len(strs)): if common not in strs[i][:len(common)]: break if i == len(strs) - 1: return common common = common[0:-1] return common <file_sep>""" Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. Note: A leaf is a node with no children. """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def hasPathSum(self, root: TreeNode, sum: int) -> bool: if not root: return False return sum in self.pathSumHelper(root) def pathSumHelper(self, root: TreeNode) -> list: if not root: return [0] sum_list = [] if root.left and root.right: for item in self.pathSumHelper(root.left) + self.pathSumHelper(root.right): sum_list.append(item + root.val) elif root.left: for item in self.pathSumHelper(root.left): sum_list.append(item + root.val) else: for item in self.pathSumHelper(root.right): sum_list.append(item + root.val) return sum_list def hasPathSumBetter(self, root: TreeNode, sum: int) -> bool: if not root: return False if not root.left and not root.right and root.val == sum: return True return self.hasPathSumBetter(root.left, sum - root.val) or self.hasPathSumBetter(root.right, sum - root.val) <file_sep>""" This question uses OrderedDict. Not like the traditional dictionary, OrderedDict is a ordered dictionary, the data can remember the order of the value inserted into the data set. 1. ordered_dict.pop(key): remove the key value. 2. ordered_dict[key] = value: assign the key with value. 3. ordered_dict.popitem(last=False): remove the 1st order key-value. In this question: When we want to change the value of key, and put it at the end of queue. We need to pop the key first, and then assign the value. """ from collections import OrderedDict class LRUCache: def __init__(self, capacity: int): self.size = 0 self.cap = capacity self.cache = OrderedDict() def get(self, key: int) -> int: if key in self.cache: res = self.cache.pop(key) self.cache[key] = res return res else: return -1 def put(self, key: int, value: int) -> None: if key in self.cache: self.cache.pop(key) self.cache[key] = value else: if self.size < self.cap: self.size += 1 self.cache[key] = value else: self.cache.popitem(last=False) self.cache[key] = value # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value) <file_sep>1. 953 Verifying an Alien Dictionary Brute search: 首先建立一个object,把每个字母的index存进去。然后遍历words数组,从1到length - 1。 然后循环遍历,每一个和前一个使用while循环进行比较。 - 如果字典里,前一个比后一个大,结果为false。 - 如果字典里,前一个比后一个小,退出while循环,继续遍历。 - 如果相等,继续下一位的检验。 - while之后,检查一下,如果后一个单词null了,但是前一个没有,还是false。 2. 301 Remove Invalid Parentheses 这道题太难了,首先明确这道题需要写一个helper,来递归检查是不是括号有效。具体help的写好如下 - 首先输入函数是字符串,返回值,上一个i,上一个j,和用来判断遍历方向的数组。 - 然后从上一个i开始到字符串结尾遍历。如果是"(",值加一,是")",值减一,如果值使用不小于零,代表从左到右, 右括号不大于左括号,因为只要符合条件就可以continue。所以结束for循环,再求翻转的情况,如果没反转过,就 再求翻转的,如果翻转过了,就把值添加到返回值里。 - 如何确保返回值不重复呢?就是上一个i和上一个j的作用了。每次去除的都是连续右括号的第一个,这样子保证,去除之后 i之前的验证值变为0,所以可以从i再开始下一轮遍历。 - 但是为了避免两轮去掉的右括号组合一样,所以添加上一个j,每次从上一个j开始检查,可以规避这种情况。 - 最后返回值是通过helper函数进行添加的。 3. 238 Product of Array Except Self 这道题很有趣,不能用除法,所以直接排除了算出所有数的积,然后逐个除以i上的数这种方法。 但是还是可以再不加入额外空间,O(n)时间内算出。 - 首先,用一个循环算出结果数据左边所有的积,这个就是每次用前一个的结果乘以前一个的数。 - 然后,再给每个结果数据乘上右边的积。引入一个中间值,记录i右边所有数的积,每次循环更新结果数组, 同时也同步更新这个中间值。 4. 67 Add Binary 这道题不是很难,但是主要有几点需要注意: - while语句是只要有一个没有遍历完就循环,长度短的用0替代。 - 最后看进位项是不是0,是的话什么也不加,不是的话加1。 这里面还有几个比较重要的js知识点。 - 翻转字符串 a = a.split(""").reverse().join("""), 转换成array翻转,再转回字符串。 - 检验Number是不是NaN,isNaN(Number) 5. 973 K Closest Points to Origin 这题纯粹就是考javascript里的array.sort()方法,sort里面可以放一个sort函数,input是a和b,如果返回值是负的,a在前,正的, b在前。 - Math.pow(a, n) 求a的n次方 6. 273 Integer to English Words - 首先,给出三个常数,一千,百万,十亿,用作以后求整数和模。 - 其次,建立三个数组,分别是1到19, 20到90,100。这三个数组放在一个单独的函数里,返回1000之内的值。 - 最后在主函数里建立数组存储一千,百万,十亿。 - 每次求num除以三个常数的整数,然后求整数的语言表达,后面加上一千或者百万或者十亿。 - 循环三次,每次num用num和常数的模来替换。 这其中用到了JavaScript求整数,求模。 - Math.floor() 求整除 - % 求余数 - string.trim() 去除字符串前后的空格。 <file_sep>""" Write a program to find the node at which the intersection of two singly linked lists begins. """ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ len1, len2 = 0, 0 moveA, moveB = headA, headB while moveA: len1 += 1 moveA = moveA.next while moveB: len2 += 1 moveB = moveB.next if len1 < len2: for _ in range(len2 - len1): headB = headB.next else: for _ in range(len1 - len2): headA = headA.next while headA and headB and headA != headB: headA = headA.next headB = headB.next return headA <file_sep>""" Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. The same repeated number may be chosen from candidates unlimited number of times. Note: All numbers (including target) will be positive integers. The solution set must not contain duplicate combinations. """ class Solution: def combinationSum(self, candidates: list, target: int) -> list: res = [] self.helper(candidates, target, res) return res def helper(self, candidates, target, result): if target < 0: return if not candidates: return if len(candidates) == 1: if target % candidates[0] == 0: temp = [] for i in range(int(target / candidates[0])): temp.append(candidates[0]) result.append(temp) return self.helper(candidates[1:], target, result) temp = [] self.helper(candidates, target - candidates[0], temp) for item in temp: item.insert(0, candidates[0]) result += temp return <file_sep>""" This is a typical Tarjan problem. Ideas: 1. By removing a edge, we will increase the number of the connected components. 2. If we have two lists, DFN and LOW. DFN is a list recording the order of DFS for each vertex. LOW is a list recording the lowest order of its neighbour except its parent. 3. If LOW[v] is larger than DFN[u], (u, v) is the only edge, which means that it is critical connection. """ from collections import defaultdict class Solution: def criticalConnections(self, n: int, connections: list) -> list: DFN = [-1] * n LOW = [-1] * n parent = [-1] * n self.time = 0 res = [] def Tarjan(u): DFN[u] = self.time LOW[u] = self.time self.time += 1 for v in graph[u]: if DFN[v] == -1: parent[v] = u # DFS Tarjan(v) # Update the LOW[u] LOW[u] = min(LOW[u], LOW[v]) if LOW[v] > DFN[u]: res.append([u, v]) # if v is explored, we still need to check and update the value of LOW[u] elif parent[u] != v: LOW[u] = min(LOW[u], DFN[v]) graph = defaultdict(list) for edge in connections: graph[edge[0]].append(edge[1]) graph[edge[1]].append(edge[0]) for i in range(n): if DFN[i] == -1: Tarjan(i) return res <file_sep>""" Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. If no valid conversion could be performed, a zero value is returned. Note: Only the space character ' ' is considered as whitespace character. Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned. """ class Solution: def myAtoi(self, str: str) -> int: str = str.strip() if str[0].isdigit() or str[0] in ['-', '+']: res = str[0] for item in str[1:]: if item.isdigit(): res += item else: break if int(res) > 2 ** 31 - 1: return 2 ** 31 - 1 elif int(res) < - 2 ** 31: return - 2 ** 31 else: return int(res) else: return 0 <file_sep>""" Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator. Return the quotient after dividing dividend by divisor. The integer division should truncate toward zero. """ class Solution: def divide(self, dividend: int, divisor: int) -> int: sig = 1 if (dividend > 0 and divisor < 0) or (dividend < 0 and divisor > 0): sig = -1 dividend = abs(dividend) divisor = abs(divisor) return min(max(-2147483648, sig * self.helper(dividend, divisor)), 2147483648) def helper(self, dividend, divisor): if dividend == 0 or dividend < divisor: return 0 sum = divisor res = 1 while sum + sum <= dividend: sum += sum res += res return res + self.helper(dividend - sum, divisor) <file_sep>/** * @param {number[]} nums * @return {number[]} */ let productExceptSelf = function(nums) { let res = [1]; for (let i = 1; i < nums.length; i++) { res[i] = res[i - 1] * nums[i - 1]; } let right = 1; for (let j = nums.length - 1; j >= 0; j--) { res[j] = res[j] * right; right = right * nums[j]; } return res; };
9f57c5403bfdb29b07e0e15c3c557d84d77bdb07
[ "Markdown", "Python", "JavaScript" ]
84
Python
JianhangYin/LeetCode
5f5018035fc5e70103e1d4bb5dadb88e5949f6ca
4124ebb0735a3ff55462b47f90573d25ab099fbc
refs/heads/master
<repo_name>FiveElephants/FiveElephants.github.io<file_sep>/javascript.js var category1 = document.getElementById('category1'); var category2 = document.getElementById('category2'); var category3 = document.getElementById('category3'); var category4 = document.getElementById('category4'); var category5 = document.getElementById('category5'); var category6 = document.getElementById('category6'); var category1_color = "#d1e8c5" var category2_color = "#fcf6b1" var category3_color = "#d2edf3" var category4_color = "#fdcc99" var category5_color = "#fbcbcc" var category6_color = "#fbf6b3" var category1_profile = document.getElementById('category1_profile'); var category2_profile = document.getElementById('category2_profile'); var category3_profile = document.getElementById('category3_profile'); var category4_profile = document.getElementById('category4_profile'); var category5_profile = document.getElementById('category5_profile'); var category6_profile = document.getElementById('category6_profile'); var category1_profile_title1 = document.getElementById('category1_profile_title1'); var category1_profile_title2 = document.getElementById('category1_profile_title2'); var category1_profile_title3 = document.getElementById('category1_profile_title3'); var category1_profile_title4 = document.getElementById('category1_profile_title4'); var category1_profile_title5 = document.getElementById('category1_profile_title5'); var category1_profile_title6 = document.getElementById('category1_profile_title6'); var category1_profile_title7 = document.getElementById('category1_profile_title7'); var category1_profile_title8 = document.getElementById('category1_profile_title8'); var category2_profile_title1 = document.getElementById('category2_profile_title1'); var category2_profile_title2 = document.getElementById('category2_profile_title2'); var category2_profile_title3 = document.getElementById('category2_profile_title3'); var category2_profile_title4 = document.getElementById('category2_profile_title4'); var category2_profile_title5 = document.getElementById('category2_profile_title5'); var category2_profile_title6 = document.getElementById('category2_profile_title6'); var category3_profile_title1 = document.getElementById('category3_profile_title1'); var category4_profile_title1 = document.getElementById('category4_profile_title1'); var category5_profile_title1 = document.getElementById('category5_profile_title1'); var category6_profile_title1 = document.getElementById('category6_profile_title1'); var category1_profile_title1_preview = document.getElementById('category1_profile_title1_preview'); var category1_profile_title2_preview = document.getElementById('category1_profile_title2_preview'); var category1_profile_title3_preview = document.getElementById('category1_profile_title3_preview'); var category1_profile_title4_preview = document.getElementById('category1_profile_title4_preview'); var category1_profile_title5_preview = document.getElementById('category1_profile_title5_preview'); var category1_profile_title6_preview = document.getElementById('category1_profile_title6_preview'); var category2_profile_title1_preview = document.getElementById('category2_profile_title1_preview'); var category2_profile_title2_preview = document.getElementById('category2_profile_title2_preview'); var category2_profile_title3_preview = document.getElementById('category2_profile_title3_preview'); var category2_profile_title4_preview = document.getElementById('category2_profile_title4_preview'); var category2_profile_title5_preview = document.getElementById('category2_profile_title5_preview'); var category2_profile_title6_preview = document.getElementById('category2_profile_title6_preview'); var category3_profile_title1_preview = document.getElementById('category3_profile_title1_preview'); var category4_profile_title1_preview = document.getElementById('category4_profile_title1_preview'); var category5_profile_title1_preview = document.getElementById('category5_profile_title1_preview'); var category6_profile_title1_preview = document.getElementById('category6_profile_title1_preview'); var toShowCategory = category2 var toShow = category2_profile; var toShowTitlePreview = category2_profile_title1_preview var toShowTitle = category2_profile_title1 var profileArray = [category1_profile, category2_profile, category3_profile, category4_profile, category5_profile, category6_profile, category1_profile_title1_preview, category1_profile_title2_preview, category1_profile_title3_preview, category1_profile_title4_preview, category1_profile_title5_preview, category1_profile_title6_preview, category2_profile_title1_preview, category2_profile_title2_preview, category2_profile_title3_preview, category2_profile_title4_preview, category2_profile_title5_preview, category2_profile_title6_preview, category3_profile_title1_preview, category4_profile_title1_preview, category5_profile_title1_preview, category6_profile_title1_preview ]; //Initializations noneInitializations(profileArray); eventInitializations(); if (toShow) { toShow.style.display = "block"; if (toShowCategory) changeCategoryColor(toShowCategory, category2_color); if (toShowTitle) changeTitleColor(toShowTitle, category2_color) } if (toShowTitlePreview) { toShowTitlePreview.style.display = "block" } //function to initialize all the profiles function noneInitializations(profile) { for (var i = 0; i < profile.length; i++) { if (profile[i]) profile[i].style.display = "none" } } //end of noneInitializations //funcition to display all the profiles function displayProfile(profile) { if (toShow) { toShow.style.display = "none" toShow = profile toShow.style.display = "block" } } //end of displayProfile //displaying all the preview function displayPreview(preview) { console.log("1"); if (toShowTitlePreview) { console.log("2"); if (toShowTitlePreview.style){ console.log("3"); toShowTitlePreview.style.display = "none" } toShowTitlePreview = preview if (toShowTitlePreview.style){ console.log("4"); toShowTitlePreview.style.display = "block" } } } function changeCategoryColor(category, color) { category1.style.backgroundColor = "#ffffff" category1.style.cssText = ":hover{color:" + category1_color + ";}"; category2.style.backgroundColor = "#ffffff" category2.style.cssText = ":hover{color:" + category2_color + ";}"; category3.style.backgroundColor = "#ffffff" category3.style.cssText = ":hover{color:" + category3_color + ";}"; category4.style.backgroundColor = "#ffffff" category4.style.cssText = ":hover{color:" + category4_color + ";}"; category5.style.backgroundColor = "#ffffff" category5.style.cssText = ":hover{color:" + category5_color + ";}"; category6.style.backgroundColor = "#ffffff" category6.style.cssText = ":hover{color:" + category6_color + ";}"; category.style.backgroundColor = color } function changeTitleColor(title, color) { category1_profile_title1.style.backgroundColor = "#ffffff" category1_profile_title1.style.cssText = ":hover{color:" + category1_color + ";}"; category1_profile_title2.style.backgroundColor = "#ffffff" category1_profile_title2.style.cssText = ":hover{color:" + category1_color + ";}"; category1_profile_title3.style.backgroundColor = "#ffffff" category1_profile_title3.style.cssText = ":hover{color:" + category1_color + ";}"; category1_profile_title4.style.backgroundColor = "#ffffff" category1_profile_title4.style.cssText = ":hover{color:" + category1_color + ";}"; category1_profile_title5.style.backgroundColor = "#ffffff" category1_profile_title5.style.cssText = ":hover{color:" + category1_color + ";}"; category1_profile_title6.style.backgroundColor = "#ffffff" category1_profile_title6.style.cssText = ":hover{color:" + category1_color + ";}"; category2_profile_title1.style.backgroundColor = "#ffffff" category2_profile_title1.style.cssText = ":hover{color:" + category2_color + ";}"; category2_profile_title2.style.backgroundColor = "#ffffff" category2_profile_title2.style.cssText = ":hover{color:" + category2_color + ";}"; category2_profile_title3.style.backgroundColor = "#ffffff" category2_profile_title3.style.cssText = ":hover{color:" + category2_color + ";}"; category2_profile_title4.style.backgroundColor = "#ffffff" category2_profile_title4.style.cssText = ":hover{color:" + category2_color + ";}"; category2_profile_title5.style.backgroundColor = "#ffffff" category2_profile_title5.style.cssText = ":hover{color:" + category2_color + ";}"; category2_profile_title6.style.backgroundColor = "#ffffff" category2_profile_title6.style.cssText = ":hover{color:" + category2_color + ";}"; title.style.backgroundColor = color } function eventInitializations() { if (category1) { category1.addEventListener('click', function(event) { displayProfile(category1_profile); displayPreview(category1_profile_title1_preview) changeCategoryColor(category1, category1_color); changeTitleColor(category1_profile_title1, category1_color) }); } if (category2) { category2.addEventListener('click', function(event) { displayProfile(category2_profile); displayPreview(category2_profile_title1_preview) changeCategoryColor(category2, category2_color); changeTitleColor(category2_profile_title1, category2_color) }); } if (category3) { category3.addEventListener('click', function(event) { displayProfile(category3_profile); displayPreview(category3_profile_title1_preview) changeCategoryColor(category3, category3_color); changeTitleColor(category3_profile_title1, category3_color) }); } if (category4) { category4.addEventListener('click', function(event) { /*displayProfile(category4_profile); displayPreview(category4_profile_title1_preview) changeCategoryColor(category4, category4_color); changeTitleColor(category4_profile_title1, category4_color)*/ }); } if (category5) { category5.addEventListener('click', function(event) { /*displayProfile(category5_profile); displayPreview(category5_profile_title1_preview) changeCategoryColor(category5, category5_color); changeTitleColor(category5_profile_title1, category5_color)*/ }); } if (category6) { category6.addEventListener('click', function(event) { /*displayProfile(category6_profile); displayPreview(category6_profile_title1_preview) changeCategoryColor(category6, category6_color); changeTitleColor(category6_profile_title1, category6_color)*/ }); } if (category1_profile_title1) { category1_profile_title1.addEventListener('click', function(event) { displayPreview(category1_profile_title1_preview) changeTitleColor(category1_profile_title1, category1_color) }); } if (category1_profile_title2) { category1_profile_title2.addEventListener('click', function(event) { displayPreview(category1_profile_title2_preview) changeTitleColor(category1_profile_title2, category1_color) }); } if (category1_profile_title3) { category1_profile_title3.addEventListener('click', function(event) { displayPreview(category1_profile_title3_preview) changeTitleColor(category1_profile_title3, category1_color) }); } if (category1_profile_title4) { category1_profile_title4.addEventListener('click', function(event) { displayPreview(category1_profile_title4_preview) changeTitleColor(category1_profile_title4, category1_color) }); } if (category1_profile_title5) { category1_profile_title5.addEventListener('click', function(event) { displayPreview(category1_profile_title5_preview) changeTitleColor(category1_profile_title5, category1_color) }); } if (category1_profile_title6) { category1_profile_title6.addEventListener('click', function(event) { displayPreview(category1_profile_title6_preview) changeTitleColor(category1_profile_title6, category1_color) }); } if (category2_profile_title1) { category2_profile_title1.addEventListener('click', function(event) { displayPreview(category2_profile_title1_preview) changeTitleColor(category2_profile_title1, category2_color) }); } if (category2_profile_title2) { category2_profile_title2.addEventListener('click', function(event) { displayPreview(category2_profile_title2_preview) changeTitleColor(category2_profile_title2, category2_color) }); } if (category2_profile_title3) { category2_profile_title3.addEventListener('click', function(event) { displayPreview(category2_profile_title3_preview) changeTitleColor(category2_profile_title3, category2_color) }); } if (category2_profile_title4) { category2_profile_title4.addEventListener('click', function(event) { displayPreview(category2_profile_title4_preview) changeTitleColor(category2_profile_title4, category2_color) }); } if (category2_profile_title5) { category2_profile_title5.addEventListener('click', function(event) { displayPreview(category2_profile_title5_preview) changeTitleColor(category2_profile_title5, category2_color) }); } if (category2_profile_title6) { category2_profile_title6.addEventListener('click', function(event) { displayPreview(category2_profile_title6_preview) changeTitleColor(category2_profile_title6, category2_color) }); } if (category3_profile_title1) { category3_profile_title1.addEventListener('click', function(event) { displayPreview(category3_profile_title1_preview) changeTitleColor(category3_profile_title1, category3_color) }); } if (category4_profile_title1) { category4_profile_title1.addEventListener('click', function(event) { displayPreview(category4_profile_title1_preview) changeTitleColor(category4_profile_title1, category4_color) }); } if (category5_profile_title1) { category5_profile_title1.addEventListener('click', function(event) { displayPreview(category5_profile_title1_preview) changeTitleColor(category5_profile_title1, category5_color) }); } if (category6_profile_title1) { category6_profile_title1.addEventListener('click', function(event) { displayPreview(category6_profile_title1_preview) changeTitleColor(category6_profile_title1, category6_color) }); } if (category1_profile_title1_preview) { category1_profile_title1_preview.addEventListener('click', function(event) { window.location = "https://freshdesk.com"; }); } if (category1_profile_title2_preview) { category1_profile_title2_preview.addEventListener('click', function(event) { }); } if (category2_profile_title1_preview) { category2_profile_title1_preview.addEventListener('click', function(event) { window.location = "category2_profile_title1_preview.html"; }); } if (category2_profile_title2_preview) { category2_profile_title2_preview.addEventListener('click', function(event) { window.location = "category2_profile_title2_preview.html"; }); } } //End of eventInitializations() function showImage(imgName) { document.getElementById('largeImg').src = imgName; showLargeImagePanel(); unselectAll(); var e = window.event; if (e.stopPropagation) { e.stopPropagation(); } //IE8 and Lower else { e.cancelBubble = true; } } function showLargeImagePanel() { document.getElementById('largeImgPanel').style.visibility = 'visible'; } function unselectAll() { if (document.selection) document.selection.empty(); if (window.getSelection) window.getSelection().removeAllRanges(); } function hideMe(obj) { obj.style.visibility = 'hidden'; } function getQueryParams(qs) { qs = qs.split('+').join(' '); var params = {}, tokens, re = /[?&]?([^=]+)=([^&]*)/g; while (tokens = re.exec(qs)) { params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]); } return params; } /****Reading the href attribute *****/ //getting the parameter from href var queryParams = getQueryParams(document.location.search); console.log(queryParams); if (queryParams.category == "acad") { displayProfile(category2_profile); displayPreview(category2_profile_title1_preview) changeCategoryColor(category2, category2_color); changeTitleColor(category2_profile_title1, category2_color) } else if (queryParams.category == "work") { displayProfile(category1_profile); displayPreview(category1_profile_title1_preview) changeCategoryColor(category1, category1_color); changeTitleColor(category1_profile_title1, category1_color) } var path = window.location.pathname; var page = path.split("/").pop(); console.log(page); if (page == "games.html") { displayProfile(category3_profile); displayPreview(category3_profile_title1_preview) changeCategoryColor(category3, category3_color); changeTitleColor(category3_profile_title1, category3_color) }
93bc554e5dfb8c3924f72653b0c21232112c086a
[ "JavaScript" ]
1
JavaScript
FiveElephants/FiveElephants.github.io
537a6a7883d9381ead5b3c42ec89fd7894b6defa
71bd63f874176589f8a9ddf5c0e9e3cebb7a8a34
refs/heads/master
<file_sep>package iotwearable.editor.command; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import iotwearable.editor.utilities.Category; import iotwearable.editor.utilities.MessageContent; import iotwearable.editor.utilities.ProjectManager; import iotwearable.editor.window.ChooseProjectWindow; import iotwearable.editor.window.MessageWindow; import iotwearable.gen.CodeGeneration; import iotwearable.gen.Manual; import iotwearable.gen.utilities.GenLogger; import iotwearable.utilities.FileUtils; import org.eclipse.gef.commands.Command; public class GenerateCodeCommand extends Command{ ProjectManager manager; public GenerateCodeCommand() { manager = new ProjectManager(); } @Override public boolean canExecute() { return true; } @Override public void execute() { GenLogger.startLog(); ChooseProjectWindow ui = new ChooseProjectWindow(manager.getProjects()); Category project = ui.view(); if( project != null) { String mainboard=""; String state =""; for(String fileName : project.file) { File file = manager.getFile(project.projectName,fileName); if(manager.classify(file).equals("Mainboard")) mainboard = file.getAbsolutePath().toString(); else state = file.getAbsolutePath().toString(); } if(!mainboard.isEmpty() && !state.isEmpty()) { CodeGeneration gen = new CodeGeneration(); String sourceCode = gen.generate(mainboard, state); sourceCode = sourceCode.replace("<project_iotw>", project.projectName); Manual manualGenerator = new Manual(mainboard); try { FileUtils.writeFile(manager.getProject(project.projectName).getLocation().toString()+"/source_code_"+project.projectName.trim()+".ino", sourceCode); manager.refreshProject(project.projectName); } catch (IOException e) { MessageWindow.show("Generate code", MessageContent.ErrorReadFileMainboard); } try { FileUtils.writeFile(manager.getProject(project.projectName).getLocation().toString()+"/manual_"+project.projectName.trim()+".html", manualGenerator.createManual(project.projectName)); manager.refreshProject(project.projectName); } catch (IOException e) { MessageWindow.show("Generate code", MessageContent.ErrorReadFileStateSchema); } DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); String log = "Generate code for "+project.projectName.trim()+": " + dateFormat.format(date) + " by ESP-LAP WAGEN Tools"; if(!GenLogger.getLogs().isEmpty()){ log += "\n\nThere was a problem in the code generation process.\n" +"You can view the information in the log.txt file in your project directory.\n" +"*Note: Some serious errors could cause your program to malfunction.\n"; log += "\n**************************Error list*******************************\n"; for(int i = 0; i< GenLogger.getLogs().size(); i++){ log += "\n" +(i+1)+", " + GenLogger.getLogs().get(i); } MessageWindow.show("Generate code", "There was a problem in the code generation process.\n" +"You can view the information in the log.txt file in your project directory.\n" +"*Note: Some serious errors could cause your program to malfunction."); } else{ log += "\nGenerate code completed."; } try { FileUtils.writeFile(manager.getProject(project.projectName).getLocation().toString()+"/log.txt", log); manager.refreshProject(project.projectName); } catch (IOException e) { } } else { MessageWindow.show("Generate code", MessageContent.NoProjectCanGen); } } } } <file_sep>package iotwearable.editor.utilities; import java.util.List; public class Category { public List<String> file; public String projectName; public List<String> getFile() { return file; } public void setFile(List<String> file) { this.file = file; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public Category(String projectName, List<String> file) { super(); this.projectName = projectName; this.file = file; } public Category() { super(); } } <file_sep># DSL4W Đây là công cụ cho phép phát sinh mã nguồn cho các ứng dụng chạy trên thiết bị đeo tay với việc đặc tả ứng dụng đó bằng các thành phần thiết bị và lược đồ trạng thái của ứng dụng http://esp-lab.net/
d629cd13c7ea3ff14c3e3404056185c502fb99e3
[ "Markdown", "Java" ]
3
Java
HuuThuat1996/DSL4Wearable
a6cad86b932ca6149203d445fc1452576f3859ea
7d5f5a4a7b3d40aa8af5f246c656d9cfce19e210
refs/heads/master
<file_sep>require 'net/http' require 'net/https' require "rack-proxy" require "rack/reverse_proxy_matcher" require "rack/exception" require "rack/reverse_proxy/http_streaming_response" require 'skylight' module Rack class ReverseProxy include NewRelic::Agent::Instrumentation::ControllerInstrumentation if defined? NewRelic include Skylight::Helpers def initialize(app = nil, &b) @app = app || lambda {|env| [404, [], []] } @matchers = [] @global_options = {:preserve_host => true, :x_forwarded_host => true, :matching => :all, :replace_response_host => false} instance_eval(&b) if block_given? end instrument_method title: 'ReverseProxy call' def call(env) rackreq = Rack::Request.new(env) matcher = get_matcher(rackreq.fullpath, Proxy.extract_http_request_headers(rackreq.env), rackreq) return @app.call(env) if matcher.nil? if @global_options[:newrelic_instrumentation] action_name = "#{rackreq.path.gsub(/\/\d+/,'/:id').gsub(/^\//,'')}/#{rackreq.request_method}" # Rack::ReverseProxy/foo/bar#GET perform_action_with_newrelic_trace(:name => action_name, :request => rackreq) do proxy(env, rackreq, matcher) end else proxy(env, rackreq, matcher) end end private instrument_method title: 'ReverseProxy proxy' def proxy(env, source_request, matcher) uri = matcher.get_uri(source_request.fullpath,env) if uri.nil? return @app.call(env) end options = @global_options.dup.merge(matcher.options) # Initialize request target_request = Net::HTTP.const_get(source_request.request_method.capitalize).new(uri.request_uri) # Setup headers target_request_headers = Proxy.extract_http_request_headers(source_request.env) if options[:preserve_host] if uri.port == uri.default_port target_request_headers['HOST'] = uri.host else target_request_headers['HOST'] = "#{uri.host}:#{uri.port}" end end if options[:x_forwarded_host] target_request_headers['X-Forwarded-Host'] = source_request.host target_request_headers['X-Forwarded-Port'] = "#{source_request.port}" end target_request.initialize_http_header(target_request_headers) # Basic auth target_request.basic_auth options[:username], options[:password] if options[:username] and options[:password] # Setup body if target_request.request_body_permitted? && source_request.body source_request.body.rewind target_request.body_stream = source_request.body end target_request.content_length = source_request.content_length || 0 target_request.content_type = source_request.content_type if source_request.content_type # Create a streaming response (the actual network communication is deferred, a.k.a. streamed) target_response = HttpStreamingResponse.new(target_request, uri.host, uri.port) # pass the timeout configuration through target_response.set_read_timeout(options[:timeout]) if options[:timeout].to_i > 0 target_response.use_ssl = "https" == uri.scheme # Let rack set the transfer-encoding header response_headers = Rack::Utils::HeaderHash.new Proxy.normalize_headers(format_headers(target_response.headers)) response_headers.delete('Transfer-Encoding') response_headers.delete('Status') # Replace the location header with the proxy domain if response_headers['Location'] && options[:replace_response_host] response_location = URI(response_headers['location']) response_location.host = source_request.host response_location.port = source_request.port response_headers['Location'] = response_location.to_s end [target_response.status, response_headers, target_response.body] end def get_matcher(path, headers, rackreq) matches = @matchers.select do |matcher| matcher.match?(path, headers, rackreq) end if matches.length < 1 nil elsif matches.length > 1 && @global_options[:matching] != :first raise AmbiguousProxyMatch.new(path, matches) else matches.first end end def reverse_proxy_options(options) @global_options=options end def reverse_proxy(matcher, url=nil, opts={}) raise GenericProxyURI.new(url) if matcher.is_a?(String) && url.is_a?(String) && URI(url).class == URI::Generic @matchers << ReverseProxyMatcher.new(matcher,url,opts) end def format_headers(headers) headers.reduce({}) do |acc, (key, val)| formated_key = key.split('-').map(&:capitalize).join('-') acc[formated_key] = Array(val) acc end end end end <file_sep>Gem::Specification.new do |s| s.name = 'rack-reverse-proxy' s.version = "0.9.1" s.authors = ["<NAME>", "<NAME>", "<NAME>", "<NAME>"] s.description = 'A Rack based reverse proxy for basic needs. Useful for testing or in cases where webserver configuration is unavailable.' s.email = ["<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>"] s.files = Dir['README.md', 'LICENSE', 'lib/**/*'] s.homepage = 'http://github.com/waterlink/rack-reverse-proxy' s.require_paths = ["lib"] s.summary = 'A Simple Reverse Proxy for Rack' s.add_development_dependency "rake", "~> 10.3" s.add_development_dependency "guard-rspec" s.add_development_dependency "guard-bundler" s.add_dependency "rack", ">= 1.0.0" s.add_dependency "rack-proxy", "~> 0.5" end <file_sep>module Rack class HttpStreamingResponse def set_read_timeout(value) self.read_timeout = value end end end <file_sep>module Rack class ReverseProxyMatcher def initialize(matcher, url=nil, options={}) @default_url=url @url=url @options=options if matcher.kind_of?(String) @matcher = /^#{matcher.to_s}/ elsif matcher.respond_to?(:match) @matcher = matcher else raise "Invalid Matcher for reverse_proxy" end end attr_reader :matcher,:url, :default_url,:options def match?(path, *args) match_path(path, *args) ? true : false end def get_uri(path,env) return nil if url.nil? _url=(url.respond_to?(:call) ? url.call(env) : url.clone) if _url =~/\$\d/ match_path(path).to_a.each_with_index { |m, i| _url.gsub!("$#{i.to_s}", m) } URI(_url) else default_url.nil? ? URI.parse(_url) : URI.join(_url, path) end end def to_s %Q("#{matcher.to_s}" => "#{url}") end private def match_path(path, *args) headers = args[0] rackreq = args[1] arity = matcher.method(:match).arity if arity == -1 match = matcher.match(path) else params = [path, (@options[:accept_headers] ? headers : nil), rackreq] match = matcher.match(*params[0..(arity - 1)]) end @url = match.url(path) if match && default_url.nil? match end end end<file_sep>source "https://rubygems.org" gemspec gem 'skylight' group :test do gem "rspec" gem "rack-test" gem "webmock" end
34f304e4ccac9f80cd391ee808347947015aa5d0
[ "Ruby" ]
5
Ruby
monkseal/rack-reverse-proxy
96604bcd6aad637eb11f3e5fc10b050a251c555f
f47c8b3f0fb9d531f1fb1d7df7c77ac736f1f44c
refs/heads/master
<repo_name>risclxm/cishilogin<file_sep>/cishilogin/src/com/bbsstep/service/TUserService.java package com.bbsstep.service; import com.bbsstep.po.TUser; public interface TUserService { //给他一个用户名和密码,他将密码加密之后到数据库查询有没有这个用户,如果有,返回这个而用户,如果没有返回null TUser checkUser(String pwd,String username)throws Exception; } <file_sep>/cishilogin/src/com/bbsstep/dao/CarouselBeanMapper.java package com.bbsstep.dao; import java.util.List; import com.bbsstep.po.CarouselBean; import com.bbsstep.util.DataTablePageUtil; public interface CarouselBeanMapper { List<CarouselBean> selectByParam(DataTablePageUtil<CarouselBean> dataTablePageUtil); int selectNumByParam(DataTablePageUtil<CarouselBean> param); int insert(CarouselBean bean); } <file_sep>/cishilogin/src/com/bbsstep/controller/TUserController.java package com.bbsstep.controller; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.bbsstep.po.TUser; import com.bbsstep.service.TUserService; import com.google.code.kaptcha.Constants; @Controller @RequestMapping(value="/tusercontroller") public class TUserController { @Autowired private TUserService service; // 有一个登陆校验的方法:如果验证通过,将跳转至到系统首页,如果验证不通过,跳转到登陆页面 @RequestMapping(method=RequestMethod.POST,value="/checklogin" ) public ModelAndView checkLogin(String username,String password,String imageContent,HttpSession session) { TUser user = null; ModelAndView mv= new ModelAndView(); String msg=null; //A、比对验证码是否正确 //得到原始的验证码 String origContent =(String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY); //B 验证码正确的情况下 去比对用户名和密码 if(origContent.equalsIgnoreCase(imageContent)) { try { user=service.checkUser(password, username); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if(null ==user) {//用户名或密码不对 mv.setViewName("redirect:/login.jsp?msg=1"); }else {//用户名或密码正确 session.setAttribute("loginUser", user); mv.setViewName("redirect:/pages/home/index.jsp"); } }else { //验证码不正确 mv.setViewName("redirect:/login.jsp?msg=0"); } return mv; } } <file_sep>/cishilogin/src/com/bbsstep/dao/TActiveMapper.java package com.bbsstep.dao; import java.util.List; import com.bbsstep.po.TActive; public interface TActiveMapper { List<TActive> getActivesByCity(String cityName) throws Exception; } <file_sep>/cishilogin/src/com/bbsstep/controller/TActiveController.java package com.bbsstep.controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.bbsstep.po.TActive; import com.bbsstep.po.TCity; import com.bbsstep.service.TActiveService; import com.bbsstep.service.TCityService; @Controller @RequestMapping("/active") public class TActiveController { @Autowired private TActiveService tActiveService; @Autowired private TCityService tCityService; @RequestMapping(value="/getActivesByCity",method=RequestMethod.GET) @ResponseBody public Map<String,Object> getActivesByCityName(String cityName) { List<TActive> activeList = new ArrayList<>(); TCity city = null; int statues=1; Map<String,Object> reslut=new HashMap<String,Object>(); try { activeList=tActiveService.getActivesByCity(cityName); city = tCityService.getLoationByName(cityName); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if( city !=null) { statues=0; } reslut.put("status", statues); reslut.put("city", city); reslut.put("activeList", activeList); return reslut; } } <file_sep>/cishilogin/src/com/bbsstep/service/TActiveService.java package com.bbsstep.service; import java.util.List; import com.bbsstep.po.TActive; public interface TActiveService { List<TActive> getActivesByCity(String cityName) throws Exception; } <file_sep>/cishilogin/src/com/bbsstep/service/TCityService.java package com.bbsstep.service; import com.bbsstep.po.TCity; public interface TCityService { TCity getLoationByName(String cityName) throws Exception; } <file_sep>/cishilogin/src/com/bbsstep/service/TActiveServiceImpl.java package com.bbsstep.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.bbsstep.dao.TActiveMapper; import com.bbsstep.po.TActive; @Service public class TActiveServiceImpl implements TActiveService{ @Autowired private TActiveMapper mapper; @Override public List<TActive> getActivesByCity(String cityName) throws Exception { return mapper.getActivesByCity(cityName); } }
1f85f4a67a2a1d36ea6fe4bca52273a5f72782ec
[ "Java" ]
8
Java
risclxm/cishilogin
fe31e67e666af939c3919f4c6631686688cdcd9d
0c5886c1f6c4b35a4622c0707727a324ecd847e3
refs/heads/master
<repo_name>skyfox93/looping-break-gets-prework<file_sep>/levitation_quiz.rb def levitation_quiz puts "What is the spell that enacts levitation?" loop do answer=gets.chomp break if answer=="Wingardium Leviosa" end puts "You passed the quiz!" end
07c193ccb51061e1b1e820fcda621cee69564747
[ "Ruby" ]
1
Ruby
skyfox93/looping-break-gets-prework
4ad8536710ffbb0e6dd0a7aba31a0784f432a49c
aeb8feea4f77d4b8ab6a0914dedec4950340c1d4
refs/heads/master
<repo_name>mikaserova/course_work<file_sep>/course_app/ViewModel/ScheduleModel.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Collections.ObjectModel; using System.Threading.Tasks; namespace course_app.ViewModel { public class ScheduleModel : INotifyPropertyChanged { //private IOrderedQueryable<working_schedule> shifts; public List<working_schedule> shifts { get; set; } public ScheduleModel(List<working_schedule> shifts1) { this.shifts = shifts1; } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged([CallerMemberName]string prop = "") { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(prop)); } } } <file_sep>/course_app/Views/room_table.xaml.cs 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; namespace course_app.Views { /// <summary> /// Interaction logic for room_table.xaml /// </summary> public partial class room_table : UserControl { public room_table() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { add_room w = new add_room(); w.ShowDialog(); GL.main.MenuItem_Click_2(sender, e); } private void Button_Click_1(object sender, RoutedEventArgs e) { GL.main.BTN_Click(sender, e); } private void Button_Click_2(object sender, RoutedEventArgs e) { room r = (room)ent_table.SelectedValue; update_room w = new update_room(r); w.ShowDialog(); GL.main.MenuItem_Click_2(sender, e); } private void Button_Click_3(object sender, RoutedEventArgs e) { try { GL.db.room.Remove((room)ent_table.SelectedValue); GL.main.MenuItem_Click_2(sender, e); } catch(Exception x) { MessageBox.Show(x.Message); } } } } <file_sep>/course_app/Views/parking_spot_table.xaml.cs 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; namespace course_app.Views { /// <summary> /// Interaction logic for parking_spot_table.xaml /// </summary> public partial class parking_spot_table : UserControl { public parking_spot_table() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { add_parking_spot w = new add_parking_spot(); w.ShowDialog(); GL.main.MenuItem_Click_4(sender, e); } private void Button_Click_2(object sender, RoutedEventArgs e) { update_parking_spot w = new update_parking_spot((parking_spot)ent_table.SelectedValue); w.ShowDialog(); GL.main.MenuItem_Click_4(sender, e); } private void Button_Click_3(object sender, RoutedEventArgs e) { GL.db.parking_spot.Remove((parking_spot)ent_table.SelectedValue); GL.main.MenuItem_Click_4(sender, e); } private void Button_Click_1(object sender, RoutedEventArgs e) { GL.main.parking_t(sender, e); } private void What_search_SelectionChanged(object sender, SelectionChangedEventArgs e) { if ((string)what_search.SelectedValue == "Type") { text_search.Visibility = Visibility.Collapsed; box_search.Visibility = Visibility.Visible; box1_search.Visibility = Visibility.Collapsed; } else if ((string)what_search.SelectedValue == "Number") { text_search.Visibility = Visibility.Visible; box_search.Visibility = Visibility.Collapsed; box1_search.Visibility = Visibility.Collapsed; } else { text_search.Visibility = Visibility.Collapsed; box_search.Visibility = Visibility.Collapsed; box1_search.Visibility = Visibility.Visible; } } private void Button_Click_4(object sender, RoutedEventArgs e) { List<parking_spot> spots = new List<parking_spot>(); if ((string)what_search.SelectedValue == "Type") { parking_type t = (parking_type)box_search.SelectedValue; spots = GL.db.parking_spot.Where(i => i.type_id == t.parking_type_id).ToList(); } else if ((string)what_search.SelectedValue == "Number") { spots = GL.db.parking_spot.Where(i => i.number == text_search.Text).ToList(); } else if ((string)what_search.SelectedValue == "Reservation") { reservation r = (reservation)box1_search.SelectedValue; spots = GL.db.parking_spot.Where(i => i.reservation_id == r.reservation_id).ToList(); } search_list.ItemsSource = spots; if (spots.Count == 0) { MessageBox.Show("No item found!"); } } private void Button_Click_5(object sender, RoutedEventArgs e) { what_search.SelectedValue = null; box_search.SelectedValue = null; box_search.Visibility = Visibility.Visible; search_list.ItemsSource = null; } } } <file_sep>/course_app/Views/add_room.xaml.cs 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.Shapes; using course_app.ViewModel; namespace course_app.Views { /// <summary> /// Interaction logic for add_room.xaml /// </summary> public partial class add_room : Window { public add_room() { InitializeComponent(); DataContext = new RoomModel(); } private void Button_Click(object sender, RoutedEventArgs e) { try { if (t1.Text.Length < 1) { MessageBox.Show("Please enter correct room number"); return; } if (t2.Text.Length < 1) { MessageBox.Show("Please enter correct room price"); return; } if (t3.SelectedIndex == -1) { MessageBox.Show("Please choose room type"); return; } room r = new room(); r.room_number = t1.Text; r.room_price = Convert.ToDecimal(t2.Text); r.room_type_id = ((room_type)t3.SelectedValue).room_type_id; r.room_description = t4.Text; GL.db.room.Add(r); GL.db.SaveChanges(); this.Close(); } catch(Exception) { MessageBox.Show("Please enter correct values"); return; } } } } <file_sep>/course_app/GL.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace course_app { public static class GL { public static int permission_level; public static hotel_newEntities db = new hotel_newEntities(); public static int cred_id; public static MainWindow main; public static Login_window login_Window; public static reservation R; } } <file_sep>/course_app/Views/Emp_pos.xaml.cs 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; namespace course_app.Views { /// <summary> /// Interaction logic for Emp_pos.xaml /// </summary> public partial class Emp_pos : UserControl { public Emp_pos() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { //add Add_position w = new Add_position(); w.ShowDialog(); } private void Button_Click_1(object sender, RoutedEventArgs e) { UpdatePosition w = new UpdatePosition((employee_position)p_table.SelectedValue); w.ShowDialog(); GL.main.MenuItem_Click(sender, e); } private void Button_Click_2(object sender, RoutedEventArgs e) { try { employee_position p = (employee_position)p_table.SelectedValue; GL.db.employee_position.Remove(p); GL.db.SaveChanges(); GL.main.MenuItem_Click(sender, e); }catch(Exception x) { MessageBox.Show(x.Message); } } } } <file_sep>/course_app/Views/client_type.xaml.cs 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; namespace course_app.Views { /// <summary> /// Interaction logic for client_type.xaml /// </summary> public partial class client_types : UserControl { bool isAdd { get; set; } client_type t { get; set; } public client_types() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { if (isAdd) { t = new client_type(); t.client_type_name = t1.Text; t.discount = Convert.ToInt32(t5.Text); GL.db.client_type.Add(t); } else { t.client_type_name = t1.Text; t.discount = Convert.ToInt32(t5.Text); GL.db.Entry(t).State = System.Data.Entity.EntityState.Modified; } GL.db.SaveChanges(); panel.Visibility = Visibility.Hidden; GL.main.MenuItem_Click_6(sender, e); } private void Button_Click_1(object sender, RoutedEventArgs e) { panel.Visibility = Visibility.Visible; isAdd = true; } private void Button_Click_2(object sender, RoutedEventArgs e) { panel.Visibility = Visibility.Visible; isAdd = false; client_type p = ((client_type)table.SelectedValue); t = GL.db.client_type.Where(i => i.client_type_id == p.client_type_id).FirstOrDefault(); t1.Text = t.client_type_name; t5.Text = Convert.ToString(t.discount); } private void Button_Click_3(object sender, RoutedEventArgs e) { GL.db.client_type.Remove((client_type)table.SelectedValue); GL.db.SaveChanges(); } } } <file_sep>/course_app/Views/update_provided.xaml.cs 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.Shapes; namespace course_app.Views { /// <summary> /// Interaction logic for update_provided.xaml /// </summary> public partial class update_provided : Window { service_request t; public update_provided(service_request s) { InitializeComponent(); DataContext = new ViewModel.AddProvidedModel(); t1.SelectedValue = s.reservation; t2.SelectedValue = s.additional_service; emp_list.SelectedValue = s.employee; pay_time.Value = s.service_provided_time; amou.Value = (byte)s.amount; t = s; } private void Button_Click(object sender, RoutedEventArgs e) { t.reservation = (reservation)t1.SelectedValue; t.additional_service = (additional_service)t2.SelectedValue; t.employee = (employee)emp_list.SelectedValue; t.service_provided_time = pay_time.Value; t.amount = (int)amou.Value; GL.db.Entry(t).State = System.Data.Entity.EntityState.Modified; GL.db.SaveChanges(); this.Close(); } } } <file_sep>/course_app/Views/add_client.xaml.cs 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.Shapes; namespace course_app.Views { /// <summary> /// Interaction logic for add_client.xaml /// </summary> public partial class add_client : Window { public add_client() { InitializeComponent(); DataContext = new course_app.ViewModel.CleaningModel(); } private void Button_Click(object sender, RoutedEventArgs e) { client c = new client(); c.client_first_name = f_n.Text; c.client_middle_name = m_n.Text; c.client_last_name = l_n.Text; c.client_email = e_n.Text; c.client_passport_serial_number = pas_n.Text; c.client_phone_number = ph_n.Text; c.client_notes = note.Text; c.client_type_id = ((client_type)pos_n.SelectedValue).client_type_id; GL.db.client.Add(c); GL.db.SaveChanges(); this.Close(); } } } <file_sep>/course_app/ViewModel/PositionModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace course_app.ViewModel { class PositionModel { public List<employee_position> positions { get; set; } public PositionModel() { this.positions = GL.db.employee_position.ToList(); } } } <file_sep>/course_app/ViewModel/currPaymentModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace course_app.ViewModel { class currPaymentModel { public List<payment> payments { get; set; } public double sum {get;set;} public double paid { get; set; } public double left { get; set; } public reservation res { get; set; } public currPaymentModel(reservation r) { res = r; payments = r.payment.ToList(); double s = 0; List<service_request> sr = r.service_request.ToList(); foreach( service_request i in sr) { s += (double)i.additional_service.service_price * i.amount; } TimeSpan x = r.check_out_date - r.check_in_date; s += (double)r.room.room_price * x.Days; List<parking_spot> ps= r.parking_spot.ToList(); foreach( parking_spot i in ps) { s+=(double)i.parking_type.price_per_day* x.Days; } s *= (1 - r.client.client_type.discount / 100.0); sum = s; paid = 0; foreach(payment i in payments) { paid += (double)i.payment_sum; } left = sum - paid; } } } <file_sep>/course_app/ViewModel/PersCleanModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace course_app.ViewModel { class PersCleanModel { public List<cleaning_schedule> cl_shifts { get; set; } public PersCleanModel() { credential c = GL.db.credential.Where(i => i.credential_id == GL.cred_id).FirstOrDefault(); cl_shifts = GL.db.cleaning_schedule.Where(i => i.employee_id == c.employee_id).ToList(); } } } <file_sep>/course_app/Views/reservations.xaml.cs 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; namespace course_app.Views { /// <summary> /// Interaction logic for reservation.xaml /// </summary> public partial class reservations : UserControl { public reservations() { InitializeComponent(); } private void What_search_SelectionChanged(object sender, SelectionChangedEventArgs e) {/* list_fields.Add("Check in date"); list_fields.Add("Check out date"); list_fields.Add("Check in date and time"); list_fields.Add("Check out date and time"); list_fields.Add("Check in and check out dates"); list_fields.Add("Reservation number"); list_fields.Add("Client"); list_fields.Add("Room"); list_fields.Add("Employee"); */ if((string)what_search.SelectedValue== "Check in date") { checkin_date.Visibility = Visibility.Visible; checkout_date.Visibility = Visibility.Collapsed; } else if ((string)what_search.SelectedValue == "Check out date") { checkin_date.Visibility = Visibility.Collapsed; checkout_date.Visibility = Visibility.Visible; } } private void Button_Click(object sender, RoutedEventArgs e) { List<reservation> reserv = new List<reservation>(); if ((string)what_search.SelectedValue == "Check in date") { if (checkin_date.SelectedDate == null) { MessageBox.Show("Please Select Value"); return; } DateTime t=(DateTime)checkin_date.SelectedDate; reserv = GL.db.reservation.Where(i => i.check_in_date.Year == t.Year&& i.check_in_date.Month == t.Month&& i.check_in_date.Day == t.Day).ToList(); } else if ((string)what_search.SelectedValue == "Check out date") { if (checkout_date.SelectedDate == null) { MessageBox.Show("Please Select Value"); return; } DateTime t = (DateTime)checkout_date.SelectedDate; reserv = GL.db.reservation.Where(i => i.check_out_date.Year == t.Year && i.check_out_date.Month == t.Month && i.check_out_date.Day == t.Day).ToList(); } res_list.ItemsSource = reserv; if (reserv.Count == 0) { MessageBox.Show("No items found!"); } } private void Button_Click_1(object sender, RoutedEventArgs e) { add_reservation w = new add_reservation(); w.ShowDialog(); GL.main.MenuItem_Click_8(sender, e); } private void Button_Click_2(object sender, RoutedEventArgs e) { if ((reservation)res_list.SelectedValue != null) { add_reservation w = new add_reservation((reservation)res_list.SelectedValue); w.ShowDialog(); GL.main.MenuItem_Click_8(sender, e); } else { MessageBox.Show("Please, select the row"); } } private void Button_Click_3(object sender, RoutedEventArgs e) { try { GL.db.reservation.Remove((reservation)res_list.SelectedValue); GL.db.SaveChanges(); GL.main.MenuItem_Click_8(sender, e); } catch(Exception x) { MessageBox.Show(x.Message); } } private void MenuItem_Click(object sender, RoutedEventArgs e) { if ((reservation)res_list.SelectedValue != null) { add_payment w = new add_payment((reservation)res_list.SelectedValue); w.ShowDialog(); GL.main.MenuItem_Click_8(sender, e); } else { MessageBox.Show("Please, select the row"); } } private void MenuItem_Click1(object sender, RoutedEventArgs e) { GL.main.DataContext = new ViewModel.currPaymentModel((reservation)res_list.SelectedValue); } private void Button_Click_4(object sender, RoutedEventArgs e) { ViewModel.ReservationModel DataContext = new ViewModel.ReservationModel(); what_search.SelectedIndex = -1; checkin_date.SelectedDate = null; checkout_date.SelectedDate = null; checkin_date.Visibility = Visibility.Collapsed; checkout_date.Visibility = Visibility.Collapsed; res_list.ItemsSource = DataContext.reservations; } private void MenuItem_Click2(object sender, RoutedEventArgs e) { GL.main.DataContext = new ViewModel.ProvidedServices((reservation)res_list.SelectedValue); GL.R = (reservation)res_list.SelectedValue; } } } <file_sep>/course_app/ViewModel/AddREservationModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace course_app.ViewModel { class AddREservationModel {public List<client> clients { get; set; } public List<room> rooms { get; set; } public List<room_type> types { get; set; } public AddREservationModel() { clients = GL.db.client.ToList(); rooms = GL.db.room.ToList(); types = GL.db.room_type.ToList(); } } } <file_sep>/course_app/Views/Add_room_type.xaml.cs 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.Shapes; namespace course_app.Views { /// <summary> /// Interaction logic for Add_room_type.xaml /// </summary> public partial class Add_room_type : Window { public Add_room_type() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { room_type t = new room_type(); t.room_type_name = t1.Text; t.room_type_description = t4.Text; GL.db.room_type.Add(t); GL.db.SaveChanges(); this.Close(); } } } <file_sep>/course_app/Views/AllPayments.xaml.cs 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; namespace course_app.Views { /// <summary> /// Interaction logic for AllPayments.xaml /// </summary> public partial class AllPayments : UserControl { public AllPayments() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { add_payment w = new add_payment(); w.ShowDialog(); GL.main.MenuItem_Click_91(sender, e); } private void Button_Click_1(object sender, RoutedEventArgs e) { add_payment w = new add_payment((payment)pay_list.SelectedValue); w.ShowDialog(); GL.main.MenuItem_Click_91(sender, e); } private void Button_Click_2(object sender, RoutedEventArgs e) { GL.db.payment.Remove((payment)pay_list.SelectedValue); GL.db.SaveChanges(); GL.main.MenuItem_Click_91(sender, e); } } } <file_sep>/course_app/Views/update_room.xaml.cs 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.Shapes; namespace course_app.Views { /// <summary> /// Interaction logic for update_room.xaml /// </summary> public partial class update_room : Window {room temp { get; set; } public update_room(room t) { InitializeComponent(); t1.Text = t.room_number; t2.Text = Convert.ToString(t.room_price); t3.SelectedValue = t.room_type; t4.Text = t.room_description; temp = GL.db.room.Where(r => r.room_id == t.room_id).FirstOrDefault(); DataContext = new course_app.ViewModel.RoomModel(); } private void Button_Click(object sender, RoutedEventArgs e) { try { if (t1.Text.Length < 1) { MessageBox.Show("Please enter correct room number"); return; } if (t2.Text.Length < 1) { MessageBox.Show("Please enter correct room price"); return; } if (t3.SelectedIndex == -1) { MessageBox.Show("Please choose room type"); return; } room temp1 = new room(); temp1.room_number = t1.Text; temp1.room_price = Convert.ToDecimal(t2.Text); temp1.room_type_id = ((room_type)t3.SelectedValue).room_type_id; temp1.room_description = t4.Text; if (temp1.room_number != temp.room_number || temp1.room_description != temp.room_description || temp1.room_price != temp.room_price || temp1.room_type_id != temp.room_type_id) { temp.room_number = temp1.room_number; temp.room_price = temp1.room_price; temp.room_type_id = temp1.room_type_id; temp.room_description = temp1.room_description; GL.db.Entry(temp).State = System.Data.Entity.EntityState.Modified; GL.db.SaveChanges(); } this.Close(); } catch( Exception x) { MessageBox.Show(x.Message); } } } } <file_sep>/course_app/ViewModel/PaymentMOdel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace course_app.ViewModel { class PaymentMOdel { public List<payment> payments { get; set; } public PaymentMOdel() { payments = GL.db.payment.ToList(); } } } <file_sep>/course_app/ViewModel/AddProvidedModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace course_app.ViewModel { class AddProvidedModel {public List<reservation> reservations { get; set; } public List<employee> employees { get; set; } public List<additional_service> services { get; set; } public AddProvidedModel() { reservations = GL.db.reservation.ToList(); employees = GL.db.employee.ToList(); services = GL.db.additional_service.ToList(); } } } <file_sep>/course_app/Views/Add.xaml.cs 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.Shapes; using System.Data.SqlClient; namespace course_app.Views { /// <summary> /// Interaction logic for Add.xaml /// </summary> public partial class Add : Window { public class DataObject { public List<employee_position> positions { get; set; } public DataObject() { positions = GL.db.employee_position.ToList(); } } public Add() { InitializeComponent(); DataContext = new DataObject(); } private void Button_Click(object sender, RoutedEventArgs e) { try { if (login.Text.Length < 4) { throw new ArgumentException("Please enter login with the length more than 4 characters!"); } if (pass_box1.Password != <PASSWORD>.Password) { throw new ArgumentException("Passwords in 1st and 2nd line are different!"); } int does_exist = GL.db.credential.Where(i => i.username == login.Text).Count(); if (does_exist != 0) { throw new ArgumentException("User with such login already exists"); } employee p = new employee { employye_first_name = f_n.Text, employye_middle_name = m_n.Text, employee_last_name = l_n.Text, employee_phone_number = ph_n.Text, employee_passport_serial_number = pas_n.Text, employee_email = e_n.Text, position_id = ((employee_position)pos_n.SelectedValue).position_id, tax_payer_id = t_n.Text, wage = (decimal)Convert.ToDouble(w_n.Text) }; credential cr = new credential { employee_id = p.employee_id, username = login.Text, password = <PASSWORD> }; try { GL.db.employee.Add(p); GL.db.SaveChanges(); GL.db.credential.Add(cr); GL.main.Emp_add_Click(GL.main, e); } catch(SqlException) { throw new ArgumentException("Unexpected error trying to write to the database"); } this.Close(); } catch(Exception ex) { MessageBox.Show(ex.Message); } } } } <file_sep>/course_app/ViewModel/ClientModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace course_app.ViewModel { class ClientModel { public List<client> clients { get; set; } public List<client_type> types { get; set; } public List<reservation> res_list { get; set; } public List<string> list_fields { get; set; } public ClientModel() { clients = GL.db.client.ToList(); types = GL.db.client_type.ToList(); list_fields = new List<string>(); list_fields.Add("First name"); list_fields.Add("Middle name"); list_fields.Add("Last name"); list_fields.Add("Phone"); list_fields.Add("Email"); list_fields.Add("Passport"); list_fields.Add("Type"); } } } <file_sep>/course_app/Views/providedS.xaml.cs 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; namespace course_app.Views { /// <summary> /// Interaction logic for providedS.xaml /// </summary> public partial class providedS : UserControl { public providedS() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { try { reservation r = ((service_request)serv_list.SelectedValue).reservation; GL.db.service_request.Remove((service_request)serv_list.SelectedValue); GL.db.SaveChanges(); GL.main.DataContext = new ViewModel.ProvidedServices(r); } catch(Exception x) { MessageBox.Show(x.Message); } } private void Button_Click_1(object sender, RoutedEventArgs e) { GL.main.DataContext = new ViewModel.ReservationModel(); } private void Button_Click_2(object sender, RoutedEventArgs e) { try { add_provided w = new add_provided(); w.ShowDialog(); GL.main.DataContext = new ViewModel.ProvidedServices(GL.R); }catch(Exception x) { MessageBox.Show(x.Message); } } private void Button_Click_3(object sender, RoutedEventArgs e) { try { update_provided w = new update_provided((service_request)serv_list.SelectedValue); w.ShowDialog(); GL.main.DataContext = new ViewModel.ProvidedServices(GL.R); } catch(Exception x) { MessageBox.Show(x.Message); } } } } <file_sep>/course_app/Login_window.xaml.cs 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.Shapes; namespace course_app { /// <summary> /// Interaction logic for Login_window.xaml /// </summary> public partial class Login_window : Window { hotel_newEntities db; public Login_window() { InitializeComponent(); try { db = new hotel_newEntities(); } catch(Exception ) { MessageBox.Show("Can`t connect to database"); } GL.login_Window = this; } private void Enter_button_Click(object sender, RoutedEventArgs e) { string log = login_box.Text; string pass = <PASSWORD>; var user = db.credential.Where(u => u.username == log).FirstOrDefault(); if(user!=null&& pass == user.password) { MainWindow main = new MainWindow(user.credential_id); main.WindowState = System.Windows.WindowState.Maximized; main.Closed += FooClosed; main.Show(); GL.main = main; this.Hide(); } else { MessageBox.Show("Wrong email or password. Please try again"); } } public void FooClosed(object sender, System.EventArgs e) { //This gets fired off GL.main = null; this.Close(); } } } <file_sep>/course_app/Views/room_types.xaml.cs 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; namespace course_app.Views { /// <summary> /// Interaction logic for room_types.xaml /// </summary> public partial class room_types : UserControl { public room_types() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { GL.main.MenuItem_Click_2(sender, e); } private void Button_Click_1(object sender, RoutedEventArgs e) { Add_room_type w = new Add_room_type(); w.ShowDialog(); GL.main.BTN_Click(sender, e); } private void Button_Click_2(object sender, RoutedEventArgs e) { update_room_type w = new update_room_type((room_type)table.SelectedValue); w.ShowDialog(); GL.main.BTN_Click(sender, e); } private void Button_Click_3(object sender, RoutedEventArgs e) { GL.db.room_type.Remove((room_type)table.SelectedValue); GL.db.SaveChanges(); GL.main.BTN_Click(sender, e); } } } <file_sep>/course_app/ViewModel/GeneralSchedule.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Collections.ObjectModel; using System.Threading.Tasks; using System.Windows.Input; namespace course_app.ViewModel { class GeneralSchedule : INotifyPropertyChanged { public ObservableCollection<emploee_workSchedule> Shifts { get; set; } public List<employee> employees { get; set; } //public int del_id { get; set; } //private ICommand _deleteCommand; //public ICommand DeleteCommand //{ // get // { // if (_deleteCommand == null) // { // _deleteCommand = new RelayCommand( // param => this.Delete(), // param => this.CanDelete() // ); // } // return _deleteCommand; // } //} //private bool CanDelete() //{ // return true; //} //private void Delete() //{ //} public GeneralSchedule(ObservableCollection<emploee_workSchedule> sd) { this.Shifts = sd; employees = GL.db.employee.ToList(); } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged([CallerMemberName]string prop = "") { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(prop)); } } } <file_sep>/course_app/Views/employees.xaml.cs 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; namespace course_app.Views { /// <summary> /// Interaction logic for AddNewEmployee.xaml /// </summary> public partial class AddNewEmployee : UserControl { public AddNewEmployee() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { Add addw = new Add(); addw.ShowDialog(); GL.main.Emp_add_Click(sender, e); } private void Button_Click_1(object sender, RoutedEventArgs e) { employee t = (employee)emp_list.SelectedValue; employee temp = GL.db.employee.Where(w => w.employee_id == t.employee_id).FirstOrDefault(); GL.db.employee.Remove(temp); GL.db.SaveChanges(); GL.main.Emp_add_Click(GL.main, e); } private void Button_Click_2(object sender, RoutedEventArgs e) { employee t = (employee)emp_list.SelectedValue; if (t != null) { Update updw = new Update(t); updw.ShowDialog(); GL.main.Emp_add_Click(sender, e); } else { MessageBox.Show("You haven`t chosen any row!"); } } } } <file_sep>/course_app/Views/update_client.xaml.cs 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.Shapes; namespace course_app.Views { /// <summary> /// Interaction logic for update_client.xaml /// </summary> public partial class update_client : Window { client c { get; set; } public update_client( client c1) { InitializeComponent(); c = GL.db.client.Where(i => i.client_id == c1.client_id).FirstOrDefault(); f_n.Text = c.client_first_name ; m_n.Text= c.client_middle_name ; l_n.Text= c.client_last_name ; e_n.Text = c.client_email; pas_n.Text= c.client_passport_serial_number ; ph_n.Text = c.client_phone_number ; note.Text = c.client_notes ; client_type ct = GL.db.client_type.Where(i => i.client_type_id == c.client_type_id).FirstOrDefault(); pos_n.SelectedValue = ct; } private void Button_Click(object sender, RoutedEventArgs e) { c.client_first_name = f_n.Text; c.client_middle_name = m_n.Text; c.client_last_name = l_n.Text; c.client_email = e_n.Text; c.client_passport_serial_number = pas_n.Text; c.client_phone_number = ph_n.Text; c.client_notes = note.Text; c.client_type_id = ((client_type)pos_n.SelectedValue).client_type_id; GL.db.Entry(c).State = System.Data.Entity.EntityState.Modified; GL.db.SaveChanges(); this.Close(); } } } <file_sep>/course_app/Views/cleaning.xaml.cs 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; namespace course_app.Views { /// <summary> /// Interaction logic for cleaning.xaml /// </summary> public partial class cleaning : UserControl { bool c; cleaning_schedule temp; public cleaning() { InitializeComponent(); c = false; } private void Delete_button_Click(object sender, RoutedEventArgs e) { try { GL.db.cleaning_schedule.Remove((cleaning_schedule)shift_table.SelectedValue); GL.db.SaveChanges(); GL.main.MenuItem_Click_5(sender, e); } catch (Exception ex) { MessageBox.Show("Please select cleaning schedule record"); } } private void Add_button_Click(object sender, RoutedEventArgs e) { try { cleaning_schedule c = new cleaning_schedule(); c.cleaning_start_time = Convert.ToDateTime(s_dt.Text); c.cleaning_end_time = Convert.ToDateTime(e_dt.Text); c.room_id = ((room)room_list.SelectedValue).room_id; c.employee_id = ((employee)emp_list.SelectedValue).employee_id; GL.db.cleaning_schedule.Add(c); GL.db.SaveChanges(); GL.main.MenuItem_Click_5(sender, e); } catch (Exception ex) { MessageBox.Show("Please enter all valid values"); } } private void Upd_button_Click(object sender, RoutedEventArgs e) { try { if (c) { temp.cleaning_start_time = Convert.ToDateTime(upd_s_dt.Text); temp.cleaning_end_time = Convert.ToDateTime(upd_e_dt.Text); temp.employee_id = ((employee)upd_emp_list.SelectedValue).employee_id; temp.room_id = ((room)upd_room_list.SelectedValue).room_id; GL.db.Entry(temp).State = System.Data.Entity.EntityState.Modified; GL.db.SaveChanges(); GL.main.MenuItem_Click_5(sender, e); } else { temp = GL.db.cleaning_schedule.Where(i => i.cleaning_schedule_id == ((cleaning_schedule)shift_table.SelectedValue).cleaning_schedule_id).FirstOrDefault(); upd_room_list.SelectedValue = ((cleaning_schedule)shift_table.SelectedValue).room; upd_emp_list.SelectedValue = ((cleaning_schedule)shift_table.SelectedValue).employee; upd_s_dt.Text = Convert.ToString(((cleaning_schedule)shift_table.SelectedValue).cleaning_start_time); upd_e_dt.Text = Convert.ToString(((cleaning_schedule)shift_table.SelectedValue).cleaning_end_time); c = !c; } } catch (Exception ex) { MessageBox.Show("Please enter all valid values"); } } } } <file_sep>/course_app/Views/add_parking_spot.xaml.cs 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.Shapes; namespace course_app.Views { /// <summary> /// Interaction logic for add_parking_spot.xaml /// </summary> public partial class add_parking_spot : Window { public add_parking_spot() { InitializeComponent(); DataContext = new course_app.ViewModel.ParkingSpotsModel(); } private void Button_Click(object sender, RoutedEventArgs e) { int exists = GL.db.parking_spot.Where(t => t.number == t1.Text).Count(); if (exists != 0) { MessageBox.Show("Parking Spot with such number already exists"); return; } if (t1.Text.Length < 2) { MessageBox.Show("Please, enter correct parking spot number"); return; } if (t2.SelectedIndex == -1) { MessageBox.Show("Please, choose type of parking spot"); return; } parking_spot s = new parking_spot(); s.number = t1.Text; s.type_id = ((parking_type)t2.SelectedValue).parking_type_id; if (t3.SelectedIndex != -1) { s.reservation_id = ((reservation)t3.SelectedValue).reservation_id; } GL.db.parking_spot.Add(s); GL.db.SaveChanges(); GL.main.MenuItem_Click_4(sender, e); this.Close(); } } } <file_sep>/course_app/ViewModel/EntranceTable.cs using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Collections.ObjectModel; using System.Threading.Tasks; using System.Windows.Input; using System.ComponentModel; using System.Collections.Generic; namespace course_app.ViewModel { class EntranceTable: INotifyPropertyChanged { public List<entrance_log> entrances { get; set; } public List<string> Status { get; set; } public List<parking_spot> spots { get; set; } public EntranceTable() { this.entrances = GL.db.entrance_log.ToList(); this.spots = GL.db.parking_spot.ToList(); this.Status = new List<string>(); this.Status.Add("in"); this.Status.Add("out"); } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged([CallerMemberName]string prop = "") { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(prop)); } } } <file_sep>/course_app/ViewModel/ServiceModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace course_app.ViewModel { class ServicesModel { public List<additional_service> services { get; set; } public ServicesModel() { services = GL.db.additional_service.ToList(); } } } <file_sep>/course_app/ViewModel/RoomTypeModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace course_app.ViewModel { class RoomTypeModel { public List<room_type> types { get; set; } public RoomTypeModel() { types = GL.db.room_type.ToList(); } } } <file_sep>/course_app/ViewModel/ReservationModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace course_app.ViewModel { class ReservationModel { public List<string> list_fields { get; set; } public List<reservation> reservations { get; set; } public ReservationModel() { list_fields = new List<string>(); list_fields.Add("Check in date"); list_fields.Add("Check out date"); reservations = GL.db.reservation.ToList(); } } } <file_sep>/course_app/Views/position_info.xaml.cs 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.Shapes; namespace course_app.Views { /// <summary> /// Interaction logic for position_info.xaml /// </summary> public partial class position_info : Window { public position_info() { InitializeComponent(); } public position_info( employee_position p) { InitializeComponent(); l11.Content = p.position_name; l212.Content = p.wage_lower_bound; l222.Content = p.wage_upper_bound; desc.Text = p.position_description; } private void Button_Click(object sender, RoutedEventArgs e) { this.Close(); } } } <file_sep>/course_app/Views/personal_schedule.xaml.cs 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; namespace course_app.Views { /// <summary> /// Interaction logic for personal_schedule.xaml /// </summary> public partial class personal_schedule : UserControl { public personal_schedule() { InitializeComponent(); } void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e) { e.Row.Header = (e.Row.GetIndex() + 1).ToString(); } private void Button_Click(object sender, RoutedEventArgs e) { GL.main.MenuItem_Click_1(sender, e); } } } <file_sep>/course_app/ViewModel/AddpaymentModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace course_app.ViewModel { class AddpaymentModel {public List<reservation> reservations { get; set; } public List<payment_type> types { get; set; } public AddpaymentModel() { reservations = GL.db.reservation.ToList(); types = GL.db.payment_type.ToList(); } } } <file_sep>/course_app/Views/entrance.xaml.cs 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; namespace course_app.Views { /// <summary> /// Interaction logic for entrance.xaml /// </summary> public partial class entrance : UserControl { public entrance() { InitializeComponent(); log_time_in.IsEnabled = false; log_time_in.Text = "Time is chosen automaticaly"; } private void Button_Click(object sender, RoutedEventArgs e) { if (spot.SelectedIndex == -1) { MessageBox.Show("Please choose parking spot"); return; } if (stat.SelectedIndex == -1) { MessageBox.Show("Please choose status"); return; } entrance_log temp = new entrance_log(); log_time_in.Value = DateTime.Now; temp.log_time =(DateTime) log_time_in.Value; temp.status = (string)stat.SelectedValue; parking_spot ps = (parking_spot)spot.SelectedValue; temp.parking_spot_id = ps.parking_spot_id; GL.db.entrance_log.Add(temp); GL.db.SaveChanges(); GL.main.Ent_log_Click(GL.main, e); } private void Button_Click_1(object sender, RoutedEventArgs e) { entrance_log t=(entrance_log )ent_table.SelectedValue; GL.db.entrance_log.Remove(t); GL.db.SaveChanges(); GL.main.Ent_log_Click(GL.main, e); } } } <file_sep>/course_app/ViewModel/ClientTypeModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace course_app.ViewModel { class ClientTypeModel { public List<client_type> types { get; set; } public ClientTypeModel() { types = GL.db.client_type.ToList(); } } } <file_sep>/course_app/ViewModel/RoomModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace course_app.ViewModel { class RoomModel { public List<room> rooms{get;set;} public List<room_type> types { get; set; } public RoomModel() { rooms = GL.db.room.ToList(); types = GL.db.room_type.ToList(); } } } <file_sep>/course_app/Views/parking_types.xaml.cs 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; namespace course_app.Views { /// <summary> /// Interaction logic for parking_types.xaml /// </summary> public partial class parking_types : UserControl { bool isAdd { get; set; } parking_type t { get; set; } public parking_types() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { if (isAdd) { t = new parking_type(); t.name = t1.Text; t.price_per_day = Convert.ToDecimal(t2.Text); t.width = Convert.ToDecimal(t3.Text); t.length = Convert.ToDecimal(t4.Text); t.weight = Convert.ToDecimal(t5.Text); GL.db.parking_type.Add(t); } else { t.name = t1.Text; t.price_per_day = Convert.ToDecimal(t2.Text); t.width = Convert.ToDecimal(t3.Text); t.length = Convert.ToDecimal(t4.Text); t.weight = Convert.ToDecimal(t5.Text); GL.db.Entry(t).State = System.Data.Entity.EntityState.Modified; } GL.db.SaveChanges(); panel.Visibility = Visibility.Hidden; GL.main.parking_t(sender, e); } private void Button_Click_1(object sender, RoutedEventArgs e) { panel.Visibility = Visibility.Visible; isAdd = true; } private void Button_Click_2(object sender, RoutedEventArgs e) { panel.Visibility = Visibility.Visible; isAdd = false; t = GL.db.parking_type.Where(i => i.parking_type_id == ((parking_type)table.SelectedValue).parking_type_id).FirstOrDefault(); t1.Text = t.name; t2.Text = Convert.ToString(t.price_per_day); t3.Text = Convert.ToString(t.width); t4.Text = Convert.ToString(t.length); t5.Text = Convert.ToString(t.weight); } private void Button_Click_3(object sender, RoutedEventArgs e) { GL.db.parking_type.Remove((parking_type)table.SelectedValue); GL.db.SaveChanges(); GL.main.parking_t(sender, e); } private void Button_Click_4(object sender, RoutedEventArgs e) { GL.main.MenuItem_Click_4(sender, e); } } } <file_sep>/course_app/Views/add_payment.xaml.cs 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.Shapes; namespace course_app.Views { /// <summary> /// Interaction logic for add_payment.xaml /// </summary> public partial class add_payment : Window { bool t = false; reservation re; payment payment; bool upd = false; public add_payment() { InitializeComponent(); DataContext = new ViewModel.AddpaymentModel(); pay_time.IsEnabled = false; pay_time.Text = "Time is chosen automaticaly"; pay_time.Value = DateTime.Now; } public add_payment(reservation r) { t = true; re = r; DataContext = new ViewModel.AddpaymentModel(); InitializeComponent(); t1.SelectedValue = r; pay_time.IsEnabled = false; pay_time.Text = "Time is chosen automaticaly"; pay_time.Value = DateTime.Now; } public add_payment(payment pay) { upd = true; InitializeComponent(); DataContext = new ViewModel.AddpaymentModel(); t1.SelectedValue = pay.reservation; payment = pay; pay_time.IsEnabled = false; t2.Text = Convert.ToString(pay.payment_sum); t3.SelectedValue = pay.payment_type; pay_time.Value = DateTime.Now; } private void Button_Click(object sender, RoutedEventArgs e) { if (!upd) { pay_time.Value = DateTime.Now; payment p = new payment(); p.reservation_id = ((reservation)t1.SelectedValue).reservation_id; p.payment_date = DateTime.Now; p.payment_sum = Convert.ToDecimal(t2.Text); p.payment_type_id = ((payment_type)t3.SelectedValue).payment_type_id; GL.db.payment.Add(p); } else { payment p = GL.db.payment.Where(i => i.payment_id == payment.payment_id).FirstOrDefault(); p.reservation_id = ((reservation)t1.SelectedValue).reservation_id; p.payment_date = DateTime.Now; p.payment_sum = Convert.ToDecimal(t2.Text); p.payment_type_id = ((payment_type)t3.SelectedValue).payment_type_id; GL.db.Entry(p).State = System.Data.Entity.EntityState.Modified; } GL.db.SaveChanges(); if (t) { GL.main.DataContext = new ViewModel.currPaymentModel(re); } else { GL.main.MenuItem_Click_91(sender, e); } this.Close(); } } } <file_sep>/course_app/Views/services.xaml.cs 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; namespace course_app.Views { /// <summary> /// Interaction logic for services.xaml /// </summary> public partial class services : UserControl { bool isAdd { get; set; } additional_service t; public services() { InitializeComponent(); } private void Button_Click_1(object sender, RoutedEventArgs e) { panel.Visibility = Visibility.Visible; isAdd = true; } private void Button_Click(object sender, RoutedEventArgs e) { try { if (!isAdd) { t.service_name = t1.Text; t.service_price = Convert.ToDecimal(t2.Text); t.service_cost = Convert.ToDecimal(t3.Text); GL.db.Entry(t).State = System.Data.Entity.EntityState.Modified; } else { additional_service t = new additional_service(); t.service_name = t1.Text; t.service_price = Convert.ToDecimal(t2.Text); t.service_cost = Convert.ToDecimal(t3.Text); GL.db.additional_service.Add(t); } GL.db.SaveChanges(); panel.Visibility = Visibility.Hidden; GL.main.MenuItem_Click_3(sender, e); } catch(Exception x) { MessageBox.Show(x.Message); } } private void Button_Click_2(object sender, RoutedEventArgs e) { panel.Visibility = Visibility.Visible; isAdd = false; t = GL.db.additional_service.Where(i => i.additional_service_id == ((additional_service)table.SelectedValue).additional_service_id).FirstOrDefault(); t1.Text = t.service_name; t2.Text = t.service_price.ToString(); t3.Text = t.service_cost.ToString(); } private void Button_Click_3(object sender, RoutedEventArgs e) { try { GL.db.additional_service.Remove((additional_service)table.SelectedValue); GL.db.SaveChanges(); GL.main.MenuItem_Click_3(sender, e); }catch(Exception x) { MessageBox.Show(x.Message); } } } } <file_sep>/course_app/ViewModel/CleaningModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace course_app.ViewModel { class CleaningModel { public List<cleaning_schedule> cleanings { get; set; } public List<room> rooms { get; set; } public List<employee> employees { get; set; } public List<employee> employees1 { get; set; } public CleaningModel() { cleanings = GL.db.cleaning_schedule.ToList(); rooms= GL.db.room.ToList(); employees= GL.db.employee.ToList(); employees1 = GL.db.employee.Where(i => i.employee_position.position_name == "Maid").ToList(); } } } <file_sep>/course_app/Views/UpdatePosition.xaml.cs 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.Shapes; namespace course_app.Views { /// <summary> /// Interaction logic for Add_position.xaml /// </summary> public partial class UpdatePosition : Window { employee_position l { get; set; } public UpdatePosition(employee_position t) { InitializeComponent(); l11.Text = t.position_name; l212.Text = t.wage_lower_bound.ToString(); l222.Text = t.wage_upper_bound.ToString(); desc.Text = t.position_description; l = GL.db.employee_position.Where(i => i.position_id == t.position_id).FirstOrDefault(); } private void Button_Click(object sender, RoutedEventArgs e) { try { if (l11.Text.Length < 2) { MessageBox.Show("Please enter correct position name"); return; } if (l212.Text.Length < 1 || l222.Text.Length < 1) { MessageBox.Show("Please enter correct wage bounds"); return; } l.position_name = l11.Text; l.wage_lower_bound = Convert.ToDecimal(l212.Text); l.wage_upper_bound = Convert.ToDecimal(l222.Text); l.position_description = desc.Text; GL.db.Entry(l).State = System.Data.Entity.EntityState.Modified; GL.db.SaveChanges(); this.Close(); } catch (Exception) { MessageBox.Show("Please enter correct values"); } } } } <file_sep>/course_app/ViewModel/ParkingTypeModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace course_app.ViewModel { class ParkingTypeModel { public List<parking_type> types { get; set; } public ParkingTypeModel() { types = GL.db.parking_type.ToList(); } } } <file_sep>/course_app/emploee_workSchedule.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.CompilerServices; using System.ComponentModel; namespace course_app { public class emploee_workSchedule : INotifyPropertyChanged { public DateTime shift_end_time { get; set; } public DateTime shift_start_time { get; set; } public string employye_first_name { get; set; } public string employee_last_name { get; set; } public int w_id { get; set; } public emploee_workSchedule(DateTime shift_end_time, DateTime shift_start_time, string employye_first_name, string employee_last_name,int id) { this.shift_end_time = shift_end_time; this.shift_start_time = shift_start_time; this.employye_first_name = employye_first_name; this.employee_last_name = employee_last_name; this.w_id = id; } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged([CallerMemberName]string prop = "") { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(prop)); } } } <file_sep>/course_app/Views/update_parking_spot.xaml.cs 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.Shapes; namespace course_app.Views { /// <summary> /// Interaction logic for update_parking_spot.xaml /// </summary> public partial class update_parking_spot : Window { parking_spot s { get; set; } public update_parking_spot(parking_spot p ) { InitializeComponent(); DataContext = new course_app.ViewModel.ParkingSpotsModel(); t1.Text = p.number; t2.SelectedValue = p.parking_type; t3.SelectedValue = p.reservation; s = p; } private void Remove_reservation(object sender, RoutedEventArgs e) { t3.SelectedIndex = -1; } private void Button_Click(object sender, RoutedEventArgs e) { if (t1.Text.Length < 2) { MessageBox.Show("Please, enter correct parking spot number"); return; } if (t2.SelectedIndex == -1) { MessageBox.Show("Please, choose type of parking spot"); return; } parking_spot temp = GL.db.parking_spot.Where(t => t.parking_spot_id == s.parking_spot_id).FirstOrDefault(); temp.number = t1.Text; temp.type_id = ((parking_type)t2.SelectedValue).parking_type_id; if (t3.SelectedIndex != -1) { temp.reservation_id = ((reservation)t3.SelectedValue).reservation_id; } else { temp.reservation_id = null; } GL.db.Entry(temp).State = System.Data.Entity.EntityState.Modified; GL.db.SaveChanges(); GL.main.MenuItem_Click_4(sender, e); this.Close(); } } } <file_sep>/course_app/Views/update_room_type.xaml.cs 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.Shapes; namespace course_app.Views { /// <summary> /// Interaction logic for update_room_type.xaml /// </summary> public partial class update_room_type : Window { room_type l { get; set; } public update_room_type( room_type t) { InitializeComponent(); t1.Text = t.room_type_name; t4.Text = t.room_type_description; l = GL.db.room_type.Where(i => i.room_type_id == t.room_type_id).FirstOrDefault(); } private void Button_Click(object sender, RoutedEventArgs e) { if (l.room_type_name == t1.Text && l.room_type_description == t4.Text) this.Close(); else { l.room_type_description = t4.Text; l.room_type_name = t1.Text; GL.db.Entry(l).State = System.Data.Entity.EntityState.Modified; GL.db.SaveChanges(); this.Close(); } } } } <file_sep>/course_app/Views/Income.xaml.cs 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; namespace course_app.Views { /// <summary> /// Interaction logic for Income.xaml /// </summary> public partial class Income : UserControl { public class C1 { public string Name { get; set; } public double Money { get; set; } public double Possible { get; set; } } public double t; public List<C1> l1; public Income() { InitializeComponent(); double x = 0; double x1 = 0; double x2 = 0; int month = DateTime.Today.Month; List<reservation> res = GL.db.reservation.Where(i => i.check_in_date.Month == month).ToList(); foreach (reservation ad in res) { x = 0; var ad_serv = ad.service_request.ToList(); foreach (service_request s in ad_serv) { x += (double)s.additional_service.service_price * s.amount; } x1 += x * (1 - ad.client.client_type.discount / 100.0); x2 += x; } C1 a = new C1 { Name = "Services", Money = x1, Possible = x2 }; x2 = 0; x1 = 0; foreach (reservation ad in res) { x = 0; TimeSpan dif = ad.check_out_date - ad.check_in_date; List<parking_spot> parking = ad.parking_spot.ToList(); foreach (parking_spot s in parking) { x += (double)s.parking_type.price_per_day * dif.Days; } x1 += x * (1 - ad.client.client_type.discount / 100.0); x2 += x; } C1 b = new C1 { Name = "Parking", Money = x1, Possible = x2 }; x2 = 0; x1 = 0; foreach (reservation ad in res) { TimeSpan dif = ad.check_out_date - ad.check_in_date; x2 += (double)ad.room.room_price* dif.Days; x1 += (double)ad.room.room_price * dif.Days * (1 - ad.client.client_type.discount / 100.0); } C1 c = new C1 { Name = "Rooms", Money = x1, Possible = x2 }; l1 = new List<C1>(); l1.Add(a); l1.Add(b); l1.Add(c); double total = a.Money + b.Money + c.Money ; t = total; t1.Content = "Profit from services: \t" + a.Money.ToString("000000.00 \t") + (a.Money / total * 100).ToString("00.00 ") + "%"; t2.Content = "Profit from parking: \t" + b.Money.ToString("000000.00 \t") + (b.Money / total * 100).ToString("00.00 ") + "%"; t3.Content = "Profit from rooms: \t" + c.Money.ToString("000000.00 \t") + (c.Money / total * 100).ToString("00.00 ") + "%"; t4.Content = "Total: \t" + (total).ToString("00.00 "); double total1 = a.Possible + b.Possible + c.Possible; t5.Content = "Without Client discount"; t6.Content = "Profit from services: \t" + a.Possible.ToString("000000.00 \t") + (a.Possible / total1 * 100).ToString("00.00 ") + "%"; t7.Content = "Profit from parking: \t" + b.Possible.ToString("000000.00 \t") + (b.Possible / total1 * 100).ToString("00.00 ") + "%"; t8.Content = "Profit from rooms: \t" + c.Possible.ToString("000000.00 \t") + (c.Possible / total1 * 100).ToString("00.00 ") + "%"; t9.Content = "Total: \t" + (total1).ToString("00.00 "); t10.Content = "Lost: \t" + (total1-total).ToString("00.00 "); this.DataContext = l1; } private void Button_Click(object sender, RoutedEventArgs e) { t11.Content= "Tax: \t" + (t*Convert.ToDouble(pers.Text)/100).ToString("00.00 "); } } } <file_sep>/course_app/Views/general_schedule.xaml.cs 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; namespace course_app.Views { /// <summary> /// Interaction logic for general_schedule.xaml /// </summary> public partial class general_schedule : UserControl { private bool c; working_schedule temp = new working_schedule(); public general_schedule() { InitializeComponent(); c = true; upd_emp_list.IsEditable = false; upd_s_dt.IsEnabled = false; upd_e_dt.IsEnabled = false; } void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e) { e.Row.Header = (e.Row.GetIndex() + 1).ToString(); } private void Button_Click(object sender, RoutedEventArgs e) { Edit_panel.Visibility = Visibility.Visible; } private void Delete_button_Click(object sender, RoutedEventArgs e) { try { //int loc_ind = Convert.ToInt32(delete_field.Text); emploee_workSchedule t = (emploee_workSchedule)shift_table.SelectedValue; working_schedule temp = GL.db.working_schedule.Where(w => w.working_schedule_id == t.w_id).FirstOrDefault(); GL.db.working_schedule.Remove(temp); GL.db.SaveChanges(); // shift_table.Items.Remove(t); GL.main.General_schedule_Click(GL.main, e); } catch (Exception a) { MessageBox.Show("Wrong number of row"+a.Message); } } private void Add_button_Click(object sender, RoutedEventArgs e) { try { working_schedule temp = new working_schedule(); temp.shift_start_time = (DateTime)s_dt.Value; temp.shift_end_time = (DateTime)e_dt.Value; if (temp.shift_end_time <= temp.shift_start_time) throw new ArgumentException("End date and time must be greater than the start one"); employee t = (employee)emp_list.SelectedValue; temp.employee_id = t.employee_id; GL.db.working_schedule.Add(temp); GL.db.SaveChanges(); GL.main.General_schedule_Click(GL.main,e); // shift_table.Items.Add() } catch (ArgumentException a) { MessageBox.Show(a.Message); } catch(Exception a) { MessageBox.Show(a.Message); } } private void Upd_button_Click(object sender, RoutedEventArgs e) { if (c) { upd_button.Content = "Update"; upd_emp_list.IsEnabled = true; upd_s_dt.IsEnabled = true; upd_e_dt.IsEnabled = true; upd_f1.IsEnabled = false; c = !c; int loc_ind = Convert.ToInt32(upd_f1.Text); emploee_workSchedule t = (emploee_workSchedule)shift_table.Items[loc_ind - 1]; temp = GL.db.working_schedule.Where(w => w.working_schedule_id == t.w_id).FirstOrDefault(); employee emp = GL.db.employee.Where(w => w.employee_id == temp.employee_id).FirstOrDefault(); upd_s_dt.Value = temp.shift_start_time; upd_e_dt.Value = temp.shift_end_time; int ind=-1; for (int i = 0; i < upd_emp_list.Items.Count; i++) { if (upd_emp_list.Items[i].Equals(emp)) { ind = i; break; } } upd_emp_list.SelectedValue = emp; } else { c = !c; upd_button.Content = "Choose item"; upd_emp_list.IsEnabled = false; upd_s_dt.IsEnabled = false; upd_e_dt.IsEnabled = false; upd_f1.IsEnabled = true; working_schedule temp1 = new working_schedule(); temp1.shift_start_time = (System.DateTime)upd_s_dt.Value; temp1.shift_end_time = (System.DateTime)upd_e_dt.Value; employee new_emp = (employee)upd_emp_list.SelectedValue; temp1.employee_id = new_emp.employee_id; GL.db.working_schedule.Add(temp1); GL.db.working_schedule.Remove(temp); GL.db.SaveChanges(); GL.main.General_schedule_Click(GL.main, e); } } } } <file_sep>/course_app/ViewModel/CostStatModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace course_app.ViewModel { class CostStatModel {public class C1 { public string Name { get; set; } public double Money { get; set; } } public List<C1> l1; /*public CostStatModel() { l1 = new List<C1>(); double x = 0; int month = DateTime.Today.Month; List<employee> employees = GL.db.employee.ToList(); foreach (employee me in employees) { List<working_schedule> shifts = GL.db.working_schedule.Where(t => t.employee_id == me.employee_id && t.shift_start_time.Month == month).ToList(); double sum = 0; foreach (working_schedule w in shifts) { TimeSpan dif = w.shift_end_time - w.shift_start_time; sum += dif.TotalHours; } x += sum * (double)me.wage; } C1 a = new C1 { Name = "Salaries", Money = x }; x = 0; List<reservation> res = GL.db.reservation.Where(i => i.check_in_date.Month == month).ToList(); foreach (reservation ad in res) { var ad_serv = ad.service_request.ToList(); foreach(service_request s in ad_serv) { x += (double)s.additional_service.service_cost; } } C1 b = new C1 { Name = "Service costs", Money = x }; x = 0; foreach (reservation ad in res) { x += (double)ad.room.room_price * 0.1; } C1 c = new C1 { Name = "Room amortisation", Money = x }; l1.Add(a); l1.Add(b); l1.Add(c); } */ } } <file_sep>/course_app/ViewModel/ProfileModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace course_app.ViewModel { class ProfileModel { public employee me { get; set; } public double salary { get; set; } public string number_shifts { get; set; } public ProfileModel() { credential cr = GL.db.credential.Where(t => t.credential_id == GL.cred_id).FirstOrDefault(); me = GL.db.employee.Where(t => t.employee_id == cr.employee_id).FirstOrDefault(); CountSalary(); } private void CountSalary() { int month = DateTime.Today.Month; List<working_schedule> shifts = GL.db.working_schedule.Where(t => t.employee_id == me.employee_id&&t.shift_start_time.Day==month).ToList(); double sum = 0; foreach( working_schedule w in shifts) { TimeSpan dif = w.shift_end_time - w.shift_start_time; sum += dif.TotalHours; } sum *= (double)me.wage; number_shifts ="( "+Convert.ToString(shifts.Count)+" shifts"+" this month"+" )"; salary = sum; } } } <file_sep>/course_app/Views/update_position.xaml.cs 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.Shapes; namespace course_app.Views { /// <summary> /// Interaction logic for Add_position.xaml /// </summary> public partial class UpdatePosition : Window { public UpdatePosition() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { try { while (l11.Text.StartsWith(" ")) { l11.Text.Remove(0, 1); } if( (l11.Text.Length < 2)||(l212.Text.Length<1)||(l222.Text.Length<1)||(desc.Text.Length<1)) throw new ArgumentNullException("You should fill all fields!"); employee_position position = new employee_position(); position.position_name = l11.Text; position.wage_lower_bound = Convert.ToDecimal(l212.Text); position.wage_upper_bound = Convert.ToDecimal(l222.Text); position.position_description = desc.Text; if (position.wage_upper_bound < position.wage_lower_bound) throw new ArgumentException("Second value of wage must be greater than first!"); GL.db.employee_position.Add(position); GL.db.SaveChanges(); this.Close(); }catch(Exception x) { MessageBox.Show(x.Message); } } } } <file_sep>/course_app/ViewModel/EmployeeModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace course_app.ViewModel { class EmployeeModel { public List<employee> employee { get; set; } public EmployeeModel() { this.employee = GL.db.employee.ToList(); } } } <file_sep>/course_app/ViewModel/ParkingSpotsModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace course_app.ViewModel { class ParkingSpotsModel { public List<parking_spot> parking_s { get; set; } public List<parking_type> types { get; set; } public List<reservation> reservations { get; set; } public List<string> list_fields { get; set; } public ParkingSpotsModel() { parking_s = GL.db.parking_spot.ToList(); types = GL.db.parking_type.ToList(); reservations= GL.db.reservation.ToList(); list_fields = new List<string>(); list_fields.Add("Number"); list_fields.Add("Type"); list_fields.Add("Reservation"); } } } <file_sep>/course_app/Views/CostsStatistics.xaml.cs 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; namespace course_app.Views { /// <summary> /// Interaction logic for Statistics.xaml /// </summary> public partial class Statistics : UserControl { public class C1 { public string Name { get; set; } public double Money { get; set; } } public List<C1> l1; public Statistics() { l1 = new List<C1>(); double x = 0; int month = DateTime.Today.Month; List<employee> employees = GL.db.employee.ToList(); foreach (employee me in employees) { List<working_schedule> shifts = GL.db.working_schedule.Where(t => t.employee_id == me.employee_id && t.shift_start_time.Month == month).ToList(); double sum = 0; foreach (working_schedule w in shifts) { TimeSpan dif = w.shift_end_time - w.shift_start_time; sum += dif.TotalHours; } x += sum * (double)me.wage; } C1 a = new C1 { Name = "Salaries", Money = x }; x = 0; List<reservation> res = GL.db.reservation.Where(i => i.check_in_date.Month == month).ToList(); foreach (reservation ad in res) { var ad_serv = ad.service_request.ToList(); foreach(service_request s in ad_serv) { x += (double)s.additional_service.service_cost * s.amount; } } C1 b = new C1 { Name = "<NAME>", Money = x }; x = 0; foreach (reservation ad in res) { x += (double)ad.room.room_price * 0.1; } C1 c = new C1 { Name = "Amortisation", Money = x }; C1 d = new C1 { Name = "Recources", Money = x / 2 + 20 }; l1.Add(a); l1.Add(b); l1.Add(c); l1.Add(d); InitializeComponent(); double total = a.Money + b.Money + c.Money + d.Money; t1.Content = "Costs for salaries: \t" + a.Money.ToString("000000.00 \t") + (a.Money/total*100).ToString("00.00 ")+"%"; t2.Content = "Costs for services: \t" + b.Money.ToString("000000.00 \t") + (b.Money / total * 100).ToString("00.00 ") + "%"; t3.Content = "Costs for amortisation: \t" + c.Money.ToString("000000.00 \t") + (c.Money / total * 100).ToString("00.00 ") + "%"; t4.Content = "Costs for resources: \t" + d.Money.ToString("000000.00 \t") + (d.Money / total * 100).ToString("00.00 ") + "%"; t5.Content = "Total: \t" + (total).ToString("00.00 ") ; this.DataContext = l1; } } } <file_sep>/course_app/MainWindow.xaml.cs using course_app.ViewModel; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Text; using System.Threading; 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; namespace course_app { /// <summary> /// Логика взаимодействия для MainWindow.xaml /// </summary> public partial class MainWindow : Window { //public static int permission_level; //public static hotel_newEntities db = new hotel_newEntities(); //int cred_id; public MainWindow(int id) { GL.cred_id = id; GL.permission_level = SetPLevel(); InitializeComponent(); if (GL.permission_level < 3) { HR.Visibility = Visibility.Collapsed; Reservation.Visibility= Visibility.Collapsed; Resources.Visibility= Visibility.Collapsed; Statistics.Visibility = Visibility.Collapsed; if (GL.permission_level == 2) { Cleaning.Visibility = Visibility.Collapsed; } else { Parking.Visibility = Visibility.Collapsed; } }else if(GL.permission_level==3) { HR.Visibility = Visibility.Collapsed; Cleaning.Visibility = Visibility.Collapsed; Parking.Visibility = Visibility.Collapsed; Statistics.Visibility = Visibility.Collapsed; } else if (GL.permission_level == 4) { HR.Visibility = Visibility.Collapsed; Cleaning.Visibility = Visibility.Collapsed; } else if (GL.permission_level == 5) { Resources.Visibility = Visibility.Collapsed; Parking.Visibility = Visibility.Collapsed; Reservation.Visibility = Visibility.Collapsed; Statistics.Visibility= Visibility.Collapsed; } } public void MWClosing(object sender, RoutedEventArgs e) { GL.login_Window.Close(); } private int SetPLevel() { var emp = GL.db.credential.Where(c => c.credential_id == GL.cred_id).FirstOrDefault(); var t = GL.db.employee.Where(w => w.employee_id == emp.employee_id).FirstOrDefault(); int pos_id = t.employee_position.position_id; if (pos_id <= 3) return pos_id;// maid-level1//security-level 2//admin-level 3 else if (pos_id == 4) return 6;//db admin-level 6 else return pos_id - 1;//manager-level 4// hr-level 5 } public void Schedule_Click(object sender, RoutedEventArgs e) { var emp = GL.db.credential.Where(c => c.credential_id == GL.cred_id).FirstOrDefault(); var shifts = GL.db.working_schedule.Where(w => w.employee_id == emp.employee_id).OrderBy(w => w.shift_start_time).ToList(); DataContext = new ScheduleModel(shifts); } public void General_schedule_Click(object sender, RoutedEventArgs e) { var s = GL.db.working_schedule.Join(GL.db.employee, eid => eid.employee_id, wid => wid.employee_id, (eid, wid) => new { eid.shift_end_time, eid.shift_start_time, wid.employye_first_name, wid.employee_last_name, eid.working_schedule_id }).ToList(); ObservableCollection<emploee_workSchedule> ew = new ObservableCollection<emploee_workSchedule>(); foreach(var i in s) { emploee_workSchedule temp = new emploee_workSchedule(i.shift_end_time, i.shift_start_time, i.employye_first_name, i.employee_last_name,i.working_schedule_id); ew.Add(temp); } DataContext = new GeneralSchedule(ew); } public void Ent_log_Click(object sender, RoutedEventArgs e) { DataContext = new EntranceTable(); } public void Emp_add_Click(object sender, RoutedEventArgs e) { DataContext = new EmployeeModel(); } public void BTN_Click(object sender, RoutedEventArgs e) { DataContext = new RoomTypeModel(); } public void MenuItem_Click(object sender, RoutedEventArgs e) { DataContext = new PositionModel(); } public void MenuItem_Click_1(object sender, RoutedEventArgs e) { DataContext = new ProfileModel(); } public void MenuItem_Click_2(object sender, RoutedEventArgs e) { DataContext = new RoomModel(); } public void MenuItem_Click_3(object sender, RoutedEventArgs e) { DataContext = new ServicesModel(); } public void MenuItem_Click_4(object sender, RoutedEventArgs e) { DataContext = new ParkingSpotsModel(); } public void MenuItem_Click_5(object sender, RoutedEventArgs e) { DataContext = new CleaningModel(); } public void MenuItem_Click_6(object sender, RoutedEventArgs e) { DataContext = new ClientModel(); } public void client_t(object sender, RoutedEventArgs e) { DataContext = new ClientTypeModel(); } public void parking_t(object sender, RoutedEventArgs e) { DataContext = new ParkingTypeModel(); } public void MenuItem_Click_7(object sender, RoutedEventArgs e) { DataContext = new EntranceTable(); } public void MenuItem_Click_8(object sender, RoutedEventArgs e) { DataContext = new ReservationModel(); } public void MenuItem_Click_9(object sender, RoutedEventArgs e) { course_app.Views.add_reservation w = new Views.add_reservation(); w.ShowDialog(); } public void MenuItem_Click_10(object sender, RoutedEventArgs e) { DataContext = new CostStatModel(); } public void MenuItem_Click_91(object sender, RoutedEventArgs e) { DataContext = new PaymentMOdel(); } private void About_Handler(object sender, RoutedEventArgs e) { var w = new AboutWindow(); w.ShowDialog(); } private void MenuItem_Click_11(object sender, RoutedEventArgs e) { DataContext = new IncomeModel(); } } } <file_sep>/course_app/Views/client_data.xaml.cs 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; namespace course_app.Views { /// <summary> /// Interaction logic for client_data.xaml /// </summary> public partial class client_data : UserControl { public client_data(client c) { DataContext = new course_app.ViewModel.ClientDataModel(c); InitializeComponent(); f_n.Text = c.client_first_name; } private void Button_Click(object sender, RoutedEventArgs e) { } } } <file_sep>/course_app/ViewModel/AppViewModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace course_app.ViewModel { class AppViewModel { private int cred_id; private hotel_newEntities db; public AppViewModel(int id) { this.cred_id = id; } } } <file_sep>/course_app/ViewModel/ProvidedServices.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace course_app.ViewModel { class ProvidedServices { public List<service_request> services { get; set; } public ProvidedServices(reservation r) { services = r.service_request.ToList(); } } } <file_sep>/course_app/ViewModel/ClientDataModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace course_app.ViewModel { class ClientDataModel { public List<reservation> res_list { get; set; } public List<client_type> types { get; set; } public ClientDataModel(client c) { res_list = GL.db.reservation.Where(i => i.client_id == c.client_id).ToList(); types = GL.db.client_type.ToList(); } } } <file_sep>/course_app/Views/clients.xaml.cs 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; namespace course_app.Views { /// <summary> /// Interaction logic for clients.xaml /// </summary> public partial class clients : UserControl { public clients() { InitializeComponent(); cont.DataContext = null; } private void Button_Click_3(object sender, RoutedEventArgs e) { GL.db.client.Remove((client)ent_table.SelectedValue); GL.db.SaveChanges(); GL.main.MenuItem_Click_6(sender, e); } private void Button_Click_2(object sender, RoutedEventArgs e) { update_client w = new update_client((client)ent_table.SelectedValue); w.ShowDialog(); GL.main.MenuItem_Click_6(sender, e); } private void Button_Click(object sender, RoutedEventArgs e) { add_client w = new add_client(); w.ShowDialog(); GL.main.MenuItem_Click_6(sender, e); } private void Button_Click_1(object sender, RoutedEventArgs e) { GL.main.client_t(sender, e); } private void MenuItem_Click(object sender, RoutedEventArgs e) { //DataContext = new course_app.ViewModel.ClientDataModel((client)ent_table.SelectedValue); stack.Visibility = Visibility.Hidden; cont.Visibility = Visibility.Visible; if (((client)ent_table.SelectedValue) != null) { cont.DataContext = new course_app.ViewModel.ClientDataModel((client)ent_table.SelectedValue); client c = (client)ent_table.SelectedValue; f_n.Text = c.client_first_name; m_n.Text = c.client_middle_name; l_n.Text = c.client_last_name; ph_n.Text = c.client_phone_number; pas_n.Text = c.client_passport_serial_number; e_n.Text = c.client_email; pos_n.SelectedValue = c.client_type; note.Text = c.client_notes; } else { MessageBox.Show("Choose the row!"); } } private void Button_Click_close(object sender, RoutedEventArgs e) { cont.Visibility = Visibility.Hidden; } private void What_search_SelectionChanged(object sender, SelectionChangedEventArgs e) { if((string)what_search.SelectedValue=="Type") { text_search.Visibility = Visibility.Collapsed; box_search.Visibility = Visibility.Visible; } else { text_search.Visibility = Visibility.Visible; box_search.Visibility = Visibility.Collapsed; } } private void Button_Click_4(object sender, RoutedEventArgs e) { List<client> clients = new List<client>(); if ((string)what_search.SelectedValue == "Type") { client_type t = (client_type)box_search.SelectedValue; clients = GL.db.client.Where(i => i.client_type_id == t.client_type_id).ToList(); }else if ((string)what_search.SelectedValue == "First name") { clients = GL.db.client.Where(i =>i.client_first_name==text_search.Text).ToList(); } else if ((string)what_search.SelectedValue == "Middle name") { clients = GL.db.client.Where(i => i.client_middle_name == text_search.Text).ToList(); } else if ((string)what_search.SelectedValue == "Last name") { clients = GL.db.client.Where(i => i.client_last_name == text_search.Text).ToList(); } else if ((string)what_search.SelectedValue == "Phone") { clients = GL.db.client.Where(i => i.client_phone_number== text_search.Text).ToList(); } else if ((string)what_search.SelectedValue == "Email") { clients = GL.db.client.Where(i => i.client_email == text_search.Text).ToList(); } else if ((string)what_search.SelectedValue == "Passport") { clients = GL.db.client.Where(i => i.client_passport_serial_number == text_search.Text).ToList(); } search_list.ItemsSource = clients; stack.Visibility = Visibility.Visible; if (clients.Count == 0) { MessageBox.Show("No item found!"); } } private void Button_Click_5(object sender, RoutedEventArgs e) { stack.Visibility = Visibility.Hidden; what_search.SelectedValue = null; text_search.Visibility= Visibility.Hidden; box_search.Visibility= Visibility.Hidden; } private void MenuItem_Click1(object sender, RoutedEventArgs e) { stack.Visibility = Visibility.Hidden; cont.Visibility = Visibility.Visible; if (((client)search_list.SelectedValue) != null) { cont.DataContext = new course_app.ViewModel.ClientDataModel((client)search_list.SelectedValue); client c = (client)search_list.SelectedValue; f_n.Text = c.client_first_name; m_n.Text = c.client_middle_name; l_n.Text = c.client_last_name; ph_n.Text = c.client_phone_number; pas_n.Text = c.client_passport_serial_number; e_n.Text = c.client_email; pos_n.SelectedValue = c.client_type; note.Text = c.client_notes; } else { MessageBox.Show("Choose the row!"); } } } } <file_sep>/course_app/Views/add_reservation.xaml.cs 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.Shapes; namespace course_app.Views { /// <summary> /// Interaction logic for add_reservation.xaml /// </summary> public partial class add_reservation : Window { public class t1 { public List<room> rooms { get; set; } } DateTime checkin, checkout; bool upd; reservation cur; public add_reservation() { InitializeComponent(); DataContext = new ViewModel.AddREservationModel(); upd = false; } public add_reservation(reservation r) { try { InitializeComponent(); DataContext = new ViewModel.AddREservationModel(); f_n.Text = r.reservation_number; m_n.Value = r.check_in_date; l_n.Value = r.check_out_date; client_n.SelectedValue = r.client; room_n.SelectedValue = r.room; upd = true; cur = r; }catch(Exception x) { MessageBox.Show(x.Message); } } private void Button_Click(object sender, RoutedEventArgs e) { add_client w = new add_client(); w.Show(); this.DataContext= new ViewModel.AddREservationModel(); //renew this page } private void Button_Click_1(object sender, RoutedEventArgs e) { r_type.Visibility = Visibility.Visible; min_price.Visibility = Visibility.Visible; max_price.Visibility = Visibility.Visible; search.Visibility = Visibility.Visible; } private void Button_Click_3(object sender, RoutedEventArgs e) { } private void Button_Click_4(object sender, RoutedEventArgs e) { if (!upd) { reservation r = new reservation(); r.check_in_date = (DateTime)m_n.Value; r.check_out_date = (DateTime)l_n.Value; r.reservation_number = f_n.Text; r.client_id = ((client)client_n.SelectedValue).client_id; r.room_id = ((room)room_n.SelectedValue).room_id; r.employee_id = (int)(GL.db.credential.Where(i => i.credential_id == GL.cred_id).FirstOrDefault()).employee_id; GL.db.reservation.Add(r); } else { reservation r = GL.db.reservation.Where(i => i.reservation_id == cur.reservation_id).FirstOrDefault(); r.check_in_date = (DateTime)m_n.Value; r.check_out_date = (DateTime)l_n.Value; r.reservation_number = f_n.Text; r.client_id = ((client)client_n.SelectedValue).client_id; r.room_id = ((room)room_n.SelectedValue).room_id; r.employee_id = (int)(GL.db.credential.Where(i => i.credential_id == GL.cred_id).FirstOrDefault()).employee_id; GL.db.Entry(r).State = System.Data.Entity.EntityState.Modified; } GL.db.SaveChanges(); GL.main.MenuItem_Click_8(sender, e); this.Close(); } private void Button_Click_11(object sender, RoutedEventArgs e) { r_type.Visibility = Visibility.Collapsed; min_price.Visibility = Visibility.Collapsed; max_price.Visibility = Visibility.Collapsed; search.Visibility = Visibility.Collapsed; List<room> all = GL.db.room.ToList(); room_n.DataContext = new t1 { rooms = all }; } private void Search_room(object sender, RoutedEventArgs e) { decimal min_p, max_p; if (min_price.Value != null) { min_p = (decimal)min_price.Value; } else { min_p = 0; } if (max_price.Value != null) { max_p = (decimal)max_price.Value; } else { max_p = 1000000; } if (r_type.SelectedValue != null) { room_type t = (room_type)r_type.SelectedValue; List<room> roms = GL.db.room.Where(i => i.room_price >= min_p && i.room_price <= max_p && i.room_type_id == t.room_type_id).ToList(); room_n.DataContext = new t1 { rooms = roms}; } else { List<room> roms = GL.db.room.Where(i => i.room_price >= min_p && i.room_price <= max_p ).ToList(); room_n.DataContext = new t1 { rooms = roms}; } } private void M_n_ValueChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { checkin = (DateTime)m_n.Value; if (checkin != null && checkout > checkin) { List<reservation> reserved = (GL.db.reservation.Where(i => (i.check_in_date >= checkin && i.check_in_date <= checkout) || (i.check_out_date >= checkin && i.check_out_date <= checkout))).ToList(); List<room> all = GL.db.room.ToList(); List<room> r = new List<room>(); foreach(reservation re in reserved) { r.Add(re.room); } List<room> roms = all.Except(r).ToList(); room_n.DataContext = new t1 { rooms = roms }; }else if(checkout <= checkin) { room_n.DataContext = null; } } private void L_n_ValueChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { checkout = (DateTime)l_n.Value; if (checkout != null && checkout > checkin) { List<reservation> reserved = (GL.db.reservation.Where(i => (i.check_in_date >= checkin && i.check_in_date <= checkout) || (i.check_out_date >= checkin && i.check_out_date <= checkout))).ToList(); List<room> all = GL.db.room.ToList(); List<room> r = new List<room>(); foreach (reservation re in reserved) { r.Add(re.room); } List<room> roms = all.Except(r).ToList(); room_n.DataContext = new t1 { rooms = roms }; } else if (checkout <= checkin) { room_n.DataContext = null; } } } } <file_sep>/course_app/Views/Update.xaml.cs using System; using System.Collections.Generic; using System.Diagnostics; 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.Shapes; namespace course_app.Views { /// <summary> /// Interaction logic for Update.xaml /// </summary> public partial class Update : Window { employee pew; bool cred; public class DataObject { public List<employee_position> positions { get; set; } public DataObject() { positions = GL.db.employee_position.ToList(); } } public Update(employee person) { InitializeComponent(); cred = false; pew = person; DataContext = new DataObject(); f_n.Text = person.employye_first_name; m_n.Text = person.employye_middle_name; l_n.Text = person.employee_last_name; ph_n.Text = person.employee_phone_number; pas_n.Text = person.employee_passport_serial_number; t_n.Text = person.tax_payer_id; w_n.Text = Convert.ToString(person.wage); e_n.Text = person.employee_email; //to do employee_position pos = GL.db.employee_position.Where(t => t.position_id == person.position_id).FirstOrDefault(); pos_n.SelectedValue = pos; } private void Button_Click(object sender, RoutedEventArgs e) { /* GL.db.employee.Remove(pew); employee n = new employee(); n.employee_last_name = l_n.Text; n.employee_passport_serial_number = pas_n.Text; n.employee_phone_number = ph_n.Text; // n.employee_position = (employee_position)pos_n.SelectedValue; n.employye_first_name = f_n.Text; n.employye_middle_name = m_n.Text; n.position_id = ((employee_position)pos_n.SelectedValue).position_id; GL.db.employee.Add(n); pew = n; if (cred) { credential del = GL.db.credential.Where(t => t.employee_id == pew.employee_id).FirstOrDefault(); if(del!=null)GL.db.credential.Remove(del); credential rep = new credential(); rep.employee_id = pew.employee_id; rep.username = login.Text; rep.password = <PASSWORD>; GL.db.credential.Add(rep); } GL.db.SaveChanges(); GL.main.Emp_add_Click(GL.main, e); this.Close();*/ try { var n = GL.db.employee.Where(t => t.employee_id == pew.employee_id).FirstOrDefault(); n.employee_last_name = l_n.Text; n.employee_passport_serial_number = pas_n.Text; n.employee_phone_number = ph_n.Text; n.employye_first_name = f_n.Text; n.tax_payer_id = t_n.Text; n.employye_middle_name = m_n.Text; n.position_id = ((employee_position)pos_n.SelectedValue).position_id; GL.db.Entry(n).State = System.Data.Entity.EntityState.Modified; if (cred) { credential del = GL.db.credential.Where(t => t.employee_id == pew.employee_id).FirstOrDefault(); if (del == null) { credential rep = new credential(); rep.employee_id = pew.employee_id; rep.username = login.Text; rep.password = <PASSWORD>; GL.db.credential.Add(rep); } else { del.password= <PASSWORD>; del.username= login.Text; GL.db.Entry(del).State = System.Data.Entity.EntityState.Modified; } } GL.db.SaveChanges(); this.Close(); }catch(Exception x) { MessageBox.Show(x.Message); } } private void Button_Click_1(object sender, RoutedEventArgs e) { credential c = GL.db.credential.Where(t => t.employee_id == pew.employee_id).FirstOrDefault(); if (c==null||current_pass_box.Password == <PASSWORD>) { cred = true; label_login.Visibility = Visibility.Visible; label_p1.Visibility = Visibility.Visible; label_p2.Visibility = Visibility.Visible; pass_box1.Visibility = Visibility.Visible; pass_box2.Visibility = Visibility.Visible; login.Visibility = Visibility.Visible; } } } } <file_sep>/course_app/Views/add_provided.xaml.cs 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.Shapes; namespace course_app.Views { /// <summary> /// Interaction logic for add_provided.xaml /// </summary> public partial class add_provided : Window { public add_provided() { InitializeComponent(); DataContext = new ViewModel.AddProvidedModel(); t1.SelectedValue = GL.R; } private void Button_Click(object sender, RoutedEventArgs e) { service_request sr = new service_request(); sr.reservation_id = ((reservation)t1.SelectedValue).reservation_id; sr.employee_id = ((employee)emp_list.SelectedValue).employee_id; sr.additional_service_id = ((additional_service)t2.SelectedValue).additional_service_id; sr.amount =(int) amou.Value; sr.service_provided_time = pay_time.Value; GL.db.service_request.Add(sr); GL.db.SaveChanges(); GL.main.DataContext = new ViewModel.ProvidedServices(GL.R); this.Close(); } } }
5eb1858f14a387ab09f715d6126ad356f1e2d069
[ "C#" ]
65
C#
mikaserova/course_work
ca34b12f31a7793ca3e558fadb4fc87b0075c5d2
3de2503d092c8711d303af0aafcf8005848443b2
refs/heads/master
<file_sep> Laboratorio Esercitazione 1 ================== Riassunto e analisi delle funzioni numpy ---------------------- ```python from numpy import * a = arange(15).reshape(3, 5) a ``` array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]) Creata matrice da 3 righe e 5 colonne ```python a.ndim ``` 2 dimensioni della matrice ```python a.size ``` 15 numero elementi della matrice ```python b = array( [ (1.5,2,3), (4,5,6) ] ) b ``` array([[ 1.5, 2. , 3. ], [ 4. , 5. , 6. ]]) array trasforma n sequenze in array n-dimensionali ```python A = array( [[1,1],[0,1]] ) B = array( [[2,0],[3,4]] ) A*B ``` array([[2, 0], [0, 4]]) ```python dot(A,B) ``` array([[5, 4], [3, 4]]) arange zeros e one so funzioni utili che consentono di generare array desiderati senza inserire manualmente i valori. rispettivamente zeros e one tutti 0 e 1, arange invece indicando intervallo e passo. ```python import numpy as np b=np.arange(12).reshape(3,4) b b.min(axis=1) ``` array([0, 4, 8]) attraverso la funzione axis è possibile scegliere in base a quale asse applicare una determianta operazione sugli arrray sono presenti altre funzioni di interesse ma che già abbiamo studiato nella slide learn x in y in particolar modo quelle relative all'accesso su array ```python from numpy import * ``` ```python punti=random.rand(100,2) ``` ```python punti ``` array([[ 0.42300084, 0.41678629], [ 0.26105348, 0.87990356], [ 0.06527506, 0.59910716], [ 0.555986 , 0.72264708], [ 0.15194172, 0.30468254], [ 0.93774678, 0.79638365], [ 0.59186759, 0.47607993], [ 0.37957217, 0.75624355], [ 0.55249329, 0.22755506], [ 0.9000241 , 0.37875888], [ 0.3130707 , 0.36016831], [ 0.93843233, 0.47092741], [ 0.41562182, 0.40898116], [ 0.13373347, 0.25242172], [ 0.09011352, 0.28354074], [ 0.50012132, 0.26042328], [ 0.35560574, 0.95294503], [ 0.51129286, 0.84417476], [ 0.36324654, 0.76847267], [ 0.8254599 , 0.55543217], [ 0.36782018, 0.52864461], [ 0.48789686, 0.98508543], [ 0.71158579, 0.31879774], [ 0.14870438, 0.88067384], [ 0.07344479, 0.65433162], [ 0.09327947, 0.10327254], [ 0.38429555, 0.43243214], [ 0.51786471, 0.46103516], [ 0.39260268, 0.66309829], [ 0.96846445, 0.16943013], [ 0.91694179, 0.73374731], [ 0.26100158, 0.10169842], [ 0.74938991, 0.67559144], [ 0.43400615, 0.8344122 ], [ 0.88265224, 0.80150342], [ 0.19733225, 0.93744355], [ 0.14867424, 0.98053814], [ 0.30358219, 0.88031032], [ 0.52610022, 0.03834761], [ 0.2811505 , 0.47170289], [ 0.07938455, 0.5809199 ], [ 0.8088384 , 0.43043154], [ 0.30294411, 0.51105192], [ 0.14574765, 0.97800252], [ 0.60568905, 0.00341819], [ 0.73021789, 0.99343297], [ 0.11733756, 0.75712313], [ 0.6209094 , 0.76000811], [ 0.52933443, 0.81985201], [ 0.99896181, 0.06510455], [ 0.78178703, 0.28301766], [ 0.60047825, 0.50959689], [ 0.65517295, 0.36935922], [ 0.53886309, 0.42672483], [ 0.58539361, 0.42631568], [ 0.85632395, 0.65428845], [ 0.80640048, 0.92992653], [ 0.93257195, 0.96258936], [ 0.05191864, 0.26142541], [ 0.54580212, 0.60578767], [ 0.39932295, 0.02391706], [ 0.66967605, 0.49720812], [ 0.43091942, 0.88699115], [ 0.84868318, 0.28064339], [ 0.38754876, 0.59199196], [ 0.97232059, 0.15244495], [ 0.42559957, 0.13707943], [ 0.71786638, 0.32088365], [ 0.33998607, 0.91983771], [ 0.99117346, 0.76791361], [ 0.19207393, 0.09592269], [ 0.55169084, 0.48713736], [ 0.41834712, 0.39121268], [ 0.61956942, 0.68133903], [ 0.12869568, 0.23634994], [ 0.38600656, 0.13962431], [ 0.02140987, 0.34157937], [ 0.1862832 , 0.9572946 ], [ 0.0219869 , 0.23116956], [ 0.81908218, 0.0399553 ], [ 0.13027081, 0.8154262 ], [ 0.83136706, 0.69690817], [ 0.94774203, 0.69473743], [ 0.0881763 , 0.26394974], [ 0.18909016, 0.97355402], [ 0.78141038, 0.70373545], [ 0.40567898, 0.14619774], [ 0.87023334, 0.81798926], [ 0.39431668, 0.02288903], [ 0.82775781, 0.20617443], [ 0.60082999, 0.9066102 ], [ 0.96437796, 0.6202025 ], [ 0.76059282, 0.3590052 ], [ 0.15476659, 0.14171739], [ 0.19272052, 0.85433772], [ 0.66290038, 0.37945794], [ 0.81133535, 0.13057391], [ 0.82272875, 0.6185559 ], [ 0.07463126, 0.10694318], [ 0.05949444, 0.89819919]]) ```python from pyplasm import * ``` Evaluating fenvs.py.. ...fenvs.py imported in 0.011543 seconds ```python VIEW(STRUCT([MK(p) for p in punti])) ``` <pyplasm.xgepy.Hpc; proxy of <Swig Object of type 'std::shared_ptr< Hpc > *' at 0xadff64b8> > ![punti piazza](punti.png) ```python def larExtrude1(model,pattern): """ Simplicial model extrusion in accord with a 1D pattern """ V, FV = model d, m = len(FV[0]), len(pattern) coords = list(cumsum([0]+(AA(ABS)(pattern)))) offset, outcells, rangelimit = len(V), [], d*m for cell in FV: tube = [v + k*offset for k in range(m+1) for v in cell] cellTube = [tube[k:k+d+1] for k in range(rangelimit)] outcells += [reshape(cellTube, newshape=(m,d,d+1)).tolist()] outcells = AA(CAT)(TRANS(outcells)) cellGroups = [group for k,group in enumerate(outcells) if pattern[k]>0] outVertices = [v+[z] for z in coords for v in V] outModel = outVertices, CAT(cellGroups) return outModel ``` ```python model = [[0,0],[1,0],[0,1]], [[0,1,2]] pattern = [1] ``` ```python from larlib import * ``` /usr/local/lib/python2.7/dist-packages/larlib/larstruct.py:233: FutureWarning: comparison to `None` will result in an elementwise object comparison in the future. self.body = [item for item in data if item != None] ```python pattern = [1]*10 VIEW(STRUCT(MKPOLS((larExtrude1(model,pattern))))) ``` <pyplasm.xgepy.Hpc; proxy of <Swig Object of type 'std::shared_ptr< Hpc > *' at 0xabfdcd88> > ![esempio 1](p1.png) ```python V = [[0,0],[1,0],[2,0],[0,1],[1,1],[2,1],[0,2],[1,2],[2,2]] FV = [[0,1,3],[1,2,4],[2,4,5],[3,4,6],[4,6,7],[5,7,8]] model = larExtrude1((V,FV),4*[1,2,-3]) VIEW(EXPLODE(1,1,1.2)(MKPOLS(model))) ``` <pyplasm.xgepy.Hpc; proxy of <Swig Object of type 'std::shared_ptr< Hpc > *' at 0xac00a7a0> > ![esempio 2](p2.png) ```python model = larExtrude1( VOID, 10*[1] ) VIEW(EXPLODE(1.5,1.5,1.5)(MKPOLS(model))) model = larExtrude1( model, 10*[1] ) VIEW(EXPLODE(1.5,1.5,1.5)(MKPOLS(model))) model = larExtrude1( model, 10*[1] ) VIEW(EXPLODE(1.5,1.5,1.5)(MKPOLS(model))) ``` <pyplasm.xgepy.Hpc; proxy of <Swig Object of type 'std::shared_ptr< Hpc > *' at 0xacd5e848> > ![esempio 3](p3.png) ```python model = larExtrude1( VOID, 13*[1,-1] ) VIEW(EXPLODE(2,1.5,2)(MKPOLS(model))) model = larExtrude1( model, 13*[1,2] ) VIEW(EXPLODE(1.5,3,1.5)(MKPOLS(model))) ``` <pyplasm.xgepy.Hpc; proxy of <Swig Object of type 'std::shared_ptr< Hpc > *' at 0xab9c1e60> > ![esempio 4](p4.png) ```python ``` <file_sep>package model; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Classe astratta che rappresenta un segnale * @author <NAME> * */ public abstract class AbstractSignal { private int length; private List<Complex> values; // costruttore no arg della classe public AbstractSignal() { this.values=new ArrayList<>(); } // Getters and Setters della classe public int getLength() { return length; } public void setLength(int length) { this.length = length; } public List<Complex> getValues() { return values; } public void setValues(List<Complex> values) { this.values = values; } // metodo che calcola l'energia di un segnale public double signalEnergy() { double value=0; for(int i =0 ; i<length;i++) { Complex c = this.values.get(i); value += Math.pow(c.abs(),2); } return value/length; } @Override public String toString() { String desc=""; for (int i=0; i<this.values.size();i++) desc += this.values.get(i).toString()+"\n"; return desc; } } <file_sep># Homework1_SDR Ho rimesso che l'energia viene calcolata dal metodo signalEnergy e non dal rumore stesso durante la creazione. Mi ero dimenticato di toglierlo, lo avevamo lasciato per migliorare le prestazioni per le prove. Il file excel va completato con il commento.
0a68d327027d51375b70ed1e54781a241cb02c0f
[ "Markdown", "Java" ]
3
Markdown
davidedm07/Homework1_SDR
35d63e00313ef15cb6542ac56a6e800a58548664
01a3867843a8cbf5186080b3b8cd8cd0ac1047ad
refs/heads/master
<file_sep>#include <stdio.h> #include <cs50.h> int main(void){ printf("Please enter the amount of change required: \n"); float totchange = GetFloat(); int count100 = 0; int count50 = 0; int count20 = 0; int count10 = 0; int count5 = 0; int count2 = 0; int count1 = 0; //Check for 100s while(totchange >=100){ count100 = count100 + 1; totchange = totchange - 100; } while(totchange >=50){ count50 = count50 + 1; totchange = totchange - 50; } while(totchange >=20){ count20 = count20 + 1; totchange = totchange - 20; } while(totchange >=10){ count10 = count10 + 1; totchange = totchange - 10; } while(totchange >=5){ count5 = count5 + 1; totchange = totchange - 5; } while(totchange >=2){ count2 = count2 + 1; totchange = totchange - 2; } while(totchange >=1){ count1 = count1 + 1; totchange = totchange - 1; } printf("Change will be given as follows: \n"); printf("R100 x %d\n", count100); printf("R50 x %d\n", count50); printf("R20 x %d\n", count20); printf("R10 x %d\n", count10); printf("R5 x %d\n", count5); printf("R2 x %d\n", count2); printf("R1 x %d\n", count1); } <file_sep>/** * helpers.c * * Computer Science 50 * Problem Set 3 * * Helper functions for Problem Set 3. */ #include <cs50.h> #include <stdio.h> #include "helpers.h" /** * Returns true if value is in array of n values, else false. */ bool search(int value, int values[], int n) { if(n <= 0) { return false; } else { for(int i = 0; i < n; i++) { if(values[i] == value) { return true; } } return false; } } /** * Sorts array of n values. */ void sort(int values[], int n) { bool run; for(int s = 1; s < n;s++) { if(values[s] > values[s+1]){ int tmp = values[s]; values[s] = values[s-1]; values[s-1] = tmp; run = true; } } if(run == true){ sort(values, n); } else { printf("Sorted Array \n"); for(int i = 0;i <n;i++) { printf("%d\n" , values[i]); } return; } } <file_sep><div> <table class="table table-striped"> <?php foreach ($stocks as $stock) { $current_stock = lookup($stock["symbol"]); $total_val = $current_stock["price"] * $stock["shares"]; print("<tr>"); print("<th>" . "Name" . "</th>"); print("<th>" . "Symbol" . "</th>"); print("<th>" . "Shares" . "</th>"); print("<th>" . "Current Stock Price" . "</th>"); print("<th>" . "Current Value" . "</th>"); print("<td>Sell</td>"); print("</tr>"); print("<tr>"); print("<th>" . $current_stock["name"] . "</th>"); print("<td>" . $stock["symbol"] . "</td>"); print("<td>" . $stock["shares"] . "</td>"); print("<td>" . $current_stock["price"] . "</td>"); print("<td>" . $total_val . "</td>"); print("<td><button value='SELL'>SELL</button></td>"); print("</tr>"); } ?> </table> </div> <div> <a href="logout.php">Log Out</a> </div> <file_sep>#include <stdio.h> int main(void){ for(int i=0; i<8;i++){ //Print the spaces for(int n=i;n<8;n++){ printf(" "); } //Print the # for(int m=i;m>0;m--){ printf("#"); } printf("\n"); } } <file_sep>/** * recover.c * * Computer Science 50 * Problem Set 5 * * Recovers JPEGs from a forensic image. */ #include <stdio.h> #include <stdlib.h> void makefile(int count, FILE* inptr, char* buffer, char* title); int main(int argc, char* argv[]) { // ensure proper usage if (argc != 2) { printf("Usage: ./copy infile \n"); return 1; } // remember filenames char* infile = argv[1]; // open input file FILE* inptr = fopen(infile, "r"); if (inptr == NULL) { printf("Could not open %s.\n", infile); return 2; } char buffer[512]; char* title = malloc(sizeof(char)*7); int i = 0; int a = 0; do { a = fread(&buffer , sizeof(char) , 512 , inptr); if(buffer[0]==(char)255 && buffer[1]==(char)216 && buffer[2]==(char)255 && (buffer[3]==(char)224 || buffer[3]==(char)225)) { i++; fseek(inptr, -512, SEEK_CUR); makefile(i, inptr, buffer, title); } } while(a==512); fclose(inptr); } //Make a new image file for writting function void makefile(int count, FILE* inptr, char* buffer, char* title){ int a = 0; int counter = 0; sprintf(title,"%03d.jpg", count); FILE* outptr = fopen(title, "a"); if (outptr == NULL) { fclose(inptr); printf("Could not create %s.\n", title); } do { a = fread(buffer , sizeof(char) , 512 , inptr); counter++; fwrite(buffer, sizeof(char), 512, outptr); printf("Current counter: %d \n" , counter); } while((counter == 1) ||( (a == 512) && (buffer[0]!=(char)255 || buffer[1]!=(char)216 || buffer[2]!=(char)255 || (buffer[3]!=(char) 224 && buffer[3]!=(char)225)))); fseek(inptr, -512, SEEK_CUR); fclose(outptr); } <file_sep><?php dump($stock); ?> <file_sep>/**************************************************************************** * dictionary.c * * Computer Science 50 * Problem Set 6 * * Implements a dictionary's functionality. ***************************************************************************/ #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "dictionary.h" int hash(const char *word); char word[LENGTH+1]; int word_count = 0; typedef struct node { char *word; struct node* next; } node; node* hash_table[HSIZE]; /** * Returns true if word is in dictionary else false. */ bool check(const char *word) { char temp_word[LENGTH +1]; node *nodep; //Convert to lower case int len = strlen(word); for(int i = 0; i < len; i++) { int low = tolower(word[i]); temp_word[i] = (char)low; } // Add the terminating char temp_word[len] = '\0'; int hv = hash(temp_word); nodep = hash_table[hv]; if (!nodep ) return false;//Not even a hash node created. // Else search in list while( nodep ) { if (!strcmp(word,temp_word)) { return true; } nodep = nodep->next; } return false; } /** * Loads dictionary into memory. Returns true if successful else false. */ bool load(const char* dictionary) { //Open File, and set it to dict FILE *dict; //Declare Hash Value int hashv; dict = fopen(dictionary, "r" ); // Initialize hash table for (int i = 0; i<HSIZE; i++) { hash_table[i] = NULL; } //Run through file and add words to hash table while(fscanf(dict, "%s" , word) != EOF) { //Malloc space for each node node* new_node = malloc(sizeof(node)); if(new_node == NULL) { return false; } hashv = hash(word); new_node->word = word; word_count++; if(hash_table[hashv] == NULL) { hash_table[hashv] = new_node; new_node->next = NULL; }else { new_node->next = hash_table[hashv]; hash_table[hashv] = new_node; } printf("%s\n" , hash_table[hashv]->word); } printf( "Total word count = %d\n",word_count); fclose(dict); return true; } /** * Returns number of words in dictionary if loaded else 0 if not yet loaded. */ unsigned int size(void) { return word_count; } /** * Unloads dictionary from memory. Returns true if successful else false. */ bool unload(void) { node *nextnodep,*nodep; // Walk hash table deleting nodes // Note need to delete both the node and the word pointed in the node. for (int i = 0; i<HSIZE; i++) { nodep = hash_table[i]; while (nodep) { nextnodep = nodep->next; free(nodep); nodep = nextnodep; } hash_table[i] = NULL; } return true; } //Make my hash function int hash(const char *word) { int len = strlen(word); int resulthash = 0; for(int i=0; i <len;i++) { resulthash += word[i]; } resulthash = resulthash%HSIZE; return resulthash; } <file_sep><?php // configuration require("../includes/config.php"); // render portfolio if($_SESSION["id"]) { $usr_stocks = query("SELECT * FROM stocks WHERE id = ?" ,$_SESSION["id"]); render("portfolio.php", ["title" => "Portfolio", "stocks" => $usr_stocks]); } else { render("login_form.php", ["title" => "Log In"]); } ?> <file_sep>#include <stdio.h> #include <cs50.h> #include <string.h> int encryptchar(int c, int n); int main(void) { printf("Enter a string to be encrypted\n"); string message = GetString(); printf("Enter the encryption range\n"); int range = GetInt(); printf("Result: "); for(int i=0, n = strlen(message); i< n; i++) { char x = (char)encryptchar(message[i] , range); printf("%c" , x); } printf("\n"); } int encryptchar(int c, int n) { char* test = "ABCDEFGHIJKLMNOPQRSTUVWQYZ"; char* test2 = "abcdefghijklmnopqrstuvwxyz"; if(strchr(test, (char)c)){ int resultc = (c + n); if(resultc > 90) { resultc = (resultc % 90) + 64; } return resultc; } else if(strchr(test2, (char)c)) { int resultc = (c + n); if(resultc > 122) { resultc = (resultc % 122) + 96; } return resultc; } return c; } <file_sep>#include <stdio.h> #include <cs50.h> int main(void){ printf("Please enter your card number :\n"); int cardnum = GetInt(); string Cardtype = ""; //Start Auth printf("%d", cardnum.charAt(3)); }
04c911fe562482249066fe3bb08a2550eac4d044
[ "C", "PHP" ]
10
C
fishr01/CS50-Problem-Sets
4d92633da4a0da43dadb1d07b737bce3762609e2
db5a5bf16afe297b20ac6ade9ff43257e44f0d96
refs/heads/master
<repo_name>Daliuxas200/nature-of-code<file_sep>/noc_p5/noc_01.2_gausian/sketch.js let dot; let tx = 0; let ty = 1000000; function setup() { createCanvas(windowWidth, windowHeight); dot = new Walker(); } function draw() { dot.step(); dot.display(); } class Walker{ constructor(){ this.x = width/2; this.y = height/2; this.xOld = width/2; this.yOld = height/2; } display(){ stroke(0); line(this.xOld,this.yOld,this.x,this.y); } // RANDOM GAUSIAN CURVE MOVEMENT // step(){ // this.xOld = this.x; // this.yOld = this.y; // const stepx = randomGaussian(0,5); // const stepy = randomGaussian(0,5); // this.x += stepx; // this.y += stepy; // } // RANDOM MONTECARLO PROBABILITY MOVEMENT // step(){ // this.xOld = this.x; // this.yOld = this.y; // const stepx = monte()*5; // const stepy = monte()*5; // this.x += stepx; // this.y += stepy; // } // RANDOM PERLIN NOISE MOVEMENT step(){ this.xOld = this.x; this.yOld = this.y; tx+=0.03; ty+=0.03; const stepx = map(noise(tx),0,1,-2,2) const stepy = map(noise(ty),0,1,-2,2) this.x += stepx; this.y += stepy; } } function monte(){ let test = true; while(test){ let r1 = random(-1,1); let prob = Math.sqrt(Math.abs(r1)); let r2 = random(0,1); if(prob>r2){ test = false; return r1; } } }<file_sep>/noc_p5/noc_01.1_random_walker/sketch.js let dot; function setup() { createCanvas(windowWidth, windowHeight); dot = new Walker(); } function draw() { dot.step(); dot.display(); } class Walker{ constructor(){ this.x = width/2; this.y = height/2; } display(){ stroke(0); point(this.x,this.y); } step(){ const stepx = random(-1,1); const stepy = random(-1,1); this.x += stepx; this.y += stepy; } }<file_sep>/noc_p5/noc_01_ecosystem/sketch.js let actors = []; function setup() { createCanvas(windowWidth-100, windowHeight-100); let bears = new Array(5).fill().map((a,i)=> new Bear(i)) let flies = new Array(60).fill().map((a,i)=> new Fly(i)) actors = [ ...bears, ...flies]; frameRate(30) } function draw() { background(250,240,250); actors = actors.filter(a => a.alive); actors.forEach( actor => actor.update(actors)); actors.forEach( actor => actor.display()); } class Bear{ constructor(i){ this.loc = createVector(...randomLoc()); this.vel = createVector(0,0); this.acc = createVector(0.1,0.1); this.color = [180, 75, 1]; this.size = 100; this.species = 'bear'; this.type = 'creature'; this.maxSpeed = 2; this.maxAcc = 0.1; this.time = i*1000; this.alive = true; this.baseSmell = 1; this.smell = this.baseSmell; this.smellDecay = 0.002; this.smellFactor = 2; } display(){ stroke(0); fill(...this.color); ellipse(this.loc.x,this.loc.y,this.size,this.size); } update(creatures){ random() < 0.001 && this.poop(); if(this.smell>this.baseSmell) this.smell -= this.smellDecay; let interaction = this.greet(creatures); !interaction && this.moveRandomly(); this.edge(); } moveRandomly(){ const r = noise(this.time+=0.01); if(r < 0.2){ this.acc = p5.Vector.mult(this.vel,-0.1); } else if(r < 1){ let rAcc = p5.Vector.random2D(); this.acc.add(rAcc); this.acc.limit(this.maxAcc) } this.move(); } move(){ this.edge(); this.vel.add(this.acc); this.vel.limit(this.maxSpeed); this.loc.add(this.vel); } greet(creatures){ // check if creature interacted with anyone let bears = creatures.filter( a => a.species === 'bear' && a !== this); let closeBears = bears.filter( a => p5.Vector.sub(this.loc,a.loc).mag() < this.size); if (closeBears.length){ let closestBear = closeBears.sort( (a,b) => p5.Vector.sub(this.loc,a.loc).mag() <= p5.Vector.sub(this.loc,b.loc).mag() ? 1 : -1 ).pop(); let distance = p5.Vector.sub(this.loc, closestBear.loc); if(distance.mag() < (this.size - this.maxSpeed*2) ){ this.acc = distance.normalize().mult(this.maxSpeed); } else { const r = random(); if(r < 0.99){ this.acc = p5.Vector.mult(this.vel,-1); } else { this.acc = distance.normalize().mult(this.maxSpeed); } } this.move(); return true; } } poop(){ const poopSize = randomGaussian(30,5); this.smell += map(poopSize,0,40,0,this.smellFactor); actors.unshift(new Poop(this.loc.x,this.loc.y,poopSize)) } edge(){ if ((this.loc.x > width) || (this.loc.x < 0)||(this.loc.y > height) || (this.loc.y < 0)){ this.vel.rotate(180) this.acc.rotate(180) } } } class Fly{ constructor(i){ this.loc = createVector(...randomLoc()); this.vel = createVector(0,0); this.acc = createVector(0.1,0.1); this.color = [0, 0, 0]; this.size = 5; this.type = 'creature'; this.species = 'fly' this.maxSpeed = 5; this.maxAcc = 1; this.time = i*500; this.alive = true; this.maxSmellDistance = 200; this.target = undefined; this.targetUpdateTimer = 0; this.targetUpdateFrequency = 30; this.smell = 0; } display(){ stroke(0); fill(...this.color); ellipse(this.loc.x,this.loc.y,this.size,this.size); } update(creatures){ let closestCreature = creatures.map( creature => { let attraction = this.smellAttraction(creature); let creatureAttr = {creature,attraction}; return creatureAttr; }) .filter( c => c.attraction > 0 ) .sort( (c1,c2) => c1.attraction - c2.attraction) .pop(); if(this.targetUpdateTimer <= 0){ if(!closestCreature){ this.target = undefined; } else { this.target = closestCreature.creature; this.targetUpdateTimer = this.targetUpdateFrequency; } } if(this.target){ this.follow(this.target); } else { this.moveRandomly(); } this.targetUpdateTimer--; } moveRandomly(){ const r = random(); if(r < 0.2){ this.acc = p5.Vector.mult(this.vel,-0.1); } else if(r < 1){ let rAcc = p5.Vector.random2D(); this.acc.add(rAcc); } this.acc.limit(this.maxAcc); this.move(); } move(){ this.edge(); this.vel.add(this.acc); this.vel.limit(this.maxSpeed); this.loc.add(this.vel); } follow(target){ let distance = p5.Vector.sub(target.loc, this.loc); let rAcc = p5.Vector.random2D().mult(this.maxAcc/2); this.acc.add(distance.normalize().mult(this.maxAcc/5)).add(rAcc); this.acc.limit(this.maxAcc); this.move(); } edge(){ if ((this.loc.x > width) || (this.loc.x < 0)||(this.loc.y > height) || (this.loc.y < 0)){ this.vel.rotate(180) this.acc.rotate(180) } } smellAttraction(target){ let distance = p5.Vector.sub(this.loc, target.loc).mag(); // inverse square law 1 to 0 for distance, and multiplied by smellyness factor let attraction = sq(max(0,map(distance,0,this.maxSmellDistance,1,0)))*target.smell return attraction; } } // Self eexplanatory class Poop{ constructor(x,y,size){ this.loc = createVector(x,y); this.size = size; this.age = 1; this.smell = this.age*map(this.size,0,40,0,5); // 0 to 5 this.type = 'inanimate'; this.alive = true; this.color = [74, 89, 23,map(this.age,0,1,0,255)]; } update(){ this.age -= 0.002; this.smell = this.age*map(this.size,0,40,0,5); this.color[3] = map(this.age,0,1,0,255); if(this.age < 0){ this.alive = false; } // console.log(this.smell) } display(){ noStroke(); fill(...this.color); ellipse(this.loc.x,this.loc.y,this.size,this.size); } } // Function to genrate a random location vector for object creation function randomLoc(){ return [random(0,width),random(0,height)] }
0e1583205ffb8487a77717d5a8af0bdf8ae3acba
[ "JavaScript" ]
3
JavaScript
Daliuxas200/nature-of-code
680b23d597831203bb523614462e6c61b5eb917b
307e2452cdda73070a88c05e79aa796f1ccf2a83
refs/heads/master
<file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="css/styles.css"> <title>Week Two Independent Project</title> </head> <body> <div class="firstHeading"> <h1>TRIANGLE TRACKER</h1> <img src="images/download.jpeg"> </div> <h2>What is Triangle Tracker ?</h2> <p>Welcome to Triangle Tracker , the only application that helps you check which triangles between <strong>Isosceles</strong>, <strong>Equilateral</strong> and <strong>Scalene</strong> using your own values.</p> <h3>Key in the Length Values to get started.</h3> <form> <div class="box"> <p><input type="number" placeholder="length 1 (NUMBER)" name="side1" id="length1" value="length1"></p> <p><input type="number" placeholder="length 2 (NUMBER)" name="side2" id="length2" value="length2"></p> <p><input type="number" placeholder="length 3 (NUMBER)" name="side3" id="length3" value="length3"></p> </div> <button onClick="triangle()">Submit</button> <button onClick= "reload()">Refresh</button> </form> <script src="js/script.js"></script> </body> </html> <file_sep>function triangle() { var side1 = parseInt(document.getElementById("length1").value); var side2 = parseInt(document.getElementById("length2").value); var side3 = parseInt(document.getElementById("length3").value); if (side1 > 0 && side2 > 0 && side3 > 0) { if (side1 == side2 && side2 == side3 && side3 == side1) { alert("Equilateral Triangle"); } else if (side1 + side2 <= side3 || side2 + side3 <= side1 || side3 + side1 <= side2){ alert("Triangel CANNOT be created!"); } else if (side1 == side2 || side2 == side3 || side3 == side1){ alert("Isosceles Triangle"); } else if(side1 != side2 && side2 != side3 && side3 != side1){ alert("Scalene Triangle"); } } else{ alert("Value has to be greater than zero"); } } function reload() { location.reload(); } <file_sep># TRIANGLE TRACKER # Project Description Knowing the type of a triangle one is sometimes is difficult isn't ? This Triangle Tracker Application uses the length values entered by the user to identify whether the triangle is Isosceles,Scalene or Obtuse. ![Sample Picture] (images/download.jpeg) ### Author Information My name is **<NAME>** the creator of this application.I am a student a **Moringa School** training to be a software developer. ## Setup Instruction To get started with this application you need to simply not get Internet Connection and get Started. ## BDD **Feature:** As a user , I want to know given types of triangles using the length measurements inputed. **Background:** There exists the following types of triangles 1. Obtuse. 2. Equilateral. 3. Scalene. 4. Right Angled. 5. Obtuse. 6. Acute. Given that this Application only tests for __three__ of the given Triangles since they are determined by their length size. **Implementation** As a developer i introduced the user to the application and how to start off. Once the user inputs data specifically in form of numbers . I collect the values inputed and validate them for the computer. This now enables the process of checking the various conditions of forming the triangles and hence manage to identify a given triangle. ## Technologies Used The application runs on: 1. HTML 5 2. CSS 3. JAVASCRIPT ## Contact information One can contribute to the project through the following link. https://github.com/derriqo/Triangle-Tracker-WK2IP- email me at <EMAIL> skype derriq6 ## License and Copyright Information This project is licensed under the MIT License Copyright 2018 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sub license, 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 NON INFRINGEMENT. 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.
8dfd00e0cbb8eb175c350c89203f16b51eb16fa3
[ "JavaScript", "HTML", "Markdown" ]
3
HTML
derriqo/Triangle-Tracker-WK2IP-
702753af77ad4aeed17dbfe8b54932a582155377
7f18b40860caa9aa891e1e7df69e8051e37fa403
refs/heads/master
<repo_name>solary2014/MeituanSeat<file_sep>/src/com/lly/meituanseat/SectionView.java package com.lly.meituanseat; import java.util.ArrayList; import java.util.Collections; import android.animation.Animator; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.util.AttributeSet; import android.util.FloatMath; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; import android.view.animation.DecelerateInterpolator; import android.widget.Space; import android.widget.Toast; public class SectionView extends View { private float mSpaceX; private float mSpaceY; private float tranlateX; private float tranlateY; /** * 座位已售 */ private static final int SEAT_TYPE_SOLD = 1; /** * 座位已经选中 */ private static final int SEAT_TYPE_SELECTED = 2; /** * 座位可选 */ private static final int SEAT_TYPE_AVAILABLE = 3; /** * 座位不可用 */ private static final int SEAT_TYPE_NOT_AVAILABLE = 4; float scaleX, scaleY; private int mViewW; private int mViewH; private int row = 10; private int column = 10; private float defSeatWidth = 40.0f; private float defSeatHight = 40.0f; private int SeatWidth; private int SeatHight; private int leftmargin; private int rigthmargin; private int middenmargin; private int topmargin; private int spaceing = 5; private Bitmap SeatChecked; private Bitmap SeatLock; private Bitmap SeatNormal; private Bitmap mBitMapOverView; private float mOverViewWidth; private float mOverViewHight; private Matrix mMatrix = new Matrix(); private float scale; protected boolean firstScale = true; private float scalef = 1.0f; private Paint mTextPaint; private int mTextHeight; private float mTextWidth; private float mNumberHeight; Paint.FontMetrics lineNumberPaintFontMetrics; private float scale1; ArrayList<String> lineNumbers = new ArrayList<String>(); private Paint OverRectPaint; private float overRectLineWidth = 2; public SectionView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { mTextPaint = new Paint(); mNumberHeight = mTextPaint.measureText("4"); mTextWidth = getResources().getDisplayMetrics().density * 20; lineNumberPaintFontMetrics = mTextPaint.getFontMetrics(); mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mTextPaint.setColor(bacColor); mTextPaint.setTextSize(getResources().getDisplayMetrics().density * 16); mTextPaint.setTextAlign(Paint.Align.CENTER); if(getWidth()>0&&getHeight()>0){ mOverViewWidth = (int) (getResources().getDisplayMetrics().density*getWidth() * 2/5); mOverViewHight = (int) (getResources().getDisplayMetrics().density*getHeight()*2/5); }else{ mOverViewWidth = (int) (getResources().getDisplayMetrics().density*140); mOverViewHight = (int) (getResources().getDisplayMetrics().density*100); } SeatChecked = BitmapFactory.decodeResource(getResources(), R.drawable.seat_checked); SeatLock = BitmapFactory.decodeResource(getResources(), R.drawable.seat_lock); SeatNormal = BitmapFactory.decodeResource(getResources(), R.drawable.seat_normal); SeatWidth = SeatChecked.getWidth(); SeatHight = SeatChecked.getHeight(); scale = defSeatWidth / SeatChecked.getWidth(); mSpaceX = getResources().getDisplayMetrics().density * 10; mSpaceY = getResources().getDisplayMetrics().density * 10; mViewW = (int) (column * SeatWidth * scale + mSpaceX * (column - 1)+mTextWidth); mViewH = (int) (row * SeatHight * scale + mSpaceY * (row - 1)); if(lineNumbers==null){ lineNumbers=new ArrayList<String>(); }else if(lineNumbers.size()<=0) { for (int i = 0; i < row; i++) { lineNumbers.add((i + 1) + ""); } } matrix.postTranslate(mTextWidth+mSpaceX, 0); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mViewH != 0 && mViewW != 0) { } drawSeat(canvas); drawText(canvas); drawOverView(canvas); drawOvewRect(canvas); } float scaleoverX; float scaleoverY ; private void drawOvewRect(Canvas canvas) { OverRectPaint = new Paint(); OverRectPaint.setColor(Color.RED); OverRectPaint.setStyle(Paint.Style.STROKE); OverRectPaint.setStrokeWidth(overRectLineWidth); int tempViewW ; int tempViewH; if(getMeasuredWidth()<mViewW){ tempViewW = getMeasuredWidth(); }else{ tempViewW = mViewW; } if(getMeasuredHeight()<mViewH){ tempViewH = getMeasuredHeight(); }else{ tempViewH = mViewH; } try{ Rect rect ; if(getMatrixScaleX()>= 1.0f){ rect = new Rect((int)(scaleoverX*Math.abs(getTranslateX())/getMatrixScaleX()), (int)(scaleoverY*Math.abs(getTranslateY())/getMatrixScaleX()), (int)(scaleoverX*Math.abs(getTranslateX())/getMatrixScaleX()+tempViewW*scaleoverX/getMatrixScaleX()), (int)(scaleoverY*Math.abs(getTranslateY())/getMatrixScaleX()+tempViewH*scaleoverY/getMatrixScaleX())); }else{ rect = new Rect((int)(scaleoverX*Math.abs(getTranslateX())), (int)(scaleoverY*Math.abs(getTranslateY())), (int)(scaleoverX*Math.abs(getTranslateX())+tempViewW*scaleoverX), (int)(scaleoverY*Math.abs(getTranslateY())+tempViewH*scaleoverY)); } canvas.drawRect(rect, OverRectPaint); }catch(Exception e){ e.printStackTrace(); } } int bacColor = Color.parseColor("#7e000000"); private void drawOverView(Canvas canvas) { mBitMapOverView = Bitmap.createBitmap((int)mOverViewWidth,(int)mOverViewHight,Bitmap.Config.ARGB_8888); Canvas OverViewCanvas = new Canvas(mBitMapOverView); Paint paint = new Paint(); paint.setColor(bacColor); scaleoverX = mOverViewWidth / mViewW; scaleoverY = mOverViewHight / mViewH; float tempX = mViewW * scaleoverX; float tempY = mViewH * scaleoverY; OverViewCanvas.drawRect(0, 0, (float)tempX, (float)tempY, paint); Matrix tempoverMatrix = new Matrix(); for (int i = 0; i < row; i++) { float top = i * SeatHight * scale * scaleoverY+ i * mSpaceY * scaleoverY; for (int j = 0; j < column; j++) { float left = j * SeatWidth * scale * scaleoverX + j * mSpaceX * scaleoverX+mTextWidth*scaleoverX; tempoverMatrix.setTranslate(left, top); tempoverMatrix.postScale(scale*scaleoverX, scale*scaleoverY, left, top); int state = getSeatType(i, j); switch (state) { case SEAT_TYPE_SOLD: OverViewCanvas.drawBitmap(SeatLock, tempoverMatrix, null); break; case SEAT_TYPE_SELECTED: OverViewCanvas.drawBitmap(SeatChecked, tempoverMatrix, null); break; case SEAT_TYPE_AVAILABLE: OverViewCanvas.drawBitmap(SeatNormal, tempoverMatrix, null); break; case SEAT_TYPE_NOT_AVAILABLE: break; } } } canvas.drawBitmap(mBitMapOverView,0,0,null); } private void drawText(Canvas canvas) { mTextPaint.setColor(bacColor); RectF rectF = new RectF(); rectF.top = getTranslateY() - mNumberHeight/2; rectF.bottom = getTranslateY()+ mViewH* getMatrixScaleX() + mNumberHeight/2; rectF.left = 0; rectF.right = mTextWidth; canvas.drawRoundRect(rectF, mTextWidth/2, mTextWidth/2, mTextPaint); mTextPaint.setColor(Color.WHITE); for (int i = 0; i < row; i++) { float top = (i *SeatHight*scale + i * mSpaceY) * getMatrixScaleX() + getTranslateY(); float bottom = (i * SeatHight*scale + i * mSpaceY + SeatHight) * getMatrixScaleX() + getTranslateY(); float baseline = (bottom + top - lineNumberPaintFontMetrics.bottom - lineNumberPaintFontMetrics.top ) / 2-6; canvas.drawText(lineNumbers.get(i), mTextWidth / 2, baseline, mTextPaint); } } Matrix tempMatrix = new Matrix(); Paint paint = new Paint(); private void drawSeat(Canvas canvas) { float zoom = getMatrixScaleX(); Log.i("lly","getMatrixScaleX = "+getMatrixScaleX()+",getMatrixScaleY = "+getMatrixScaleY()); scale1 = zoom; tranlateX = getTranslateX(); tranlateY = getTranslateY(); paint.setColor(Color.RED); paint.setTextSize(getResources().getDisplayMetrics().density * 16); Log.i("lly", "scale1 ===" + scale1); for (int i = 0; i < row; i++) { float top = i * SeatHight * scale * scale1 + i * mSpaceY * scale1 + tranlateY; for (int j = 0; j < column; j++) { float left = j * SeatWidth * scale * scale1 + j * mSpaceX * scale1 + tranlateX; tempMatrix.setTranslate(left, top); tempMatrix.postScale(scale, scale, left, top); tempMatrix.postScale(scale1, scale1, left, top); int state = getSeatType(i, j); switch (state) { case SEAT_TYPE_SOLD: canvas.drawBitmap(SeatLock, tempMatrix, null); break; case SEAT_TYPE_SELECTED: canvas.drawBitmap(SeatChecked, tempMatrix, null); break; case SEAT_TYPE_AVAILABLE: canvas.drawBitmap(SeatNormal, tempMatrix, null); break; case SEAT_TYPE_NOT_AVAILABLE: break; } } } } private int getSeatType(int row, int column) { if (isHave(getID(row, column)) >= 0) { return SEAT_TYPE_SELECTED; } return SEAT_TYPE_AVAILABLE; } @Override public boolean onTouchEvent(MotionEvent event) { scaleGestureDetector.onTouchEvent(event); gestureDetector.onTouchEvent(event); return true; } float[] m = new float[9]; Matrix matrix = new Matrix(); private float getTranslateX() { matrix.getValues(m); return m[2]; } private float getTranslateY() { matrix.getValues(m); return m[5]; } private float getMatrixScaleY() { matrix.getValues(m); return m[4]; } private float getMatrixScaleX() { matrix.getValues(m); Log.i("lly", "zoom ==g= " + m[Matrix.MSCALE_X]); return m[Matrix.MSCALE_X]; } private void setMatrixScale(float scale){ m[Matrix.MSCALE_X] = scale; m[Matrix.MSCALE_Y] = scale; } ScaleGestureDetector scaleGestureDetector = new ScaleGestureDetector( getContext(), new ScaleGestureDetector.OnScaleGestureListener() { @Override public boolean onScale(ScaleGestureDetector detector) { float scaleFactor = detector.getScaleFactor(); //scaleX = detector.getCurrentSpanX(); //scaleY = detector.getCurrentSpanY(); //直接判断大于2会导致获取的matrix缩放比例继续执行一次从而导致变成2.000001之类的数从而使 //判断条件一直为真从而不会执行缩小动作 //判断相乘大于2 可以是当前获得的缩放比例即使是1.9999之类的数如果继续放大即使乘以1.0001也会比2大从而 //避免上述问题。 if (getMatrixScaleY() * scaleFactor > 2) { scaleFactor = 2 / getMatrixScaleY(); } if (getMatrixScaleY() * scaleFactor < 0.8) { scaleFactor = 0.8f / getMatrixScaleY(); } matrix.postScale(scaleFactor, scaleFactor); invalidate(); return true; } @Override public boolean onScaleBegin(ScaleGestureDetector detector) { return true; } @Override public void onScaleEnd(ScaleGestureDetector detector) { } }); GestureDetector gestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() { public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { float tempMViewW = column * SeatWidth*scale*scale1+(column -1)*mSpaceX*scale1+mTextWidth-getWidth(); float tempmViewH = row * SeatHight * scale * scale1 + (row -1) * mSpaceY * scale1 - getHeight(); if((getTranslateX()>mTextWidth+mSpaceX)&& distanceX<0){ distanceX = 0; } if((Math.abs(getTranslateX())>tempMViewW)&&(distanceX>0)){ distanceX = 0; } if((getTranslateY()>0)&&distanceY<0){ distanceY=0; } if((Math.abs(getTranslateY())>tempmViewH)&&(distanceY>0)){ distanceY = 0; } matrix.postTranslate(-distanceX, -distanceY); Log.i("lly","distanceX =="+distanceX+",distanceY ="+distanceY+",tempMViewW ="+tempMViewW +",getTranslateX()="+getTranslateX()); invalidate(); return false; } public boolean onSingleTapConfirmed(MotionEvent e) { int x = (int) e.getX(); int y = (int) e.getY(); for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { int tempX = (int) ((j * SeatWidth * scale + j * mSpaceX) * getMatrixScaleX() + getTranslateX()); int maxTemX = (int) (tempX + SeatWidth * scale * getMatrixScaleX()); int tempY = (int) ((i * SeatHight * scale + i * mSpaceX) * getMatrixScaleY() + getTranslateY()); int maxTempY = (int) (tempY + SeatHight * scale * getMatrixScaleY()); if (x >= tempX && x <= maxTemX && y >= tempY && y <= maxTempY) { int id = getID(i, j); int index = isHave(id); if (index >= 0) { remove(index); } else { addChooseSeat(i, j); Log.i("lly","i === "+i+",j === "+j); } float currentScaleY = getMatrixScaleY(); if (currentScaleY < 1.7f) { scaleX = x; scaleY = y; zoomAnimate(currentScaleY, 1.9f); } invalidate(); break; } } } return super.onSingleTapConfirmed(e); } }); private float zoom; private void zoom(float zoom) { float z = zoom / getMatrixScaleX(); matrix.postScale(z, z, scaleX, scaleY); invalidate(); } private void zoomAnimate(float cur, float tar) { ValueAnimator valueAnimator = ValueAnimator.ofFloat(cur, tar); valueAnimator.setInterpolator(new DecelerateInterpolator()); ZoomAnimation zoomAnim = new ZoomAnimation(); valueAnimator.addUpdateListener(zoomAnim); valueAnimator.addListener(zoomAnim); valueAnimator.setDuration(400); valueAnimator.start(); } class ZoomAnimation implements ValueAnimator.AnimatorUpdateListener, Animator.AnimatorListener { @Override public void onAnimationUpdate(ValueAnimator animation) { zoom = (Float) animation.getAnimatedValue(); zoom(zoom); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } @Override public void onAnimationStart(Animator animation) { } } ArrayList<Integer> selects = new ArrayList<Integer>(); private int getID(int row, int column) { return row * this.column + (column + 1); } private int isHave(Integer seat) { return Collections.binarySearch(selects, seat); } private void remove(int index) { selects.remove(index); } private void addChooseSeat(int row, int column) { int id = getID(row, column); for (int i = 0; i < selects.size(); i++) { int item = selects.get(i); if (id < item) { selects.add(i, id); return; } } selects.add(id); } }
f4789fde1cdde3635542fa5f34705aabad858c71
[ "Java" ]
1
Java
solary2014/MeituanSeat
c746e29a99833217ad5e5f912703e8b309574d8e
f2a4f9bfc3dd80a3dc920c7f7ec356dfe312f9f6
refs/heads/master
<file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 7/31/18 * Time: 09:44 AM */ include "../db_connection.php"; require_once(__DIR__ . '/vendor/autoload.php'); $job1 = new \Cron\Job\ShellJob(); $job1->setCommand('python /Users/raka_matsukaze/Documents/python_docs/hello_world.py'); $job1->setSchedule(new Cron\Schedule\CrontabSchedule('* * * * *')); //Tambahkan cron $resolver = new \Cron\Resolver\ArrayResolver(); $resolver->addJob($job1); $cron = new \Cron\Cron(); $cron->setExecutor(new \Cron\Executor\Executor()); $cron->setResolver($resolver); $cron->run();<file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 4/22/18 * Time: 08:12 AM */ include "db_connection.php" ?> <!doctype html> <head> <?php include "head_tag.php"?> </head> <body> <?php include "left_panel.php"?> <div id="right-panel" class="right-panel"> <?php include "header_tag.php"?> <div class="breadcrumbs"> <div class="col-sm-4"> <div class="page-header float-left"> <div class="page-title"> <h1>Temperature</h1> </div> </div> </div> <div class="col-sm-8"> <div class="page-header float-right"> <div class="page-title"> <ol class="breadcrumb text-right"> <li class="active">Table</li> </ol> </div> </div> </div> </div> <div class="content mt-3"> <div class="animated fadeIn"> <div class="col-sm-6 col-lg-12"> <h3>Database Suhu Udara</h3><hr> </div> <div class="col-sm-6 col-lg-12"> <h5>Pilih tanggal:</h5> <form method="post" action=""> <div class="form-row align-items-center"> <div class="col-sm-3 my-1"> <select class="custom-select" name="tanggal"> <option>--- Tanggal ---</option> <?php for($i = 1; $i <= 31; $i++) { ?> <option value="<?php echo $i?>"><?php echo $i?></option> <?php } ?> </select> </div> <div class="col-sm-3 my-1"> <select class="custom-select" name="bulan"> <option>--- Bulan ---</option> <option value="01">Januari</option> <option value="02">Februari</option> <option value="03">Maret</option> <option value="04">April</option> <option value="05">Mei</option> <option value="06">Juni</option> <option value="07">Juli</option> <option value="08">Agustus</option> <option value="09">September</option> <option value="10">Oktober</option> <option value="11">November</option> <option value="12">Desember</option> </select> </div> <div class="col-sm-3 my-1"> <select class="custom-select" name="tahun"> <option>--- Tahun ---</option> <?php $q = $conn->query("SELECT DISTINCT substr(tanggal, 1, 4) AS tahun FROM suhu_kelembapan;"); while($baris = $q->fetch_array()) { ?> <option value="<?php echo $baris['tahun']?>"><?php echo $baris['tahun']?></option> <?php } ?> </select> </div> <div class="col-sm-3 my-1"> <input type="submit" class="btn btn-outline-primary" value="LIHAT"> </div> </div> </form> </div> <div class="col-sm-6 col-lg-12"> <hr> <div class="card"> <div class="card-header"> <strong class="card-title">Data Temperatur</strong> </div> <div class="card-body"> <table id="bootstrap-data-table" class="table table-striped table-bordered"> <thead> <tr> <th>No.</th> <th>Suhu</th> <th>Jam</th> </tr> </thead> <tbody> <?php error_reporting(0); $nomor = 1; $tanggal = $_POST['tanggal']; $bulan = $_POST['bulan']; $tahun = $_POST['tahun']; $komplit_tanggal = $tahun.'-'.$bulan.'-'.$tanggal; $result = $conn->query("SELECT * FROM suhu_kelembapan WHERE tanggal = '$komplit_tanggal'"); while ($row = $result->fetch_array()) { ?> <tr> <td><?php echo $nomor++?></td> <td><?php echo $row['temperature']?></td> <td><?php echo $row['waktu']?></td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div> </div> </div> <?php include "assets_js.php"?> </body> </html><file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 6/2/18 * Time: 23:03 PM */ include "koneksi.php"; // $sql = $conn->query("SELECT suhu, kelembapan FROM realtime_suhu_kelembapan ORDER BY id DESC LIMIT 1"); $sql = $conn->query("SELECT suhu, kelembapan FROM skripsi_realtime.coba_koneksi_arduino ORDER BY record_id DESC LIMIT 1"); $data = $sql->fetch_array(); $kelembapan = $data['kelembapan']; echo $kelembapan; ?><file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 8/7/18 * Time: 00:53 AM */ include "Ssh2_crontab_manager.php"; $crontab = new Ssh2_crontab_manager('192.168.1.24', '21', 'pi', 'raspberry'); $crontab->append_cronjob('* * * * * python hello_world.py');<file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 8/6/18 * Time: 19:47 PM */ include "db_connection.php"; ?> <!doctype html> <head> <?php include "head_tag.php";?> </head> <body> <?php include "left_panel.php"?> <div class="right-panel" id="right-panel"> <?php include "header_tag.php";?> <div class="breadcrumbs"> <div class="col-sm-4"> <div class="page-header float-left"> <div class="page-title"> <h1>Documentations</h1> </div> </div> </div> <div class="col-sm-8"> <div class="page-header float-right"> <div class="page-title"> <ol class="breadcrumb text-right"> <li class="active">Videos</li> </ol> </div> </div> </div> </div> <div class="content mt-3"> <div class="animated fadeIn"> <div class="col-sm-6 col-lg-12"> <h3>Video Penempatan Sensor</h3><hr> </div> <div class="col-sm-6 col-lg-12"> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" src="https://www.youtube.com/embed/eBMN6aWgc6k" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe> </div><hr> </div> <div class="col-sm-6 col-lg-12"> <h3>Video Penyiraman Reguler</h3><hr> </div> <div class="col-sm-6 col-lg-12"> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" src="https://www.youtube.com/embed/XXC2PgAK4bI" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe> </div> </div> </div> </div> </div> <?php include "assets_js.php";?> </body> </html><file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 6/30/18 * Time: 13:13 PM */ error_reporting(0); include "db_connection.php"; $sekarang = date('Y-m-d'); $seminggu_sebelumnya = date('Y-m-d', strtotime('-7 days', strtotime(date('Y-m-d')))); $batas_suhu = 27; $batas_humidity = 50-1; ?> <!doctype html> <head> <?php include "head_tag.php";?> </head> <body> <?php include "left_panel.php"?> <div class="right-panel"> <?php include "header_tag.php"?> <div class="breadcrumbs"> <div class="col-sm-4"> <div class="page-header float-left"> <div class="page-title"> <h1>Analisis</h1> </div> </div> </div> <div class="col-sm-8"> <div class="page-header float-right"> <div class="page-title"> <ol class="breadcrumb text-right"> <li class="active">Suhu dan Kelembapan</li> </ol> </div> </div> </div> </div> <div class="content mt-3"> <div class="animated fadeIn"> <div class="row"> <div class="col-sm-6 col-lg-12"> <h3>Analisis</h3><hr> </div> <div class="col-sm-6 col-lg-12"> <canvas id="temperature-chart"></canvas> <p>Sumber: Nursyamsi, D. 2015. <i>Karakteristik dan Kesesuaian Lahan Tanaman Cabai dan Bawang Merah</i>. Litbang Sumber Daya Lahan Pertanian, Kementerian Pertanian</p><hr> <?php $result = $conn->query("SELECT temperature, humidity, tanggal, waktu FROM suhu_kelembapan WHERE temperature > $batas_suhu AND tanggal BETWEEN '$seminggu_sebelumnya' AND '$sekarang'"); while($row = $result->fetch_array()) { $waktu = explode(":", $row['waktu']); // AMBIL JAM SAJA $s[$row['temperature']][$waktu[0]]+=1; // s[suhu][waktu]. // s[28][10] = 1 // s[28][10] = 2 // s[28][10] = 3 // s[29][10] = 1 // s[28][11] = 1 // s[28][11] = 2 } // echo "<pre>"; // print_r($s); // echo "</pre>"; $maxsuhu = max(array_keys($s)); // dapatkan key(suhu) array tertinggi. $iterbanyak = max(array_values($s[$maxsuhu])); // cari jam terbanyak beerdasarkan value $jamterbanyak = array_search($iterbanyak, $s[$maxsuhu]); echo "<h3>Hasil Analisis</h3>"; $d_temp = $conn->query("SELECT DISTINCT temperature FROM suhu_kelembapan where temperature > $batas_suhu"); $d_humidity = "SELECT DISTINCT humidity FROM suhu_kelembapan WHERE temperature = "; $d_jumhum = "SELECT COUNT(humidity) as jumlah, humidity, HOUR(waktu) as waktu FROM suhu_kelembapan WHERE temperature = "; $arr = array(); $var_se = array(); while($row = mysqli_fetch_assoc($d_temp)) { $h_temp = $conn->query($d_jumhum.$row["temperature"]." GROUP BY humidity, HOUR(waktu)"); while($hrow = mysqli_fetch_assoc($h_temp)) { $a = $row["temperature"]; $b = $hrow['humidity']; $c = $hrow['waktu']; $arr[$a][$b][$c] = $hrow['jumlah']; } } foreach ($arr as $i => $valuos){ //echo $i." , "; foreach ($valuos as $a => $b){ $keys = (int)$a; if ($keys > ($batas_humidity)){ unset($arr[$i][$keys]); } } } echo "<pre><br>"; print_r($arr); echo "</pre>"; $minimum_humidity = 1000; foreach ($arr[$maxsuhu] as $key => $value){ if($key < $minimum_humidity){ $minimum_humidity = $key; } } echo "<hr>"; echo "<strong>Suhu</strong> terbesar adalah <b>".$maxsuhu."</b> dengan <i><b>Humidity</b></i> minimum <b>".$minimum_humidity."</b> pada jam ".$jamterbanyak.":00:00"; ?> </div> </div> </div> </div> </div> <?php include "assets_js.php";?> <script> var ctx = document.getElementById( "temperature-chart" ); ctx.height = 150; var myChart = new Chart( ctx, { type: 'line', data: { // labels: [ "2010", "2011", "2012", "2013", "2014", "2015", "2016" ], labels : [ <?php $result = $conn->query("SELECT temperature, humidity, tanggal, waktu FROM suhu_kelembapan WHERE temperature > $batas_suhu AND tanggal BETWEEN '$seminggu_sebelumnya' AND '$sekarang'"); while($row = $result->fetch_array()) { $tanggal = $row['tanggal']; $waktu = $row['waktu']; echo "'$tanggal | $waktu', "; } ?> ], type: 'line', defaultFontFamily: 'Montserrat', datasets: [ { label: "Temperature", // data: [ 0, 30, 10, 120, 50, 63, 10 ], data: [ <?php $result = $conn->query("SELECT temperature, humidity, tanggal, waktu FROM suhu_kelembapan WHERE temperature > $batas_suhu AND tanggal BETWEEN '$seminggu_sebelumnya' AND '$sekarang'"); while($row = $result->fetch_array()) { $temperature = $row['temperature']; echo $temperature.", "; } ?> ], backgroundColor: 'transparent', borderColor: 'rgba(220,53,69,0.75)', borderWidth: 3, pointStyle: 'circle', pointRadius: 5, pointBorderColor: 'transparent', pointBackgroundColor: 'rgba(220,53,69,0.75)', }, { label: "Humidity", // data: [ 0, 50, 40, 80, 40, 79, 120 ], //data: [ // <?php // $query = mysqli_query($conn, "SELECT humidity FROM suhu_kelembapan WHERE tanggal = '".date('Y-m-d')."'"); // while($row = mysqli_fetch_array($query, MYSQLI_BOTH)) // { // $humidity = $row['humidity']; // echo $humidity.", "; // } // ?> //], backgroundColor: 'transparent', borderColor: 'rgba(40,167,69,0.75)', borderWidth: 3, pointStyle: 'circle', pointRadius: 5, pointBorderColor: 'transparent', pointBackgroundColor: 'rgba(40,167,69,0.75)', } ] }, options: { responsive: true, tooltips: { mode: 'index', titleFontSize: 12, titleFontColor: '#000', bodyFontColor: '#000', backgroundColor: '#fff', titleFontFamily: 'Montserrat', bodyFontFamily: 'Montserrat', cornerRadius: 3, intersect: false, }, legend: { display: false, labels: { usePointStyle: true, fontFamily: 'Montserrat', }, }, scales: { xAxes: [ { display: true, gridLines: { display: true, drawBorder: false }, scaleLabel: { display: false, labelString: 'Tanggal | Waktu' } } ], yAxes: [ { display: true, gridLines: { display: true, drawBorder: false }, scaleLabel: { display: true, labelString: 'Su<NAME>' }, id: 'y-axis-1', ticks: { beginAtZero: true, max: 50 } } ] }, title: { display: false, text: 'Graphic' }, annotation: { drawTime: "afterDraw", annotations: [{ id: 'box1', type: 'box', yScaleID: 'y-axis-1', yMin: 0, yMax: 18, backgroundColor: 'rgba(200, 100, 200, 0.2)', borderColor: 'rgba(100, 100, 100, 0.2)', },{ id: 'box2', type: 'box', yScaleID: 'y-axis-1', yMin: 18, yMax: 30, backgroundColor: 'rgba(148, 255, 162, 0.3)', borderColor: 'rgba(200, 100, 200, 0.2)', },{ id: 'box3', type: 'box', yScaleID: 'y-axis-1', yMin: 30, yMax: 50, backgroundColor: 'rgba(200, 100, 200, 0.2)', borderColor: 'rgba(200, 100, 200, 0.2)', }] } } } ); </script> </body> </html><file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 5/29/18 * Time: 23:35 PM */ include "db_connection.php"; $id = $_GET['id']; $edit_photo = $conn->query("SELECT * FROM documentation WHERE record_id = $id"); $data = $edit_photo->fetch_array(); ?> <!doctype html> <head> <?php include "head_tag.php";?> </head> <body> <?php include "left_panel.php";?> <div class="right-panel" id="right-panel"> <?php include "header_tag.php";?> <div class="breadcrumbs"> <div class="col-sm-4"> <div class="page-header float-left"> <div class="page-title"> <h1>Documentation</h1> </div> </div> </div> <div class="col-sm-8"> <div class="page-header float-right"> <div class="page-title"> <ol class="breadcrumb text-right"> <li class="active">Photos</li> </ol> </div> </div> </div> </div> <div class="content mt-3"> <div class="animated fadeIn"> <div class="col-sm-12"> <h3>Edit Foto dan Data Dokumentasi</h3><hr> </div> <div class="col-sm-12"> <form method="post" enctype="multipart/form-data" action="photo_form_action.php?id=<?php echo $data['record_id']?>"> <table class="table table-bordered"> <tr> <td rowspan="2"> <img src="images/docs/photos/<?php echo $data['file_name']?>" width="400" height="400"> </td> <td> <div class="form-group"> <label>Title</label> <input type="text" class="form-control" name="title" value="<?php echo $data['name']?>" required/> </div> <div class="form-group"> <label>Description</label> <textarea name="description" class="form-control"><?php echo $data['description']?></textarea> </div> <div class="form-group"> <label>Photo File (No need to be filled if you don't want to be replaced)</label> <input type="file" class="form-control-file" name="foto"/> </div> <div class="form-group"> <input type="submit" class="btn btn-outline-primary" value="EDIT"/> <a href="photo_docs.php" class="btn btn-outline-danger">CANCEL</a> </div> </td> </tr> </table> </form> </div> </div> </div> </div> <?php include "assets_js.php"?> </body> </html><file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 7/2/18 * Time: 20:59 PM */ require_once __DIR__ . '/vendor/autoload.php'; $stemmerFactory = new \Sastrawi\Stemmer\StemmerFactory(); $stemmer = $stemmerFactory->createStemmer(); $kalimat = 'Saya galau ditinggal pacar karena saya melihat dia bersama orang lain'; $output = $stemmer->stem($kalimat); echo 'Variabel biasa<br>'; echo '---------------------------------------------------------<br>'; echo 'Kalimat asli: '.$kalimat.'<br>'; echo 'Kalimat <i>stemming</i>: '.$output.'<br>'; ?><file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 5/8/18 * Time: 00:50 AM */ include "db_connection.php"; ?> <!doctype html> <head> <?php include "head_tag.php";?> </head> <body> <?php include "left_panel.php"?> <div class="right-panel" id="right-panel"> <?php include "header_tag.php"?> <div class="breadcrumbs"> <div class="col-sm-4"> <div class="page-header float-left"> <div class="page-title"> <h1>Documentations</h1> </div> </div> </div> <div class="col-sm-8"> <div class="page-header float-right"> <div class="page-title"> <ol class="breadcrumb text-right"> <li class="active">Photos</li> </ol> </div> </div> </div> </div> <?php error_reporting(0); $sukses = $_GET['sukses']; if($sukses == 1) { ?> <div class="alert alert-success alert-dismissible fade show" role="alert"> <strong>Data berhasil diubah!</strong> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <?php } else if($sukses == 2) { ?> <div class="alert alert-success alert-dismissible fade show" role="alert"> <strong>Data berhasil dimasukkan!</strong> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <?php } else if($sukses == 3) { ?> <div class="alert alert-success alert-dismissible fade show" role="alert"> <strong>Data berhasil dihapus!</strong> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <?php } ?> <div class="content mt-3"> <div class="animated fadeIn"> <div class="col-sm-12"> <h3>Database Foto Perkembangan Tanaman</h3><hr> </div> <div class="col-lg-12"> <form method="post" enctype="multipart/form-data" action="upload_pict.php"> <div class="form-row"> <div class="form-group col-md-3"> <label>Photo</label> <input type="file" class="form-control-file" name="foto"/> </div> <div class="form-group col-md-3"> <label>Title</label> <input type="text" class="form-control" name="title" required/> </div> <div class="form-group col-md-3"> <label>Description</label> <input type="text" class="form-control" name="description" required/> </div> <div class="form-group col-md-3"> <label>&nbsp;</label><br> <input type="submit" value="UPLOAD" class="btn btn-outline-success"/> </div> </div> </form><hr> </div> <!-- Foto di sini --> <?php $photo_result = $conn->query("SELECT * FROM documentation ORDER BY documentation.date DESC;"); while($row_photo = $photo_result->fetch_array()) { ?> <div class="col-md-4"> <div class="card"> <img class="card-img-top" src="images/docs/photos/<?php echo $row_photo['file_name']?>" width="260" height="180"> <div class="card-header bg-transparent"><h5 class="card-title"><?php echo $row_photo['name'];?></h5></div> <div class="card-body"> <p class="card-text"> <?php echo "<font color='black'>".$row_photo['description']."</font>"; ?> </p> </div> <div class="card-footer bg-transparent"> <?php echo "<font color='red'>Updated on ".$row_photo['date']." at ".$row_photo['time']."</font><br>"?> <div class="btn-group"> <a href="photo_form.php?id=<?php echo $row_photo['record_id']?>" class="btn btn-outline-success">EDIT</a> <a href="photo_delete.php?id=<?php echo $row_photo['record_id']?>" class="btn btn-outline-danger" onclick="return confirm('Yakin mau menghapus data ini?')">DELETE</a> </div> </div> </div> </div> <?php } ?> <!-- End of foto --> </div> </div> </div> <?php include "assets_js.php"?> </body> </html><file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 5/2/18 * Time: 16:23 PM */ $url = "http://api.openweathermap.org/data/2.5/weather?id=1636722&APPID=a58d462b62efd9a6d2376ddd797c91e1&mode=xml&type=accurate&units=metric"; $getWeather = simplexml_load_file($url); $getTemperature = $getWeather->temperature['value']; $getHumidity = $getWeather->humidity['value']; $getCloud = $getWeather->clouds['name']; $getPrecipitation = $getWeather->precipitation['mode']; $getWindSpeed = $getWeather->wind->speed['value']; $getWindDirection = $getWeather->wind->direction['name']; ?><file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 6/2/18 * Time: 22:16 PM */ include "db_connection.php"; $id = $_GET['id']; $get_img = $conn->query("SELECT * FROM documentation WHERE record_id = $id"); $data_img = $get_img->fetch_array(); $gambar = "images/docs/photos/".$data_img['file_name']; $sql = $conn->query("DELETE FROM documentation WHERE record_id = $id"); if($sql) { if(file_exists($gambar)) { unlink($gambar); } header("Location: photo_docs.php?sukses=3"); $conn->close(); }<file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 4/20/18 * Time: 09:45 AM */ date_default_timezone_set("Asia/Jakarta"); $servername = "192.168.100.5"; $username = "rakaflyhigh"; $password = "<PASSWORD>"; $dbname = "skripsi_cuy"; // $servername = "localhost"; // $username = "root"; // $password = ""; // $dbname = "skripsi_cuy_2"; $conn = new mysqli($servername, $username, $password, $dbname); if($conn->connect_error) { die("Connection failed: ".$conn->connect_error); } ?><file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 6/2/18 * Time: 21:16 PM */ include "db_connection.php"; //Form $id = $_GET['id']; $tanggal = date("Y-m-d"); $jam = date("H:m:s"); $title = $_POST['title']; $description = $_POST['description']; if(empty($_FILES['foto']['name'])) { $sql = "UPDATE documentation SET name = '$title', description = '$description', date = '$tanggal', time = '$jam' WHERE record_id = $id"; if($conn->query($sql)) { header("Location: photo_docs.php?sukses=1"); $conn->close(); } } else { $file_info = PATHINFO($_FILES['foto']['name']); $new_fileName = $file_info['filename']."_".time().".".$file_info['extension']; move_uploaded_file($_FILES['foto']['tmp_name'], "images/docs/photos/".$new_fileName); $location = "images/docs/photos/".$new_fileName; chmod($location, 0777); $sql = "UPDATE documentation SET name = '$title', file_name = '$new_fileName', description = '$description', date = '$tanggal', time = '$jam' WHERE record_id = $id"; if($conn->query($sql)) { header("Location: photo_docs.php?sukses=1"); $conn->close(); } }<file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 5/10/18 * Time: 00:44 AM */ include "db_connection.php"; $file_info = PATHINFO($_FILES['foto']['name']); $new_fileName = $file_info['filename']."_".time().".".$file_info['extension']; move_uploaded_file($_FILES['foto']['tmp_name'], "images/docs/photos/".$new_fileName); $location = "images/docs/photos/".$new_fileName; chmod($location, 0777); $tanggal = date("Y-m-d"); $jam = date("H:m:s"); $title = $_POST['title']; $description = $_POST['description']; //SQL $sql = "INSERT INTO documentation(name, file_name,description, date, time) VALUES('$title', '$new_fileName','$description','$tanggal','$jam')"; if($conn->query($sql)) { header("Location: photo_docs.php?sukses=2"); $conn->close(); } else { echo "<script type='text/javascript'>alert('Error: ".$sql."<br>".$conn->error."');</script>"; } // mysqli_query($conn,"INSERT INTO documentation(name, description, date, time) VALUES('$new_fileName','','$tanggal','$jam')"); ?><file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 5/3/18 * Time: 23:50 PM */ include "db_connection.php"; include "decode_xml_current_weather.php"; date_default_timezone_set("Asia/Jakarta"); $windSpeedFinal = floatval($getWindSpeed) * 3.6; $windSpeedFinal_2 = number_format($windSpeedFinal, 2); mysqli_query($conn, "INSERT INTO suhu_kelembapan(temperature, humidity, tanggal, waktu) VALUES ('".(int) $getTemperature."', '$getHumidity', '".date("Y-m-d")."', '".date("H:i:s")."')"); mysqli_query($conn,"INSERT INTO wind(wind_speed, wind_direction, tanggal, waktu) VALUES ('$windSpeedFinal_2', '$getWindDirection', '".date("Y-m-d")."', '".date("H:i:s")."')"); ?><file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 7/13/18 * Time: 23:04 PM */ $url = "http://localhost/skripsi_cuy/forecast_weather.xml"; $getForecast = simplexml_load_file($url); // $getSymbolNumber = $getForecast->{'forecast'}->{'time'}->symbol['number']; $getSymbolNumber = $getForecast->{'forecast'}->time['from']; $getSymbolNumber2 = $getForecast->{'forecast'}->time['from']; echo $getSymbolNumber."<br>".$getSymbolNumber2; ?><file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 7/14/18 * Time: 18:37 PM */ ?> <!doctype html> <head> <?php include 'head_tag.php'?> </head> <body> <p id="ajax_suhu"></p> <?php include 'assets_js.php'?> <script> $(document).ready(function () { $.ajaxSetup({cache: false}); setInterval(function () { $('#ajax_suhu').load('api/nilai_koneksi_arduino.php'); }, 1000); }); </script> </body> </html><file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 6/4/18 * Time: 07:20 AM */ // include "../db_connection.php"; // $sql = $conn->query("SELECT wind_speed FROM wind ORDER BY record_id DESC LIMIT 1"); // $data = $sql->fetch_array(); // $kecepatan_angin = $data['wind_speed']; // echo $kecepatan_angin; include "../decode_xml_current_weather.php"; echo number_format(floatval($getWindSpeed) * 3.6, 2); ?><file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 6/4/18 * Time: 06:56 AM */ include "koneksi.php"; $sql = $conn->query("SELECT luminance FROM skripsi_cuy.light_intensity ORDER BY record_id DESC LIMIT 1"); $data = $sql->fetch_array(); $intensitas_cahaya = $data['luminance']; echo $intensitas_cahaya; ?><file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 6/2/18 * Time: 22:52 PM */ include "koneksi.php"; $sql = $conn->query("SELECT suhu, kelembapan FROM realtime_suhu_kelembapan ORDER BY id DESC LIMIT 1"); // $sql = $conn->query("SELECT suhu, kelembapan FROM skripsi_realtime.coba_koneksi_arduino ORDER BY record_id DESC LIMIT 1"); $data = $sql->fetch_array(); $suhu = $data['suhu']; echo $suhu.' derajat celcius'; ?><file_sep><?php include "db_connection.php"; include "decode_xml_current_weather.php"?> <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]--> <head> <?php include "head_tag.php"?> </head> <body> <?php include "left_panel.php"?> <div id="right-panel" class="right-panel"> <?php include "header_tag.php"?> <div class="breadcrumbs"> <div class="col-sm-4"> <div class="page-header float-left"> <div class="page-title"> <h1>Dashboard</h1> </div> </div> </div> <div class="col-sm-8"> <div class="page-header float-right"> <div class="page-title"> <ol class="breadcrumb text-right"> <li class="active">Dashboard</li> </ol> </div> </div> </div> </div> <div class="content mt-3"> <div class="col-sm-6 col-lg-4"> <div class="card text-white bg-flat-color-1"> <div class="card-body pb-0"> <div class="dropdown float-right"> <button class="btn bg-transparent dropdown-toggle theme-toggle text-light" type="button" id="dropdownMenuButton" data-toggle="dropdown"> <i class="fa fa-thermometer"></i> </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <div class="dropdown-menu-content"> <a class="dropdown-item" href="index.html#">See graphics...</a> <a class="dropdown-item" href="index.html#">See data...</a> </div> </div> </div> <h4 class="mb-0"> <span id="ajax_suhu"></span> &#8451; </h4> <p class="text-light">Suhu</p> <div class="chart-wrapper px-0" style="height:70px;" height="70"> <canvas id="widgetChart1"></canvas> </div> </div> </div> </div> <!--/.col--> <div class="col-sm-6 col-lg-4"> <div class="card text-white bg-flat-color-2"> <div class="card-body pb-0"> <div class="dropdown float-right"> <button class="btn bg-transparent dropdown-toggle theme-toggle text-light" type="button" id="dropdownMenuButton" data-toggle="dropdown"> <i class="fa fa-snowflake-o"></i> </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <div class="dropdown-menu-content"> <a class="dropdown-item" href="index.html#">See graphics...</a> <a class="dropdown-item" href="index.html#">See data...</a> </div> </div> </div> <h4 class="mb-0"> <span id="ajax_kelembapan"></span> % </h4> <p class="text-light">Kelembapan</p> <div class="chart-wrapper px-0" style="height:70px;" height="70"> <canvas id="widgetChart2"></canvas> </div> </div> </div> </div> <!--/.col--> <div class="col-sm-6 col-lg-4"> <div class="card text-white bg-flat-color-3"> <div class="card-body pb-0"> <div class="dropdown float-right"> <button class="btn bg-transparent dropdown-toggle theme-toggle text-light" type="button" id="dropdownMenuButton" data-toggle="dropdown"> <i class="fa fa-sun-o"></i> </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <div class="dropdown-menu-content"> <a class="dropdown-item" href="index.html#">See graphics...</a> <a class="dropdown-item" href="index.html#">See data...</a> </div> </div> </div> <h4 class="mb-0"> <span id="ajax_intesitascahaya" class="count"></span> lx </h4> <p class="text-light">Light Intensity</p> <div class="chart-wrapper px-0" style="height:70px;" height="70"> <canvas id="widgetChart3"></canvas> </div> </div> </div> </div> <!--/.col--> <div class="col-sm-6 col-lg-6"> <div class="card text-white bg-flat-color-4"> <div class="card-body pb-0"> <div class="dropdown float-right"> <button class="btn bg-transparent dropdown-toggle theme-toggle text-light" type="button" id="dropdownMenuButton" data-toggle="dropdown"> <i class="fa fa-fighter-jet"></i> </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <div class="dropdown-menu-content"> <a class="dropdown-item" href="index.html#">See graphics...</a> <a class="dropdown-item" href="index.html#">See data...</a> </div> </div> </div> <h4 class="mb-0"> <!-- <span class="count">10468</span> Km/h--> <span id="ajax_kecepatanangin" class="count"></span> Km/h </h4> <p class="text-light">Wind Speed</p> <div class="chart-wrapper px-0" style="height:70px;" height="70"> <canvas id="widgetChart4"></canvas> </div> </div> </div> </div> <!--/.col--> <div class="col-sm-6 col-lg-6"> <div class="card text-white bg-flat-color-5"> <div class="card-body pb-0"> <div class="dropdown float-right"> <button class="btn bg-transparent dropdown-toggle theme-toggle text-light" type="button" id="dropdownMenuButton" data-toggle="dropdown"> <i class="fa fa-arrows-alt"></i> </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <div class="dropdown-menu-content"> <a class="dropdown-item" href="index.html#">See graphics...</a> <a class="dropdown-item" href="index.html#">See data...</a> </div> </div> </div> <h4 class="mb-0"> <!-- <span class="count">10468</span>--> <span id="ajax_arahangin" class="count"></span> </h4> <p class="text-light">Wind Direction</p> </div> <div class="chart-wrapper px-0" style="height:70px;" height="70"> </div> </div> </div> <!--/.col--> <div class="col-md-12"> <aside class="profile-nav alt"> <section class="card"> <div class="card-header user-header alt bg-dark"> <div class="media"> <a href="ui-cards.html#"> <img class="align-self-center rounded-circle mr-3" style="width:85px; height:85px;" alt="" src="http://openweathermap.org/img/w/<?php echo $getWeatherIcon?>.png"> </a> <div class="media-body"> <h2 class="text-light display-6">T: <?php echo (int) $getTemperature;?> &#8451; | H: <?php echo $getHumidity."%";?></h2> <p>Lowokwaru, ID</p> </div> </div> </div> <ul class="list-group list-group-flush"> <li class="list-group-item"> <a href="ui-cards.html#"> <i class="fa fa-cloud"></i> Cloud <span class="badge badge-success pull-right"><?php echo ucwords($getCloud);?></span></a> </li> <li class="list-group-item"> <a href="ui-cards.html#"> <i class="fa fa-snowflake-o"></i> Precipitation <span class="badge badge-warning pull-right r-activity"><?php echo $getPrecipitation;?></span></a> </li> <li class="list-group-item"> <a href="ui-cards.html#"> <i class="fa fa-fighter-jet"></i> Wind Speed <span class="badge badge-primary pull-right"><?php $windSpeedFinal = floatval($getWindSpeed) * 3.6; echo number_format($windSpeedFinal, 2);?> Km/h</span></a> </li> <li class="list-group-item"> <a href="ui-cards.html#"> <i class="fa fa-arrows-alt"></i> Wind Direction <span class="badge badge-danger pull-right"><?php echo $getWindDirection;?></span></a> </li> </ul> </section> </aside> </div> </div> </div> <?php include "assets_js.php"?> <!-- Script sensor --> <script> //WidgetChart 1 var ctx = document.getElementById( "widgetChart1" ); ctx.height = 150; var myChart = new Chart( ctx, { type: 'line', data: { // labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'], labels: [ <?php $query = mysqli_query($conn, "SELECT tanggal, waktu FROM (SELECT * FROM suhu_kelembapan ORDER BY record_id DESC LIMIT 7) sub ORDER BY record_id ASC;"); while($row = mysqli_fetch_array($query, MYSQLI_BOTH)) { $tanggal = $row['tanggal']; $waktu = $row['waktu']; echo "'$tanggal | $waktu',"; } ?> ], type: 'line', datasets: [ { // data: [65, 59, 84, 84, 51, 55, 40], data: [<?php $query = mysqli_query($conn, "SELECT * FROM (SELECT * FROM suhu_kelembapan ORDER BY record_id DESC LIMIT 7) sub ORDER BY record_id ASC;"); while($row = mysqli_fetch_array($query, MYSQLI_BOTH)) { $temperature = $row['temperature']; echo "'$temperature',"; // echo $temperature.','; } ?>], label: 'Temperature', // backgroundColor: '#63c2de', backgroundColor: 'transparent', borderColor: 'rgba(255,255,255,.55)', }, ] }, options: { maintainAspectRatio: false, legend: { display: false }, responsive: true, tooltips: { mode: 'index', titleFontSize: 12, titleFontColor: '#000', bodyFontColor: '#000', backgroundColor: '#fff', titleFontFamily: 'Montserrat', bodyFontFamily: 'Montserrat', cornerRadius: 3, intersect: false, }, scales: { xAxes: [ { gridLines: { color: 'transparent', zeroLineColor: 'transparent' }, ticks: { fontSize: 2, fontColor: 'transparent' } } ], yAxes: [ { display:false, ticks: { display: false, } } ] }, title: { display: false, }, elements: { line: { tension: 0.00001, borderWidth: 1 }, point: { radius: 4, hitRadius: 10, hoverRadius: 4 } } } } ); //WidgetChart 2 var ctx = document.getElementById( "widgetChart2" ); ctx.height = 150; var myChart = new Chart( ctx, { type: 'line', data: { // labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'], labels: [ <?php $query = mysqli_query($conn, "SELECT tanggal, waktu FROM (SELECT * FROM suhu_kelembapan ORDER BY record_id DESC LIMIT 7) sub ORDER BY record_id ASC;"); while($row = mysqli_fetch_array($query, MYSQLI_BOTH)) { $tanggal = $row['tanggal']; $waktu = $row['waktu']; echo "'$tanggal | $waktu',"; } ?> ], type: 'line', datasets: [ { // data: [1, 18, 9, 17, 34, 22, 11], data: [ <?php $query = mysqli_query($conn, "SELECT * FROM (SELECT * FROM suhu_kelembapan ORDER BY record_id DESC LIMIT 7) sub ORDER BY record_id ASC;"); while($row = mysqli_fetch_array($query, MYSQLI_BOTH)) { $humidity = $row['humidity']; echo "'$humidity',"; } ?> ], label: 'Humidity', backgroundColor: '#63c2de', borderColor: 'rgba(255,255,255,.55)', }, ] }, options: { maintainAspectRatio: false, legend: { display: false }, responsive: true, tooltips: { mode: 'index', titleFontSize: 12, titleFontColor: '#000', bodyFontColor: '#000', backgroundColor: '#fff', titleFontFamily: 'Montserrat', bodyFontFamily: 'Montserrat', cornerRadius: 3, intersect: false, }, scales: { xAxes: [ { gridLines: { color: 'transparent', zeroLineColor: 'transparent' }, ticks: { fontSize: 2, fontColor: 'transparent' } } ], yAxes: [ { display:false, ticks: { display: false, } } ] }, title: { display: false, }, elements: { line: { tension: 0.00001, borderWidth: 1 }, point: { radius: 4, hitRadius: 10, hoverRadius: 4 } } } } ); </script> <script> $(document).ready(function () { $.ajaxSetup({cache: false}); setInterval(function () { //Dari sensor // $('#ajax_suhu').load('api/nilai_suhu.php'); // $('#ajax_kelembapan').load('api/nilai_kelembapan.php'); $('#ajax_intesitascahaya').load('api/nilai_intensitas_cahaya.php'); $('#ajax_arahangin').load('api/nilai_arah_angin.php'); $('#ajax_kecepatanangin').load('api/nilai_kecepatan_angin.php'); //Dari open weather $('#ajax_suhu').load('api/nilai_suhu_openweather.php'); $('#ajax_kelembapan').load('api/nilai_kelembapan_openweather.php'); }, 5000); }); </script> </body> </html><file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 7/8/18 * Time: 17:58 PM */ include "db_connection.php"; ?> <!doctype html> <head> <?php include "head_tag.php"?> </head> <body> <?php include "left_panel.php"?> <div class="right-panel"> <?php include "header_tag.php"?> <div class="breadcrumbs"> <div class="col-sm-4"> <div class="page-header float-left"> <div class="page-title"> <h1>Coba Skripsi Orang</h1> </div> </div> </div> <div class="col-sm-8"> <div class="page-header float-right"> <div class="page-title"> <ol class="breadcrumb text-right"> <li class="active">Elka Ismy Chalbualdy</li> </ol> </div> </div> </div> </div> <div class="content mt-3"> <div class="animated fadeIn"> <div class="row"> <div class="col-sm-6 col-lg-12"> <h3>Tabel Registrasi</h3><hr> </div> <div class="col-sm-6 col-lg-12"> <!-- <table id="bootstrap-data-table" class="table table-striped table-bordered">--> <!-- <tr>--> <!-- <th>No.</th>--> <!-- <th>Tanggal Masuk</th>--> <!-- <th>Dokumen Medik</th>--> <!-- <th>Nama</th>--> <!-- <th>Alamat</th>--> <!-- <th>Agama</th>--> <!-- <th>Jenis Kelamin</th>--> <!-- <th>Cara Kunjungan</th>--> <!-- </tr>--> <!-- </table>--> <table id="bootstrap-data-table" class="table table-striped table-bordered"> <thead> <tr> <td rowspan="4" class="align-middle"><strong>No.</strong></td> <td rowspan="4" class="align-middle"><strong>Tanggal Masuk</strong></td> <td rowspan="4" class="align-middle"><strong>Dokumen Medik</strong></td> <td rowspan="4" class="align-middle"><strong>Nama</strong></td> <td rowspan="4" class="align-middle"><strong>Alamat</strong></td> <td rowspan="4" class="align-middle"><strong>Agama</strong></td> <td rowspan="4" class="align-middle"><strong>Jenis Kelamin</strong></td> <td colspan="6">Cara Kunjungan</td> <td colspan="6">Asal Pasien</td> <td colspan="9">Keadaan Pasien Setelah di Poliklinik / UGD</td> <td colspan="2">Jenis Kasus</td> <td colspan="6">Cara Pembayaran</td> <td rowspan="4">Keterangan</td> </tr> <tr> <td>Kunjungan Baru</td> <td colspan="2">Kunjungan Lama</td> <td rowspan="3">Kunjungan Ulang</td> <td colspan="2">Kunjungan Konsultasi</td> <td rowspan="3">Datang Sendiri</td> <td rowspan="3">Puskesmas</td> <td rowspan="3">RS. Pemerintah</td> <td rowspan="3">RS. Swasta</td> <td rowspan="3">Dokter Praktik</td> <td rowspan="3">Lain-Lain</td> <td colspan="6">Dirujuk</td> <td rowspan="3">Pulang</td> <td rowspan="3">Mati di Poliklinik / UGD</td> <td rowspan="3">Datang Sudah Mati</td> <td rowspan="3">Baru</td> <td rowspan="3">Lama</td> <td rowspan="3">Umum</td> <td rowspan="3">Jamkesmas</td> <td rowspan="3">Askes</td> <td rowspan="3">Mandiri / JKN</td> <td rowspan="3">Jamkesda</td> <td rowspan="3">SPM</td> </tr> <tr> <td rowspan="2">Langsung / Tidak Lewat TP2RJ</td> <td colspan="2">Melalui TP2RJ</td> <td rowspan="2">Antar Poliklinik</td> <td rowspan="2">Dari Rawat Inap</td> <td rowspan="2">Dirawat</td> <td rowspan="2">Ke RS. Lebih Tinggi</td> <td rowspan="2">Ke RS. Lebih Rendah</td> <td rowspan="2">Ke Puskesmas</td> <td rowspan="2">Ke Dokter Praktek</td> <td rowspan="2">Lain-Lain</td> </tr> <tr> <td>Pengunjung Baru</td> <td>Pengunjung Lama</td> </tr> </thead> <tbody> <?php $nomor = 1; $sql = $conn->query("SELECT * FROM rekammedis.data_register"); while($row = $sql->fetch_array()) { ?> <tr> <td><?php echo $nomor++?></td> <td><?php echo $row['tanggal_masuk']?></td> <td><?php echo $row['nama']?></td> <td><?php echo $row['alamat']?></td> <td><?php echo $row['agama']?></td> <td><?php echo $row['jenis_kelamin']?></td> <td><?php echo $row['umur']?></td> <td><?php echo $row['tipe_kunjungan']?></td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div> </div> <?php include "assets_js.php";?> </body> </html><file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 7/24/18 * Time: 07:57 AM */ include "db_connection.php"; $sekarang = date('Y-m-d'); // $seminggu_sebelumnya = date('Y-m-d', strtotime('-7 days', strtotime(date('Y-m-d')))); $sehari_sebelumnya = date('Y-m-d', strtotime('-1 days', strtotime(date('Y-m-d')))); $batas_suhu = 25; $batas_humidity = 50-1; ?> <!doctype html> <head> <?php include 'head_tag.php'?> </head> <body> <?php include 'left_panel.php'?> <div class="right-panel"> <?php include 'header_tag.php'?> <div class="breadcrumbs"> <div class="col-sm-4"> <div class="page-header float-left"> <div class="page-title"> <h1>Machine Learning</h1> </div> </div> </div> <div class="col-sm-8"> <div class="page-header float-right"> <div class="page-title"> <ol class="breadcrumb text-right"> <li class="active">Suhu dan Kelembapan</li> </ol> </div> </div> </div> </div> <div class="content mt-3"> <div class="animated fadeIn"> <div class="row"> <div class="col-sm-6 col-lg-12"> <h3>Analisa</h3><hr> </div> <div class="col-sm-6 col-lg-12"> <canvas id="temperature_chart" width="800" height="400"></canvas> </div> </div> </div> </div> </div> <?php include 'assets_js.php'?> <script> var ctx = document.getElementById("temperature_chart").getContext('2d'); Chart.defaults.multicolorLine = Chart.defaults.line; Chart.controllers.multicolorLine = Chart.controllers.line.extend({ draw: function(ease) { var startIndex = 0, meta = this.getMeta(), points = meta.data || [], colors = this.getDataset().colors, area = this.chart.chartArea, originalDatasets = meta.dataset._children .filter(function(data) { return !isNaN(data._view.y); }); function _setColor(newColor, meta) { meta.dataset._view.borderColor = newColor; } if (!colors) { Chart.controllers.line.prototype.draw.call(this, ease); return; } for (var i = 2; i <= colors.length; i++) { if (colors[i-1] !== colors[i]) { _setColor(colors[i-1], meta); meta.dataset._children = originalDatasets.slice(startIndex, i); meta.dataset.draw(); startIndex = i - 1; } } meta.dataset._children = originalDatasets.slice(startIndex); meta.dataset.draw(); meta.dataset._children = originalDatasets; points.forEach(function(point) { point.draw(area); }); } }); var chart = new Chart(ctx, { type: 'multicolorLine', data: { labels:[ <?php $sql_datetime = $conn->query("SELECT time_date FROM skripsi_realtime.realtime_suhu_kelembapan"); while($data_datetime = $sql_datetime->fetch_array()) { $datetime = $data_datetime[0]; echo "'$datetime', "; } ?> ], datasets: [{ label: "Temperature Graphic", // borderColor: 'rgb(255, 99, 132)', borderColor: 'rgb(255,255,255)', data: [ <?php $sql_temp = $conn->query("SELECT id, suhu FROM skripsi_realtime.realtime_suhu_kelembapan"); while($data_temp = $sql_temp->fetch_array()) { $temp = $data_temp[1]; echo $temp.","; } ?> ], colors:[ <?php $sql_status = $conn->query("SELECT status FROM skripsi_realtime.realtime_suhu_kelembapan"); while($data_status = $sql_status->fetch_array()) { $status = $data_status[0]; if($status == 'Sensor unplugged or error') { echo "'red', "; } else { echo "'green', "; } } ?> ] }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] }, legend: { display: false } } }); </script> </body> </html> <file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 6/2/18 * Time: 23:10 PM */ // include "koneksi.php"; include "../decode_xml_current_weather.php"; echo (int) $getTemperature;<file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 8/7/18 * Time: 00:29 AM */ system("") ?><file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 8/8/18 * Time: 08:42 AM */ include "db_connection.php"; ?> <!doctype html> <head> <?php include "head_tag.php"?> </head> <body> <?php include "left_panel.php"?> <div id="right-panel" class="right-panel"> <?php include "header_tag.php";?> <div class="breadcrumbs"> <div class="col-sm-4"> <div class="page-header float-left"> <div class="page-title"> <h1>Timer</h1> </div> </div> </div> <div class="col-sm-8"> <div class="page-header float-right"> <div class="page-title"> <ol class="breadcrumb text-right"> <li class="active">Graphic</li> </ol> </div> </div> </div> </div> <div class="content mt-3"> <div class="animated fadeIn"> <div class="row"> <div class="col-sm-6 col-lg-12"> <canvas id="timer-chart"></canvas> </div> <div class="col-sm-6 col-lg-12"> <?php // $tanggal_sekarang = date("Y-m-d"); // $coba = new DateTime($tanggal_sekarang); // $tanggal_sekarang = $coba->format('Y-m-d'); // // $sql = $conn->query("SELECT * FROM skripsi_cuy.log_activities"); // while($row = $sql->fetch_array()) // { // $ambil_tanggal = substr($row[2], 0, 10); // $ambil_jam_aja = substr($row[2], 11, 2); // // if($ambil_tanggal == $tanggal_sekarang) // { // echo $ok = 1; // } // } // ?> </div> </div> </div> </div> </div> <?php include "assets_js.php"?> <script> var ctx = document.getElementById("timer-chart"); ctx.height = 150; var myChart = new Chart(ctx, { type: 'line', data: { labels:[ <?php for($i = 1; $i <= 24; $i++) { echo "'$i',"; } ?> ], type: 'line', defaultFontFamily: 'Montserrat', datasets: [ { label: "Timer", data: [ <?php $nol = 0; $satu = 1; $tanggal_sekarang = date("Y-m-d"); $coba = new DateTime($tanggal_sekarang); $tanggal_sekarang = $coba->format('Y-m-d'); $sql = $conn->query("SELECT * FROM skripsi_cuy.log_activities WHERE tanggal_waktu LIKE '%".$tanggal_sekarang."%'"); while($row = $sql->fetch_array()) { $ambil_tanggal = substr($row[2], 0, 10); $ambil_jam_aja = substr($row[2], 11, 2); $jamInt = (int) $ambil_jam_aja; if($ambil_tanggal == $tanggal_sekarang) { for($i = 1; $i <= 24; $i++) { if($i == $jamInt) { echo $satu.", "; } else { echo $nol.", "; } } } } ?> ], backgroundColor: 'transparent', borderColor: 'rgba(220,53,69,0.75)', borderWidth: 3, pointStyle: 'circle', pointRadius: 5, pointBorderColor: 'transparent', pointBackgroundColor: 'rgba(220,53,69,0.75)', }] } }); </script> </body> </html><file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 7/30/18 * Time: 18:27 PM */ include "db_connection.php"; ?> <!doctype html> <head> <?php include "head_tag.php"?> </head> <body> <?php include "left_panel.php";?> <div id="right-panel" class="right-panel"> <?php include "header_tag.php";?> <div class="breadcrumbs"> <div class="col-sm-4"> <div class="page-header float-left"> <div class="page-title"> <h1>Light Intensity</h1> </div> </div> </div> <div class="col-sm-8"> <div class="page-header float-right"> <div class="page-title"> <ol class="breadcrumb text-right"> <li class="active">Graphic</li> </ol> </div> </div> </div> </div> <div class="content mt-3"> <div class="animated fadeIn"> <div class="row"> <div class="col-sm-6 col-lg-12"> <h3>Grafik Monitoring Intensitas Cahaya Hari Ini</h3><hr> </div> <div class="col-sm-6 col-lg-12"> <div class="card"> <div class="card-header"> <strong>Data Intensitas Cahaya</strong> </div> <div class="card-body"> <canvas id="lightintensity-chart"></canvas> </div> </div> </div> <div class="col-sm-6 col-lg-12"> <p>Gardner, et.al. 1992. <i>Fisiologi Tanaman Budidaya Tropik</i>. Yogyakarta: Gadjah Mada University Press</p> </div> </div> </div> </div> </div> <?php include "assets_js.php";?> <script> var ctx = document.getElementById("lightintensity-chart"); ctx.height = 150; var myChart = new Chart( ctx, { type: 'line', data: { // labels: [ "2010", "2011", "2012", "2013", "2014", "2015", "2016" ], labels : [ <?php $sql = "SELECT * FROM skripsi_cuy.light_intensity WHERE tanggal = '".date('Y-m-d')."'"; $result = $conn->query($sql); while($row = $result->fetch_array()) { $tanggal = $row[2]; $waktu = $row[3]; echo "'$tanggal | $waktu',"; } ?> ], type: 'line', defaultFontFamily: 'Montserrat', datasets: [ { label: "Light Intensity", // data: [ 0, 30, 10, 120, 50, 63, 10 ], data: [ <?php $query = mysqli_query($conn, "SELECT * FROM skripsi_cuy.light_intensity WHERE tanggal = '".date('Y-m-d')."'"); while($row = mysqli_fetch_array($query, MYSQLI_BOTH)) { $value = $row[1]; echo $value.", "; } ?> ], backgroundColor: 'transparent', borderColor: 'rgba(220,53,69,0.75)', borderWidth: 3, pointStyle: 'circle', pointRadius: 5, pointBorderColor: 'transparent', pointBackgroundColor: 'rgba(220,53,69,0.75)', }] }, options: { responsive: true, tooltips: { mode: 'index', titleFontSize: 12, titleFontColor: '#000', bodyFontColor: '#000', backgroundColor: '#fff', titleFontFamily: 'Montserrat', bodyFontFamily: 'Montserrat', cornerRadius: 3, intersect: false, }, legend: { display: false, labels: { usePointStyle: true, fontFamily: 'Montserrat', }, }, scales: { xAxes: [ { display: true, gridLines: { display: true, drawBorder: false }, scaleLabel: { display: false, labelString: 'Tanggal | Waktu' } } ], yAxes: [ { display: true, gridLines: { display: true, drawBorder: false }, scaleLabel: { display: true, labelString: "Intensitas Cahaya" }, id: 'y-axis-1', ticks: { beginAtZero: true, max: 1000 } } ] }, title: { display: false, text: 'Light Intensity Graphic' }, annotation: { drawTime: "afterDraw", annotations: [{ id: 'box1', type: 'box', yScaleID: 'y-axis-1', yMin: 0, yMax: 390, backgroundColor: 'rgba(200, 100, 200, 0.2)', borderColor: 'rgba(100, 100, 100, 0.2)', },{ id: 'box2', type: 'box', yScaleID: 'y-axis-1', yMin: 390, yMax: 760, backgroundColor: 'rgba(148, 255, 162, 0.3)', borderColor: 'rgba(200, 100, 200, 0.2)', },{ id: 'box3', type: 'box', yScaleID: 'y-axis-1', yMin: 760, yMax: 1000, backgroundColor: 'rgba(200, 100, 200, 0.2)', borderColor: 'rgba(100, 100, 100, 0.2)', }] } } } ); </script> </body> </html><file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 7/14/18 * Time: 18:40 PM */ include '../db_connection.php'; $sql = $conn->query("SELECT * FROM skripsi_cuy.coba_koneksi_arduino ORDER BY record_id DESC LIMIT 1"); $data = $sql->fetch_array(); if($data['suhu'] > 30) { $suhu_akhir = $data['suhu'].'<br>Lakukan pendinginan!<br>'; $cmd = escapeshellcmd('/Users/raka_matsukaze/Documents/python_docs/suhu_kelembapan/jam_11.py'); shell_exec($cmd); // shell_exec('/Users/raka_matsukaze/Documents/python_docs/suhu_kelembapan/jam_11.py'); } else { $suhu_akhir = $data['suhu'].'<br>Suhu normal!<br>'; $cmd = escapeshellcmd('/Users/raka_matsukaze/Documents/python_docs/suhu_kelembapan/jam_12.py'); shell_exec($cmd); // shell_exec('/Users/raka_matsukaze/Documents/python_docs/suhu_kelembapan/jam_12.py'); } echo $suhu_akhir;<file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 6/30/18 * Time: 02:13 AM */ include "db_connection.php"; ?> <!doctype html> <head> <?php include "head_tag.php"?> </head> <body> <?php include "left_panel.php";?> <div id="right-panel" class="right-panel"> <?php include "header_tag.php";?> <div class="breadcrumbs"> <div class="col-sm-4"> <div class="page-header float-left"> <div class="page-title"> <h1>Documentations</h1> </div> </div> </div> <div class="col-sm-8"> <div class="page-header float-right"> <div class="page-title"> <ol class="breadcrumb text-right"> <li class="active">Log Activities</li> </ol> </div> </div> </div> </div> <div class="content mt-3"> <div class="animated fadeIn"> <div class="row"> <div class="col-sm-6 col-lg-12"> <h3>Daftar Aktivitas</h3><hr> </div> <div class="col-sm-6 col-lg-12"> <table id="bootstrap-data-table" class="table table-striped table-bordered"> <thead> <tr> <th>No.</th> <th>Activity</th> <th>Date Time</th> </tr> </thead> <tbody> <?php $nomor = 1; $result = $conn->query("SELECT * FROM log_activities"); while($row = $result->fetch_array()) { ?> <tr> <td><?php echo $nomor++;?></td> <td><?php echo $row['activity']?></td> <td><?php echo $row['tanggal_waktu']?></td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div> </div> <?php include "assets_js.php";?> </body> </html><file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 6/27/18 * Time: 16:50 PM */ $output = exec('python /Users/raka_matsukaze/Documents/python_docs/hello_world.py'); echo $output;<file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 6/4/18 * Time: 07:25 AM */ // include "../db_connection.php"; // $sql = $conn->query("SELECT wind_direction FROM wind ORDER BY record_id DESC LIMIT 1"); // $data = $sql->fetch_array(); // $arah_angin = include "../decode_xml_current_weather.php"; echo $getWindDirection; ?><file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 7/6/18 * Time: 14:01 PM */ error_reporting(0); include "../db_connection.php"; $sekarang = date('Y-m-d'); $seminggu_sebelumnya = date('Y-m-d', strtotime('-7 days', strtotime(date('Y-m-d')))); $result = $conn->query("SELECT temperature, humidity, tanggal, waktu FROM suhu_kelembapan WHERE temperature > 27 AND tanggal BETWEEN '$seminggu_sebelumnya' AND '$sekarang'"); while($row = $result->fetch_array()) { $waktu = explode(":", $row['waktu']); // AMBIL JAM SAJA $s[$row['temperature']][$waktu[0]]+=1; // s[suhu][waktu]. // s[28][10] = 1 // s[28][10] = 2 // s[28][10] = 3 // s[29][10] = 1 // s[28][11] = 1 // s[28][11] = 2 } echo "<pre>"; print_r($s); echo "</pre>"; $maxsuhu = max(array_keys($s)); // dapatkan key(suhu) array tertinggi. $iterbanyak = max(array_values($s[$maxsuhu])); // cari jam terbanyak beerdasarkan value $jamterbanyak = array_search($iterbanyak, $s[$maxsuhu]); // ambil key(jam) berdasarkan value tertinggi $jamterbanyak = $jamterbanyak.":00:00"; echo "<strong>Suhu terbesar adalah ".$maxsuhu." pada jam ".$jamterbanyak."</strong>"; // $conn->query("INSERT INTO suhu_tertinggi(suhu, waktu) VALUES ($maxsuhu, '$jamterbanyak') "); ?><file_sep><?php /** * Created by PhpStorm. * User: raka_matsukaze * Date: 6/2/18 * Time: 22:55 PM */ $servername = "192.168.100.5"; $username = "rakaflyhigh"; $password = "<PASSWORD>"; $dbname = "skripsi_realtime"; $conn = new mysqli($servername, $username, $password, $dbname); if($conn->connect_error) { die("Connection failed: ".$conn->connect_error); } ?>
d6ec6d3d240dd8fe188db41d4b2622fada1e27db
[ "PHP" ]
33
PHP
RFA96/skripsi_cuy
fd922c8424147b066b397b4d5f65b7820d834215
dfb3ae968f5b8681839abc3107d9ec337b3db766
refs/heads/master
<file_sep>require "octoks/version" require "octoks/receiver" require "octoks/event" module Octoks end <file_sep>module Octoks class Event attr_accessor :name, :payload def initialize(name, payload) @name = name @payload = payload end end end <file_sep># Octoks Octoks is Github Hooks Receiver. inspired by `GitHub::Hooks::Receiver` https://github.com/Songmu/Github-Hooks-Receiver ## Installation Add this line to your application's Gemfile: gem 'octoks' And then execute: $ bundle Or install it yourself as: $ gem install octoks ## Usage ```ruby # this file name is `config.ru` require 'octoks' receiver = Octoks::Receiver.new receiver.on :push do |event| # event is Octoks::Event object p event.name p event.payload end run receiver ``` And `rackup` ```sh # run receiver rackup config.ru ``` You can check the following hook name. https://developer.github.com/v3/activity/events/types/ ## Contributing 1. Fork it ( http://github.com/hisaichi5518/octoks/fork ) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new Pull Request <file_sep>source 'https://rubygems.org' # Specify your gem's dependencies in octoks.gemspec gemspec <file_sep>require 'octoks' receiver = Octoks::Receiver.new receiver.on :push do |event| p event.name p event.payload # ... end run receiver <file_sep>require 'minitest/autorun' require 'octoks' class TestEvent < MiniTest::Unit::TestCase def test_name event = Octoks::Event.new(:name, {"test" => "test"}) assert_equal event.name, :name end def test_payload event = Octoks::Event.new(:name, {"test" => "test"}) assert_equal event.payload, {"test" => "test"} end end <file_sep>require 'rack' require 'json' require 'openssl' require 'secure_compare' module Octoks class Receiver attr_accessor :hooks attr_reader :secret def initialize(secret = nil) @hooks = {} @secret = secret end def on(name, &cb) @hooks[name] ||= [] @hooks[name].push(cb) end def emit(event) hooks[event.name] ||= [] hooks[event.name].each do |hook| hook.call(event) end end def call(env) req = Rack::Request.new(env) failed = [400, [], ["BAD REQUEST"]] if !req.post? or req.params['payload'].nil? or req.env["HTTP_X_GITHUB_EVENT"].nil? return failed end unless verify_signature(req) return failed end begin payload = JSON.parse(req.params['payload']) rescue return failed end event_name = req.env["HTTP_X_GITHUB_EVENT"] event = Octoks::Event.new(event_name.to_sym, payload) emit(event) [200, [], ["OK"]] end HMAC_DIGEST = OpenSSL::Digest.new('sha1') def verify_signature(req) return true unless @secret return false unless req.body sig = 'sha1='+OpenSSL::HMAC.hexdigest(HMAC_DIGEST, @secret, req.body.read) req.body.rewind SecureCompare.compare(sig, req.env["HTTP_HUB_SIGNATURE"]) end end end <file_sep>require 'minitest/autorun' require 'octoks' class TestReceiver < MiniTest::Unit::TestCase def test_call receiver = Octoks::Receiver.new("secret1234") env = { 'rack.version' => [1, 2], 'REQUEST_METHOD' => 'POST', 'SERVER_NAME' => 'example.com', 'SERVER_PORT' => 80, 'QUERY_STRING' => '', 'PATH_INFO' => '/', 'rack.url_scheme' => 'http', 'HTTPS' => 'off', 'CONTENT_LENGTH' => 15, 'rack.input' => StringIO.new('payload={"hoge":"fuga"}'), 'HTTP_X_GITHUB_EVENT' => 'issue', 'HTTP_HUB_SIGNATURE' => 'sha1=b2d620dd0b514b814685364d637058fe5ce29479', 'HTTP_X_GITHUB_DELIVERY' => 'gggg', } res = receiver.call(env) assert_equal 200, res[0] env['HTTP_HUB_SIGNATURE'] += "fail!" res = receiver.call(env) assert_equal 400, res[0] end end <file_sep>require 'minitest/autorun' require 'octoks' class TestReceiver < MiniTest::Unit::TestCase def test_on receiver = Octoks::Receiver.new receiver.on :push do |event| end receiver.on :push do |event| end assert_equal receiver.hooks[:push].size, 2 end def test_emit receiver = Octoks::Receiver.new receiver.on :push do |event| event.payload["count"] = 1 end receiver.on :push do |event| event.payload["count"] += 1 end event = Octoks::Event.new(:push, {"test" => "test"}) receiver.emit(event) assert_equal event.payload["count"], 2 event = Octoks::Event.new(:test, {"test" => "test"}) receiver.emit(event) assert_equal receiver.hooks[:test].size, 0 end end
86c1e0d576c121f18b6996b134935ee77903179f
[ "Markdown", "Ruby" ]
9
Ruby
kenchan/octoks
14187d16fe7ad2355fed2962e055d5b8093b0e06
cd3197ce4ad971a0759e7453c2fecff6a432a52c
refs/heads/master
<repo_name>geometryglobal-emea/pathfinder-algorithm<file_sep>/lib/consolidate_events.rb require_relative 'constants' module Discover def consolidate_events(sgmnt, attrs, thrshld, mandatory_attrs) sgmnt.each do |jrny| jrny.init_surrogates [Discover::CONSIDERING_STEP, Discover::BUYING_STEP].each do |t| jrny.types[t].each do |evt| #jrny.surrogates[t] << sgmnt.get_representative(evt, attrs, thrshld, mandatory_attrs) if evt.surrogate $LOG.warn "consolidate_events, surrogate is already set!" end evt.surrogate = sgmnt.get_representative(evt, attrs, thrshld, mandatory_attrs) if not evt.surrogate $LOG.error "consolidate_events, no surrogate was generated!" end end end jrny.use_event_as_surrogate(Discover::TRIGGER) jrny.use_event_as_surrogate(Discover::READY_TO_PURCHASE) jrny.use_event_as_surrogate(Discover::PURCHASE) end end end <file_sep>/_docsAndTemplates/dsDump.js { // md5 hash code calculated on the content of config, results and sqlite3_dump "md5_hash" : , // Configuration file settings "config" : { "global" : { "event_table_name" : , // --- NEW SETTINGS "input_file" : , // NEW "output_path" : // NEW // --- END OF NEW SETTINGS }, "dynamic_segment" : { "mode" : "direct", // [direct|iterative|skip|stop] skip and stop will be made redundant and removed when entry_point and exit_point are implemented "cluster_method" : "", // [single_linkage|complete_linkage] "edit_distance_cost_insert" : , "edit_distance_cost_delete" : , "edit_distance_cost_substitute" : , "trigger_attributes" : "", "considering_step_attributes" : "", "ready_to_purchase_attributes" : "", "buying_step_attributes" : "", "purchase_attributes" : "", "print_cluster_histogram" : "", // [true|false] "cluster_similarity_threshold" : , "cluster_test_runs_similarity" : "", // "min,max" The test runs mode will probably be removed "event_similarity_threshold" : , // -1 disables the two-pass mechanism "protected_considering_step_attributes" : "", "protected_buying_step_attributes" : "", "swap_window" : , "number_of_results" : "", // the empty string lifts the restriction // --- NEW SETTINGS // Number of times the dynamic segmentation is repeated with a lower threshold (runs). If mode=direct this parameter is forced to 1 "dynamic_segmentation_runs" : , // Starting cluster similarity threshold. At each successive run the threshold is going to decrease by 0.1 "cluster_similarity_threshold_init" : , // Minimum acceptable size of the cluster indicated as a percentage of the static segment size (i.e. "0.1" = 10% static segment size) "significant_cluster_size" : // --- END OF NEW SETTINGS } }, // Summary of the results produced by the dynamic segmentation "results" : [ { // Static segment ID as will be reported in the sqlite DB "dat_segment_id" : , // The cluster similarity threshold that was actually used to identify the specific dynamic segment "cluster_similarity_threshold" : , // Dynamic segment ID as will be reported in the sqlite DB "res_dynamic_segment_id" : , // Number of journeys in the dynamic segment "res_dynamic_segment_size" : , // List of the dat_journey_id that are clustered together "journeys" : [ ] } ], // sqlite3_dump should contain the dump of the memory representation of the output sqlite database "sqlite3_dump" : { } }<file_sep>/lib/segment.rb require_relative 'constants' include Discover # A Segment is nothing but an Array of PDJs belonging to this segment # ammended with some further utilty functions class Segment < Array # - enc_map: A hash for event encoding. The fist level key is the # event-type-id, e.g. 3 == trigger. # The second level attr_accessor :segment_id, :enc_map, :nec_chars, :attributes, :swap_window # Prototypes for 2-pass approach. # If an event is similar to one of the events in the prototype array, it # will be substitute by the prototype. attr_accessor :representatives, :substitutes, :unchanged def initialize(segment_id = -1) @segment_id = segment_id init_representative end def get_nth_events(n) res = {} each do |j| res[j.user_id] = j[n] end res end def get_trigger() res = {} each do |j| next if not j.types[Discover::TRIGGER] or j.types[Discover::TRIGGER].length < 1 res[j.user_id] = j.types[Discover::TRIGGER] end res end def to_s each do |j| res += j.to_s + "\n" end res end def init_representative @representatives = Array.new(Discover::EVENT_TYPE_ARRAY.length) Discover::EVENT_TYPE_ARRAY.each do |t| @representatives[t] = Array.new end @substitutes = 0 @unchanged = 0 end # Substitute an event by a reference event, if they have some common # features. # A representatives event is an event which has n attributes in common with # the provided one. If no surrogate to the provided event exists in # the representative set, the provided event is added to the set of # representatives and hence can be a representative for a future event. def get_representative(evnt, attrs, n, mandatory_attrs = nil) type = evnt.type @representatives[type].each do |p| if mandatory_attrs and mandatory_attrs[type] and mandatory_attrs[type].length > 0 if not PdjEvent::similar(p, evnt, mandatory_attrs[type], false) == mandatory_attrs[type].length @representatives[type] << evnt return evnt end end $LOG.error "Segment::get_representative, representative is nil!" if not p sim = PdjEvent::similar(p, evnt, attrs[type], false) # Found a representative event to provided event if sim >= n # Add event only to representatives if it has new manifestations in # its attributes. if sim < attrs[type].length @representatives[type] << evnt end @substitutes += 1 return p end end @unchanged += 1 @representatives[type] << evnt evnt end def clear_surrogates() init_representative() self.each do |pdj| pdj.clear_surrogates() end end def adjust_positions(orig_pos = false) self.each do |pdj| pdj.adjust_positions() end end end <file_sep>/lib/json_dumper.rb require 'json' def dumper(phase,ini,db,event_tbl_name,dyn_segs,bpms,pdjms,dump) # Retrieves the config parameters affected by the actual run simply rejecting # those of the phases further the Exit_point. # ini_hash = ini_to_hash(phase,ini) ini_hash = ini_to_hash_incremental(phase,ini,dump) # Convert the db table to an array of hashes: each element is a hash and #corresponds to a record #db_array = db.execute("select * from " + event_tbl_name) # Clean the db_array from the annoying Fixnum => value duplicates #db_array.each do |element| # element.reject!{|key,value| key.class == Fixnum } #end # Retrieves the list of all the results columns of all the passed phases # and wraps them in an hash #results = get_results(phase,db, event_tbl_name) # Creates the hash containing inifile on top and results htd = {"config" => ini_hash} #htd.merge!("results" => results) if phase >= 2 htd.merge!("dyn_segs" => YAML.dump(dyn_segs)) end if phase >= 3 htd.merge!("bpms" => YAML.dump(bpms)) end if phase >=4 htd.merge!("pdjms" => YAML.dump(pdjms)) end # htd.merge!("sqlite3_dump" => YAML.dump(db)) # <----------------- it doesn't track the changes done by the phases # following the dump so it returns mismatch! # md5_db = Digest::MD5.file(ini["global"]["input_file"]).hexdigest # htd.merge!("md5_db"=> md5_db) #-----------------> md5_dump = Digest::MD5.hexdigest(htd.to_s) htd.merge!("md5_dump"=> md5_dump) dump_to_json(phase,htd) end # <------------------------ Methods called by the dumper--------------------> def get_ini_sections(ini) return ini.access_inifile_class.sections end def ini_to_hash_incremental(phase,ini,dump) if dump dumped_conf = dump["config"].to_h else dumped_conf = Hash.new() end ini_hash = ini.access_inifile_class.to_h Entry_point["config_fields"].each do |field| dumped_conf.merge!(field => ini_hash[field]) end # binding.pry return dumped_conf end # DEPRECATED ----------------------------------------------> # def ini_to_hash(phase,ini) # ini_hash = ini.access_inifile_class.to_h # sections = get_ini_sections(ini) # # <------------ Clean up the ini_hash removing the sections not affected # # by the actual entry_point -> exit_point run # # ini_hash.reject!{|key,value| key == "version_check"} # where_to_start = Entry_point["name"] # if where_to_start == "ds" # where_to_start = "dynamic_segment" # end # sections.each do |sec| # break if sec == where_to_start # if sec != "global" and sec != "version_check" # ini_hash.reject!{|key,value| key == sec} # end # end # where_to_stop = STAGES.find{|key,value| value["n"] == phase}.first # if where_to_stop == "ds" # where_to_stop = "dynamic_segment" # end # sections.reverse.each do |sec| # break if sec == where_to_stop # ini_hash.reject!{|key,value| key == sec} # end # # -------------------------> End of cleaning # return ini_hash # end # <--------------------------DEPRECATED def get_results(phase,db, event_tbl_name) columns=Discover::ALGORITHM_COLUMNS.values.keep_if{|x| x.start_with?("res_")} # The next block reads all the STAGES and adds to the query the columns of the # results of the phases having a smaller "n" qry = "SELECT #{Pk}" # Primary key of the DataBase STAGES.each do |key,value| if value["n"] <= phase value["results"].each do |res| qry += ", #{res}" end end end qry += " FROM #{event_tbl_name}" res = db.execute(qry) res.each do |element| # it's very ugly but I don't know why the db.query returns a copy of every # field as with a Fixnum in place of the column_name element.reject!{|key,value| key.class == Fixnum } end return res end def dump_to_json(phase,hash_to_dump) json = JSON.pretty_generate(hash_to_dump) # $base_folder = hash_to_dump["config"]["global"]["$base_folder"] phase_name = STAGES.find{|key,value| value["n"] == phase}.first file_to_cp = [] for i in phase.downto(2) file_to_cp += STAGES[STAGES.find{|key,value| value["n"] == i-1}.first]["files_to_copy"] end while File.exists?($base_folder + "/#{phase_name}.js") do if $base_folder.gsub(/[^\d]/, '').to_i == 0 $base_folder = $base_folder.gsub(/[\d]/, '') + "1" else $base_folder = $base_folder.gsub(/[\d]/, '') + "#{$base_folder.gsub(/[^\d]/, '').to_i + 1}" end $LOG.info("Dump file already exists. New base_folder #{$base_folder} will be created") end FileUtils::mkdir_p $base_folder if hash_to_dump["config"]["global"]["base_folder"] != $base_folder and $already_done == nil file_to_cp.each do |f| FileUtils.cp(hash_to_dump["config"]["global"]["base_folder"]+"/"+f, $base_folder) end $already_done = true # I have to copy in the new_base_folder only the OLD files, ONCE, end # If i come again at this point I don't have to copy anything File.write( $base_folder + "/" + phase_name +".js", json) msg = "json_dumper: phase #{phase} completed. File '#{phase_name}.js'" msg += " was successfully created in base_folder: '#{$base_folder}'" $LOG.info msg end <file_sep>/lib/visualizer.rb require 'fileutils' require 'graphviz' require 'sqlite3' require_relative 'bpm' class Visualizer attr_accessor :pdjms, :type, :db, :vis_attrs def initialize(pdjms, vis_attrs, db, res_tbl_name, type, ini, fp = nil, prfx = nil, wtdb = true, tmp = "/tmp") @pdjms = pdjms @db = db @type = type @ini = ini @res_tbl_name = res_tbl_name @tmp = tmp @file_path = fp @output_prefix = prfx @write_to_db = wtdb @vis_attrs = vis_attrs end def buildgraph(label_id = false, graph_label = nil, ini = nil) $LOG.info "Visualizer::buildgraph, starting to generate PDJ-Maps" if ini legend = ini.to_s.gsub(/\n/, "\\l") end # For each PDJ map in the entire result set over all stat / dyn segments @pdjms.each do |p| ss_id = 0 ds_id = 0 # 1:1 mapping between PDM and BPM and Segement # IDs are extracted using the first PDJ of the segment if p.bpm and p.bpm.segment and p.bpm.segment[0] and p.bpm.segment[0].static_segment ss_id = p.bpm.segment[0].static_segment.segment_id else msg = "Visualizer::buildgraph, skipping static segment because it is empty" $LOG.warn(msg) next end if p.bpm and p.bpm.segment and p.bpm.segment[0] and p.bpm.segment[0].dyn_segment ds_id = p.bpm.segment[0].dyn_segment.segment_id else msg = "Visualizer::buildgraph, skipping dynamic segment because it is empty" $LOG.warn(msg) next end ss_id_str = ss_id.to_s.rjust(2, "0") ds_id_str = ds_id.to_s.rjust(2, "0") msg = "Visualizer::buildgraph, building PDJ-Map for static " msg += "segment #{ss_id_str} and dynamic segment #{ds_id_str}" $LOG.debug(msg) next if not p next if not p.bpm chunks = p.bpm.get_vis_hash to_prnt = graph_label grph_frq = "#{p.bpm.segment.length.to_s} / #{p.bpm.node_arry[0].pdj_events[0].pdj.static_segment.length.to_s}" if to_prnt to_prnt += "\n\n" else to_prnt = "" end to_prnt += grph_frq + "\n\n\n" g = GraphViz.strict_digraph("Q", :label => to_prnt, :labeljust => 'l', :rankdir => 'LR', :splines => 'curved', :compound => 'true', :layout =>'dot', :concentrate => 'true', :fontname => 'HelveticaNeueThin, helvetica_neuethin, Roboto, arial', :fontsize => '24', :labelloc => 't') # Add a legend if ini g.add_nodes(legend, :label => "\n\n\n\n\n\n\n\n#{legend}", :shape => 'rectangle', :style => 'filled, rounded', :color => 'none', :fillcolor => 'none', :fontname => 'Courier, HelveticaNeueThin, helvetica_neuethin, Roboto, arial') end # Visualisation of the actual graph p.bpm.visualize(g, vis_attrs, label_id, chunks) if @write_to_db #g.output(:@type} => "#{@path}#{@name}_#{itr}.#{@type}") tmp_name = Dir::Tmpname.make_tmpname([@tmp + "/" + ss_id_str + "_" + ds_id_str + "_", "." + @type], nil) g.output(:"#{@type}" => tmp_name) to_fill = File.open(tmp_name).read() stmt = "INSERT INTO #{@res_tbl_name} " stmt += "(#{Discover::ALGORITHM_COLUMNS[:segment_id]}, " stmt += "#{Discover::ALGORITHM_COLUMNS[:dynamic_segment_id]}, " stmt += "res_pdjmap, res_config) VALUES (#{ss_id}, #{ds_id}, ?, ?)" @db.execute(stmt, to_fill, @ini.to_s) msg = "Visualizer::buildgraph, storing output for static " msg += "segment: #{ss_id}, dynamic segment: #{ds_id} as " msg += "#{@type} in DB" $LOG.info(msg) end if @file_path and @output_prefix fn = "#{@file_path}/#{@output_prefix}_#{ss_id_str}_#{ds_id_str}.#{@type}" # <----------------------------- Output folder coherence # while File.exists?(fn) do # if @file_path.gsub(/[^\d]/, '') # @file_path = @file_path.gsub(/[\d]/, '').chop + "#{@file_path.gsub(/[^\d]/, '').to_i + 1}/" # fn = "#{@file_path}/#{@output_prefix}_#{ss_id_str}_#{ds_id_str}.#{@type}" # # else # # @file_path = @file_path.gsub(/[\d]/, '').chop + "0/" # # fn = "#{@file_path}/#{@output_prefix}_#{ss_id_str}_#{ds_id_str}.#{@type}" # end # end # ------------------------------> if not File.directory?(@file_path) msg = "Visualizer::buildgraph, output directory #{@file_path} " msg += "does not exists, creating it." $LOG.warn(msg) FileUtils.mkdir_p(@file_path) end g.output(:"#{@type}" => fn) $LOG.info "Visualizer::buildgraph, writing output to #{fn}" end #g.output(:"#{@type}" => "#{@path}#{@name}_#{iterator}.#{@type}") end end end <file_sep>/bin/util.rb require 'logger' require 'optparse' require 'graphviz' def extract_journey(segment) end def extract_dynamic_segments(static_segments, nec_chars, db, ini, nof_res = nil) dyn_segs = [] distance_fct = nil static_segments.each do |s| s.nec_chars = nec_chars s.enc_map = get_encoding_map(nec_chars) tmp_dyn_segs = Discover.extract_dynamic_segments(s, distance_fct, nec_chars, db, ini) tmp_dyn_segs.sort! {|s1, s2| s2.length <=> s1.length} if nof_res and nof_res < tmp_dyn_segs.length tmp_dyn_segs = tmp_dyn_segs[0...nof_res] end # Set id within each dyn segment of the current static segment tmp_dyn_segs.each_with_index do |seg, idx| seg.segment_id = idx + 1 end # Store the dynamic segments of the current static segment in the overall result dyn_segs.concat(tmp_dyn_segs) end dyn_segs end def calculate_bpms(segments, ini, db, event_tbl_name) res = [] segments.each do |s| bpm = Bpm.new(s, ini, db, event_tbl_name) bpm.calc_bpm() #puts bpm.topology_to_s #exit res << bpm end res end # Calculate reduced reduced BPMss, i.e. the BPMs with only the important steps left. def calculate_pdjms(ini, bpms) calc_method = ini["pdjm"]["method"] chunk = ini["chunk"]["chunk"] chunk = (chunk ? chunk == "true" : false) if calc_method != "enum" and calc_method != "mcl" if calc_method != "none" unknown_calc_method = calc_method calc_method = "none" msg = "util::calculate_pdjms, unknown calculation method '#{unknown_calc_method}' for PdjMaps, " msg += "assuming 'none', hence neither enumeration nor mcl-clustering is used" $LOG.warn msg end # nothing to do if no pdj map calculation and no chunking is required return bpms if not chunk end r_bpms = [] attrs = ini.get_pdjm_attributes() bpms.each do |b| if calc_method == 'mcl' $LOG.info("util::calculate_pdjms, starting MCL") max_iterations = ini["mcl"]["max_iterations"] exp_fac = ini["mcl"]["expansion_factor"] infl_fac = ini["mcl"]["inflation_factor"] directed = ini["mcl"]["directed"] weighted = ini["mcl"]["weighted"] max_iterations = (max_iterations ? max_iterations.to_i : 200) exp_fac = (exp_fac ? exp_fac.to_i : 3) infl_fac = (infl_fac ? infl_fac.to_i : 2) if $LOG str = "util::calculate_pdjms, MCL calculation with exp_fac = #{exp_fac}, infl_fac = #{infl_fac}," str += " directed = #{directed} and weighted = #{weighted}" $LOG.debug str end if not directed directed = false else directed = directed == "true" end if not weighted weighted = false else weighted = weighted == "true" end pdjm_result = calc_pdj_map_mcl(b, max_iterations, exp_fac, infl_fac, directed, weighted) elsif calc_method == 'enum' $LOG.info("util::calculate_pdjms, starting enumeration") enum = Enumerator.new(b, ini) pdjm_result = enum.enumerate() elsif calc_method == 'none' #nothing to do: this case is already processed out of this loop pdjm_result = b.dup else $LOG.error "util::calculate_pdjms, could not change unknown calculation method '#{unknown_calc_method}' to 'none'" end r_bpms << pdjm_result end if chunk chunk_attrs = ini.get_chunk_attributes() attributes = false if chunk_attrs chunk_attrs.each_pair do |k, v| if v.length > 0 attributes = true end end end if not attributes str = "util::calculate_pdjms, no attributes for chunking defined, " str += "using PDJ-Map attributes" $LOG.info str chunk_attrs = attrs end if $LOG.debug? $LOG.debug "util::calculate_pdjms, chunk attributes:" chunk_attrs.each_pair do |k, v| at = v.length > 0 ? v.join(", ") : "<none>" $LOG.debug " chunk attributes for #{ID_EVENT_MAP[k]}: #{at}" end end sim = ini["chunk"]["similarity"] pos_type = ini["chunk"]["pos_type"] radius = ini["chunk"]["radius"] chunk_level = ini["chunk"]["chunk_level"] chunk_crit = ini["chunk"]["chunk_crit"] sim = (sim ? sim.to_f : 0.7) radius = (radius ? radius.to_i : 3) if $LOG str = "util::calculate_pdjms, chunking with similarity = #{sim}, pos_type = #{pos_type}, radius = " str += " #{radius}, chunk_level = #{chunk_level}, chunk_crit =" str += " #{chunk_crit}." $LOG.debug str end r_bpms.each do |r_bpm| r_bpm.chunks = chunk(r_bpm, chunk_attrs, sim, pos_type, radius, chunk_level, chunk_crit) end end r_bpms end def get_attributes_for_types(ini) attrs = {} ini_segments = ["dynamic_segment", "bpm", "pdjm", "chunk"] attr_names = Discover.get_all_milestone_names().concat(Discover.get_all_step_names()) pr_fx = "" if ini["global"] and ini["global"]["attribute_prefix"] pr_fx = ini["global"]["attribute_prefix"] end ini_segments.each do |seg| attr_names.each do |ms| attributes = ini[seg][ms + "_attributes"] if attributes ms_id = Discover.get_id_to_name(ms) if not attrs[ms_id] attrs[ms_id] = Array.new() end ((attributes.split(",").map! {|x| x.strip}).map {|x| pr_fx + x}).each do |atna| attrs[ms_id] << atna if not attrs[ms_id].include?(atna) end end prot_attributes = ini[seg]["protected_" + ms + "_attributes"] if prot_attributes ms_id = Discover.get_id_to_name(ms) if not attrs[ms_id] attrs[ms_id] = Array.new() end ((prot_attributes.split(",").map! {|x| x.strip}).map {|x| pr_fx + x}).each do |atna| attrs[ms_id] << atna if not attrs[ms_id].include?(atna) end end end end if ini["visualisation"] pst_fix = "_text_attribute" ini["visualisation"].each_pair do |key, name| if key.end_with?(pst_fix) attr_name = key[0...key.length-pst_fix.length] ms_id = Discover.get_id_to_name(attr_name) next if not ms_id ((name.split(",").map! {|x| x.strip}).map {|x| pr_fx + x}).each do |atna| attrs[ms_id] << atna if not attrs[ms_id].include?(atna) end end end end attrs end <file_sep>/lib/json_reader.rb require 'json' def dump_reader(ini,phase) input_path = ini["global"]["base_folder"]+"/"+STAGES.find{|key,value| value["n"] == phase-1}.first.to_s+".js" input_db = input_path.chop.chop + "db" if File.exist?(input_path) and File.exist?(input_db) input_file = File.read(input_path) else $LOG.error "json_reader: Unable to find '#{input_path}' and/or '#{input_db}'! Check input file and/or configuration.ini." exit 0 end # Validation switch if ini["global"]["input_validation"] == "true" validate(ini,input_file) else $LOG.warn "json_reader: Input_validation is OFF. MD5 nor input_type check are activated. WARNING!" end # Actual parse of the dump_file d = JSON.parse(input_file) rescue Exception => e $LOG.error "Could not parse <#{input_path}>. PLease check if it's a valid json file dump." $LOG.error " Exception message:" $LOG.error e exit 0 return d end def validate(ini,input_file) # <------- Dump_file md5 validation dump = JSON.parse(input_file) d = dump.reject{|key,value| key == "md5_dump"} md5_d = Digest::MD5.hexdigest(d.to_s) if md5_d == dump["md5_dump"] $LOG.info "json_reader: MD5_dump check: OK! Provided dump's MD5 matches with 'md5_dump' field in the dumped input_file." else $LOG.error "json_reader: MD5_dump mismatch!. Dump_file corrupted or bad inputs in configuration ini. ABORTING! " exit 0 end # <-------- Database md5 validation # original_db = ini["global"]["db_path"] # if File.exist?(original_db) # md5_db = Digest::MD5.file(original_db).hexdigest # else # $LOG.error "json_reader: Could not find '#{original_db} file'. Check configuration. ABORTING" # exit 0 # end # <------------it doesn't track the changes done by the phases following the # dump so it returns mismatch! # if md5_db == dump["md5_db"] # $LOG.info "json_reader: MD5_db check: OK! Provided db's MD5 matches with 'md5_db' field in the dumped input_file." # else # $LOG.error "json_reader: MD5_db mismatch!. Database corrupted or bad inputs Digest::MD5.hexdigest(d.to_s) in configuration ini. ABORTING! " # exit 0 # end # --------------------> end of validation end def check_folder_consistency() STAGES.each do |field| break if field[1]["n"] == Entry_point["n"] field[1]["files"].each do |i| if not File.exist?($base_folder + "/" + i) $LOG.error "Unable to find '#{i}' in base folder '#{$base_folder}'! Check base folder and/or configuration.ini." exit 0 end end end end <file_sep>/lib/bpm_node.rb require_relative 'constants' # Class to represent a node in the BPM graph. class BpmNode attr_accessor :id # prv and nxt represent graph edges. # This means prv and nxt contain pointer to other BPM steps. # All events in the prv array happened semantically before and all events # in the nxt array after this step. attr_accessor :nxt, :prv # pdj_events contain all pdj events belonging to this BPM step. # The events are ordered by user_id attr_accessor :pdj_events # Type of elements this node represents. attr_accessor :type # Access to BPM structure attr_accessor :bpm # If this BpmNode represents a step, the following attributes #attr_reader :end_milestones, :start_milestones attr_accessor :end_milestones, :start_milestones # position of nodes in bpm to check radius for chunking attr_accessor :phase_pos # count manifestations for every attribute attr_accessor :attrs_cnt # Acces to the graphviz represantion of the node attr_reader :gvn # attr_reader :uniq_user_ids # Id of the chunk the node belongs to attr_accessor :chunk_id def initialize(id, type, evt = nil, prv = nil, bpm = nil) @id = id @prv = [] @nxt = [] @pdj_events = [] @type = type @bpm = bpm @uniq_user_ids = nil if evt add_pdj_event(evt) end if prv and not @prv.include(prv) @prv << prv end @phase_pos = [] @frequency = nil @importance = nil @prv_frequency = nil @print_pos = false @chunk_id = -1 end def add_pdj_event(s) @pdj_events << s if @pdj_events.length > 1 ta = @pdj_events.last(2) if (ta[0].pdj.user_id > ta[1].pdj.user_id) @pdj_events.sort! {|x, y| x.pdj.user_id <=> y.pdj.user_id} end end end def delete_pdj_events(s) tmp = @pdj_events.delete(s) return tmp != nil end def equals(node, attrs) @pdj_events.each do |n| if n.equals(node, attrs) return true end end false end # Returns the maximum similarity of all pdj_events in this BPM-Node. def similar(node, attrs) max = 0 @pdj_events.each do |n| max = [max, PdjEvent.similar(node, n, attrs)].max end max end def get_nof_pdj_events() @pdj_events.length end def get_node_frequency() if not @frequency @frequency = pdj_events.length.to_f / @bpm.segment.length.to_f end @frequency end def get_unique_user_ids return @uniq_user_ids if @uniq_user_ids @uniq_user_ids = Array.new tmp = Array.new @pdj_events.each do |evt| tmp << evt.pdj.user_id end tmp2 = tmp.uniq tmp = tmp2 if tmp2 @uniq_user_ids = tmp.sort @uniq_user_ids end def get_prv_frequency() if not @prv_frequency @prf_frequency = 0 if @prv.length = 0 @prf_frequency = get_node_frequency() else @prv.each do |p| @prv_frequency += p.pdj_events.length end @prv_frequency = @prv_frequency / @bpm.segment.length.to_f end end @prv_frequency end def get_importance(imp_name = Discover::ALGORITHM_COLUMNS[:importance]) if not @importance if not Discover.step?(@type) @importance = 0.0 else @importance = 0.0 @pdj_events.each do |evt| @importance += evt.attributes[imp_name].to_f end @importance = @importance / @pdj_events.length.to_f end end @importance end def calc_end_milestones(recalc = false) if @end_milestones and @end_milestones.length > 0 and not recalc return end em = Array.new @nxt.each do |nx| if [Discover::TRIGGER, Discover::READY_TO_PURCHASE, Discover::PURCHASE].include?(nx.type) em << nx next end nx.calc_end_milestones em.concat(nx.end_milestones) end @end_milestones = em.uniq end def calc_start_milestones(recalc = false) if @start_milestones and @start_milestones.length > 0 and not recalc return end sm = Array.new @prv.each do |pr| if [Discover::TRIGGER, Discover::READY_TO_PURCHASE].include?(pr.type) sm << pr next end pr.calc_start_milestones sm.concat(pr.start_milestones) end @start_milestones = sm.uniq end def get_nxt_ids() res = Array.new @nxt.each do |n| res << n.id end res end def get_prv_ids() res = Array.new @prv.each do |n| res << n.id end res end def cpy() #res = BpmNode.new(@id, @type, nil, nil, @bpm) res = BpmNode.new(@id, @type, nil, nil, nil) res.pdj_events = @pdj_events.clone res.nxt = @nxt.clone res.prv = @prv.clone if @start_milestones res.start_milestones = @start_milestones.clone end if @end_milestones res.end_milestones = @end_milestones.clone end res end def to_s res = "BPMNode: #{id}, type: #{@type}, phase_pos: #{@phase_pos}\n" res += " -> prv node ids: " res += (@prv.map {|n| n.id.to_s}).join(", ") if @prv.length == 0 res += "<none>" end res += "\n" res += " -> nxt node idx: " res += (@nxt.map {|n| n.id.to_s}).join(", ") if @nxt.length == 0 res += "<none>" end res += "\n" res += " -> pdj events in this node:\n" @pdj_events.each do |n| res += " [#{n.pdj.user_id}]: #{n}\n\n" end res end def topology_to_s(spcs = 0) res = "" spces = "" spcs.times do |t| spces+= " " end res += spces res += "id :#{@id} (nof_evts: #{pdj_events.length} " res += "pos: #{@pdj_events[0].position}, freq: #{get_frequency()}, phase_pos: #{@phase_pos})\n" res += spces res += " prv: " @prv.each do |p| res += p.id.to_s + ", " end res += "\n" res += spces res += " nxt: " @nxt.each do |n| res += n.id.to_s + ", " end res += "\n" res end def draw_node(grph_obj, vis_attrs, journey_numbers, label_id, threshold) frequency = calc_frequency(journey_numbers, 2) type = pdj_events[0].type node_id = @id.to_s stmt = nil valid_attribute = nil # check if attribute available and set statement if vis_attrs[type] stmt = pdj_events[0].attributes[vis_attrs[type][0]] valid_attribute = vis_attrs[type][0] end if vis_attrs[type] and not stmt stmt = pdj_events[0].attributes[vis_attrs[type][1]] valid_attribute = vis_attrs[type][1] end # ensuring statement is character string stmt = stmt.to_s if stmt if type == Discover::TRIGGER statement = forge_statement(stmt) cluster_tr = nil if statement and statement.length > 0 cluster_tr = grph_obj.add_graph("cluster_tr", :label => '', :style => 'filled, rounded', :color => 'whitesmoke', :fontname => 'HelveticaNeueThin, helvetica_neuethin, Roboto, arial') @gvn = cluster_tr.add_nodes("Trigger", :color => '#334355', :shape => 'circle', :style => 'filled',:fillcolor => '#334355', :fontcolor => '#FFFFFF', :fixedsize => 'true', :width => '2.0', :height => '2.0', :fontname => 'HelveticaNeueThin, helvetica_neuethin, Roboto, arial') if frequency >= threshold tr = cluster_tr.add_nodes(node_id, :label => "#{statement}\nF:#{frequency}%", :color => 'none', :shape => 'box', :style => 'filled', :fillcolor => 'none', :fontcolor => '#334355', :fontname => 'HelveticaNeueThin') end else @gvn = grph_obj.add_nodes("Trigger", :color => '#334355', :shape => 'circle', :style => 'filled',:fillcolor => '#334355', :fontcolor => '#FFFFFF', :fixedsize => 'true', :width => '2.0', :height => '2.0', :fontname => 'HelveticaNeueThin, helvetica_neuethin, Roboto, arial') end elsif type == Discover::READY_TO_PURCHASE cluster_rp = grph_obj.add_graph("cluster_rb", :label => '', :style => 'dotted', :color => '#FFFFFF') @gvn = cluster_rp.add_nodes("Ready to\n purchase", :color => '#334355', :shape => 'circle', :style => 'filled', :fillcolor => '#334355', :fontcolor => '#FFFFFF', :fixedsize => 'true', :width => '2.0', :height => '2.0', :fontname => 'HelveticaNeueThin, helvetica_neuethin, Roboto, arial') elsif type == Discover::PURCHASE statement = "" if stmt and stmt.length > 0 statement = forge_statement(stmt) end @gvn = grph_obj.add_nodes("Purchase", :label => "Purchase", :color => '#ED1B2D', :shape => 'circle', :style => 'filled', :fillcolor => '#ED1B2D', :fontcolor => '#FFFFFF', :fixedsize => 'true', :width => '2.0', :height => '2.0', :fontname => 'HelveticaNeueThin, helvetica_neuethin, Roboto, arial') else if not valid_attribute msg = "BpmNode::draw_node, no attribute has been defined for textual " msg += "representation of steps. Trying to use jrn_goal." $LOG.warn(msg) if $LOG if pdj_events[0].attributes.has_key?("jrn_goal") statement = forge_statement(pdj_events[0].attributes["jrn_goal"]) end else statement = forge_statement(stmt) end importance = calc_importance() label = "#{statement}\n\nF: #{frequency}% I: #{importance}" if label_id label += "\n Id:#{node_id}" end if @print_pos label += "\n pos:#{@pdj_events[0].position}" end ratio = is_re_active if ratio > 0.5 # reactive @gvn = grph_obj.add_nodes(node_id, :label => label, :color => '#EBE7DB', :shape => 'circle', :style => 'filled', :style => 'bold', :fillcolor => '#FFFFFF', :fontcolor => '#334355', :fontname => 'HelveticaNeueThin, helvetica_neuethin, Roboto, arial') else # active @gvn = grph_obj.add_nodes(node_id, :label => label, :color => '#999ba7', :shape => 'circle', :style => 'filled', :style => 'bold', :fillcolor => '#FFFFFF', :fontcolor => '#334355', :fontname => 'HelveticaNeueThin, helvetica_neuethin, Roboto, arial') end end end def draw_chunk_node(grph_obj, vis_attrs, journey_numbers, chunk_id, label_id, threshold) frequency = calc_frequency(journey_numbers, 2) type = pdj_events[0].type node_id = @id.to_s stmt = nil valid_attribute = nil # check if attribute available and set statement if vis_attrs[type] stmt = pdj_events[0].attributes[vis_attrs[type][0]] valid_attribute = vis_attrs[type][0] end if vis_attrs[type] and not stmt stmt = pdj_events[0].attributes[vis_attrs[type][1]] valid_attribute = vis_attrs[type][1] end # ensuring statement is character string stmt = stmt.to_s if stmt if type == Discover::TRIGGER statement = forge_statement(stmt) cluster_tr = nil if statement and statement.length > 0 cluster_tr = grph_obj.add_graph("cluster_tr", :label => '', :style => 'filled, rounded', :color => 'whitesmoke', :fontname => 'HelveticaNeueThin, helvetica_neuethin, Roboto, arial') @gvn = cluster_tr.add_nodes("Trigger", :color => '#334355', :shape => 'circle', :style => 'filled',:fillcolor => '#334355', :fontcolor => '#FFFFFF', :fixedsize => 'true', :width => '2.0', :height => '2.0', :fontname => 'HelveticaNeueThin, helvetica_neuethin, Roboto, arial') if frequency >= threshold tr = cluster_tr.add_nodes(node_id, :label => "#{statement}\nF:#{frequency}%", :color => 'none', :shape => 'box', :style => 'filled', :fillcolor => 'none', :fontcolor => '#334355', :fontname => 'HelveticaNeueThin, helvetica_neuethin, Roboto, arial') end else @gvn = grph_obj.add_nodes("Trigger", :color => '#334355', :shape => 'circle', :style => 'filled',:fillcolor => '#334355', :fontcolor => '#FFFFFF', :fixedsize => 'true', :width => '2.0', :height => '2.0', :fontname => 'HelveticaNeueThin, helvetica_neuethin, Roboto, arial') end elsif type == Discover::READY_TO_PURCHASE cluster_rp = grph_obj.add_graph("cluster_rb", :label => '', :style => 'dotted', :color => '#FFFFFF') @gvn = cluster_rp.add_nodes("Ready to\n purchase", :color => '#334355', :shape => 'circle', :style => 'filled', :fillcolor => '#334355', :fontcolor => '#FFFFFF', :fixedsize => 'true', :width => '2.0', :height => '2.0', :fontname => 'HelveticaNeueThin, helvetica_neuethin, Roboto, arial') elsif type == Discover::PURCHASE statement = forge_statement(pdj_events[0].attributes['statement']) @gvn = grph_obj.add_nodes("Purchase", :label => "Purchase", :color => '#ED1B2D', :shape => 'circle', :style => 'filled', :fillcolor => '#ED1B2D', :fontcolor => '#FFFFFF', :fixedsize => 'true', :width => '2.0', :height => '2.0', :fontname => 'HelveticaNeueThin, helvetica_neuethin, Roboto, arial') else if not valid_attribute msg = "BpmNode::draw_node, no attribute has been defined for textual " msg += "representation of steps. Using jrn_goal." $LOG.warn(msg) if $LOG end statement = forge_statement(stmt) importance = calc_importance() label = "#{statement}\nF: #{frequency}% I: #{importance}" if label_id label += "\n Id:#{node_id}" end cluster_ch = grph_obj.add_graph("cluster_#{chunk_id}", :label => "Chunk_nr: #{chunk_id}", :labeljust => 'l', :fontsize => '16',:fontcolor => '#334355', :style => 'dashed', :color => '#334355', :fontname => 'HelveticaNeueThin, helvetica_neuethin, Roboto, arial') ratio = is_re_active() if ratio > 0.5 # reactive To Do: adjust colors @gvn = cluster_ch.add_nodes(label, :color => '#EBE7DB', :shape => 'circle', :style => 'filled', :style => 'bold', :fillcolor => '#FFFFFF', :fontcolor => '#334355', :fontname => 'HelveticaNeueThin, helvetica_neuethin, Roboto, arial') else # active @gvn = cluster_ch.add_nodes(label, :color => '#999ba7', :shape => 'circle', :style => 'filled', :style => 'bold', :fillcolor => '#FFFFFF', :fontcolor => '#334355', :fontname => 'HelveticaNeueThin, helvetica_neuethin, Roboto, arial') end end end def draw_edge(grph_obj) if not @gvn $LOG.error "BPM_Node::draw_edge, graphviz object has not been initialized!" $LOG.error " Node: #{self.to_s}" end @nxt.each do |c| grph_obj.add_edges(@gvn , c.gvn)[:color => '#999BA7'] end end def forge_statement(stmt) #s = pdj_events[0].attributes['statement'] return "" if not stmt a = stmt.split statement = "" line_length = 0 if a.length < 5 statement = statement + '\n\n' end if a.first statement = statement + a.first a.delete_at(0) end a.each do |word| if word.length + line_length >= 14 if line_length <= 3 statement = statement + ' ' + word line_length = line_length + word.length + 1 else line_length = 0 statement = statement + '\n' + word line_length = line_length + word.length end else statement = statement + ' ' + word line_length = line_length + word.length + 1 end end statement end def is_re_active() nr_all = pdj_events.length.to_f nr_reactive = 0 pdj_events.each do |pdj_event| if pdj_event.attributes['interaction_direction'].to_i == 2 nr_reactive = nr_reactive + 1 end end nr_reactive.to_f #@ratio = nr_reactive/nr_all #puts "nr_reactive.to_f #{nr_reactive.to_f}" #puts "nr_all #{nr_all.to_f}" ratio = nr_reactive.to_f / nr_all.to_f msg = "BPM-Node::is_re_active, node id #{@id} ratio is #{ratio} " msg += "(reactive: #{nr_reactive})" $LOG.debug msg ratio end def calc_attrs_cnt() @attrs_cnt = Hash.new() @attrs_cnt[@type] = Hash.new() pdj_events.each do |event| # check if event is what it should be if not @attrs_cnt.has_key?(event.type) $LOG.error "Event type of pdj node and bpm node are not equal!" if $LOG puts "Event type of pdj node and bpm node are not equal!" if not $LOG exit 1 end event.attributes.each_pair do |attr, attr_value| next if not attr_value # creating hash for current attribute if not @attrs_cnt[@type][attr] @attrs_cnt[@type][attr] = Hash.new end # counting manifestations # remark: empty attr_value strings are counted as a # manifestations of the attribute if not @attrs_cnt[@type][attr][attr_value] @attrs_cnt[@type][attr][attr_value] = 1 else @attrs_cnt[@type][attr][attr_value] += 1 end end end end def calc_importance() importance_array = Array.new pdj_events.each do |x| importance_array.push(x.attributes[Discover::ALGORITHM_COLUMNS[:importance]].to_f) end length = importance_array.length.to_f sum = importance_array.inject(:+) importance = sum.to_f / length.to_f importance.round(2) end def calc_frequency(journey_numbers, rnd = nil) journey_numbers = journey_numbers.to_f nodes_in_bpm_node = pdj_events.length.to_f #@frequency = [((nodes_in_bpm_node / journey_numbers) * 100).to_i, 1.0].max frequency = ((nodes_in_bpm_node / journey_numbers) * 100.0).to_f if rnd frequency = frequency.round(rnd) end return frequency end def get_frequency(rnd = 2) return -1 if not bpm or not bpm.segment or bpm.segment.length == 0 return pdj_events.length.to_f / bpm.segment.length.to_f end end <file_sep>/lib/pdj_event.rb # Parent class for all event types. # An event is modelled as an hash of attributes and an event type. # The key of the attribute hash is the name of an attribute and the key the # corresponding value. The attribute hash should be sorted according to the # keys, i.e. the attribute names. # type encodes the type of this step, e.g. 3 == trigger, 4 == considering_step, # ... # Besides storing attributes and types this class mainly provides comparison # functions for steps. class PdjEvent attr_accessor :attributes, :type, :pdj attr_accessor :surrogate # Position of this event in a pdj. # The first event has position 0! attr_accessor :position, :orig_pos def initialize(attr, type, position, dummy = false) @attributes = attr || Hash.new() @type = type @surrogate = nil @position = position @dummy = dummy @orig_pos = position end def cpy() res = PdjEvent.new(@attributes.clone(), @type, @position, @dummy) res.surrogate = @surrogate.cpy() res.orig_pos = @orig_pos end #def order_attributes(attr, typ) #end def clear_surrogate @surrogate = nil end def use_event_as_surrogate @surrogate = self end def get_entropy end def is_connected? false end def add_attribute ; end def get_nof_attributes @attributes.size() end def is_dummy?() return @dummy end def to_s #res = ">>> Event type #{type}, pos: #{@pos}, attributes:\n" res = ">>> Event type '#{Discover::ID_EVENT_MAP[type]}' (#{type}), " res += "position: #{@position}, orig_pos: #{orig_pos}, " if is_dummy?() res += "DUMMY \n" else res += ", attributes:\n" #res = ">>> Event type #{type}, attributes:\n" @attributes.each_pair do |k, v| res += " #{k} => #{v}\n" end end res end def self.similarity(s1, s2, attribute_list = nil) attrs = [] if attribute_list attrs = attribute_list.sort else attrs = s1.attributes.keys.sort end return (PdjEvent::similar(s1, s2, attrs)).to_f / attrs.length.to_f end def self.similar(s1, s2, attribute_list = nil, use_surrogate = true) if not s1.type == s2.type if $LOG msg = "PdjEvent::similar, cannot compare types " msg += "#{s1.type} and #{s2.type}, returning 0!" $LOG.error msg end return 0 end attrs = [] if attribute_list attrs = attribute_list.sort else attrs = s1.attributes.keys.sort end eq = 0 attrs.each do |a| s1a = s1.attributes[a] s2a = s2.attributes[a] if use_surrogate if s1.surrogate and s2.surrogate s1a = s1.surrogate.attributes[a] s2a = s2.surrogate.attributes[a] elsif (s1.surrogate and not s2.surrogate) or (not s1.surrogate and s2.surrogate) msg = "PdjEvent.similar, should use surrogates but only" msg += " one of the provided pdj events has a surrogate" $LOG.error(msg) if $LOG end end if s1a == s2a eq += 1 end end # attrs.each eq end def ==(other) return false if not other if @dummy and other.is_dummy?() return true end return false if other == nil res1 = @attributes == other.attributes res2 = @type == other.type res = res1 && res2 return res end def equals(other, attr) if @dummy and other.is_dummy?() return true end count = 0 attr.each do |a| if @surrogate and other.surrogate if not @surrogate.attributes[a] == other.surrogate.attributes[a] count += 1 end end if not @attributes[a] == other.attributes[a] count += 1 end end return count == 0 end def self.get_dummy(pos, type = -1) dummy = true PdjEvent.new(nil, type, pos, dummy) end end <file_sep>/lib/configuration.rb require 'inifile' require_relative 'constants' class Configuration DYNAMIC_SEGMENT = "dynamic_segment" BPM = "bpm" PDJM = "pdjm" CHUNK = "chunk" attr_accessor :file_name def initialize(file_name) @file_name = file_name @config = IniFile.load(@file_name) # IniFile is a class defined in ruby inifile gem and can manage the parsing of .ini automatically @dynamic_segment_attributes = {} @bpm_attributes = {} @pdjm_attributes = {} @chunk_attributes = {} end def access_inifile_class # Returns de IniFile class which was not reachable while wrapped in the Configuration class return @config end def [](i) return @config[i] end def get_dynamic_segment return @config[DYNAMIC_SEGMENT] end def get_dynamic_segment_attributes if not @dynamic_segment_attributes.empty? return @dynamic_segment_attributes end pr_fx = @config["global"]["attribute_prefix"] ||= "" pr_fx.strip!() @config["dynamic_segment"].each do |k, v| id = Discover::EVENT_ID_MAP[k[0...-"_attributes".length]] next if not id v ||= "" #@dynamic_segment_attributes[id] = (v.split(",").each {|x| x.strip!}).sort! @dynamic_segment_attributes[id] = (v.split(",").map! {|x| x.strip!; x = pr_fx + x}).sort! end @dynamic_segment_attributes end def get_dynamic_segment_protected_attributes res = {} pr_fx = @config["global"]["attribute_prefix"] ||= "" pr_fx.strip!() @config["dynamic_segment"].each do |k, v| if k.start_with?("protected_") and k.end_with?("_attributes") id = Discover::EVENT_ID_MAP[k["protected_".length...-"_attributes".length]] next if not id res[id] = (v.split(",").map! {|x| x.strip!; x = pr_fx + x}).sort! end end res end def get_bpm_attributes if not @bpm_attributes.empty? return @bpm_attributes end pr_fx = @config["global"]["attribute_prefix"] ||= "" pr_fx.strip!() @config[BPM].each do |k, v| id = Discover::EVENT_ID_MAP[k[0...-"_attributes".length]] next if not id v ||= "" @bpm_attributes[id] = (v.split(",").map! {|x| x.strip!; x = pr_fx + x}).sort! end @bpm_attributes end def get_bpm_protected_attributes res = {} pr_fx = @config["global"]["attribute_prefix"] ||= "" pr_fx.strip!() @config[BPM].each do |k, v| if k.start_with?("protected_") and k.end_with?("_attributes") id = Discover::EVENT_ID_MAP[k["protected_".length...-"_attributes".length]] next if not id res[id] = (v.split(",").map! {|x| x.strip!; x = pr_fx + x}).sort! end end res end def get_pdjm_attributes if not @pdjm_attributes.empty? return @pdjm_attributes end pr_fx = @config["global"]["attribute_prefix"] ||= "" pr_fx.strip!() @config[PDJM].each do |k, v| id = Discover::EVENT_ID_MAP[k[0...-"_attributes".length]] next if not id v ||= "" @pdjm_attributes[id] = (v.split(",").map! {|x| x.strip!; x = pr_fx + x}).sort! end @pdjm_attributes end def get_chunk_attributes if not @chunk_attributes.empty? return @chunk_attributes end pr_fx = @config["global"]["attribute_prefix"] ||= "" pr_fx.strip!() Discover::JOURNEY_EVENT_ORDER.each do |t| @chunk_attributes[t] = Array.new end @config[CHUNK].each do |k, v| id = Discover::EVENT_ID_MAP[k[0...-"_attributes".length]] next if not id @chunk_attributes[id] = (v.split(",").map! {|x| x.strip!; x = pr_fx + x}).sort! end @chunk_attributes end def to_s res = "INI file: #{@file_name}\n" res += @config.to_s res end end <file_sep>/lib/mcl.rb require 'matrix' require_relative 'constants' require_relative 'bpm' require_relative 'mtx' require_relative 'tools' module Discover def calc_pdj_map_mcl(bpm, max_iterations = 200 , exp_fac = 3, infl_fac = 2, directed = false, weighted = false) # get matrix which consists of the number of journeys between all nodes # following options are used self_loops = false #should self loops for every step be allowed? direct_connection = true #only direct edges betw nodes considered in adj mtx ignore_milestones = true #milestones will be ignored in whole adj mtx # (no connections at all) adj_mtx = bpm.calc_adj_mtx(directed, weighted, self_loops, direct_connection, ignore_milestones) # add connections to milestones as weighted selfloops prepare_adj_mtx_for_mcl(adj_mtx, bpm, 'repl_milestones') initial_col_norm = get_initial_col_norm(bpm, adj_mtx) prob_matrix = turn_into_prob_matrix(adj_mtx, initial_col_norm, false) mcl_mtx = calc_mcl_mtx(max_iterations, exp_fac, infl_fac, prob_matrix, initial_col_norm) include_attracted = true idx_mcl_nodes = get_attractors(mcl_mtx, include_attracted) ms = (bpm.node_arry.select {|x| Discover.milestone?(x.type)}).map {|x| x.id} pdjm = Discover.build_pdjm(bpm, idx_mcl_nodes, ms, true) return pdjm end def calc_mcl_mtx(max_iterations, exp_fac, infl_fac, prob_matrix, col_norm = []) # initialize result mtx mcl_matrix = Matrix.build(prob_matrix.row_size) {nil} mcl_matrix.each_with_index do |e, row, col| mcl_matrix.set(row, col, prob_matrix[row, col]) end # iteration over expand and inflate steps i = 1 while i <= max_iterations $LOG.debug "mcl::calc_mcl_mtx, iteration: #{i}" if $LOG expanded_prob_matrix = expand_prob_matrix(mcl_matrix, exp_fac) inflated_matrix = inflate_matrix(expanded_prob_matrix, infl_fac, col_norm) if mcl_matrix == inflated_matrix $LOG.debug "mcl::Algorithm converged after #{i} iterations." if $LOG break elsif i == max_iterations if not $LOG puts "mcl::Algorithm stopped after #{max_iterations} without convergence." else $LOG.debug "mcl::calc_pdj_map_mcl: Algorithm stopped after #{max_iterations} without convergence." end end mcl_matrix = inflated_matrix i += 1 end Mtx.from_matrix(mcl_matrix) end def prepare_adj_mtx_for_mcl(adj_mtx, bpm, method = 'none', self_loop_factor = 0.33) return if method == 'none' if method == 'del_milestones' bpm.node_arry.each do |nd| if Discover.milestone?(nd.type) nd.nxt.each do |n| adj_mtx[nd.id][n.id] = 0 adj_mtx[n.id][nd.id] = 0 end nd.prv.each do |p| adj_mtx[nd.id][p.id] = 0 adj_mtx[p.id][nd.id] = 0 end end end elsif method == 'repl_milestones' # add number of journeys from milestone to connected steps bpm.node_arry.each do |node| next if not Discover.milestone?(node.type) # end milestone? if node.nxt.empty? node.prv.each do |prv| next if Discover.milestone?(prv.type) cnt_for_loop = Discover.nof_jrnys_btw_nodes(bpm.node_arry, prv.id, node.id, true) adj_mtx[prv.id][prv.id] += (cnt_for_loop * self_loop_factor) end # start milestone? elsif node.prv.empty? node.nxt.each do |nxt| next if Discover.milestone?(nxt.type) cnt_for_loop = Discover.nof_jrnys_btw_nodes(bpm.node_arry, node.id, nxt.id, true) adj_mtx[nxt.id][nxt.id] += (cnt_for_loop * self_loop_factor) end # milestone in the middle of journey? else # searching for direct connections btw milestones node.nxt.each do |nxt| next if not Discover.milestone?(nxt.type) node.prv.each do |prv| next if Discover.milestone?(prv.type) cnt_over_ms = Discover.nof_jrnys_btw_nodes(bpm.node_arry, prv.id, nxt.id, true, false, [node.id]) adj_mtx[prv.id][prv.id] += cnt_over_ms end end node.prv.each do |prv| next if not Discover.milestone?(prv.type) node.nxt.each do |nxt| next if Discover.milestone?(nxt.type) cnt_over_ms = Discover.nof_jrnys_btw_nodes(bpm.node_arry, prv.id, nxt.id, true, false, [node.id]) adj_mtx[nxt.id][nxt.id] += cnt_over_ms end end end end else msg = "ERROR in prepare_adj_mtx_for_mcl: method '#{method}' unknown, " msg += "nothing done with milestones, original adjacency matrix is used" if not $LOG puts msg else $LOG.error msg end end end def get_initial_col_norm(bpm, mtx) # get total number of user journeys distinct_uids = [] bpm.node_arry.each do |node| distinct_uids += Discover.get_user_ids_for_node(node) distinct_uids.uniq! end nof_users = distinct_uids.length # get colsums and 'normalize' them col_sums = mtx.transpose.map {|x| x.reduce(:+)} col_norm = col_sums.map {|x| x.to_f/nof_users} return col_norm end def turn_into_prob_matrix(mtx, col_norm = [], add_self_loops = false) # input mtx must be array of arrays mtx = Mtx.from_matrix(mtx) if mtx.class.to_s == 'Matrix' # get sums of columns col_sums = mtx.transpose.map {|x| x.reduce(:+)} # should self loops be added? (one 'connection' for every node to itself) if add_self_loops col_sums.each_index do |i| col_sums[i] += 1 end # initial creation of result matrix matrix = Matrix.rows(mtx) + Matrix.identity(mtx.nof_cols) else # initial creation of result matrix matrix = Matrix.rows(mtx) end # check how the columns should be normed if col_norm.empty? col_norm = Array.new(col_sums.length, 1) end matrix.each_with_index do |e, row, col| if col_sums[col] == 0 matrix.set(row, col, 0.0) else # normalization matrix.set(row, col, col_norm[col]*((e.to_f)/(col_sums[col]))) end end return matrix end def expand_prob_matrix(prob_matrix, e = 3) nof_cols = prob_matrix.row_size expanded_prob_matrix = 1 if e < 0 $LOG.error "PdjMap::expand_prob_matrix, power paramater e = #{e} is not reasonable" exit 1 elsif e == 0 $LOG.warn "PdjMap::expand_prob_matrix, power paramater e = #{e} provides identity mtx" return Matrix.identity(nof_cols) else while e.nonzero? e -= 1 expanded_prob_matrix *= prob_matrix end end expanded_prob_matrix end def inflate_matrix(expanded_prob_matrix, r = 2, col_norm = []) inflated_r_matrix = expanded_prob_matrix.collect{|e| e**r} inflated_prob_matrix = Matrix.build(expanded_prob_matrix.row_size) {nil} inflated_prob_matrix = turn_into_prob_matrix(inflated_r_matrix, col_norm) return inflated_prob_matrix end def get_attractors(mcl_mtx, include_attracted) # remark: attractors could be find by selecting rows with positiv entries # it is not necessary for the pdj map, which nodes are represented by # which attractor idx_mcl_nodes = Array.new mcl_mtx.rows.each_with_index do |row, idx| row_sum_tmp = row.reduce(:+) if row_sum_tmp > 0 idx_mcl_nodes << idx if include_attracted # also include the nodes, that are attracted from the selected ones # we focus on nodes, that are connected with minimum 100 % to the # regarded attractor (higher values could occur because of the used # milestone handling (added selfloops) row.each_with_index do |col, id| idx_mcl_nodes << id if col > 1 end end end end # nodes may be selected several time, so delted redundant information idx_mcl_nodes = idx_mcl_nodes.uniq return idx_mcl_nodes end end <file_sep>/lib/constants.rb module Discover DUMMY = -1 SCREENER = 0 NON_BUYER = 1 BUYER = 2 OCCASION = 3 TRIGGER = 4 READY_TO_PURCHASE = 5 CONSIDERING_STEP = 6 BUYING_STEP = 7 STEP_CANVAS = 8 STEP_DRILL_DOWN = 9 PURCHASE = 10 POST_PURCHASE_STEP = 11 OTHER = 12 CLOSURE = 20 EVENT_TYPE_ARRAY = [SCREENER, NON_BUYER, BUYER, OCCASION, TRIGGER, READY_TO_PURCHASE, CONSIDERING_STEP, BUYING_STEP, STEP_CANVAS, STEP_DRILL_DOWN, PURCHASE, POST_PURCHASE_STEP, OTHER] EVENT_ID_MAP = { "screener" => SCREENER, "non_buyer" => NON_BUYER, "buyer" => BUYER, "occasion" => OCCASION, "trigger" => TRIGGER, "ready_to_purchase" => READY_TO_PURCHASE, "considering_step" => CONSIDERING_STEP, "buying_step" => BUYING_STEP, "step_canvas" => STEP_CANVAS, "step_drill_down" => STEP_DRILL_DOWN, "purchase" => PURCHASE, "post_purchase_step" => POST_PURCHASE_STEP, "other" => OTHER, "closure" => CLOSURE, "dummy" => DUMMY} ID_EVENT_MAP = EVENT_ID_MAP.invert() JOURNEY_EVENT_ORDER = [TRIGGER, CONSIDERING_STEP, READY_TO_PURCHASE, BUYING_STEP, PURCHASE] =begin ALGORITHM_COLUMNS = {:user_id => "user_id", :event_type => "event_type", :segment_id => "segment_id", :bpm_id => "bpm_id", :chunk_id => "chunk_id", :dynamic_segment_id => "dynamic_segment_id", :pdjm_id => "pdjm_id", :position => "position", :new_position => "position"} =end ALGORITHM_COLUMNS = {:user_id => "dat_journey_id", :event_type => "dat_object_type", :segment_id => "dat_segment_id", :bpm_id => "res_bpm_id", :chunk_id => "res_chunk_id", :dynamic_segment_id => "res_dynamic_segment_id", :pdjm_id => "res_pdjm_id", :position => "res_position", :jrn_position => "jrn_position", :importance => "jrn_importance", :tactical_opps => "res_tactical_opps"} # Maps the phase of the staged approach to integers to allow priority rules in conditionals # STAGES = { "start" => {"n" => 1, "name" => "start", "files" => ["source.db","ds.db"], "config_fields" => ["global", "version_check"], "results" => []}, # "ds" => {"n" => 2, "name" => "ds", "files" => ["bpm.db","ds.js"], "config_fields" => ["global", "version_check","dynamic_segment"], "results" => [ALGORITHM_COLUMNS[:dynamic_segment_id]]}, # "bpm" => {"n" => 3, "name" => "bpm", "files" => ["pdjm.db","bpm.js"], "config_fields" => ["bpm"], "results" => [ALGORITHM_COLUMNS[:bpm_id]]}, # "pdjm" => {"n" => 4, "name" => "pdjm", "files" => ["pdjm.js"], "config_fields" => ["pdjm", "enumeration", "mcl", "chunk"], "results" => [ALGORITHM_COLUMNS[:pdjm_id]]}, # "visualisation" => {"n" => 5, "name" => "visualisation","files" => ["visualisation.js"], "config_fields" => ["visualisation", "tactical_opportunities"], "results" => []} # } STAGES = { "start" => {"n" => 1, "name" => "start", "files" => ["source.db"], "files_to_copy" => ["source.db","ds.db"], "config_fields" => ["global", "version_check"], "results" => []}, "ds" => {"n" => 2, "name" => "ds", "files" => ["ds.js","ds.db"], "files_to_copy" => ["bpm.db","ds.js"], "config_fields" => ["global", "version_check","dynamic_segment"], "results" => [ALGORITHM_COLUMNS[:dynamic_segment_id]]}, "bpm" => {"n" => 3, "name" => "bpm", "files" => ["bpm.js","bpm.db"], "files_to_copy" => ["pdjm.db","bpm.js"], "config_fields" => ["bpm"], "results" => [ALGORITHM_COLUMNS[:bpm_id]]}, "pdjm" => {"n" => 4, "name" => "pdjm", "files" => ["pdjm.js","pdjm.db"], "files_to_copy" => ["pdjm.js"], "config_fields" => ["pdjm", "enumeration", "mcl", "chunk"], "results" => [ALGORITHM_COLUMNS[:pdjm_id]]}, "visualisation" => {"n" => 5, "name" => "visualisation","files" => ["visualisation.js"], "files_to_copy" => ["visualisation.js"], "config_fields" => ["visualisation", "tactical_opportunities"], "results" => []} } Pk = "dat_object_id" def Discover.get_all_step_types() [CONSIDERING_STEP, BUYING_STEP, POST_PURCHASE_STEP] end def Discover.get_all_step_names() step_ids = get_all_step_types() res = [] EVENT_ID_MAP.each_pair do |name, id| if step_ids.include?(id) res << name end end res end def Discover.get_all_milestone_types() [TRIGGER, READY_TO_PURCHASE, PURCHASE] end def Discover.get_all_milestone_names() step_ids = get_all_milestone_types() res = [] EVENT_ID_MAP.each_pair do |name, id| if step_ids.include?(id) res << name end end res end def Discover.step?(typ) get_all_step_types().include?(typ) end def Discover.milestone?(typ) get_all_milestone_types().include?(typ) end def Discover.get_id_to_name(name) return EVENT_ID_MAP[name] end def Discover.get_name_to_id(i) EVENT_ID_MAP.each_pair do |name, id| return name if id == i end return nil end SEGMENT_TABLE = { "id" => "Integer", "sql" => "Text" } RESULT_TABLE = { "id" => "Integer", "pdjmap" => "BLOB" } end <file_sep>/_benchmarking/README.txt This folder contains reference files. Do not use them directly or edit. Copy them to the "xxxTemp" folders for testing purposes, and remove the heading "_" from their name.<file_sep>/lib/dswap.rb require_relative 'constants' module Discover # Default dummy function. default_dummy_fct = lambda do |pos, *args| nil end # Default compare function. # If a "==" function has been defined on the used structure, then the default # compare function can be used. # In most cases it is better to define a "==" compare function for a # structure then expressing the similarity via an external compare function. default_cmp_fct = lambda do |a, b| a == b end # Function to align a journey (to_align) against a reference journey (ref). # This will be done by aligning all phases separately and then combining them # again. # == Parameter # ref:: Pdj: Reference journey. This journey will not be modified in this # function. # to_align:: Pdj: Journey to align against the reference journey. # NOTE: THIS PDJ WILL BE (VERY LIKELY) MODIFIED. # swap_window:: Int: How far can an event be swapped in the to_align PDJ. # attrs:: Hash: # dummy_fct:: Function: What to insert as a dummy. The result of the # dummy_fct call will be added as dummy element, if # necessary, into the to_align PDJ. # resolve_strategy:: Ruby-Constant: Possible values are: :force, :delete and # nil # extend_to_align_array:: Bolean: If true and to_align.length < ref.length, # to_align will be extended with dummys until # it has the same length as ref # # == Return # Pdj:: The modified, to_align, PDJ. This functions modifies directly the # to_align input PDJ. def Discover.align_pdj(ref, to_align, swap_window, attrs, dummy_fct = default_dummy_fct, resolve_strategy = :force, extend_to_align_array = true) ref.types.each_with_index do |t, idx| next if not t or t.length == 0 next if Discover.milestone?(t[0].type) ref_ary = t.clone align_ary = to_align.types[idx] cmp_fct = lambda {|a, b| a == b} if attrs typ_attr = attrs[idx] cmp_fct = lambda do |a, b| res = true return true if not typ_attr return false if not a return a.equals(b, typ_attr) end end res = align(ref_ary, align_ary, swap_window, cmp_fct, dummy_fct, resolve_strategy, extend_to_align_array) to_align.types[idx] = res end # Assign new positions to_align.adjust_positions() # Assign types to dummies to_align.set_type_to_dummys() to_align end # Align two arrays. # Workflow: # 1:: Find for all element +to_swap+ array possible swap positions, i.e. # at what position appears the nth element in the +to_swap+ array in the # +ref+ array. # 2:: Find optimal solution # 3:: Apply solution to +to_swap+ array # # The key structure for the alignment algorithm is +swap_pos+. # +swap_pos+ is an hash of hashes. The structure of the hash is: # swap_position[0] = {:con => {:ele => "a", :orig_pos => 0}, # :alt => [2, 3, 19], # :col = []} # # This means: # - Content (:con) of position 0 in +to_swap+ is "a", and it it original position is 0. # - "a" appears on position 2, 3, and 19 in the reference array. # - No collisions. # The collision array is used during optimisation to store # temporarily elements that need to to moved to other positions # If it is used, it looks like: # cur_position=>{:content=>{:pdj event =>"c", :original_pos=>1,}, # 2=>{:con=>{:ele=>"c", :orig_pos=>1,}, # :alt=>[], # :col=>[{:ele=>"x", :orig_pos=>2}]} # This means, element "c" has been moved from position 1 to 2. "x" used to # be on this position, therefore it is moved into the :col array. # # # == Paramter # ref:: Array: Reference array # to_swap:: Array: Array to align against ref this is being altered during the call # Call by reference # swap_window:: Int: In what window can be elements of to_swap be moved # around. # cmp_fct:: Ruby-Function: Compare function for elements in ref and to_swap. # dummy_fct:: Ruby-Function: Function that generates dummy elements. # resolve_strategy:: Ruby-Constant: Possible values are: :force, :delete and # nil # :force This value forces to move a # collision element to the nearest # available position, even if this # position is beyond the swap_window size. # If no suitable position is # available, the collision element # will be deleted. # :delete Delete all collision elements. # nil Do nothing. # extend_to_align_array:: Boolean: If true and to_align.length < ref.length, # to_align will be extended with dummys until # it has the same length as ref def Discover.align(ref, to_swap, swap_window, cmp_fct = nil, dummy_fct = default_dummy_fct, resolve_strategy = :force, extend_to_align_array = true) # First, assign to all elements in to_swap possible swap positions. # This means, for every element in to_swap find equal elements in ref and # if these elements are in the provided swap window size, mark the position # for the element. swap_pos = get_swap_positions(ref, to_swap, swap_window, cmp_fct, dummy_fct, extend_to_align_array) # Find best alignment solution with the provided +swap_pos+ array. align_arrays(ref, to_swap, swap_pos, swap_window, cmp_fct, dummy_fct, resolve_strategy, extend_to_align_array) # Build result array according to +swap_pos+ structure. res = traslate_swap_pos_to_array(swap_pos, dummy_fct) return res end # Computes a help structure for the permutations algorithm. # The structure is a hash, where the key is the initial position of an element. # the value of a hash with two entries: # :con:: => Content of the position. Content itself is stored in a hash # with following keys. # :ele:: => Element # :orig_pos:: => Original position of the element # if dummy_fct is not nil, the following key is also part of :con # :dummy:: => Is this element a dummy? # # :alt:: => alternative positions, where this element occurs in the # reference array. # :col:: => an array with all elements that want to occupy the same place. # Although, it is an array, it should never hold more then one # element. # For example # swap_position[0] = {:con => {:ele => "a", :orig_pos => 0}, # :alt => [2, 3, 19], # :col = []} # In the above case an "a" is in position 0 (swap_position[0]). The element # occurs in the reference array at positions 2, 3 and 19 def Discover.get_swap_positions(ref, to_swap, sw, cmp_fct = nil, dummy_fct = nil, extend_to_align_array = false) # We need a compare function. Use "==" if no compare function was provided. if not cmp_fct cmp_fct = lambda {|a, b| a == b} end res = {} # Iterate over all to_swap entries to_swap.each_with_index do |ts, idx| ele = {:ele => ts, :orig_pos => idx} res[idx] = {:con => ele, :alt => Array.new(), :col => Array.new()} # Determine ranges, according to swap window, where to look in ref array # for equal elements. l = [0, idx - sw].max r = [idx + sw, ref.length].min ele = to_swap[idx] # Use above range to search for equal elements for i in l..r do next if i == idx next if i >= to_swap.length and not extend_to_align_array if cmp_fct.call(ref[i], ele) res[idx][:alt] << i end end end # If ref array is longer than to_swap, extend to swap and fill it with # dummy elements if extend_to_align_array for idx in to_swap.length...ref.length dummy = dummy_fct.call(idx) ele = {:ele => dummy, :orig_pos => idx, :dummy => true} res[idx] = {:con => ele, :alt => Array.new(), :col => Array.new()} end end return res end # Use +swap_pos+ array to find an "optimal" alignment solution. # The alignment happens in 4 phases: # 1. If an element in to_swap is already at the right position, do nothing. # 2. Apply direct swaps. Direct swaps are: # a x x x b # b x x x a # In this case "a" and "b" can be directly swapped without producing # conflicts. # 3. Apply all other "swaps". # Details are explained in function +get_all_other_swaps+ # 4. Resolve collisions # Details are explained in function +resolve_collisions+ def Discover.align_arrays(ref, to_swap, swap_pos, sw, cmp_fct = nil, dummy_fct = nil, resolve_strategy = nil, extend_to_align_array = false) # First: Fixed position stay fixed get_fixed_positions(ref, to_swap, swap_pos, cmp_fct) get_direct_swaps(swap_pos) get_all_other_swaps(ref, to_swap, swap_pos, sw) resolve_collisions(swap_pos, sw, dummy_fct, resolve_strategy) return swap_pos end # If an element is already at the position is should be moved to, do nothing. # This function modifies +swap_pos+ structure. # # == Parameter # ref:: Array: Reference array # to_swap:: Array: Array to be aligned against ref # swap_pos:: Hash: swap_pos structure # cmp_fct:: Ruby-Function: Function to compare elements in ref and to_swap. # # == Return # None def Discover.get_fixed_positions(ref, to_swap, swap_pos, cmp_fct = nil) if not cmp_fct cmp_fct = lambda {|a, b| a == b} end ref.each_with_index do |ele, idx| if cmp_fct.call(to_swap[idx], ele) swap_pos[idx][:alt] = [] remove_alt_pos(idx, swap_pos) end end end # Process direct swaps. # Direct swaps are: # a x x x b # b x x x a # => # a x x x b # a x x x b # # A special case needs to be considered, where several swaps are possible: # 0 1 2 3 # ------- # a x b a # b y a b # In this case two swaps are possible: 0 <-> 2 and 2 <-> 3. Because # 2 <-> 3 are closer, this swap should be selected # # If several swaps have same distance, an arbitrary will be selected. # # Another case that needs to be dealt with is the following: # a b c d e f # d e f _ _ _ # Whereas the last three elements are "dummy" elements of the second array. # The solution is obviously to swap dummies. # # This function modifies +swap_pos+ structure. # # == Parameter # swap_pos:: Hash: swap_pos structure # # == Return # None def Discover.get_direct_swaps(swap_pos) swap_pos.each_pair do |pos, val| val[:alt].each do |idx| # Dummies can be always swapped. if swap_pos[idx][:con][:dummy] swap_elements(idx, pos, swap_pos) next end if swap_pos[idx][:alt].include?(pos) # direct swap npos = pos dist = (idx - pos).abs swap_pos[idx][:alt].each_with_index do |p, idx2| next if p == pos if swap_pos[p][:alt].include?(idx) and (p - idx).abs < dist dist = (p - idx).abs npos = p end end swap_elements(idx, npos, swap_pos) end end end end # Function to swap two elements in the +swap_pos+ structure. # Apart from the swap itself a little bit housekeeping needs to be done, # especially: # - Clean from swapped elements alternative vector. # - As the two provided swap positions are now processed, delete these two # positions from all other elements as alternative positions. # # This function modifies +swap_pos+ structure. # # == Parameter # pos1:: Int: A swap position # pos2:: Int: A swap position # swap_pos:: Hash: swap_pos structure. # This structure will be modified in this function # # == Return # None def Discover.swap_elements(pos1, pos2, swap_pos) swap_pos[pos1][:con], swap_pos[pos2][:con] = swap_pos[pos2][:con], swap_pos[pos1][:con] if not swap_pos[pos1][:con][:dummy] # Remove pos1 as alternative position of all other elements remove_alt_pos(pos1, swap_pos) end if not swap_pos[pos2][:con][:dummy] # Remove pos2 as alternative position of all other elements remove_alt_pos(pos2, swap_pos) end # Elements are processed, no further need for alternatives. swap_pos[pos1][:alt] = [] swap_pos[pos2][:alt] = [] end # After fixed positions and direct swaps have been resolved, this function # tries to find to all elements that have alternative positions the best # solution. This basically works by finding closed permutations (cycles). A # cycle is for example: # pos 0 1 2 # reference: a b c # to_align: b c a # In this case "b" can be moved from 0 to 1, "c" from 1 to 2 and "a" from 2 # to 0. Because one element "a" goes to the position of the first "b", it is # a closed permutation = cycle. # This function also resolve permutation, that are not closed, e.g. # pos 0 1 2 # reference: a b c # to_align: b c x # In this case, position 2 will have a collision. Collisions are then # resolved in another function. # # == Parameter # ref:: Array: Reference array. # to_swap:: Array: Array to align against reference array. # swap_pos:: Hash: swap_pos structure. # This structure will be modified in this function # sw:: Int: Swap window # # == Return # None def Discover.get_all_other_swaps(ref, to_swap, swap_pos, sw) # Find elements that have alternative positions pos = get_pos_with_alt_values(swap_pos) there_is_something_to_do = pos != nil while there_is_something_to_do # Do the remaining elements have a cyclic permutation? from, to, what = get_cycle(pos, swap_pos) apply_from_to_what_to_swap_pos(from, to, what, swap_pos) # Clean :alt vector of processed elements. mark_swapped_elements(from, to, swap_pos) # Check if there are elements with alternative positions. pos = get_pos_with_alt_values(swap_pos) if not pos there_is_something_to_do = false end end end # Function to resolve collisions. # A collision occurs if a position has its :col element filled in the # +swap_pos+ structure. # # This function should be called after +get_fixed_positions+ and # +get_direct_swaps+. # Depending on the resolve_strategy, collisions will be moved either to # nearest empty position or will be deleted. # # == Parameter # swap_pos:: Hash: swap_pos structure. # This structure will be modified in this function # sw:: Int: Swap window # dummy_fct:: Ruby-Function: Function to generate a dummy element # resolve_strategy:: Runy-Constant: # # == Return # None # def Discover.resolve_collisions(swap_pos, sw, dummy_fct, resolve_strategy = nil) swap_pos.each_pair do |pos, val| if val[:col].length > 0 if val[:col].length > 1 msg = "dswap::resolve_collisions, rare case, more then one collision in an element!" msg += " element: #{val}" $LOG.info(msg) end new_pos = find_closest_empty_field(pos, swap_pos, sw) if not new_pos case resolve_strategy when nil next when :delete # Delete collision by adding an empy array swap_pos[pos][:col] = [] msg = "dswap::resolve_collisions, element collision, alignment forced - " msg += " element: #{val}" $LOG.debug(msg) next when :force # Find nearest position, not considering swap window size. new_pos = find_closest_empty_field(pos, swap_pos) if (new_pos - pos).abs > sw msg = "dswap::resolve_collisions, element collision, alignment forced - " msg += " element: #{val}" $LOG.debug(msg) end # No next operation since the forced position needs to be written else next end end swap_pos[new_pos][:con] = swap_pos[pos][:col].pop if swap_pos[pos][:col] and swap_pos[pos][:col][0] == nil swap_pos[pos][:col] = [] end end end if dummy_fct # Fill all empty positions with dummies. swap_pos.each_pair do |pos, val| if not val[:con] dummy_ele = nil if dummy_fct dummy_ele = dummy_fct.call(pos) end val[:con] = {:ele => dummy_ele, :orig_pos => -1, :dummy => true} end end end end # Check if a permutation cycle exist. # A permutation cycle is: # ref: a b c d e f # to_align: b c a x x x # In this case the permutation is [1, 2, 0], meaning b at position 0 in # to_align array goes to 1, c to 2 and a to 0. Since the last element of the # permutation goes to the position of the first element of the permutation, # this is a cycle. # # One cases that needs to be considered is, if the last element of a cycle # has no alternative position. In this case two things can happen: # - The position of the first element of the cycle is within the swap window # => Move last element to position of first element. # - The position of the first element is not within the swap window size # => The element becomes a collision element, i.e. it is moved to the :col # entry of the hash. # Another function (resolve_collisions) resolves collisions. # # == Parameter # pos:: Int: At what position to start with the search for a cycle # swap_pos:: Hash: swap_pos structure. Explanation see above. # # == Return # Array: An array of arrays, containing the elements # - from: Position from where to move an elemenet # - to: To what position to move an element # - what: What to move, content # Example: # - from: [0, 1, 2] # - to: [1, 2, 0] # - what: [a, b, c] # This means move element "a" from position 0 to 1 def Discover.get_cycle(pos, swap_pos) alt_val = swap_pos[pos][:alt].first() alt_pos = get_nearest_element(alt_val, swap_pos) from = [alt_pos] to = [alt_val] what = [swap_pos[alt_pos][:con]] cycle_closed = false while not cycle_closed alt_val = swap_pos[to.last][:alt].first if not alt_val alt_pos = to.last() # found an element that has no alternative position. Thus, this is the # end of a cycle from << alt_pos to << nil what << swap_pos[alt_pos][:con] cycle_closed = true next end alt_pos = get_nearest_element(alt_val, swap_pos) from << alt_pos to << alt_val what << swap_pos[alt_pos][:con] if from.include?(alt_val) cycle_closed = true end end return [from, to, what] end # Translates a +swap_pos+ structure back to an array. # # == Parameter # swap_pos:: Hash: swap pos structure that should be translated into an array # dummy_fct:: Ruby-Function: What to use as dummy elements # # == Return # Array:: Array representation of +swap_pos+ def Discover.traslate_swap_pos_to_array(swap_pos, dummy_fct) res = Array.new(swap_pos.length) swap_pos.each_pair do |pos, val| if not val[:con] or not val[:con][:ele] res[pos] = dummy_fct.call(pos) else res[pos] = val[:con][:ele] end end return res end # This function applies the permutation that are provided in the from and to # vectors. E.g: # reference: a b c # to align: b c a # The corresponding vectors look like this: # from: 0 1 2 # to : 1 2 0 # The first column says: position 0 (b) goes to position 1 # # The function need to take two possible situation into account: a closed # and an open cycle. # The above example is a closed cycle, meaning the last element of to goes to # the first element of from: from[0] == to[to.lenght-1] # This means all elements can "permute through" # # The other case is for example # reference: a b c # to align : b c x # In this case from[0] != to[to.length-1]. In this case the first position # will be left empty and the third position will have a collision def Discover.apply_from_to_what_to_swap_pos(from, to, what, swap_pos, dummy_element = nil) from_rev = from.reverse to_rev = to.reverse what_rev = what.reverse tmp_ele = nil closed_cycle = false if to_rev[0] tmp_ele = swap_pos[from[0]][:con] closed_cycle = true else tmp_ele = swap_pos[from_rev[0]][:con] end from_rev.each_with_index do |f, idx| to_idx = to_rev[idx] next if not to_idx next if closed_cycle and idx == from_rev.length - 1 swap_pos[to_idx][:con] = swap_pos[f][:con] swap_pos[f][:con] = nil end if tmp_ele if to_rev[0] swap_pos[to[0]][:con] = tmp_ele else swap_pos[from_rev[0]][:col] << tmp_ele end end end # Remove processed elements from +swap_pos+ # This function works directly on the +swap_pos+ structure, thus, it does not # have a return value. # # == Parameter # from:: Array: not used # to:: Array: Processed position that must not be used for other elements. # # == Return # None def Discover.mark_swapped_elements(from, to, swap_pos) swap_pos.each_pair do |pos, val| val[:alt].delete_if {|idx| to.include?(idx)} end end # Delete a position from alternative vectors. # # If a position has been processed, no other element can be moved to this # position. To have a consistent +swap_pos+ structure, the processed position # needs to be removed from all elements, having this position as an # alternative. # # == Parameter # pos:: Int: Processed position, that should be removed from all elements. # swap_pos:: Hash: swap_pos structure # # == Return # None def Discover.remove_alt_pos(pos, swap_pos) swap_pos.each_pair do |p, val| val[:alt].delete(pos) end end # Find an element that has an alternative position. # # == Parameter # swap_pos:: Hash: swap_pos structure in which to search for elements with # alternative positions. # == Return # Int or nil:: Position of an element with an alternative position. # nil if no such position exisits in +swap_pos+. def Discover.get_pos_with_alt_values(swap_pos) swap_pos.each_pair do |pos, val| return pos if val[:alt].length > 0 end return nil end def Discover.get_nearest_element(pos, swap_pos, ele = nil) res = nil swap_pos.each_pair do |p, val| if val[:alt].include?(pos) if ele and not val[:con][:ele] == ele next end if not res res = p else if (p - pos).abs < (res -pos).abs res = p end end end end return res end def Discover.find_closest_empty_field(pos, swap_pos, sw = nil) l = 0 r = swap_pos.length if sw l = [0, pos - sw].max r = [swap_pos.length, pos + sw].min end res = Float::INFINITY for p in l...r do if not swap_pos[p][:con] or (swap_pos[p][:con] and swap_pos[p][:con][:dummy]) res = p if (p - pos).abs < (res - pos).abs end end if res == Float::INFINITY res = nil end return res end end <file_sep>/lib/serialiser_tools.rb require 'sqlite3' require_relative "constants" ## # = Summery # This file contains all necessary methods to serialise PDJs to strings. # The main function to serialise a PDJ is: # <tt>encode_pdj_events(PDJ, necessary_chars, encoding_map, attributes)</tt> # # The values of "necessary_chars", "encoding_map" obviously need to be # calculated before this function can be called. The information of these # variables is: # <tt>necessary_chars</tt>:: How many characters are necessary to encode all # values of all attributes of all events in a unique # way. # <tt>encoding_map</tt>:: A hash, holding for every already processed attribute # value a unique string. The first level of this hash # is the phase, e.g. Discover::TRIGGER, # Discover::CONSIDERING_STEP, ... # Example # enc_map[Discover::CONSIDERING_STEP]["jrn_goal"]["I used a search engine"] = "ca " # enc_map[Discover::CONSIDERING_STEP]["jrn_goal"]["I aked my friends"] = "cb " # # The function: <tt>get_encoding(enc_maps, event_type, attribute_name, # attribute_value, necessary_chars)</tt> # returns to a phase (= evtent_type) the name of the attribute (= "jrn_goal") # and its value (= "I used a search engine") the encoding (= "ca ", in the above # example). If the provided attribute_name and attribute_value don't have an # encoding in the enc_map structure, a new one will be computed, stored for # future queries. # # To determine the number of necessary chars the function: # <tt>get_max_nof_attr_val(db, event_tbl_name, attrs)</tt> # Parameters: # - db: SQLite3 DB connection # - event_tbl_name: Name of table that holds all events # - attrs: a hash, where the keys are phase ids, e.g. Discover::BUYING_STEP # the values are attribute names to consider. # # Since it is very likely that more attribute values are present in PDJs than # it can be expressed with one character, the # # Only used internaly def get_attr_lst_sorted(event_type) evt_typ = get_event_id(event_type) return nil if not evt_typ atr = ID_ATTRIBUTES_MAP[evt_typ].keys.sort atr end # How many different values are present in DB for the attributes in attr_lst # for the given event_type. # # == Parameter # db:: SQLite3 db connection: Connection to SQLite3 db # tbl_name:: String: Name of table holding events # event_type:: Int: Event-type id, e.g. 6 for Discover::CONSIDERING_STEP # attr_lst:: Array: Array of attribute-names. # # == Return # Int:: Number of different attribute values for all attributes in attr_lst, # for the provided event_type. def get_max_evt_attr_val(db, tbl_nme, event_type, attr_lst) res = 0 attr_lst.each do |a| sql_stmt = "SELECT COUNT(DISTINCT(#{a})) FROM #{tbl_nme}" sql_stmt += " WHERE dat_object_type = #{event_type};" row = Integer(db.get_first_value(sql_stmt)) res = res + row end res end # How many different values are present in DB for the attributes attrs. # == Parameter # db:: SQLite3 db connection: Connection to SQLite3 db # tbl_name:: String: Name of table holding events # attrs:: Hash: Keys: event-types, values: array of attribute-names # # == Return # Int:: Maximum over different attribute values in different event-types. def get_max_nof_attr_val(db, tbl_nme, attrs) max = 0 attrs.each_pair do |event_id, attributes| next if not event_id next if not attributes or attributes.length == 0 max = [get_max_evt_attr_val(db, tbl_nme, event_id, attributes), max].max end max end # Computes how man small case letters are necessary to encode max_attr_val # different values. # == Parameter # max_attr_val:: Int:: How many values need to be encoded # == Return # Int:: That many small case characters are necessary to encode max_attr_val # differnet values def get_nof_nec_chars(max_attr_val) return [(Math.log(max_attr_val, 26 - ["t", "c", "r", "b", "p", "d"].length)).ceil, 1].max end # Every phase gets a one character prefix. # Note: This has been only introduced to allow a human to "decode" an encoded # PDJ. The following prefixes are not necessary for the program to work # correctly. # == Parameter: # evt_type:: int:: For what phase to return a prefix # == Return: # Char:: For every phase a prefix. # nil, for an unknown phase. def get_event_prefix(evt_typ) case evt_typ when Discover::TRIGGER return "t" when Discover::CONSIDERING_STEP return "c" when Discover::READY_TO_PURCHASE return "r" when Discover::BUYING_STEP return "b" when Discover::PURCHASE return "p" else msg = "get_event_prefix, unknown event tpye: #{evt_typ}" $LOG.error msg if $LOG return nil end end # Returns for a phase-attribute_name-attribute_value a new, unique string. # == Parameter: # enc_maps:: Int: # evt_type:: Int: Phase id, e.g. Discover::CONSIDERING_STEP) # attr_nme:: String: Name of the attribute, e.g. "jrn_goal" # attr_val:: String: Value of attribute, e.g. "I used a search engine" # nec_chars:: Int: How many characters to use for encoding the new # attr_nme, attr_val pair. # == Return # Char:: A new unique string for the provided attr_nme and attr_val pair, # with nec_chars characters. def get_new_encoding(enc_maps, evt_typ, attr_nme, attr_val, nec_chars) if not enc_maps[evt_typ][attr_nme] enc_maps[evt_typ][attr_nme] = {} end enc_map = enc_maps[evt_typ][attr_nme] init_val = "" if enc_map.has_key?(attr_val) return enc_map[attr_val] else if enc_map.empty? if attr_val and attr_val.size > 0 init_val = enc_maps[evt_typ][:max_type_value] ret = enc_maps[evt_typ][:max_type_value].succ() enc_maps[evt_typ][:max_type_value] = ret else nec_chars.times { init_val += " " } end #ret = get_event_prefix(evt_typ) + enc_maps[evt_typ][:max_type_value] ret = get_event_prefix(evt_typ) + init_val else ret = enc_maps[evt_typ][:max_type_value] val = enc_maps[evt_typ][:max_type_value].succ() enc_maps[evt_typ][:max_type_value] = val ret = get_event_prefix(evt_typ) + ret end end if ret.size > nec_chars + 1 ret = ret[0..nec_chars] end enc_map[attr_val] = ret ret end # Returns for an event_phase, attribute_name, attribute_value triple an unique # encoding. If an encoding doesn't exist for the triple, a new one will be # calculated and returned. # # == Parameter # enc_maps:: Hash: An hash of hashes. # The first level keys are event types, encoded as numerical # values (6 = Discover::CONSIDERING_STEP, ...). # The second level keys are attribute names and the third # level are attribute values. The third level values are # encodings for third level attribute values. # evt_typ:: Int: Event type id, e.g. 6 (= Discover::CONSIDERING_STEP) # attr_nme:: String: Name of the attribute, e.g. "jrn_goal" # attr_val:: String: Value of the attribute, e.g. "I used a search engine" # nec_chars:: Int: How many chars are necessary to encode all occurring # attribute_name, attribute_value pairs for an event type. # == Return # string:: A unique string encoding the event_phase, attribute_name, # attribute_value triple # # == Example for Encoding Map (enc_map) # enc_maps[Discover::CONSIDERING_STEP]["motivations"]["I needed a new car"] = "ca " # This means, for the event type CONSIDERING_STEP (== 6) the attribute with the # name "motivations" and its manifestation "I needed a new car" has the # # serialisation string "ca ". def get_encoding(enc_maps, evt_typ, attr_nme, attr_val, nec_chars) if enc_maps.empty? enc_maps[evt_typ] = {} end if attr_val == :dummy if not enc_maps[:dummy] dummy_str = "d" nec_chars.times {dummy_str += "_"} enc_maps[:dummy] = dummy_str end return enc_maps[:dummy] end if not enc_maps[evt_typ] enc_maps[evt_typ] ={} end if not enc_maps[evt_typ][attr_nme] enc_maps[evt_typ][attr_nme] ={} end if not enc_maps[evt_typ][attr_nme][attr_val] get_new_encoding(enc_maps, evt_typ, attr_nme, attr_val, nec_chars) end enc_maps[evt_typ][attr_nme][attr_val] end # Encode an event of a PDJ as string. # == Parameter # event:: PdjEvent: The event to encode # nec_chars:: Int: How many characters are necessary to encode all occurring # <event-type, attribute_name, attribute_value> with a unique # string # NOTE: This structure can be modified during this function, # by adding an encoding to not yet encoded <type, name, # value> triple. # enc_map:: Hash: A mapping of all already encoded events. # attrs:: Hash: Holding to every event_type the attribute names that need # to be encoded. # # == Return # string:: A string of nec_chars characters, encoding the all attributes in the provided # PdjEvent. def encode_event(event, nec_chars, enc_maps, attrs) res = "" evt_typ = event.type #ID_ATTRIBUTES_MAP[evt_typ].each do |k, v| a = attrs[evt_typ].sort a.each do |k, v| atr_nme = k atr_val = event.attributes[k] if event.is_dummy?() atr_val = :dummy end if event.surrogate atr_val = event.surrogate.attributes[k] end res += get_encoding(enc_maps, evt_typ, atr_nme, atr_val, nec_chars) end res end def extract_pdj_string(enc_maps) res = "" Discover::EVENT_TYPE_ARRAY.each do |t| next if not enc_maps[t] #ID_ATTRIBUTES_MAP[t].each do |an, at| # next if not enc_maps[t][an] # enc_maps[t][an].each do |k2, val| # res += val # end #end end res end # Function to encode a PDJ as one string. # In contrast to encode_pdj_events, this function returns one string, # representing the whole provided PDJ. The function encode_pdj_events returns a # hash with phases as keys and values the string encoding of the phase. # # == Parameter # pdj:: Pdj: The PDJ to encode # nec_chars:: Int: How many characters are necessary to encode all attributes # in a unique way # enc_map:: Hash: Encoding map, storing to all occurring distinct event-type, # attribute_name, attribute_value triple a unique encoding. # attrs:: Hash: Key: event-type-id, value: Array of attributes to encode for # the event-type # # == Return # string:: String representation of the whole PDJ (event). def encode_pdj(pdj, nec_chars, enc_maps, attrs) if not pdj $LOG.error("encode_pdj: no pdj to encod!") if $LOG end #types = [] #if pdj.static_segment.substitutes > 0 # types = pdj.surrogates #else # types = pdj.types #end res = "" pdj.types.each do |t| next if not t or t.length == 0 t.each do |e| if e.is_dummy?() puts e end res += encode_event(e, nec_chars, enc_maps, attrs) end end res end # Function to encode a PDJ as hash of encoded journey parts. # In contrast to encode_pdj, this function returns a hash. The keys of the hash # are event_types ids, e.g. 6 (=Discover::CONSIDERING_STEP). The values are # strings, that encode the corresponding event-type in the provided PDJ. # # == Parameter # pdj:: Pdj: The PDJ to encode # nec_chars:: Int: How many characters are necessary to encode all attributes # in a unique way # enc_map:: Hash: Encoding map, storing to all occurring distinct event-type, # attribute_name, attribute_value triple a unique encoding. # attrs:: Hash: Key: event-type-id, value: Array of attributes to encode for # the event-type (taken from config file) # == Return # String:: String representation of the whole PDJ (event). def encode_pdj_events(pdj, nec_chars, enc_maps, attrs) if not pdj $LOG.error("encode_pdj_event_eventss: no pdj to encod!") if $LOG end # Initialise return value # Each phase is encoded individually, initialised with an empty string res = {} Discover::EVENT_TYPE_ARRAY.each do |ev| res[ev] = "" end #types = [] #if pdj.static_segment.substitutes > 0 # types = pdj.surrogates #else # types = pdj.types #end # Iterate through the PDJ by phase, the phase is identified by type pdj.types.each do |t| next if not t or t.length == 0 t.each do |e| res[e.type] += encode_event(e, nec_chars, enc_maps, attrs) end end res end # Returns the initialzied enc_map structure, needed by all functions that compute PDJ # serialisation. # The resulting hash has following structure: # * enc_maps[event_type]: The key for the highest level is the event-type id: # * enc_maps[event_type][:max_type_value]: The resulting value holds the up to # this point "maximum" encoding # string. Since we use lower case # characters, it initial value is an # "a" plus spaces to fill up # nec_chars. # Note: This function only generates the structure, IT DOES NOT FILL THE # STRUCTURE. # The structure is filled "on the fly" every time, a not yet encoded # <event-type, attribute-name, attribute-value> triple appears, an encoding for # it will be computed and added at the corresponding place in this structure. # == Parameter # nec_chars:: Int: how many characters are necessary to encode all <event-type, # attribute_name, attribute-value> triples. # # == Return # Hash:: The resulting hash has following structure: # def get_encoding_map(nec_chars) # Generate "white space" used to fill the current encoding to the # necessary length spaces = "" enc_maps = {} (nec_chars-1).times { spaces += " " } #Discover::EVENT_TYPE_ARRAY.each do |t| # For each ID of the different phases, ininitalize the max encoding # used Discover::JOURNEY_EVENT_ORDER.each do |t| enc_maps[t] = {} enc_maps[t][:max_type_value] = "a" + spaces end enc_maps end # Function to encode a set journeys, stored in an array of journeys. # # == Parameter # segment:: Array: Array of journeys to serialise # nec_char: Int:: How many characters to use to encode one attribute of an # event # # == Return # Hash:: Key: user_id, value: encoded PDJ of the user def serialise_segment(segment, nec_chars, attrs) res = {} enc_maps = segment.enc_map spaces = "" segment.each do |j| res[j.user_id] = encode_pdj_events(j, nec_chars, enc_maps, attrs) end res end <file_sep>/lib/ai4r/cluster.rb #!/usr/bin/env ruby # Welche Sachen werden required? require_relative './ai4r' require_relative './single_linkage' require_relative './data_set' require_relative './proximity' include Ai4r::Clusterers include Ai4r::Data data = ["ta sa sb sc ra pa ", "ta sg sh si sa sb sc ra pa "] puts Proximity.block_distance(data[0], data[1]) =begin clusterer = Ai4r::Clusterers::SingleLinkage.new clusterer.build(DataSet.new(:data_items => data), 5) puts "*** data:" p clusterer.data_set puts puts "*** Clusters:" p clusterer.clusters puts puts "*** Cluster indices:" p clusterer.index_clusters puts puts "Hallo belongs to cluster: #{clusterer.clusters[clusterer.eval("Hallo")].data_items}" puts "Juri belongs to cluster: #{clusterer.clusters[clusterer.eval("Juri")].data_items}" puts "Juli belongs to cluster: #{clusterer.clusters[clusterer.eval("Juli")].data_items}" puts "Tobias belongs to cluster: #{clusterer.clusters[clusterer.eval("Tobias")].data_items}" puts "Tobi belongs to cluster: #{clusterer.clusters[clusterer.eval("Tobi")].data_items}" =end <file_sep>/lib/ai4r/ai4r.rb # Data require_relative 'data_set' require_relative 'statistics' require_relative 'proximity' require_relative 'parameterizable' # Clusterers require_relative 'clusterer' require_relative 'single_linkage' require_relative 'complete_linkage' #require_relative "average_linkage" <file_sep>/lib/pdj_map_step.rb require './Step.rb' class PdjMapStep < Step attr_accessor :bpmStep, :chunkIid, :nxt, :is_next_transition_virtual, :prv, :is_prev_transition_virtual def initialize @bpmStep = nil @chunkId = nil @nxt = nil @is_next_transition_virtual = nil @prv = nil @is_prev_transition_virtual = nil end def initialize(bpmStep, chunkId, nxt, is_next_transition_virtual, prv, is_prev_transition_virtual) @bpmStep = bpmStep @chunkId = chunkId @nxt = nxt @is_next_transition_virtual = is_next_transition_virtual @prv = prv @is_prev_transition_virtual = is_prev_transition_virtual end def get_avg_payload_values end end <file_sep>/lib/chunk.rb def chunk(bpm, attrs, sim = 0.8, pos_type = 'min', radius = 2, chunk_level = 'single', chunk_crit = 'both') # attrs: which attributes should be compared? # sim: similarity threshold in percent (propotion of identical attributes) # pos_type('min', 'max'): which phase pos should be used, if several exist # radius: max number of edges that could be chunked into the same section # chunk_level: new node must be similar to all ('complete') or only one # ('single') other in the chunk he wants to belong to # chunk_crit = should only be the similary threshold be fulfilled ('sim', # or additionally the position ('both') return if not bpm return if not attrs # If no attributes were provided for chunking, return, start at = false attrs.each_pair do |k, v| if v.length > 0 at = true end end return if not at # If no attributes were provided for chunking, return, end # calc phase_pos bpm.calc_phase_pos() # create hash to get right index for every node # key = node_id # value = number of row (col) in adj_mtx and dst_mtx idx = Hash.new i = 0 bpm.node_arry.each do |node| idx[node.id] = i i += 1 end # get undirected dst_mtx for bpm directed = false weighted = false dst_mtx = Discover.calc_dist_mtx(bpm.calc_adj_mtx(directed, weighted)) # initialize hash to save results chunks = Hash.new() chunk_tmp = 1 if not bpm.node_arry or bpm.node_arry.length < 1 $LOG.warn "chunk, no nodes to chunk. Returning empty set" return chunks end # first node in first chunk chunks[chunk_tmp] = [bpm.node_arry[0].id] chunk_hits = Hash.new() # loop for all other nodes bpm.node_arry.drop(1).each do |node| #puts "START LOOP OVER NODES: node_id = #{node.id}" chunk_hit = 1 # tmp variable to save possible chunks and similarity values chunk_hits[node.id] = Hash.new() # check if node could be added to existing chunks chunks.each_pair do |chunk, ids_in_chunk| chunk_hits[node.id][chunk] = Hash.new() ids_in_chunk.each do |id| node_to_compare = bpm.node_arry.find {|x| x.id == id} # different events could not be in the same chunk next if node.type != node_to_compare.type # check 'vertikal' radius if pos_type == 'min' r = (node.phase_pos.min - node_to_compare.phase_pos.min).abs elsif pos_type == 'max' r = (node.phase_pos.max - node_to_compare.phase_pos.max).abs else $LOG.error "PdjMap::chunk pos_type #{pos_type} unknown" if $LOG end if r > radius and chunk_crit == 'both' break if chunk_level == 'complete' next end # check 'horizontal' radius row = idx.values_at(node.id)[0] col = idx.values_at(node_to_compare.id)[0] if dst_mtx[row][col] > radius and chunk_crit == 'both' break if chunk_level == 'complete' next end # check similarity sim_val = calc_node_sim(node, node_to_compare, attrs) if sim_val < sim if chunk_level == 'complete' chunk_hits[node.id][chunk] = Hash.new() break end next else chunk_hits[node.id][chunk][id] = sim_val end end end # get chunk with max similarity value, if exists sim_max = 0 best_chunk = nil chunk_hits[node.id].each_pair do |chnk, sim_node| next if sim_node.empty? sim_node.each_pair do |sim_node_id, sim_val| if sim_val > sim_max sim_max = sim_val best_chunk = chnk end end end if not best_chunk # Create new chunk chunks[chunks.length + 1] = [node.id] else # Add node to its chunk chunks[best_chunk] << node.id end end chunk_nr = 1 chunks.each_pair do |chunk_id, nodes| if nodes.length > 1 nodes.each do |nd| bpm.node_arry[nd].chunk_id = chunk_nr end chunk_nr += 1 end end chunks end def calc_node_sim(node_1, node_2, attrs = nil) # generate initial hash with all neceassary attrs node_name_1 = 'node1' node_name_2 = 'node2' node_attrs = Hash.new() evt = node_1.type attrs[evt].each do |attr| node_attrs[attr] = Hash.new() end # add counts of attribute manifestations for each node node_attrs = cnt_attr_values(node_1, node_attrs, node_name_1, node_name_2) node_attrs = cnt_attr_values(node_2, node_attrs, node_name_2, node_name_1) # get absolute numbers of attribute manifestations node_1_sum = 0 node_2_sum = 0 node_attrs.each_key do |attr| node_attrs[attr].each_key do |attr_value| node_1_sum += node_attrs[attr][attr_value][node_name_1] node_2_sum += node_attrs[attr][attr_value][node_name_2] end end # overwrite with percentage values node_attrs.each_key do |attr| node_attrs[attr].each_key do |attr_value| node_attrs[attr][attr_value][node_name_1] = node_attrs[attr][attr_value][node_name_1].to_f/node_1_sum node_attrs[attr][attr_value][node_name_2] = node_attrs[attr][attr_value][node_name_2].to_f/node_2_sum end end # calc differences between values and get average node_attrs.each_key do |attr| node_attrs[attr].each_key do |attr_value| delta = (node_attrs[attr][attr_value][node_name_1] - node_attrs[attr][attr_value][node_name_2]).abs node_attrs[attr][attr_value] = delta end end # get average of deltas for every single attribute node_attrs.each_key do |attr| sum = node_attrs[attr].values.inject{|a, b| a + b} cnt = node_attrs[attr].values.length if cnt == 0 node_attrs[attr] = 0 else node_attrs[attr] = sum/cnt end end sum = node_attrs.values.inject{|sum, attr| sum + attr}.to_f avg = sum / node_attrs.values.length 1 - avg end def cnt_attr_values(node, node_attrs, node_name_1, node_name_2) node.pdj_events.each do |event| event.attributes.each_pair do |attr, attr_value| # counting manifestations # remark: empty attr_value variables are counted as a # "normal" manifestations of the attribute next if not node_attrs[attr] if not node_attrs[attr][attr_value] node_attrs[attr][attr_value] = Hash.new() node_attrs[attr][attr_value][node_name_1] = 1 node_attrs[attr][attr_value][node_name_2] = 0 else node_attrs[attr][attr_value][node_name_1] += 1 end end end node_attrs end <file_sep>/lib/tools.rb require 'tsort' require 'sqlite3' require_relative 'mtx' require_relative 'chunk' class Hash include TSort alias tsort_each_node each_key def tsort_each_child(node, &block) fetch(node).each(&block) end end class Array def powerset return to_enum(:powerset) unless block_given? 1.upto(self.size) do |n| self.combination(n).each{|i| yield i} end end def includes_all?(oth_arry) oth_arry.each do |i| return false if not self.include?(i) end return true end end module Discover def initialize_logger(options = nil) if (options == nil) $LOG = nil $LOG = Logger.new(STDOUT, 'daily') $LOG.formatter = proc do |severity, datetime, progname, msg| if severity.length == 4 severity = severity + " " end "#{severity} [#{datetime.strftime("%Y-%m-%d %H:%M:%S")}] #{msg}\n" end else # Here the logger must exist, the code does not work if options are # passed without having a $LOG initialized $LOG.level = Logger::INFO if options[:l] case options[:l].downcase when "debug" $LOG.level = Logger::DEBUG when "info" $LOG.level = Logger::INFO when "warn" $LOG.level = Logger::WARN when "error" $LOG.level = Logger::ERROR end end end end def Discover.check_if_column_exist(db, tbl_name, col_name) begin qry = "SELECT * FROM #{tbl_name} LIMIT 1" pst = db.prepare(qry) return pst.columns.include?(col_name) rescue SQLite3::Exception => e return false end return true end def Discover.tbl_exists?(db, tbl_name) qry = "SELECT name " qry += "FROM sqlite_master " qry += "WHERE type='table' AND name='#{tbl_name}'" begin db.execute(qry) do |row| return row['name'] == tbl_name end rescue SQLite3::Exception => e return false end return false end def Discover.check_if_all_attributes_are_present_in_db(db, tbl_name, attrs) res = Array.new() attrs.each do |col_name| if not check_if_column_exist(db, tbl_name, col_name) res << col_name end end res end def Discover.calc_dist_mtx(adj_mtx) # calc shortest distances #dist_mtx = (Matrix.rows(adj_mtx)).dcpy() dist_mtx = adj_mtx.dcpy() #nof_cols = adj_mtx.length for k in 0..(dist_mtx.nof_cols - 1) do for i in 0..(dist_mtx.nof_cols - 1) do for j in 0..(dist_mtx.nof_cols - 1) do e = dist_mtx[i][j] d_1 = dist_mtx[i][k] d_2 = dist_mtx[k][j] d_check = d_1 + d_2 if (d_1 == 0 or d_2 == 0) d_min = e elsif e == 0 d_min = d_check else d_min = [e, d_check].min end dist_mtx.set(i, j, d_min) end end end dist_mtx end def Discover.bpm_to_array(bpm) return nil if not bpm res = Hash.new() bpm.node_arry.each do |n| res[n.id] = (n.nxt.map {|x| x.id}).sort end res end def Discover.bpm_topological_sort(bpm) return nil if not bpm arry = bpm_to_array(bpm) ts = arry.tsort.reverse! ts end def Discover.check_nonsig_threshold(bpm, node_ids, nonsignificant, milestones = false) jrnys = bpm.segment.length.to_f return node_ids if nonsignificant <= 0 bpm.node_arry.each do |n| next if Discover.milestone?(n.type) and not milestones nid = n.id if nonsignificant and nonsignificant > 0 and node_ids.include?(nid) if n.get_frequency() <= nonsignificant if $LOG and $LOG.debug?() msg = "tools::check_nonsig_threshold, removing node " msg += "#{nid} because frequency is below #{nonsignificant}" $LOG.debug(msg) end node_ids.delete(nid) end end end node_ids end def Discover.check_sig_threshold(bpm, node_ids, significant, milestones = false) return node_ids if significant <= 0 jrnys = bpm.segment.length.to_f bpm.node_arry.each do |n| next if Discover.milestone?(n.type) and not milestones nid = n.id if significant and significant > 0 and not node_ids.include?(nid) if n.get_frequency() >= significant if $LOG and $LOG.debug?() msg = "tools::check_sig_threshold, adding node " msg += "#{nid} because frequency is above #{significant}" $LOG.debug(msg) end node_ids << nid end end end node_ids end # Function to compute a bpm on basis of a set of node-ids and a reference # bpm. # The main idea behind the build_pdjm function is to remove iteratively nodes # from the original bpm until only the nodes remain that should be part of # the final bpm. # If a bpm-node should be removed, it needs to be checked what predecessor # and successor need to be connected via an edge. # # !!!! IMPORTANT !!!! # THE INPUT BPM WILL BE MODIFIED # !!!! IMPORTANT !!!! # # == Parameter # bpm: original bpm. On basis of the connection of this bpm a new bpm will be # generated. # THIS BPM WILL BE MODIFIED IN THIS FUNCTION. # node_ids: Node ids of nodes that should be in the resulting bpm. # Note: If there is no path between two nodes in this array in the # original bpm they will not be connected in the resulting bpm. # op_nds: A set of optional nodes that will be added to the resulting bpm # if they can be connected. # This can be used to provide milestone. # direct_connections_between_milestones: If this is set to true, the # resulting bpm can have direct connections between milestones, i.e. # without an intermediate step. # # == Return # None def Discover.build_pdjm(bpm, node_ids, op_nds = [], direct_connections_between_milestones = true) return nil if not bpm return nil if not node_ids or node_ids.length < 1 # if significant and non-significant thresholds have been set, filter first # the node set. if bpm.nonsignificant >= 0 or bpm.significant >= 0 node_ids = check_nonsig_threshold(bpm, node_ids, bpm.nonsignificant) op_nds = check_sig_threshold(bpm, op_nds, bpm.significant) end # One array for all nodes that should be part of result nodes_in = node_ids.clone.concat(op_nds) nodes_in.uniq!() # Add all milestones to the nodes that should be part of the result bpm.node_arry.each do |n| next if not Discover.milestone?(n.type) if not nodes_in.include?(n.id) nodes_in << n.id end end # For the build up algorithm we need the nodes that should not be part of # the BPM, rather than the nodes that should be part. nodes_to_remove = [] bpm.node_arry.each do |n| next if nodes_in.include?(n.id) nodes_to_remove << n end # Here happens the magic. # Iterate over all nodes that must not be part of the resulting BPM. nodes_to_remove.each do |n| # The remove_node method of the BPM class takes care of the prv and nxt # pointer of every node that is adjacent to the one that will be removed. bpm.remove_node(n) end # Remove all nodes that have no previous and next elements, i.e. they are # not connected in the bpm nodes_to_delete = [] bpm.node_arry.each do |n| if n.prv and n.prv.length == 0 and n.nxt and n.nxt.length == 0 nodes_to_delete << n end end nodes_to_delete.each do |n| bpm.remove_node(n) end if not direct_connections_between_milestones bpm.node_arry.each do |n| next if Discover.step?(n.type) n.nxt.delete_if {|nx| Discover.milestone?(nx.type) } n.prv.delete_if {|np| Discover.milestone?(np.type) } end end # Check if all events are present in the result, start trg_nds = get_events(bpm, Discover::TRIGGER) cns_nds = get_events(bpm, Discover::CONSIDERING_STEP) rtp_nds = get_events(bpm, Discover::READY_TO_PURCHASE) byn_nds = get_events(bpm, Discover::BUYING_STEP) prc_nds = get_events(bpm, Discover::PURCHASE) msg = "tools::build_pdjm, " if trg_nds.length < 1 and $LOG and $LOG.warn? tp = msg + "no trigger milestone in result set" $LOG.error(tp) end if cns_nds.length < 1 and $LOG and $LOG.warn? tp = msg + "no considering steps in result set" $LOG.warn(tp) end if rtp_nds.length < 1 and $LOG and $LOG.warn? tp = msg + "no ready-to-purchse milestone in result set" $LOG.warn(tp) end if byn_nds.length < 1 and $LOG and $LOG.warn? tp = msg + "no buying steps in result set" $LOG.warn(tp) end if prc_nds.length < 1 and $LOG and $LOG.warn? tp = msg + "no purchse milestone in result set" $LOG.error(tp) end # Check if all events are present in the result, end bpm end def Discover.get_most_frequent_trigger_nodes(res_bpm, bpm, n) return nil if not bpm return nil if not bpm.segment trgs = Array.new trg_ids = Array.new jrnys = bpm.segment.length.to_f res_bpm.node_arry.each do |nd| trgs << bpm.node_arry[nd.id].start_milestones end trgs.flatten! trgs.uniq! if trgs.length < 1 return nil end if not trgs[0] return nil end trgs.delete_if { |x| x.type != Discover::TRIGGER } # check if triggers are connected to nodes, start trgs_connected = false if not bpm.dst_mtx bpm.dst_mtx = calc_dist_mtx(bpm.calc_adj_mtx) end trgs.each do |t| res_bpm.node_arry.each do |b| if bpm.dst_mtx[t.id][b.id] > 0 trgs_connected = true end end end if not trgs_connected $LOG.warn "tools::get_most_frequent_trigger_nodes, all found triggers are not connected to any node in resulting PDJ-Map" end # check if triggers are connected to nodes, end trgs_wth_frq = Array.new trgs.each do |trg| trg_frq = Array.new(2) trg_frq[0] = trg.pdj_events.length.to_f / jrnys trg_frq[1] = trg trgs_wth_frq << trg_frq end trgs_wth_frq.compact! trgs_wth_frq.sort! { |x, y| y[0] <=> x[0]} #trgs_wth_frq.reverse! trgs_wth_frq.map! { |x| x[1] } res = Array.new trgs_wth_frq.each do |trg| ntrg = trg.cpy ntrg.nxt = Array.new ntrg.prv = Array.new ntrg.start_milestones = Array.new ntrg.end_milestones = Array.new res << ntrg end if res.length < n return res else return res[0...n] end end def Discover.get_milestone(res_bpm, bpm, typ) res = bpm.node_arry.select {|x| x.type == typ} ms_connected = false if not bpm.dst_mtx bpm.dst_mtx = calc_dist_mtx(bpm.calc_adj_mtx) end res_node = nil dst = Array.new(2) min = Float::INFINITY res.each do |ms| res_bpm.node_arry.each do |b| dst[0] = bpm.dst_mtx[ms.id][b.id] dst[1] = bpm.dst_mtx[b.id][ms.id] dst.each do |d| if d > 0 and d < min ms_connected = true res_node = ms min = d end end end end if not ms_connected if $LOG and $LOG.warn? msg = "tools::get_milestone, all found milestones are not connected to " msg += "any node in resulting PDJ-Map" $LOG.warn msg end return nil end res_node = res_node.cpy res_node.nxt = Array.new res_node.prv = Array.new res_node.start_milestones = Array.new res_node.end_milestones = Array.new res_node end def Discover.get_min_idx_frm_dst_mtx(bpm, row, dst_mtx, ar, forward, all_shortest) min = Float::INFINITY #res_idx = Array.new res_idx = nil ary = nil #next if milestone?(bpm.node_arry[row].type) and milestone?(bpm.node_arry[i].type) if forward ary = dst_mtx[row] else ary = dst_mtx.get_col(row) end res_idx = ary.clone res_idx.each_with_index do |e, idx| if e == 0 or not ar.include?(idx) or idx == row res_idx[idx] = Float::INFINITY end end if res_idx.all? {|e| e == Float::INFINITY} $LOG.warn "tools::get_min_dst_frm_dst_mtx, found no min distance!" if $LOG return [] end res_idx = res_idx.each_with_index.find_all {|a, i| a == res_idx.min}.map{ |a, b| b } res_idx = res_idx & ar if not all_shortest res_idx.uniq! end if min == 0 $LOG.warn "tools::get_min_dst_frm_dst_mtx, found no min distance!" if $LOG end res_idx end def get_node_id_array(bpm) res = Array.new bpm.node_arry.each do |n| res << n.id end res end def get_trigger(bpm, node_arry) res = Array.new node_arry.each do |n| if bpm.node_arry[n].type == Discover::TRIGGER res << bpm.node_arry[n] end end end def Discover.align_array(ref, to_align) res = Array.new ref.each do |r| if to_align.include?(r) res << r end end res end def Discover.get_events(bpm, typ) res = Array.new bpm.node_arry.each do |n| if n.type == typ res << n end end res end def Discover.common_user_ids?(node1, node2) uids1 = get_user_ids_for_node(node1) uids2 = get_user_ids_for_node(node2) return (uids1 & uids2).length > 0 end def calc_attrs_cnt(node_arry) attrs_cnt = Hash.new node_arry.each do |node| node.calc_attrs_cnt() if not node.attrs_cnt node.attrs_cnt.each_pair do |type, attr| attr.each_pair do |attr_tmp, attr_value| attrs_cnt[type] = Hash.new() if not attrs_cnt[type] attrs_cnt[type][attr_tmp] = Hash.new() if not attrs_cnt[type][attr_tmp] attr_value.each_pair do |attr_value_tmp, cnt| if not attrs_cnt[type][attr_tmp][attr_value_tmp] attrs_cnt[type][attr_tmp][attr_value_tmp] = cnt else attrs_cnt[type][attr_tmp][attr_value_tmp] += cnt end end end end end attrs_cnt end def chunk(bpm, attrs, sim, pos_type, radius, chunk_level, chunk_crit) calc_chunks(bpm, attrs, :im, pos_typ, radius, chunk_level, chunk_crit) end def Discover.get_user_ids_for_node(node) # node must be an element of node_arry u_ids = Array.new node.pdj_events.each do |pdje| u_ids << pdje.pdj.user_id end return u_ids end def Discover.nof_jrnys_btw_nodes(node_arry, id_node_1, id_node_2, direct_connection = false, ignore_milestones = false, ignore_ids = []) node_1 = node_arry[id_node_1] node_2 = node_arry[id_node_2] u_ids_node_1 = get_user_ids_for_node(node_1) u_ids_node_2 = get_user_ids_for_node(node_2) possible_linked_u_ids = u_ids_node_1 & u_ids_node_2 cnt = possible_linked_u_ids.length # nothing to do if no common user_ids return 0 if cnt == 0 # nothing to do if one of the ids should be ignored return 0 if (ignore_ids.include?(id_node_1) or ignore_ids.include?(id_node_2)) # check if nodes are equal if id_node_1 == id_node_2 if Discover.milestone?(node_1.type) and ignore_milestones return 0 else return cnt end end # initializing a hash for checking positions per user in nodes # {user_id => [position_in_node_1, position_in_node_2], ...} direction_check = Hash.new node_1.pdj_events.each do |pdje| tmp_uid = pdje.pdj.user_id next if not possible_linked_u_ids.include?(tmp_uid) direction_check[tmp_uid] = [pdje.position.to_i] end node_2.pdj_events.each do |pdje| tmp_uid = pdje.pdj.user_id next if not possible_linked_u_ids.include?(tmp_uid) direction_check[tmp_uid] << pdje.position.to_i end # counting journeys, that are NOT including a higher position in node_2 cnt_wrong_direction = 0 possible_linked_u_ids.each do |u_id| if direction_check[u_id][0] >= direction_check[u_id][1] cnt_wrong_direction += 1 end end # check if there are journeys with 'wrong direction' if cnt_wrong_direction > 0 # additional check to ensure, that the direction is the same for all user # in both nodes if cnt_wrong_direction != possible_linked_u_ids.length msg = "tools::nof_jrnys_btw_nodes, CONSISTENCY CHECK: direction check " msg += "failed, unsymmetric user flow between nodes" $LOG.warn msg end # nothing to do if direction is 'wrong' return 0 end # not needed CASE will not be implemented # (ignore ids, but not searching a 'direct connection') if not direct_connection and ignore_ids.length != 0 msg = "tools::nof_jrnys_btw_nodes, argument selection not implemented" $LOG.error msg exit(1) end # CASE 1: we are only interested in the existence of any connection if not direct_connection and not ignore_milestones return cnt end # CASE 2: # the milestones must be ignored and we are not looking for direct # connections (detours are allowed) if not direct_connection and ignore_milestones if (Discover.milestone?(node_1.type) or Discover.milestone?(node_2.type)) return 0 else return cnt end end # CASE 3 & 4: only direct connections (milestone check implicit) # we have to check for detours of user_ids # => which user_ids are in 'other next nodes' of node_1 # AND in 'other previous nodes' of node_2 if direct_connection if (ignore_milestones and (Discover.milestone?(node_1.type) or Discover.milestone?(node_2.type))) return 0 end node_1.nxt.each do |other_nxts| next if other_nxts == node_2 u_ids_in_other_nxt = get_user_ids_for_node(other_nxts) if (possible_linked_u_ids & u_ids_in_other_nxt).length > 0 node_2.prv.each do |other_prvs_of_node_2| next if other_prvs_of_node_2 == node_1 if Discover.milestone?(other_nxts.type) and ignore_milestones next if other_nxts == other_prvs_of_node_2 end # nothing to do if id should be ignored #next if ignore_ids.include?(other_nxts.id) next if ignore_ids.include?(other_prvs_of_node_2.id) u_ids_in_other_prvs = get_user_ids_for_node(other_prvs_of_node_2) u_ids_on_detoures = possible_linked_u_ids & u_ids_in_other_nxt & u_ids_in_other_prvs if u_ids_on_detoures.length > 0 possible_linked_u_ids.delete_if { |x| u_ids_on_detoures.include?(x) } #cnt = cnt - u_ids_on_detoures.length #cnt = 0 if cnt < 0 end end end end return possible_linked_u_ids.length #return cnt end end end <file_sep>/lib/swap.rb # Function to align elements of two vectors in window of a certain size. # The function basically works by making a deep copy of the shorter of the two # provided vectors and rearranging elements in this copy, so that a maximal # alignment will be achieved. # Note: # - The alignment works only on the first n elements, where n is the length # of the shorter of the two provided arrays" # - The result depends on the window size! # For example: # v1 = [1, 2, 3, 4, 5, 6, 7] # v2 = [3, 4, 2, 1] # The function called with window size 2: # res = [3, 2, 1, 4] # The function called with window size 3: # res = [4, 2, 3, 1] # The function called with window size 4: # res = [1, 2, 3, 4] # # v1:: First vector # v2:: Second vector # ws:: Window size # Result:: A new vector with it's elements permutated so that v1 and v2 have maximal alignment. # The size will be [v1.lenght, v2.length].min def swap(v1, v2, ws) vt = nil vl = nil if (v1.length >= v2.length) vt = v2.dup vl = v1 else vt = v1.dup vl = v2 end ge = vt.length st = 0 en = st + ws if (ws > ge) en = ge end while (st <= [ge - ws, 0].max) c = st while (c < en) i = st while (i < en) if i == c i += 1 next end if (vl[c] == vt[i]) vt[i], vt[c] = vt[c], vt[i] i += 1 next end i += 1 end c += 1 end st += 1 en += 1 end return vl, vt end def step_equals(s1, s2, attr) count = 0 attr.each do |a| #if a == "position" # #puts "step_equals, skipping position" # next #end if not s1[a] == s2[a] count += 1 end end return count == 0 end # Function to compare two steps. This function takes into care, that steps can # have surrogates attached. If they have, the surrogates will be compared. def comp_steps(stp1, stp2, attr, surr=true) stp1_attrs = [] stp2_attrs = [] if surr and stp1.surrogate # if stp1 has surrogate, stp2 should also stp1_attrs = stp1.surrogate.attributes stp2_attrs = stp2.surrogate.attributes else stp1_attrs = stp1.attributes stp2_attrs = stp2.attributes end res = step_equals(stp1_attrs, stp2_attrs, attr) return res end # This swap function works directly on the provided arrays. It furthermore # assumes that the first array is longer. def swap2(v1, v2, ws, attr) if ws < 2 return end ge = v1.length sm = v2.length st = 0 en = st + ws if (ws > ge) en = ge end while (st <= [ge - ws, 0].max) c = st while (c < en and c < sm) i = st while (i < en and i < sm) if i == c i += 1 next end #if (step_equals(v1[c].attributes, v2[i].attributes, attr)) if (comp_steps(v1[c], v2[i], attr)) #puts "performing swap, swapping #{i} with #{c}" #puts " pre swap: #{v2}" v2[i], v2[c] = v2[c], v2[i] #puts " post swap: #{v2}" #performed_swaps += 1 i += 1 #next end i += 1 end c += 1 end st += 1 en += 1 end end # Function to align pdj2 against pdj1 by swapping the steps in event_types. def swap_pdj(pdj1, pdj2, ws, attrs) res = pdj2.cpy Discover::EVENT_TYPE_ARRAY.each do |t| next if Discover::milestone?(t) next if not attrs[t] or attrs[t].length == 0 v1 = pdj1.types[t] v2 = res.types[t] next if not v1 next if not v2 next if v1.length == 1 and v2.length == 1 swap2(v1, v2, ws, attrs[t]) end return res end # This is just a test function I added to test some aspects of the swap # functionality. def swap3(v1, v2, ws) ge = v1.length sm = v2.length st = 0 en = st + ws if (ws > ge) en = ge end while (st <= [ge - ws, 0].max) c = st while (c < en and c < sm) i = st while (i < en and i < sm) if i == c i += 1 next end #if (step_equals(v1[c].attributes, v2[i].attributes, attr)) if (v1[c] == v2[i]) v2[i], v2[c] = v2[c], v2[i] #puts "permforming swap" i += 1 next end i += 1 end c += 1 end st += 1 en += 1 end end =begin def shift_swap(v1, v2) if (v1.length >= v2.length) vt = v2.dup vl = v1 else vt = v1.dup vl = v2 end res = Array.new(vl.length, nil) i1 = 0 i2 = 0 for i1 in (0..vl.length) go end =end =begin v1 = [1, 2, 3, 4, 5, 6, 7] v2 = [2, 3, 4, 5] v3 = [3] puts "v2: #{v2.join(", ")}" v2t = v2.clone swap3(v1, v2t, 2) puts "Swap window 2" puts v1.join(", ") puts v2t.join(", ") v2t = v2.clone puts "Swap window 3" swap3(v1, v2t, 3) puts v1.join(", ") puts v2t.join(", ") swap3(v1, v3, 3) puts v3.join(", ") =end <file_sep>/bin/tactical_opps.rb #!/usr/bin/env ruby require 'logger' require 'optparse' require 'sqlite3' require 'graphviz' require_relative './util' require_relative '../lib/consolidate_events' require_relative '../lib/bpm' require_relative '../lib/configuration' require_relative '../lib/dynamic_segmenter' require_relative '../lib/mcl' require_relative '../lib/pdj' require_relative '../lib/pdj_map' require_relative '../lib/retention' require_relative '../lib/static_segment' require_relative '../lib/visualizer' require_relative '../lib/opt_parser' require_relative '../lib/database/sqlite3_connect.rb' VERSION = "1.1.1.3" #include Discover # Starting up the DAE, setting default values, and reading options file options = {} options[:p] = false options[:c] = "" options[:ds] = nil options[:n] = nil options[:e] = nil options[:o] = nil options[:m] = false # Initialize logger and log level with infos from options initialize_logger() opt_parser = Option_Parser.new(options, true) initialize_logger(options) opt_parser.check_options(options) # Read ini file ini = Configuration.new(options[:i]) $LOG.debug "Main: configuration:" $LOG.debug ini db = connect_db(options[:d]) event_tbl_name = ini["global"]["event_table_name"] if options[:e] event_tbl_name = options[:e] end if ini["bpm"]["optimise"] != "global" $LOG.error("Optimization must run globaly for the DAE to generate defection or acquisition PDJ maps") exit 1 end if not Discover.tbl_exists?(db, event_tbl_name) msg = "Main, provided table name #{event_tbl_name} does not exists!" $LOG.error(msg) msg = " ABORTING!" $LOG.error(msg) exit 1 end clean_tables(db, event_tbl_name, true) # Read values from ini file res_tbl_name = ini["visualisation"]["result_table"] res_tbl_name = res_tbl_name ? res_tbl_name : "results" # Parameter deprecated, now always true file_output_path = ini["visualisation"]["file_output_path"] tactical_opps_prfx = ini["visualisation"]["file_output_prefix"] format = ini["visualisation"]["format"] format = format ? format : "svg" # Start compatibilty check concerning db version and attributes to be used attrs = get_attributes_for_types(ini) check_columns(db, event_tbl_name, attrs) # Extract "static_segment" which serves as base for tactical_opps identifification static_segments = extract_static_segments(db, attrs, event_tbl_name) if static_segments.length > 1 $LOG.error("The tactical opportunity functionality does only work if one and only one static segment is provided!") exit 1 end if static_segments[0].length < 3 $LOG.error("At least 3 PDJs must be given in the retention for the DAE to generate defection or acquisition PDJ maps") exit 1 end bpms = calculate_bpms(static_segments, ini, db, event_tbl_name) write_static_segments(db, static_segments, event_tbl_name) if (static_segments.length > 1) $LOG.error("More than one static segment to be used as retention set cannot be passed to tactical opps calculation") exit 1 end # Retention: Set of PDJs to be screened for tactical opportunities retention = nil # Defection: Are similar to the buyers of own brand defection = nil # Acquisition: Are dissimilar to the buyers of own brand acquisition = nil attrs = ini.get_pdjm_attributes() retention = extract_retention(db, attrs, event_tbl_name) event_tbl_name = retention[1] clean_tables(db, event_tbl_name) retention = retention[0] write_static_segments(db, [retention], event_tbl_name) dt = ini["tactical_opportunities"]["defection_similarity_threshold"] at = ini["tactical_opportunities"]["acquisition_similarity_threshold"] connection = ini["tactical_opportunities"]["connection"] # Set default if not parameters are given if not dt # Acquisition of clients that are "similar" to our own cliens dt = 0.7 else dt = dt.to_f end if not at at = 0.3 else at = at.to_f end if connection if not ["complete", "single"].include?(connection) $LOG.debug "dc.rb: Setting connection for retention to: #{connection}" connection = "complete" end else connection = "complete" end mode = options[:m] result_setof_pdjs = nil if mode == "defection" result_setof_pdjs = Discover::extract_defection(retention, static_segments, dt, connection ) elsif mode == "acquisition" result_setof_pdjs = Discover::extract_acquisition(retention, static_segments, at, connection ) else $LOG.error ("Tactical opps must be called for either defection or acquisition calculation") exit (1) end # Update database with appr. "dyn" IDs for tactical opps if result_setof_pdjs and result_setof_pdjs.length > 0 # Mark set of PDJs with the appropriate dynamic segment ID (defection = 0, acquisition = 1) msg = "Main::tactical_oportunities, marking results journeys with " msg += Discover::ALGORITHM_COLUMNS[:dynamic_segment_id] + " = " msg += result_setof_pdjs.segment_id.to_s $LOG.info(msg) Discover.update_db_with_dynamic_segment_ids(db, [result_setof_pdjs], event_tbl_name) Discover.update_db_with_tactical_opps(db, [result_setof_pdjs], event_tbl_name) end result_bpms = nil if result_setof_pdjs and result_setof_pdjs.length > 0 result_bpms = calculate_bpms([result_setof_pdjs], ini, db, event_tbl_name) write_bpm_ids_to_db(result_bpms, db, event_tbl_name, false) end result_pdjms = nil if result_bpms and result_bpms.length > 0 result_pdjms = calculate_pdjms(ini, result_bpms) write_pdjm_ids_to_db(result_pdjms, db, event_tbl_name) else msg = "Main::tactical opportunities, no result for tactical opps calculation" $LOG.info(msg) end label_id = true graph_label = options[:c] # Visualisation if result_pdjms pdjs = Array.new() result_pdjms.each do |b| pdjs << PdjMap.new(b) end vis_attrs = get_visualisation_attributes(ini) viz_object = Visualizer.new(pdjs, vis_attrs, db, res_tbl_name, format, ini, file_output_path, tactical_opps_prfx) if options[:p] viz_object.buildgraph(label_id, graph_label, ini) else viz_object.buildgraph(label_id, graph_label) end end close_db(db) <file_sep>/lib/ai4r/single_linkage.rb # Author:: <NAME> (implementation) # License:: MPL 1.1 # Project:: ai4r # Url:: http://ai4r.org/ # # You can redistribute it and/or modify it under the terms of # the Mozilla Public License version 1.1 as published by the # Mozilla Foundation at http://www.mozilla.org/MPL/MPL-1.1.txt require_relative 'data_set' require_relative 'proximity' require_relative 'clusterer' module Ai4r module Clusterers # Implementation of a Hierarchical clusterer with single linkage (Everitt et # al., 2001 ; Johnson, 1967 ; <NAME> Dubes, 1988 ; Sneath, 1957 ) # Hierarchical clusteres create one cluster per element, and then # progressively merge clusters, until the required number of clusters # is reached. # With single linkage, the distance between two clusters is computed as the # distance between the two closest elements in the two clusters. # # D(cx, (ci U cj) = min(D(cx, ci), D(cx, cj)) class SingleLinkage < Clusterer attr_reader :data_set, :number_of_clusters, :clusters, :index_clusters attr_reader :distance_matrix parameters_info :distance_function => "Custom implementation of distance function. " + "It must be a closure receiving two data items and return the " + "distance bewteen them. By default, this algorithm uses " + "ecuclidean distance of numeric attributes to the power of 2." def initialize @print_cluster_histogram = false init_stats_matrix() @distance_function = lambda do |a,b| #Ai4r::Data::Proximity.block_distance(a, b) Ai4r::Data::Proximity.edit_distance(a, b) end end def init_stats_matrix nof_sims = 11 nof_bins = 9 @stats = Array.new(nof_sims) #, Array.new(nof_bins, Array.new(2, 0))) @stats.each_with_index do |s, idx| @stats[idx] = Array.new(nof_bins) @stats[idx].each_with_index do |s2, idx2| @stats[idx][idx2] = Array.new(2, 0) end end end # Build a new clusterer, using data examples found in data_set. # Items will be clustered in "number_of_clusters" different # clusters. def build(data_set, number_of_clusters) @data_set = data_set @number_of_clusters = number_of_clusters @index_clusters = create_initial_index_clusters create_distance_matrix(data_set) while get_min_distance() <= @number_of_clusters # ci, cj = get_closest_clusters(@index_clusters) # update_distance_matrix(ci, cj) # merge_clusters(ci, cj, @index_clusters) #end #while @index_clusters.length > @number_of_clusters ci, cj = get_closest_clusters(@index_clusters) update_distance_matrix(ci, cj) merge_clusters(ci, cj, @index_clusters) end @clusters = build_clusters_from_index_clusters @index_clusters # calc stats, start if @print_cluster_histogram print_cluster_histogram_fct() end return self end # Classifies the given data item, returning the cluster index it belongs # to (0-based). def eval(data_item) get_min_index(@clusters.collect {|cluster| distance_between_item_and_cluster(data_item, cluster)}) end def get_min_distance() ar = @distance_matrix.flatten if not ar or ar.length == 0 return 1.0/0 # infinity else return ar.min end end def get_number_of_clusters @index_clusters.length end # returns [ [0], [1], [2], ... , [n-1] ] # where n is the number of data items in the data set def create_initial_index_clusters index_clusters = [] @data_set.data_items.length.times {|i| index_clusters << [i]} return index_clusters end # Create a partial distance matrix: # [ # [d(1,0)], # [d(2,0)], [d(2,1)], # [d(3,0)], [d(3,1)], [d(3,2)], # ... # [d(n-1,0)], [d(n-1,1)], [d(n-1,2)], ... , [d(n-1,n-2)] # ] # where n is the number of data items in the data set def create_distance_matrix(data_set) @data_set = data_set @distance_matrix = Array.new(data_set.data_items.length-1) {|index| Array.new(index+1)} data_set.data_items.each_with_index do |a, i| i.times do |j| b = data_set.data_items[j] @distance_matrix[i-1][j] = @distance_function.call(a, b) end end end def compute_average_distance(idx) dst = 0.0 @data_set.data_items.each_with_index do |a, i| dst += read_distance_matrix(idx, i) end return dst / (@data_set.data_items.length.to_f - 1.0) end protected # Returns the distance between element data_item[index_a] and # data_item[index_b] using the distance matrix def read_distance_matrix(index_a, index_b) return 0 if index_a == index_b index_a, index_b = index_b, index_a if index_b > index_a return @distance_matrix[index_a-1][index_b] end # ci and cj are the indexes of the clusters that are going to # be merged. We need to remove distances from/to ci and ci, # and add distances from/to new cluster (ci U cj) def update_distance_matrix(ci, cj) ci, cj = cj, ci if cj > ci distances_to_new_cluster = Array.new (@distance_matrix.length+1).times do |cx| if cx!= ci && cx!=cj distances_to_new_cluster << linkage_distance(cx, ci, cj) end end if cj==0 && ci==1 @distance_matrix.delete_at(1) @distance_matrix.delete_at(0) elsif cj==0 @distance_matrix.delete_at(ci-1) @distance_matrix.delete_at(0) else @distance_matrix.delete_at(ci-1) @distance_matrix.delete_at(cj-1) end @distance_matrix.each do |d| d.delete_at(ci) d.delete_at(cj) end @distance_matrix << distances_to_new_cluster end # return distance between cluster cx and new cluster (ci U cj), # using single linkage def linkage_distance(cx, ci, cj) [read_distance_matrix(cx, ci), read_distance_matrix(cx, cj)].min end # cluster_a and cluster_b are removed from index_cluster, # and a new cluster with all members of cluster_a and cluster_b # is added. # It modifies index clusters array. def merge_clusters(index_a, index_b, index_clusters) index_a, index_b = index_b, index_a if index_b > index_a new_index_cluster = index_clusters[index_a] + index_clusters[index_b] index_clusters.delete_at index_a index_clusters.delete_at index_b index_clusters << new_index_cluster return index_clusters end # Given an array with clusters of data_items indexes, # it returns an array of data_items clusters def build_clusters_from_index_clusters(index_clusters) @distance_matrix = nil return index_clusters.collect do |index_cluster| Ai4r::Data::DataSet.new(:data_labels => @data_set.data_labels, :data_items => index_cluster.collect {|i| @data_set.data_items[i]}) end end # Returns ans array with the indexes of the two closest # clusters => [index_cluster_a, index_cluster_b] def get_closest_clusters(index_clusters) min_distance = 1.0/0 # infinity closest_clusters = [1, 0] index_clusters.each_index do |index_a| index_a.times do |index_b| cluster_distance = read_distance_matrix(index_a, index_b) if cluster_distance < min_distance closest_clusters = [index_a, index_b] min_distance = cluster_distance end end end return closest_clusters end def distance_between_item_and_cluster(data_item, cluster) min_dist = 1.0/0 cluster.data_items.each do |another_item| dist = @distance_function.call(data_item, another_item) min_dist = dist if dist < min_dist end return min_dist end def print_cluster_histogram_fct idx1 = (1- @number_of_clusters) idx = (idx1 * 10).round msg = " -> Got #{@index_clusters.length} clusters for similarity #{idx1.round(2)}" $LOG.info(msg) @index_clusters.each do |c| l = c.length if l > 400 @stats[idx][8][0] += 1 @stats[idx][8][1] += l end if l > 200 and l <= 400 @stats[idx][7][0] += 1 @stats[idx][7][1] += l end if l > 100 and l <= 200 @stats[idx][6][0] += 1 @stats[idx][6][1] += l end if l > 80 and l <= 100 @stats[idx][5][0] += 1 @stats[idx][5][1] += l end if l > 60 and l <= 80 @stats[idx][4][0] += 1 @stats[idx][4][1] += l end if l > 40 and l <= 60 @stats[idx][3][0] += 1 @stats[idx][3][1] += l end if l > 20 and l <= 40 @stats[idx][2][0] += 1 @stats[idx][2][1] += l end if l > 10 and l <= 20 @stats[idx][1][0] += 1 @stats[idx][1][1] += l end if l >= 1 and l <= 10 @stats[idx][0][0] += 1 @stats[idx][0][1] += l end end # calc stats, end printf "%4s | %10s | %10s | %10s | %10s | %10s | %11s | %13s | %13s | %11s \n", "sim", "1-10", "11-20", "21-40", "41-60", "61-80", "81-100", "101-200", "201-400", "> 400" printf "-----+------------+------------+------------+" printf "------------+------------+-------------+---------------+" printf "---------------+-------------------\n" @stats.each_with_index do |s, idx| printf "%4s | %4s (%3s) | %4s (%3s) | %4s (%3s) | %4s (%3s) | %4s (%3s) | %5s (%3s) | %7s (%3s) | %7s (%3s) | %5s (%3s) \n", idx.to_f / 10.0, s[0][0], s[0][1], s[1][0], s[1][1], s[2][0], s[2][1], s[3][0], s[3][1], s[4][0], s[4][1], s[5][0], s[5][1], s[6][0], s[6][1], s[7][0], s[7][1], s[8][0], s[8][1] printf "-----+------------+------------+------------+" printf "------------+------------+-------------+---------------+" printf "---------------+-------------------\n" end puts end end end end <file_sep>/lib/get_testdata.rb require 'spreadsheet' require 'sqlite3' require 'optparse' OBJECTS_TBL_NME = "objects" VERSIONS_TBL_NME = "versions" SEGMENTS_TBL_NME = "segments" RESULTS_TBL_NME = "results" options = {} options[:e] = nil options[:o] = "" options[:s] = "all" optparse = OptionParser.new do |opts| opts.on("-e", "--excel <Excel file nam>", String, "Excel file with journeyes") do |e| options[:e] = e end opts.on("-o", "--out_prefix <String>", String, "Name prefix of SQLite3 DB") do |o| options[:o] = o end opts.on("-s", "--sheets <Comma seperated numbers | all>", String, "What tests to extract") do |s| options[:s] = s end end optparse.parse! PATH = "/home/juri/develop/discover/acceptance" #FILE = "/realistic_test_case_128_values_20141214.xls" Spreadsheet.client_encoding = 'UTF-8' book = Spreadsheet.open(options[:e]) # generate statement to create table 'objects' create_objects_sheet = book.worksheet('Create statement for object tab') create_objects_stmt = "" create_objects_sheet.each do |row| create_objects_stmt += row.join.strip + " " end # generate statement to create table 'versions' create_versions_sheet = book.worksheet('Create stmt for versions tab') create_versions_stmt = "" create_versions_sheet.each do |row| create_versions_stmt += row.join.strip + " " end # generate statement to create table 'segments' create_segments_sheet = book.worksheet('Create stmt for segments tab') create_segments_stmt = "" create_segments_sheet.each do |row| create_segments_stmt += row.join.strip + " " end # generate statement to create table 'results' create_results_sheet = book.worksheet('Create stmt for results tab') create_results_stmt = "" create_results_sheet.each do |row| create_results_stmt += row.join.strip + " " end # loop over all test cases #for i in ARGV[1]..ARGV[2] do # get db name and create db or connect if exists i = options[:s].to_i db_name = "test_" + i.to_s + "_database.db" if options[:o] and options[:o].length > 0 db_name = options[:o] + "_" + db_name end db = SQLite3::Database.new(db_name) # drop table if exists and create new ones drop_if_ex_objects = "DROP TABLE IF EXISTS " + OBJECTS_TBL_NME db.execute(drop_if_ex_objects) db.execute(create_objects_stmt) drop_if_ex_versions = "DROP TABLE IF EXISTS " + VERSIONS_TBL_NME db.execute(drop_if_ex_versions) db.execute(create_versions_stmt) drop_if_ex_segments = "DROP TABLE IF EXISTS " + SEGMENTS_TBL_NME db.execute(drop_if_ex_segments) db.execute(create_segments_stmt) drop_if_ex_results = "DROP TABLE IF EXISTS " + RESULTS_TBL_NME db.execute(drop_if_ex_results) db.execute(create_results_stmt) # insert version row insert_versions_stmt = "INSERT INTO " + VERSIONS_TBL_NME insert_versions_stmt += " (dat_adapter_version) VALUES (1);" db.execute(insert_versions_stmt) # insert version row insert_segments_stmt = "INSERT INTO " + SEGMENTS_TBL_NME insert_segments_stmt += " (dat_id, dat_sql) VALUES (1, " insert_segments_stmt += "'SELECT * FROM " + OBJECTS_TBL_NME + "');" db.execute(insert_segments_stmt) # open worksheet for current test and read every row testdata_sheet = book.worksheet('Test ' + i.to_s) #next if not testdata_sheet # initialize dat_object_id (primary key) dat_object_id = 1 testdata_sheet.each_with_index do |row, idx| # only rows that starts with "PDJ" will be used! next if row[0] != "PDJ" # Get PDJ data journey_info = Hash.new() journey_info["dat_journey_id"] = Integer(row[1]) journey_info["dat_segment_id"] = Integer(row[2]) journey_info["dat_respondent_id"] = "\'null\'" journey_info["dat_session_duration"] = "\'null\'" journey_info["dat_session_submitted"] = "\'null\'" # Get event data starting from column 4 in each row j = 4 while (row[j] != nil) do # Collect info for current event event_info = Hash.new() event_token = row[j].split(",") event_token.map!{|e| e.strip} event_token.map!{|e| e != "" ? e : "NULL"} event_info["dat_object_id"] = dat_object_id dat_object_id += 1 event_info["dat_object_type"] = event_token[0].to_i event_info["jrn_goal"] = event_token[1].to_s.inspect event_info["jrn_importance"] = event_token[2].to_i event_info["jrn_touchpoint"] = event_token[3].to_s.inspect event_info["jrn_channel"] = event_token[4].to_s.inspect event_info["jrn_mission"] = event_token[5].to_s.inspect event_info["jrn_position"] = j-4 # Write current step of current PDJ into the SQLITE3 database # get beginning of insert statement insert_stmt = "INSERT INTO " + OBJECTS_TBL_NME + " (" # get all column names insert_stmt += journey_info.keys.join(", ") + ", " insert_stmt += event_info.keys.join(", ") insert_stmt += ") VALUES (" # get values insert_stmt += journey_info.values.join(", ") + ", " insert_stmt += event_info.values.join(", ") insert_stmt += ");" # fill table in sqlite database db.execute(insert_stmt) # Get next step j+=1 end end db.close #end <file_sep>/lib/pdj_map.rb require_relative 'graph' require_relative 'enumerator' require_relative 'constants' require_relative 'tools' class PdjMap < Graph attr_accessor :bpm attr_reader :attrs attr_reader :graphics def initialize(bpm = nil, attrs = nil) @bpm = bpm @attrs = attrs # variable to save all values necessary for entropy calculation end def calc_pdj_map(calc_method = nil) if calc_method == 'enumeration' $LOG.debug "PdjMap::calc_pdj_map, calc_method: #{calc_method}" enum = Enumerator.new(@bpm, @attrs) #enum.enumerate #normed_entropy = bpm_entropy(bpm, attrs) #normed_entropy elsif calc_method == 'mcl' $LOG.debug "PdjMap::calc_pdj_map, calc_method: #{calc_method}" calc_pdj_map_mcl() else $LOG.error "PdjMap::calc_pdj_map, unknown calc_method: #{calc_method}" return end end def to_s res = "PdjMap, Bpm.id: #{bpm.segment.segment_id}, attributes:\n" res += "#{attrs}" res += "Bpms: #{bpm}" end end <file_sep>/lib/pdj_step.rb require_relative "pdj_event" class PdjStep < PdjEvent def to_s res = " Step: " + super end end <file_sep>/lib/ai4r/proximity.rb # Author:: <NAME> # License:: MPL 1.1 # Project:: ai4r # Url:: http://ai4r.org/ # # You can redistribute it and/or modify it under the terms of # the Mozilla Public License version 1.1 as published by the # Mozilla Foundation at http://www.mozilla.org/MPL/MPL-1.1.txt require_relative '../dswap' require_relative '../serialiser_tools' module Ai4r module Data # This module provides classical distance functions module Proximity @@blockdistance_blocksize = 1 @@editdistance_delete = 1 @@editdistance_insert = 1 @@editdistance_substitute = 1 @@max_swap_edit = true #@@dummy_dist = 0.1 * [@@editdistance_delete, @@editdistance_insert, # @@editdistance_substitute].min @@dummy_dist = 1 # Similarity histogram, printed in 0.05 steps. @@histogram = Array.new(20, 0) def self.set_blockdistance_blocksize(n) @@blockdistance_blocksize = n end def self.get_blockdistance_blocksize @@blockdistance_blocksize end def self.set_editdistance_delete(n) @@editdistance_delete = n end def self.get_editdistance_delete @@editdistance_delete end def self.set_editdistance_insert(n) @@editdistance_insert = n end def self.get_editdistance_insert @@editdistance_insert end def self.set_editdistance_substitute(n) @@editdistance_substitute = n end def self.get_editdistance_substitute @@editdistance_substitute end def self.set_dummy_dist(n) @@dummy_dist = n end def self.get_histogram @@histogram end def self.set_max_swap_edit(tf) @@max_swap_edit = tf end # This is a Levenshtein Edit Distance method working on # chunks/blocks of chars, instad of one char. # # == Paramter # str1:: String: String1 for distance computation # str2:: String: String2 for distance computation # dummy:: String: How is a dummy represented. # # == Return # Float: How many edit operations were necessary to transform str1 into # str2 def self.block_distance(str1, str2, dummy = nil) blockdistance_delete = @@editdistance_delete blockdistance_insert = @@editdistance_insert blockdistance_substitute = @@editdistance_substitute dummy_dist = @@dummy_dist block_size = @@blockdistance_blocksize # Transform strings to Arrays, where every element has block_size # chars.THis ensures that edit distance works correctly when # an attribute value is encoded with arbitrary many characters. s = str1.scan(/.{1,#{block_size}}/) t = str2.scan(/.{1,#{block_size}}/) m = s.length n = t.length return m if n == 0 return n if m == 0 d = Array.new(m+1) {Array.new(n+1)} d[0][0] = 0 (0..m).each {|i| d[i][0] = i} (0..n).each {|j| d[0][j] = j} (1..n).each do |j| (1..m).each do |i| d[i][j] = if s[i-1] == t[j-1] and s[i-1] != dummy # adjust index into string d[i-1][j-1] # no operation required # Integrated for alternative weighting of dummies. # CURRENTLY NOT USED. #elsif t[j-1] == dummy or s[i-1] == dummy # [ # d[i-1][j] + dummy_dist, # deletion # d[i][j-1] + dummy_dist, # insertion # d[i-1][j-1] + dummy_dist, # substitution # ].min else [ d[i-1][j] + blockdistance_delete, # deletion d[i][j-1] + blockdistance_insert, # insertion d[i-1][j-1] + blockdistance_substitute, # substitution ].min end end end return d[m][n] end # Calculating _similarity_ (not distance) between two strings. # 0 means no similarity at all, 1 means identically. # This method basically calls edit distance on the provided strings. # Note: The expected strucutre for entry1 and entry2 is an array of two # elements. The first, i.e. entry1[0], is a user_id the second # element is an hash. The key of the hash is the event-type as ID, # i.e. 6 for Discover::CONSIDERING_STEP, ..... # The value to the event-type-id is the string of a string # representing the events # # == Parameter # entry1:: Array: See description above # entry2:: Array: # meth:: Int: How to compute similarity. # 1: Calculate edit distance per phase and combine the # results at the end. # 2: Transform both journeys into strings and use them as # input for edit distance. # This method is deprecated. # dummy_ele:: Ruby-Function: What is an dummy # # == Return # Float:: Similarity between two strings. 1 means strings are # identically, 0 no similarity at all. def self.edit_similarity(entry1, entry2, meth=1, dummy_ele = nil) tr = [] res = 0 sub = 0 maxs = 0 # How long is one element. bs = @@blockdistance_blocksize # Method 1: Compute similarity per phase and combine them at the end. if meth == 1 Discover::JOURNEY_EVENT_ORDER.each do |et| str1 = entry1[1][et] str2 = entry2[1][et] if str1 == "" and str2 == "" sub += 1 next end ed = block_distance(str1, str2, dummy_ele) #avr = ((str1.length / bs).to_f + (str2.length / bs).to_f) / 2.0 max = [(str1.length / bs).to_f, (str2.length / bs).to_f].max #puts "ed: #{ed}, max: #{max}, ed/max: #{ed.to_f / max}" if ed.to_f / max > 1 $LOG.error("proximity::edit_similarity, computed distance > 1") exit 1 end #res += 1 - (ed.to_f / max) res += (1 - (ed.to_f / max)) * max maxs += max end #res = res / (Discover::JOURNEY_EVENT_ORDER.length - sub) #res = 1 if maxs > 0 res = res / maxs else msg = "proximity::edit_similarity, something is wrong with " msg += "one of the users: #{entry1[0]} and/or #{entry2[0]} - " msg += "None of the necessary attributes for similarity caluclation is set!!!" $LOG.warn msg end res # Method 2: Transform both PDJs into two strings and compute edit # distance on them. else meth == 2 str1 = "" str2 = "" # Build up string representation of both PDJs Discover::JOURNEY_EVENT_ORDER.each do |et| str1 += entry1[1][et] str2 += entry2[1][et] end ed = block_distance(str1, str2, dummy_ele) #avr = ((str1.length / bs).to_f + (str2.length / bs).to_f) / 2.0 max = [(str1.length / bs).to_f, (str2.length / bs).to_f].max res = 1 - [ed.to_f / max, 1.0].min end pos = (res / 0.05).to_i if pos > 19 pos = 19 elsif pos < 0 pos = 0 end @@histogram[pos] += 1 #res = 1 - res res end # Function to compute edit _distance_ (not similarity) for two PDJs. # PJDs are translated into strings and are then put into the # edit_distance function for strings. # # == Paramter # pdj1:: Pdj: First PDJ # pdj2:: Pdj: Second PDJ # swap_window:: Int: In what window can elements be swapped. # nec_chars:: Int: How many characters are necessary to encode all # attributes. # enc_map:: Hash: Encoding map. See lib/serialiser.rb for details # attrs:: Hash: What attributes to use for comparison. # # == Return # Float: Value in range [0, 1]: 0 means absolute identical, 1 means no # similarity at all. def self.edit_distance(pdj1, pdj2, swap_window = nil, nec_chars = nil, enc_map = nil, attrs = nil) #set_blockdistance_blocksize(pdjy1.static_segment.nec_chars+1) p1 = pdj1.cpy p2 = pdj2.cpy sc = nil lc = nil sb = nil lb = nil sw = nil if swap_window sw = swap_window else sw = p1.static_segment.swap_window end if not nec_chars nec_chars = pdj1.static_segment.nec_chars end if not enc_map enc_map = pdj1.static_segment.enc_map end if not attrs attrs = pdj1.static_segment.attributes end # Results for distance calculations, one with swap, the other without. res_swap = 0.0 res_no_swap = 0.0 t1 = p1.types t2 = p2.types if (sw and sw > 1) if p2.length > p1.length p1, p2 = p2, p1 end dummy_gen_fct = lambda {|x| PdjEvent.get_dummy(x)} p2 = Discover.align_pdj(p1, p2, sw, attrs, dummy_gen_fct) str1 = encode_pdj_events(p1, nec_chars, enc_map, attrs) str2 = encode_pdj_events(p2, nec_chars, enc_map, attrs) entry1 = [] entry2 = [] entry1[0] = p1.user_id entry1[1] = str1 entry2[0] = p2.user_id entry2[1] = str2 res_swap = edit_similarity(entry1, entry2, 1) end str1 = encode_pdj_events(pdj1, nec_chars, enc_map, attrs) str2 = encode_pdj_events(pdj2, nec_chars, enc_map, attrs) entry1 = [] entry2 = [] entry1[0] = pdj1.user_id entry1[1] = str1 entry2[0] = pdj2.user_id entry2[1] = str2 res_no_swap = edit_similarity(entry1, entry2, 1, enc_map[:dummy]) if (sw and sw > 0) res = res_swap else res = res_no_swap end if sw and sw > 0 and @@max_swap_edit res = [res_swap, res_no_swap].max end return 1.0 - res end # This is a faster computational replacement for eclidean distance. # Parameters a and b are vectors with continuous attributes. def self.squared_euclidean_distance(a, b) sum = 0.0 a.each_with_index do |item_a, i| item_b = b[i] sum += (item_a - item_b)**2 end return sum end # Euclidean distance, or L2 norm. # Parameters a and b are vectors with continuous attributes. # Euclidean distance tends to form hyperspherical # clusters(Clustering, Xu and Wunsch, 2009). # Translations and rotations do not cause a # distortion in distance relation (Duda et al, 2001) # If attributes are measured with different units, # attributes with larger values and variance will # dominate the metric. def self.euclidean_distance(a, b) Math.sqrt(squared_euclidean_distance(a, b)) end # city block, Manhattan distance, or L1 norm. # Parameters a and b are vectors with continuous attributes. def self.manhattan_distance(a, b) sum = 0.0 a.each_with_index do |item_a, i| item_b = b[i] sum += (item_a - item_b).abs end return sum end # Sup distance, or L-intinity norm # Parameters a and b are vectors with continuous attributes. def self.sup_distance(a, b) distance = 0.0 a.each_with_index do |item_a, i| item_b = b[i] diff = (item_a - item_b).abs distance = diff if diff > distance end return distance end # The Hamming distance between two attributes vectors of equal # length is the number of attributes for which the corresponding # vectors are different # This distance function is frequently used with binary attributes, # though it can be used with other discrete attributes. def self.hamming_distance(a,b) count = 0 a.each_index do |i| count += 1 if a[i] != b[i] end return count end # The "Simple matching" distance between two attribute sets is given # by the number of values present on both vectors. # If sets a and b have lengths da and db then: # # S = 2/(da + db) * Number of values present on both sets # D = 1.0/S - 1 # # Some considerations: # * a and b must not include repeated items # * all attributes are treated equally # * all attributes are treated equally def self.simple_matching_distance(a,b) similarity = 0.0 a.each {|item| similarity += 2 if b.include?(item)} similarity /= (a.length + b.length) return 1.0/similarity - 1 end end end end <file_sep>/lib/pdj_milestone.rb require_relative "pdj_event" class PdjMilestone < PdjEvent def to_s res = " MileStone: " + super end end <file_sep>/lib/pdj.rb require_relative "constants" require_relative "pdj_step" require_relative "pdj_milestone" class Pdj attr_accessor :user_id attr_accessor :static_segment, :dyn_segment attr_accessor :types attr_accessor :ser_evnts attr_accessor :pos_name attr_accessor :tactical_opps def initialize(user_id, rows, static_segment = nil, attrs = nil, pos_name = nil, type_name = nil, tactical_opps = "none") @user_id = user_id @types = [] @attrs = attrs #Discover::EVENT_TYPE_ARRAY.each do |t| if attrs attrs.keys.each do |t| @types[t] = [] end else @type = Array.new() end if @attrs @attrs.each_pair do |typ, ary| if not ary.include?(Discover::ALGORITHM_COLUMNS[:importance]) ary << Discover::ALGORITHM_COLUMNS[:importance] end end end @rows = rows @static_segment = static_segment @dyn_segment = nil @pos_name = pos_name @tactical_opps = tactical_opps @type_name = type_name extract_pdj(rows, @pos_name, @type_name, attrs) end def init_surrogates @types.each do |t| next if not t t.each do |e| e.clear_surrogate end end #Discover::EVENT_TYPE_ARRAY.each do |t| # @surrogates[t] = [] #end end def clear_surrogates @types.each do |t| next if not t t.each do |e| e.clear_surrogate end end end def use_event_as_surrogate(t) if t < 0 or t > @types.length $LOG.error "Pdj::use_event_as_surrogate, type out of range!" return end @types[t].each do |evt| evt.use_event_as_surrogate() end end def extract_pdj(rows, pos_name, type_name, attrs) return if not rows extract_events(rows, pos_name, type_name, attrs) end def extract_row(kys, row) res = {} kys.each do |k| res[k] = row[k] end res end def to_s res = "\nuser_id: #{@user_id}\n" Discover::JOURNEY_EVENT_ORDER.each do |typ| #@types.each do |t| next if not @types[typ] or @types[typ].length == 0 @types[typ].each do |e| res += e.to_s end end res end def [](i) ti = i @types.each do |e| next if not e or e.length == 0 if e.length <= ti ti = ti - e.length else return e[ti] end end return nil end def adjust_positions(orig_pos = false) pos = 0 Discover::JOURNEY_EVENT_ORDER.each do |typ| next if not @types[typ] @types[typ].each do |e| next if not e e.position = pos if orig_pos e.orig_pos = pos end pos += 1 end end end def set_type_to_dummys() @types.each_with_index do |t, typ_idx| next if not t t.each do |ele| next if not ele next if not ele.is_dummy?() ele.type = typ_idx end end end def strip_dummys() @types.each_with_index do |t, typ_idx| next if not t t.delete_if {|x| x.is_dummy?()} end end def has_dummy?() @types.each do |t| next if not t if t.any? {|x| x.is_dummy?} return true end end return false end def <<(e) @types[e.type] << e e.pdj = self adjust_positions(true) end def each(&block) arry = Array.new @types.each do |t| next if not t arry.concat(t) end arry.each(&block) end def length res = 0 @types.each do |e| next if not e res += e.length end res end # Performs a deep copy down to the level of events def cpy pdj = Pdj.new(@user_id, @rows, @static_segment, @attrs, @pos_name, @type_name, @tactical_opps) pdj =begin #pdj = self.clone pdj.types = [] Discover::EVENT_TYPE_ARRAY.each do |t| next if not t next if not @types[t] pdj.types[t] = @types[t].cpy() end pdj =end end def ==(othr) return false if othr == nil return false if not length == othr.length @types.each_with_index do |e, idx| if not e and othr.types[idx] return false end return false if not e == othr.types[idx] end true end private def extract_events(rows, pos_name, type_name, attrs) tmp = [] rows.delete_if {|evt| not Discover::JOURNEY_EVENT_ORDER.include?(evt[Discover::ALGORITHM_COLUMNS[:event_type]]) } rows.delete_if {|evt| not evt[Discover::ALGORITHM_COLUMNS[:jrn_position]] } trows = rows.sort {|a, b| a[pos_name] <=> b[pos_name]} trows.each do |r| typ = r[type_name].to_i #kys = Discover::TABLE_TO_ID[typ].keys kys = attrs[typ] next if not kys hsh = extract_row(kys, r) evt = nil if Discover.step?(typ) evt = PdjStep.new(hsh, typ, r[pos_name]) elsif Discover.milestone?(typ) evt = PdjMilestone.new(hsh, typ, r[pos_name]) else evt = nil $LOG.error "Journey::extract_events, unknown type #{typ}" if $LOG next end if evt evt.pdj = self @types[typ] << evt end end adjust_positions() end end <file_sep>/lib/opt_parser.rb require 'optparse' class Option_Parser attr_accessor :options # Init the parser with the options to call def initialize(options, tact_opps = false) optparse = OptionParser.new do |opts| opts.on("-c", "--caption <STRING>", "Use provided string as caption for PDJ-Map") do |c| options[:c] = c end opts.on("-h", "--help", "Print this help") do |h| puts opts exit 0 end opts.on("-i", "--config <file-name>", String, "INI Configuration file", String) do |dbs| options[:i] = dbs end opts.on("-p", "--print_ini", "Print configuration file to resulting PDJ-Map") do |p| options[:p] = true end opts.on("-v", "--version", "Print program version and exit") do |v| puts VERSION.to_s exit 0 end opts.on("-l <level>", "--log_level <level>", String, "Level can be [DEBUG | INFO | WARNING | ERROR]. Default is WARNING", String) do |l| options[:l] = l end # <--- If we remove the possibility to set the table from the command line this block can be removed. The table will be configurable through the config only opts.on("-e", "--event_table <table name>", String, "Table from which to read events.") do |e| options[:e] = e end # ---> # <--- If we remove the possibility to set the output prefix from the command line this block can be removed. The output prefix will be configurable through the config only opts.on("-o", "--output_prefix <prefix>", String, "Prefix to use for graphics output to file system.") do |o| options[:o] = o end # ---> # Regular PDJM generation if (! tact_opps) # <--- If we remove the possibility to set the number_of_results from the command line this block can be removed. The number_of_results will be configurable through the config only opts.on("-n <n>", "--number_of_results <n>", Numeric, "How many PDJ-Maps to produce") do |n| options[:n] = n end # ---> # <--- If we remove the possibility to set the dynamic segmentation mode from the command line this block can be removed. The dynamic segmentation mode will be configurable through the config only opts.on("--ds <skip|stop> ", String, "Skip dynamic segmentation, respectivly stop DAE after dynamic segmentation") do |ds| options[:ds] = ds end # ---> end # Tactical opps if (tact_opps) then opts.on("-m <mode>", "--mode <mode>", String, "Mode can be [defection | acquisition]", String) do |mode| options[:m] = mode end end end optparse.parse! end # Check whether the options that are available make sense from a functional perspective # for the DAE def check_options(opts) # Check for database if not opts[:i] or opts[:i].length < 2 $LOG.error "Main::check_options: No config file provided! Aborting!" exit 1 end if not File.exists?(opts[:i]) $LOG.error "Main::check_options: Configuration file <#{opts[:i]}> does not exist! Aborting!" exit 1 end # <--- If we remove the possibility to set the dynamic segmentation mode from the command line this block can be removed. The dynamic segmentation mode will be configurable through the config only ds = opts[:ds] if ds if ds != "skip" and ds != "stop" msg = "Main::check_options: Unknown argument <#{ds}> for --ds. " msg += "Arguments for --ds can only be <skip> or <stop>" $LOG.error msg exit 1 end end # ---> mode = opts[:m] if mode if mode != "acquisition" and mode != "defection" msg = "Main::check_options: Unknown argument <#{mode}> for --mode. " msg += "Arguments for --mode can only be <acquisition> or <defection>" $LOG.error msg exit 1 end end # <--- If we remove the possibility to set the number_of_results from the command line this block can be removed. The number_of_results will be configurable through the config only nof_res = opts[:n] if nof_res if nof_res < 1 msg = "Main::check_options, -n option needs a positive number as argument. " msg += "Provided argument was: #{nof_res}" $LOG.error msg end end # ---> end end <file_sep>/lib/retention.rb require_relative 'ai4r/proximity' module Discover def extract_acquisition(ret, segs, acq_thrshld, mode = "single") if (segs.length() > 1) $LOG.error("Tactical opps is not working if more than one statice segment is provided! ") exit 1 end $LOG.info "Retention::extract_acquisition, acquisition distance threshold: #{acq_thrshld}" $LOG.info "Retention::extract_acquisition, classifying journeys according to: #{mode}" # Acquisition gets id 2, defection - called in individual method below - get 1 - just for init reasons acqu = Segment.new(2) ac_ary = nil # Get the one static segment to be processed s = segs[0] # Check for each rpdj how similar it is to ALL PDJs in the original set of PDJs ret.each do |rpdj| # Lookup arrays describing whether a similarity condition is met ac_ary = Array.new(s.length, nil) # Set info for distance calculation for retention PDJs, all other values are # filled using the database rpdj.static_segment.nec_chars = s.nec_chars rpdj.static_segment.enc_map = s.enc_map rpdj.static_segment.attributes = s.attributes # Set swap window, in this case alignment is executed properly rpdj.static_segment.swap_window = s.swap_window s.each_with_index do |pdj, idx| ed = Data::Proximity::edit_distance(pdj, rpdj) similarity = 1-ed if similarity <= acq_thrshld ac_ary[idx] = pdj.user_id end end if mode == "complete" if (ac_ary.all? {|x| x}) rpdj.tactical_opps = "acquisition" acqu << rpdj end elsif mode == "single" if (ac_ary.any? {|x| x}) rpdj.tactical_opps = "acquisition" acqu << rpdj end end end pre_de_length = acqu.length acqu.uniq! post_de_length = acqu.length if not pre_de_length == post_de_length $LOG.error("Retention::extract_acquisition, uniqueness error in acquisition calculation") end msg = "Retention::extract_acquisition, extracted #{acqu.length} " msg += "acquisition journeys" $LOG.info(msg) acqu.each do |pdj| pdj.dyn_segment = acqu end return acqu end # ATTENTION: All PDJs brand / non-brand etc must be stored in the same table!!! # param:: ret - buyers of other brands (as defined in the retention table) # param:: segs - buyers of own brand, must be given in ONE static segment # def extract_defection(ret, segs, def_thrshld, mode = "single") if (segs.length() > 1) $LOG.error("Tactical opps is not working if more than one statice segment is provided! ") exit 1 end $LOG.info "Retention::extract_def_acq, defection distance threshold: #{def_thrshld}" $LOG.info "Retention::extract_def_acq, classifying journeys according to: #{mode}" # Defection gets id 1, acquistion - calleed as individual method above - gets 2 - just for init reasons defe = Segment.new(1) de_ary = nil # Get the one static segment to be processed s = segs[0] # Check for each rpdj how similar it is to ALL PDJs in the original set of PDJs ret.each do |rpdj| # Lookup arrays describing whether a similarity condition is met de_ary = Array.new(s.length, nil) # Set info for distance calculation for retention PDJs, all other values are # filled using the database rpdj.static_segment.nec_chars = s.nec_chars rpdj.static_segment.enc_map = s.enc_map rpdj.static_segment.attributes = s.attributes # Set swap window, in this case alignment is executed properly rpdj.static_segment.swap_window = s.swap_window s.each_with_index do |pdj, idx| ed = Data::Proximity::edit_distance(pdj, rpdj) similarity = 1-ed if similarity >= def_thrshld de_ary[idx] = pdj.user_id end end if mode == "complete" if (de_ary.all? {|x| x}) rpdj.tactical_opps = "defection" defe << rpdj #next # PDJ can only be assigned to defection or acquisition cluster end elsif mode == "single" if (de_ary.any? {|x| x}) rpdj.tactical_opps = "defection" defe << rpdj #next # PDJ can only be assigned to defection or acquisition cluster end end pre_de_length = defe.length defe.uniq! post_de_length = defe.length if not pre_de_length == post_de_length $LOG.error("Retention::extract_defection, uniqueness error in defection calculation") end msg = "Retention::extract_defection, extracted #{defe.length} " msg += "defection journeys" $LOG.info(msg) defe.each do |pdj| pdj.dyn_segment = defe end return defe end end def get_table_name(sql) return nil if not sql or sql.length == 0 ary = sql.downcase.split(/\s/) return nil if not ary idx = ary.index("from") return nil if not idx return nil if not ary.length >= idx+1 ary[idx + 1] end end <file_sep>/lib/static_segment.rb require_relative "constants" require_relative "pdj" require_relative "pdj_step" require_relative "pdj_milestone" require_relative "segment" module Discover def self.extract_static_segment(db, sgmt_query, sgmt_id, attrs) rows = [] clmn_names = attrs.values().flatten().uniq() # Columns needed by the AE. clmn_names << Discover::ALGORITHM_COLUMNS[:user_id] clmn_names << Discover::ALGORITHM_COLUMNS[:event_type] clmn_names << Discover::ALGORITHM_COLUMNS[:jrn_position] clmn_names << Discover::ALGORITHM_COLUMNS[:importance] clmn_names.uniq! if not sgmt_query or sgmt_query.length < 2 qry = "SELECT * FROM objects" else qry = sgmt_query.dup end rows = [] db_res = db.execute(qry) db_res.each do |r| res = extract_row(clmn_names, r) rows << res end if rows.size > 0 msg = "StaticSegment::extract_segment, extracted #{rows.size} rows" msg += " for segment id: #{sgmt_id}" $LOG.info msg if $LOG return extract_pdjs(rows, sgmt_id, attrs) else msg = "StaticSegment::extract_segment, extracted #{rows.size} rows" msg += " for segment id: #{sgmt_id}, nothing to do here" $LOG.warn msg if $LOG return nil end end private def get_user_events(rows) user_id = Discover::ALGORITHM_COLUMNS[:user_id] user_events = {} rows.each do |r| #id = r["user_id"].to_i id = r[user_id] if not user_events[id] user_events[id] = [] end user_events[id] << r end user_events end def extract_pdjs(rows, sgmt_id, attrs) sgmt = Segment.new(sgmt_id) user_events = get_user_events(rows) pos_name = Discover::ALGORITHM_COLUMNS[:jrn_position] type_name = Discover::ALGORITHM_COLUMNS[:event_type] user_events.each_pair do |uid, events| pdj = Pdj.new(uid, events, sgmt, attrs, pos_name, type_name) sgmt << pdj end msg = "StaticSegment::extract_segment, extracted #{sgmt.length} " msg += "journeys for segment id: #{sgmt_id}" $LOG.info msg if $LOG return sgmt end def extract_row(kys, row) res = {} kys.each do |k| res[k] = row[k] end res end end <file_sep>/lib/graph.rb class Graph attr_accessor :nof_nodes, :nodes, :adjacency_matrix # Calculate entropy of the whole graph def get_entropy end # Calculate graph entropy without step s def get_entropy(s) end # Add a step def add_step(s) end # Add a step and connect it with another step def add_step(s1, s2) end # Connect two steps def connect(s1, s2) end # Delete Step def delete_step(s) end # Check if two steps are connected def is_connected(s1, s2) end # Print important aspect of the graph def to_str end end <file_sep>/lib/database/sqlite3_connect.rb require 'sqlite3' require 'logger' def connect_db(sqlite3) db = nil begin db = SQLite3::Database.open(sqlite3) db.results_as_hash = true # A boolean that indicates whether rows in # result sets should be returned as hashes or not db.integrity_check rescue Exception => e $LOG.error "Could not open SQLite3 database <#{sqlite3}>." $LOG.error " Please check that this file is a valid SQLite3 database file." $LOG.error " Exception message:" $LOG.error e exit 1 end db end def close_db(db) return if not db begin db.close rescue SQLite3::BusyException => e ; end end def clean_results_in_event_table(db, tbl_name) # clean the ALL the res_ columns and VACUUM the db # useful before MD5 and/or updating the results columns = Discover::ALGORITHM_COLUMNS.values.keep_if {|x| x.start_with?("res_")} qry = "UPDATE #{tbl_name} SET " columns.each do |col| qry += "#{col} = null, " end qry = qry[0...-2] #Chomps last comma and space db.execute(qry) db.execute("VACUUM") end def clean_tables(db, tbl_name, del_results = false) # <--- begin block: Manage the initialization from an already existing _orig table or the creation of a backup in the _orig table. This block will probably be removed as there is no need to manage a backup within the AE orig_tbl = tbl_name + "_orig" if Discover.tbl_exists?(db, orig_tbl) qry = "DROP TABLE IF EXISTS #{tbl_name}" db.execute(qry) else qry = "CREATE TABLE #{orig_tbl} AS SELECT * FROM #{tbl_name}" db.execute(qry) return end qry = "CREATE TABLE #{tbl_name} AS SELECT * FROM #{orig_tbl}" db.execute(qry) # :end block ---> # <--- begin block: The cleaning should depend on the entry_point once the staged approach is implemented if del_results # Clean results table qry = "DELETE FROM results" db.execute(qry) end # Set all algo columns to -1 columns = Discover::ALGORITHM_COLUMNS.values.keep_if {|x| x.start_with?("res_")} qry_prfx = "UPDATE #{tbl_name} SET " columns.each do |c| qry = qry_prfx + c + " = -1" # Set all res_ columns to -1 db.execute(qry) end # Reset the dat_segment_id qry = "UPDATE #{tbl_name} SET #{Discover::ALGORITHM_COLUMNS[:segment_id]} = -1" db.execute(qry) # :end block ---> end def write_static_segments(db, segments, evt_tbl) $LOG.info("sqlite3_connect::write_static_segments, writing static_segment ids to db") stmt1 = "UPDATE #{evt_tbl} " stmt1 += "SET #{Discover::ALGORITHM_COLUMNS[:segment_id]} = " stmt2 = "WHERE #{Discover::ALGORITHM_COLUMNS[:user_id]} = " db.transaction() segments.each do |s| s.each do |pdj| qry = stmt1 + s.segment_id.to_s + " " + stmt2 + "\"" + pdj.user_id + "\"" if $LOG.debug?() msg = "sqlite3_connect::write_static_segments, SQL query: " + qry $LOG.debug(msg) end db.execute(qry) end end db.commit() # ends the transaction end # Returns array - [Array of PDJs, name of the segment table in the db] def extract_retention(db, attrs, evt_tbl_name) retention_segment = [] stmt = "SELECT dat_id, dat_sql FROM comparison_segment" rows = db.execute(stmt) rows.each do |r| sgmt_query = r["dat_sql"] sgmt_query_s = sgmt_query.split(/\s/).map! {|x| x.downcase} tbl_name_idx = sgmt_query_s.index("from") + 1 sgmt_query_s[tbl_name_idx] = evt_tbl_name sgmt_query = sgmt_query_s.join(" ") sgmt_id = r["dat_id"] $LOG.debug "Extracting comparision segment with query: #{sgmt_query}" tmp = [] tmp << Discover.extract_static_segment(db, sgmt_query, sgmt_id, attrs) tmp << Discover.get_table_name(sgmt_query) retention_segment = tmp end retention_segment end # DEPRECATED: The version check is now executed via the Frontend not the DAE. The method # is still kept in case this might change in the future. def check_for_version(db, ini) version = nil version_table = nil version_column = nil if ini["version_check"] and ini["version_check"]["version"] version = ini["version_check"]["version"] end if ini["version_check"] and ini["version_check"]["table"] version_table = ini["version_check"]["table"] end if ini["version_check"] and ini["version_check"]["column"] version_column = ini["version_check"]["column"] end if version and version_table and version_column msg = "dc::main, checking whether verion in table #{version_table}, " msg += "column #{version_column} is #{version}" $LOG.info(msg) qry = "SELECT #{version_column} " qry += "FROM #{version_table}" res = nil begin db.execute(qry) do |row| res = row[version_column] end rescue SQLite3::SQLException => e msg = "****************************************************************" $LOG.error(msg) msg = "* DC::MAIN, CANNOT EXTRACT VERSION INFORMATION WITH SQL " msg += "STATEMENT:" $LOG.error(msg) $LOG.error(" " + qry) msg = "* DC::MAIN, COULD IT BE, THAT TABLE #{version_table} OR COLUMN " msg += "#{version_column} DOES NOT EXISTS?" $LOG.error(msg) msg = "* DC::MAIN, ABORTING" $LOG.error(msg) msg = "*******************************************************************" $LOG.error(msg) exit 1 end if not res == version msg = "dc::main, version provided in INI: #{version} and version in " msg += "DB: #{res} don't match!" $LOG.error(msg) $LOG.error("Aborting") exit 1 else msg = " Version is okay" $LOG.info(msg) end else msg = "*******************************************************************" $LOG.warn(msg) msg = "* DC::MAIN, CANNOT FIND VERSION INFORMATION IN INI FILE." $LOG.warn(msg) msg = "* DC::MAIN, WILL CONTINUE WITH PROGRAM BUT EXPECT STRANGE BEHAVIOUR." $LOG.warn(msg) msg = "* DC::MAIN, YOU HAVE BEEN WARNED." $LOG.warn(msg) msg = "*******************************************************************" $LOG.warn(msg) end end def check_columns(db, event_tbl_name, attrs) not_present = Discover.check_if_all_attributes_are_present_in_db(db, event_tbl_name, attrs.values().flatten().uniq()) not_present.each do |col_name| msg = "sqlite3_connect::column_name_check, provided DB does not have column: " msg += "#{col_name}!" $LOG.error(msg) msg = " Please check correct column name in configuration file or DB" $LOG.error(msg) exit 1 end not_present = Discover.check_if_all_attributes_are_present_in_db(db, event_tbl_name, Discover::ALGORITHM_COLUMNS.values()) not_present.each do |col_name| msg = "sqlite3_connect::column_name_check, provided DB does not have for the algorithm necessary column: " msg += "#{col_name}!" $LOG.error(msg) msg = " Please check correct column name in configuration file or DB" $LOG.error(msg) exit 1 end end def get_visualisation_attributes(ini) attrs = {} pr_fx = "" if ini["global"] and ini["global"]["attribute_prefix"] pr_fx = ini["global"]["attribute_prefix"] end if ini["visualisation"] pst_fix = "_text_attribute" ini["visualisation"].each_pair do |key, name| if key.end_with?(pst_fix) attr_name = key[0...key.length-pst_fix.length] ms_id = Discover.get_id_to_name(attr_name) if not attrs[ms_id] attrs[ms_id] = Array.new() end next if not ms_id if not name or name.length == 0 attrs[ms_id] = nil next end # in case of more than one specified attribute we need to add global prefix for all name_array = name.split(",") name_array.collect!(&:strip) attrs[ms_id] = name_array.each{ |a| a.prepend(pr_fx) } end end end attrs end # Write PDJM to db, juset call write BPM internally, log msg is trigger via parameter def write_pdjm_ids_to_db(bpm, db, evt_tbl) write_bpm_ids_to_db(bpm, db, evt_tbl, true) end def write_bpm_ids_to_db(bpm, db, evt_tbl, pdjm = false) msg = "" if pdjm msg = "sqlite3_connect::write_pdjm_ids_to_db, writing PDJM " else msg = "sqlite3_connect::write_bpm_ids_to_db, writing BPM " end msg += "ids to db" $LOG.info(msg) stmt = "UPDATE #{evt_tbl} SET " if pdjm stmt += "pdjm_id " else stmt += "bpm_id " end stmt += "= ? WHERE user_id = ?" db.transaction() bpm.each_with_index do |b, idx| next if not b b.node_arry.each_with_index do |nd, nidx| nd.pdj_events.each do |evt| stmt = "" if pdjm stmt = "UPDATE #{evt_tbl} " stmt += "SET #{Discover::ALGORITHM_COLUMNS[:pdjm_id]} = #{nd.id} " stmt += " WHERE #{Discover::ALGORITHM_COLUMNS[:user_id]} = " stmt += "\"#{evt.pdj.user_id}\" AND " stmt += "#{Discover::ALGORITHM_COLUMNS[:jrn_position]} = " stmt += evt.orig_pos.to_s if (pdjm == true) $LOG.debug "sqlite3_connect::write_pdjm_ids_to_db (PDJM_node_id), SQL: #{stmt}" else $LOG.debug "sqlite3_connect::write_bpm_ids_to_db (PDJM_node_id), SQL: #{stmt}" end db.execute(stmt) stmt = "UPDATE #{evt_tbl} " stmt += "SET #{Discover::ALGORITHM_COLUMNS[:chunk_id]} = #{nd.chunk_id} " stmt += " WHERE #{Discover::ALGORITHM_COLUMNS[:user_id]} = " stmt += "\"#{evt.pdj.user_id}\" AND " stmt += "#{Discover::ALGORITHM_COLUMNS[:jrn_position]} = " stmt += evt.orig_pos.to_s if (pdjm == true) $LOG.debug "sqlite3_connect::write_pdjm_ids_to_db (pdjm_chunk_id), SQL: #{stmt}" else $LOG.debug "sqlite3_connect:write_bpm_ids_to_db (pdjm_chunk_id), SQL: #{stmt}" end db.execute(stmt) else stmt = "UPDATE #{evt_tbl} " stmt += "SET #{Discover::ALGORITHM_COLUMNS[:bpm_id]} = #{nd.id} " stmt += "WHERE #{Discover::ALGORITHM_COLUMNS[:user_id]} = " stmt += "\"#{evt.pdj.user_id}\" AND " stmt += "#{Discover::ALGORITHM_COLUMNS[:jrn_position]} = " stmt += evt.orig_pos.to_s if (pdjm == true) $LOG.debug "sqlite3_connect::write_pdjm_ids_to_db (bpm_id), SQL: #{stmt}" else $LOG.debug "sqlite3_connect::write_bpm_ids_to_db (bpm_id), SQL: #{stmt}" end db.execute(stmt) end end end end db.commit() end def extract_static_segments(db, attrs, event_tbl_name) segments = [] stmt = "SELECT dat_id, dat_sql FROM segments" rows = db.execute(stmt) rows.each do |r| sgmt_query = r["dat_sql"] sgmt_query_s = sgmt_query.split(/\s/).map! {|x| x.downcase} tbl_name_idx = sgmt_query_s.index("from") + 1 sgmt_query_s[tbl_name_idx] = event_tbl_name sgmt_query = sgmt_query_s.join(" ") sgmt_id = r["dat_id"] $LOG.debug "Extracting static segments with query: #{sgmt_query}" #ss = StaticSegment.new(db, sgmt_query, sgmt_id) ss = Discover.extract_static_segment(db, sgmt_query, sgmt_id, attrs) segments << ss if ss end segments end def get_attrbutes(ini, segment) attrs = {} Discover::EVENT_TYPE_ARRAY.each do |t| @attrs[t] = ini[segment] end end <file_sep>/lib/dynamic_segmenter.rb require_relative './ai4r/ai4r' require_relative './ai4r/single_linkage' require_relative './ai4r/data_set' require_relative './serialiser_tools' include Ai4r::Clusterers include Ai4r::Data module Discover def self.extract_dynamic_segments(static_segment, distance_fct, nec_chars, db, ini) data = [] #max_journey_length = 0 similarity = ini["dynamic_segment"]["cluster_similarity_threshold"].to_f swap_window = ini["dynamic_segment"]["swap_window"].to_i msg = "DynamicSegmenter, calculating clusters for segment id: " msg += "#{static_segment.segment_id}" $LOG.info msg static_segment.attributes = ini.get_dynamic_segment_attributes static_segment.swap_window = swap_window if $LOG.warn? print_attributes(ini) end # 2-pass approach. est = ini["dynamic_segment"]["event_similarity_threshold"] if est and est.to_i >= 0 attrs = ini.get_dynamic_segment_attributes() $LOG.info "DynamicSegmenter, consolidating events that have #{est} attributes in common" pa = ini.get_dynamic_segment_protected_attributes pa.each_pair do |k, v| next if not v msg = " -> Protected attributes for <#{Discover::ID_EVENT_MAP[k]}>: {#{v.join(', ')}}" $LOG.info msg end Discover::consolidate_events(static_segment, attrs, est.to_i, pa) $LOG.info " -> Substituted #{static_segment.substitutes} events" $LOG.info " -> Unchanged #{static_segment.unchanged} events" end # clusterer is a class object from the AI4R library of either single_linkage or complete_linkage type, with the appropriate methods defined clusterer = set_cluster_method(ini) print_cluster_histogram = ini["dynamic_segment"]["print_cluster_histogram"] if print_cluster_histogram and (print_cluster_histogram.downcase == "true" or print_cluster_histogram == "1") clusterer.print_cluster_histogram = true end set_edit_distance_costs(ini) Proximity::set_blockdistance_blocksize(nec_chars + 1) msg = "DynamicSegmenter::segmenter, setting block size to " msg += "#{Proximity::get_blockdistance_blocksize}" $LOG.info msg msg = "DynamicSegmenter::segmenter, starting to cluster, cluster " msg += "similarity #{similarity}" $LOG.debug msg # <--- This is related to the test mode which writes the output of multiple runs to the stdout # If configured, make several cluster runs with different cluster distance # thresholds. sr = ini["dynamic_segment"]["cluster_test_runs_similarity"] if sr se = sr.split(",").map {|x| x.to_f } distance_runs(se[0], se[1], 0.1, clusterer, static_segment) end # ---> # Start actual clustering msg = "DynamicSegmenter::segmenter, starting to cluster, swap " msg += "window #{static_segment.swap_window}" $LOG.debug msg clusterer.build(DataSet.new(:data_items => static_segment), 1.0 - similarity) $LOG.debug "DynamicSegmenter::segmenter, finished clustering" # clusterer is the class object from which we must extract the dsDump.results data nof_cluster = clusterer.get_number_of_clusters() msg = "DynamicSegmenter::segmenter: got #{nof_cluster} clusters" msg += " with element similarity: #{similarity}" $LOG.info msg segs = extract_segments(clusterer, static_segment) msg = "DynamicSegmenter::segmenter, similarity histogram, 0.05 steps:\n" msg += "#{Proximity::get_histogram.join(", ")}" $LOG.info msg #$LOG.info "DynamicSegmenter::segmenter, updateing DB with DS information" #update_db(db, segs) if est and est.to_i >= 0 static_segment.clear_surrogates() end segs end def update_db_with_dynamic_segment_ids(db, seg, tbl_name) msg = "DynamicSegmenter::update_db_with_dynamic_segment_ids, " msg += "writing dynamic segment informaiton to db" $LOG.debug(msg) pre = "UPDATE #{tbl_name} SET " pre += "#{Discover::ALGORITHM_COLUMNS[:dynamic_segment_id]} = " pst = " WHERE #{Discover::ALGORITHM_COLUMNS[:user_id]} = " db.transaction() msg = "DynamicSegmenter::update_db_with_dynamic_segment_ids, " msg += "SQL statement: " seg.each_with_index do |val, index| val.each do |pdj| stmt = pre + pdj.dyn_segment.segment_id.to_s + pst + "\"" + pdj.user_id.to_s + "\"" $LOG.debug(msg + stmt) db.execute(stmt) end end db.commit() msg = "DynamicSegmenter::update_db_with_dynamic_segment_ids, " msg += "finished writing dynamic segment informaiton to db" $LOG.debug(msg) end def update_db_with_tactical_opps(db, seg, tbl_name) msg = "DynamicSegmenter::update_db_with_tactical_opps, " msg += "writing tactical opp informaiton to db" $LOG.debug(msg) pre = "UPDATE #{tbl_name} SET " pre += "#{Discover::ALGORITHM_COLUMNS[:tactical_opps]} = " pst = " WHERE #{Discover::ALGORITHM_COLUMNS[:user_id]} = " db.transaction() msg = "DynamicSegmenter::update_db_with_tactical_opps, " msg += "SQL statement: " seg.each_with_index do |val, index| val.each do |pdj| stmt = pre + "\"" + pdj.tactical_opps + "\"" + pst + "\"" + pdj.user_id.to_s + "\"" $LOG.debug(msg + stmt) db.execute(stmt) end end db.commit() msg = "DynamicSegmenter::update_db_with_tactical_opps, " msg += "finished writing tactical opp informaiton to db" $LOG.debug(msg) end def set_cluster_method(ini) cluster_method = "complete_linkage" cm = ini["dynamic_segment"]["cluster_method"] clusterer = nil clstMsg = "DynamicSegmenter::segmenter, using cluster method " if cm if cm == "complete_linkage" clstMsg += "Complete Linkage" clusterer = Ai4r::Clusterers::CompleteLinkage.new elsif cm == "single_linkage" clstMsg += "Single Linkage" clusterer = Ai4r::Clusterers::SingleLinkage.new else msg = "DynamicSegmenter::segmenter, unknown cluster method #{cm}, " msg += "defaulting to Complete Linkage" clstMsg += "Complete Linkage" $LOG.warn msg clusterer = Ai4r::Clusterers::CompleteLinkage.new end else clusterer = Ai4r::Clusterers::CompleteLinkage.new clstMsg += "Complete Linkage" end $LOG.info clstMsg clusterer end private def set_edit_distance_costs(ini) # Setting edit distance costs, start ed_insert = 1 ed_delete = 1 ed_subsitute = 1 if ini["dynamic_segment"]["edit_distance_cost_insert"] ed_insert = ini["dynamic_segment"]["edit_distance_cost_insert"].to_f end if ini["dynamic_segment"]["edit_distance_cost_delete"] ed_delete = ini["dynamic_segment"]["edit_distance_cost_delete"].to_f end if ini["dynamic_segment"]["edit_distance_cost_substitute"] ed_subsitute = ini["dynamic_segment"]["edit_distance_cost_substitute"].to_f end Proximity::set_editdistance_insert(ed_insert) res = Proximity::get_editdistance_insert $LOG.debug "DynamicSegmenter::segmenter, setting edit costs for insert to #{res}" Proximity::set_editdistance_delete(ed_delete) res = Proximity::get_editdistance_delete $LOG.debug "DynamicSegmenter::segmenter, setting edit costs for delete to #{res}" Proximity::set_editdistance_substitute(ed_subsitute) res = Proximity::get_editdistance_substitute $LOG.debug "DynamicSegmenter::segmenter, setting edit costs for substitute to #{res}" # Setting edit distance costs, end end def print_attributes(ini) ini.get_dynamic_segment_attributes.each_pair do |k, v| msg = "DynamicSegmenter::segmenter, using for " msg += "<#{Discover::ID_EVENT_MAP[k]}> attributes {#{v.join(', ')}}" $LOG.debug msg end end # <--- This code is responsible for the test runs with different thresholds def distance_runs(s, e, stp, clusterer, sgmnt) $LOG.info "Performing cluster runs from #{s} to #{e} similarity in #{stp} steps" (s..e).step(stp) do |i| $LOG.info(" -> Starting to cluster with similarity threshold: #{i.round(1)}") clusterer.build(DataSet.new(:data_items => sgmnt), 1.0 - (i)) end clusterer.init_stats_matrix end # ---> def test_distance_matrices(sgmnt, sw=2) sgmnt.swap_window = 0 $LOG.debug ">>> Calculating distance matrix without swap window" clstr_sw0 = Ai4r::Clusterers::CompleteLinkage.new clstr_sw0.create_distance_matrix(DataSet.new(:data_items => sgmnt)) sgmnt.swap_window = sw $LOG.debug ">>> Calculating distance matrix with swap window" clstr_sw2 = Ai4r::Clusterers::CompleteLinkage.new clstr_sw2.create_distance_matrix(DataSet.new(:data_items => sgmnt)) $LOG.debug ">>> Finished calculations" mtrx1 = clstr_sw0.distance_matrix mtrx2 = clstr_sw2.distance_matrix error = 0 comps = 0 greater = 0 equal = 0 mtrx1.each_with_index do |row, i| row.each_with_index do |ele, j| comps += 1 if mtrx1[i][j] < mtrx2[i][j] #puts "****************** ERROR" #puts "swap0 dist: #{mtrx1[i][j]}, swap2 dist: #{mtrx2[i][j]}" error += 1 elsif mtrx1[i][j] > mtrx2[i][j] greater += 1 else equal += 1 end end end puts "Found #{error} smaller, greater: #{greater}, equal: #{equal} in #{comps} comaprisons" exit 1 end def extract_segments(clusters, seg) id = 1 res = [] clusters.index_clusters.each do |c| dyn_sgmnt = Segment.new(-1) dyn_sgmnt.nec_chars = seg.nec_chars id += 1 c.each do |j| evt = seg[j] evt.dyn_segment = dyn_sgmnt dyn_sgmnt << evt end res << dyn_sgmnt end res end end <file_sep>/lib/mtx.rb require 'matrix' class Matrix def set(i, j, x) @rows[i][j] = x end def dcpy() Matrix.build(self.row_size){|r, c| self[r, c]} end end class Mtx attr_accessor :rows attr_reader :nof_rows, :nof_cols def initialize(r = 0, c = 0, ele = nil) @nof_rows = r @nof_cols = c @rows = Array.new(r) @rows.each_with_index do |r, idx| @rows[idx] = Array.new(c, ele) end end def dcpy() res = Mtx.new(@nof_rows, @nof_cols) @rows.each_with_index do |row, idx1| row.each_with_index do |col, idx2| res.set(idx1, idx2, @rows[idx1][idx2]) end end res end def self.from_matrix(matrix) res = Mtx.new(matrix.row_size, matrix.column_size) matrix.each_with_index do |ele, row, col| res.set(row, col, ele) end res end def self.from_arrays(arrays) res = Mtx.new(arrays.length, arrays[0].length) arrays.each_with_index do |ary, idx| res.rows[idx] = ary.clone() end res end def [](i) @rows[i] end def transpose @rows.transpose end def get_row(i) @rows[i] end def get_col(i) res = Array.new(nof_cols) j = 0 @rows.each do |r| res[j] = r[i] j += 1 end res end def set(i, j, x) @rows[i][j] = x end def to_s res = "" @rows.each_with_index do |r, idx| dx = "" if idx < 10 dx = " " + idx.to_s else dx = idx.to_s end res += dx + ": [" + r.join(", ") + "]\n" end res end def self.zero(r = 0, c = 0) Mtx.new(r, c, 0) end def to_ary @rows end def ==(other) return false if not @nof_rows == other.nof_rows return false if not @nof_cols == other.nof_cols @rows.each_with_index do |row, idx| return false if not row == other[idx] end return true end end <file_sep>/lib/bpm.rb require_relative "bpm_node" require_relative "constants" require_relative "dswap" require_relative "graph" require_relative "swap" require_relative "serialiser_tools" require_relative "tools" require_relative 'ai4r/data_set' class Bpm < Graph attr_accessor :segment # typs_pos is an array of arrays that manages BPM-Nodes by type and position. # type is the first and position the second dimension. The third dimension is # an array of BPM-Nodes with the corresponding type and pos. # To iterate over all CONSIDERING_STEP pdj_events at position 3 (i.e. all # considering steps that happend as third event in a journey) one could use: # @typs_pos[CONSIDERING_STEP][3].each do |node| # node.pdj_event.each do |evt| # puts "Considering step at position 3: #{evt}" # end # end # Note: This is only intended for the build up phase to have easy access to # the different phases. attr_accessor :typs_pos # Attributes used for BPM generation. attr_accessor :attrs # All pdj_events of a certain position in a journey are stored in the # corresponding pos array attr_accessor :pos # Start nodes for BPM. # This very likely will be bpm_nodes with trigger events. attr_accessor :start_nodes # All nodes stored in an array where the node_id is the index. # This allows for an easy iteration of all BPM-Nodes in a BPM. # Note: The order is given ONLY by the BPM-Node id, this means for example # one cannot imply the type from the posiiton in the array. attr_accessor :node_arry # Contains the connectivity matrix. # If two nodes of this bpm are connected by a path, the corresponding entry # in the connectivity matrix is 1, otherwise 0 #attr_reader :con_mtx # This array will contain the node ids in topological order. # This means if a Bpm-Node A happens before B in the BPM, the id of event # will be in the top_srt before the id of B. # Note1: This array WILL NOT be computed automatically. One need to call the # function bpm_topological_sort(bpm) from tools.rb # Note2: The resulting order only makes assumption about the topological order # not about the position. # Note3: If a function changed the structure of a BPM, the function needs to # compute a new topological array if one was set. attr_accessor :top_srt # Topological distance matrix. # This matrix contains the minimal distance between two arbitrary nodes in # the BPM. # Note1: This matrix WILL NOT be computed automatically. To fill this matrix # the function calc_dist_mtx(adj_mtx) from tools.rb needs to be called. # Note2: If a function changed the structure of a BPM, the function needs to # compute a new distance matrix if one was set. attr_accessor :dst_mtx # save count for all manifestations of node attributes attr_accessor :attrs_cnt # get chunks attr_accessor :chunks attr_accessor :stmt_colmn attr_accessor :nonsignificant, :significant def initialize(segment, ini, db = nil, event_tbl_nme = nil) @segment = segment @pos = Array.new @ini = ini @attrs = {} if @ini @attrs = @ini.get_bpm_attributes end @event_count = 0 if @ini and @ini["bpm"] and @ini["bpm"]["swap_window"] @swap_window = Integer(@ini["bpm"]["swap_window"]) msg = "Bpm::initialize, using swap_window #{@swap_window} for BPM " msg += "generation" $LOG.info(msg) end @typs_pos = Array.new(Discover::EVENT_TYPE_ARRAY.length) Discover::JOURNEY_EVENT_ORDER.each do |t| @typs_pos[t] = [] end # The ID is used construction of a BPM node @bpm_node_id = 0 @prv_bpm_node = nil @sequence = Array.new @node_arry = Array.new #@con_mtx = nil @adj_mtx = nil @gvn = nil @top_srt = nil @dst_mtx = nil @max_imp = nil @chunks = nil @db = db @stmt_colmn = nil if ini and ini["bpm"]["node_text_attribute"] @stmt_colmn = ini["bpm"]["node_text_attribute"] end @nonsignificant = -1 if ini and ini["bpm"] and ini["bpm"]["nonsignificant"] @nonsignificant = ini["bpm"]["nonsignificant"].to_f end @significant = -1 if ini and ini["bpm"] and ini["bpm"]["significant"] @significant = ini["bpm"]["significant"].to_f end @event_tbl_nme = event_tbl_nme # try to read event table name from ini file, if not called with an specified name if not @event_tbl_nme and ini and ini["global"] and ini["global"]["event_table_name"] @event_tbl_nme = ini["global"]["event_table_name"] end # use event table name 'objects', if DAE not called with an specified name and no entry in config file @event_tbl_nme = "objects" if not @event_tbl_nme @prune = false if ini and ini["bpm"] and ini["bpm"]["prune"] pr = ini["bpm"]["prune"] @prune = (pr == "true" or pr == "1") end end def calc_bpm $LOG.debug "Bpm::calc_bpm for segment #{segment.segment_id}" # 2-pass approach. est = @ini["bpm"]["event_similarity_threshold"] if est and Integer(est) >= 0 attrs = @ini.get_bpm_attributes() mandatory_attrs = @ini.get_bpm_protected_attributes() $LOG.info "Bpm::calc_bpm, consolidating events that have #{est} attributes in common" ma = @ini.get_bpm_protected_attributes ma.each_pair do |k, v| next if not v or v.length < 1 msg = " -> Protected attributes for <#{Discover::ID_EVENT_MAP[k]}>: {#{v.join(', ')}}" $LOG.info msg end @segment.init_representative() @segment.clear_surrogates() consolidate_events(@segment, attrs, Integer(est), mandatory_attrs) $LOG.info " -> Substituted #{@segment.substitutes} events." $LOG.info " -> #{@segment.unchanged} events were not substituted." end optimise = nil if @ini["bpm"] and @ini["bpm"]["optimise"] optimise = @ini["bpm"]["optimise"].strip end if optimise # Check whether ini_avg_pdj is a boolen if !!optimise == optimise ; else if optimise.downcase == "none" optimise = nil elsif optimise.downcase == "average" optimise = :average elsif optimise.downcase == "global" optimise = :global end end end if optimise and @segment.length < 3 msg = "Bpm::calc_bpm, current segment has only #{@segment.length} " msg += "PDJs. Computing average journey does not make sense!" $LOG.warn(msg) msg = " Processing with default approach." $LOG.warn(msg) optimise = nil end dummy_gen_fct = lambda {|x| PdjEvent.get_dummy(x)} # Use average journey to swap all against this if optimise and optimise == :average require_relative 'dynamic_segmenter' dummy_gen_fct = lambda {|x| PdjEvent.get_dummy(x)} avg_pdj = nil # Get values necessary for encoding max_attr_vals = get_max_nof_attr_val(@db, @event_tbl_nme, @attrs) nec_chars = get_nof_nec_chars(max_attr_vals) enc_map = get_encoding_map(nec_chars) Ai4r::Data::Proximity.set_blockdistance_blocksize(nec_chars + 1) @segment.nec_chars = nec_chars @segment.enc_map = enc_map @segment.swap_window = @swap_window @segment.attributes = @attrs clusterer = set_cluster_method(@ini) avg_pdj_idx = compute_average_pdj(clusterer) avg_pdj = @segment[avg_pdj_idx] extract_nodes(avg_pdj) @segment.each_with_index do |pdj, idx| next if idx == avg_pdj_idx @prv_bpm_node = nil if @swap_window and @swap_window > 0 pdj = Discover.align_pdj(avg_pdj, pdj, @swap_window, @attrs, dummy_fct = dummy_gen_fct) end extract_nodes(pdj) end end if optimise and optimise == :global require_relative 'dynamic_segmenter' dummy_gen_fct = lambda {|x| PdjEvent.get_dummy(x)} avg_pdj = nil max_attr_vals = get_max_nof_attr_val(@db, @event_tbl_nme, @attrs) nec_chars = get_nof_nec_chars(max_attr_vals) enc_map = get_encoding_map(nec_chars) Ai4r::Data::Proximity.set_blockdistance_blocksize(nec_chars + 1) @segment.nec_chars = nec_chars @segment.enc_map = enc_map @segment.swap_window = @swap_window @segment.attributes = @attrs clusterer = set_cluster_method(@ini) avg_pdj_idx = compute_average_pdj(clusterer) avg_pdj = @segment[avg_pdj_idx] avg_pdj.static_segment.swap_window = 0 extract_nodes(avg_pdj) processed_pdjs = [] processed_pdjs << avg_pdj $LOG.debug("Bpm::calc_bpm, global_optimisation, starting to align journeys") tmp_seg = @segment.clone() tmp_seg.delete_at(avg_pdj_idx) Ai4r::Data::Proximity.set_dummy_dist(1) while not tmp_seg.empty?() res_pdj = nil res_pdj_idx = nil res_dist = -1 dist_array = [] dist = Float::INFINITY best_proc_pdj = nil orig_pdj = nil tmp_seg.each_with_index do |pdj, idx| align_pdj = nil # Needed for BPM build up @prv_bpm_node = nil processed_pdjs.each do |proc_pdj| cpdj = pdj.cpy() if @swap_window and @swap_window > 0 cpdj = Discover.align_pdj(proc_pdj, cpdj, @swap_window, @attrs, dummy_fct = dummy_gen_fct) end swap_window = 0 ndist = Ai4r::Data::Proximity.edit_distance(proc_pdj, cpdj, swap_window, nec_chars, enc_map, @attrs) dist_array << ndist if ndist < dist orig_pdj = pdj dist = ndist best_proc_pdj = proc_pdj res_dist = ndist res_pdj = cpdj res_pdj_idx = idx end end end if not dist_array.min == res_dist $LOG.error("BPM::build_bpm, min dist is not min dist") end #$LOG.debug("BPM::build_bpm, current best dist #{res_dist.round(4)}, #{tmp_seg.length-1} to go") extract_nodes(res_pdj) #res_pdj.strip_dummys() processed_pdjs << res_pdj tmp_seg.delete_at(res_pdj_idx) end end if not optimise # Use "normal" workflow. This means, sort journeys by length # descending and add journeys to bpm iteratively. If swap window is # provided, swap always against the previous journey. @sgmnt_sort = @segment.sort {|x, y| y.length <=> x.length} prev_pdj = nil @sgmnt_sort.each do |pdj| @prv_bpm_node = nil if @swap_window and prev_pdj and @swap_window > 0 #Discover.align_pdj(prev_pdj, pdj, @swap_window, @attrs, # dummy_fct = dummy_gen_fct) pdj = Discover.align_pdj(prev_pdj, pdj, @swap_window, @attrs, dummy_fct = dummy_gen_fct) end extract_nodes(pdj) prev_pdj = pdj end end if $LOG.debug? msg = "Bpm::calc_bpm, generated BPM with #{@bpm_node_id} " msg += "nodes for #{@event_count} events in #{@segment.length} pdjs" $LOG.debug(msg) end if @prune and @nonsignificant > 0 prune(@nonsignificant) end end def compute_average_pdj(clusterer) avg_pdj = nil msg = "Bpm::compute_average_pdj, starting to compute average pdj" $LOG.info(msg) if $LOG $LOG.debug("Bpm::compute_average_pdj, computing similarity matrix") if $LOG sw = segment.swap_window #segment.swap_window = 0 ds = Ai4r::Data::DataSet.new(:data_items => segment) clusterer.create_distance_matrix(ds) min_avg_dst = Float::INFINITY min_jrny_id = nil min_jrny_user_id = nil min_jrny_length = -1 ds.data_items.each_with_index do |d, idx| avg = clusterer.compute_average_distance(idx) if avg < min_avg_dst min_avg_dst = avg min_jrny_user_id = d.user_id min_jrny_id = idx min_jrny_length = d.length elsif avg == min_avg_dst and d.length > min_jrny_length min_avg_dst = avg min_jrny_user_id = d.user_id min_jrny_id = idx min_jrny_length = d.length end end msg = "Bpm::compute_average_pdj, finished computing average pdj" $LOG.info(msg) if $LOG msg = "Bpm::compute_average_pdj, min_avg_distance is #{min_avg_dst}, journey_id: #{min_jrny_id}, user_id: #{min_jrny_user_id}" $LOG.info(msg) if $LOG segment.swap_window = sw return min_jrny_id end def init_adj_mtx(n = nil) if not n n = @node_arry.length end @adj_mtx = Mtx.zero(n, n) end def calc_adj_mtx(directed = true, weighted = false, self_loops = false, direct_connection = true, ignore_milestones = false, ignore_ids = []) adj_mtx = init_adj_mtx() @node_arry.each do |node_1| row = node_1.id @node_arry.each do |node_2| col = node_2.id next if not self_loops and row == col weight = Discover.nof_jrnys_btw_nodes(@node_arry, row, col, direct_connection, ignore_milestones, ignore_ids) next if weight == 0 weight = 1 if not weighted adj_mtx[row][col] = weight if not directed and adj_mtx[col][row] == 0 adj_mtx[col][row] = weight end end end return adj_mtx end def extract_nodes(pdj) Discover::JOURNEY_EVENT_ORDER.each do |t| next if not pdj.types[t] pdj.types[t].each_with_index do |evt, rel_pos| add_event_by_type(evt, rel_pos) end end end def add_event_by_type(evt, rel_pos) @event_count += 1 typ = evt.type if evt.is_dummy?() return end if not @typs_pos[typ] @typs_pos[typ] = Array.new end if not @typs_pos[typ][rel_pos] @typs_pos[typ][rel_pos] = Array.new nn = BpmNode.new(@bpm_node_id, typ, evt, nil, self) @node_arry[@bpm_node_id] = nn @typs_pos[typ][rel_pos] << nn @bpm_node_id += 1 add_prv_nxt(nn) return end # No attributes for this attribute available # => all events go into the same node if @attrs[typ] and @attrs[typ].length < 1 @typs_pos[typ][0][0].add_pdj_event(evt) add_prv_nxt(@typs_pos[typ][0][0]) return end # Find most similar (i.e. equal) node for current event and attach event to # it max = 0 max_node = nil node = nil @typs_pos[typ][rel_pos].each do |n| next if not @attrs[typ] sim = n.similar(evt, @attrs[typ]) if sim == @attrs[typ].length node = n break end #if sim > max # max = sim # max_node = n #end end #if max_node # max_node.add_pdj_event(evt) # add_prv_nxt(max_node) if node node.add_pdj_event(evt) add_prv_nxt(node) else # No similar node was found. Create a new node with the current event as # first inhabitant nn = BpmNode.new(@bpm_node_id, typ, evt, nil, self) @node_arry[@bpm_node_id] = nn @bpm_node_id += 1 @typs_pos[typ][rel_pos] << nn add_prv_nxt(nn) end end def update_db end def calc_start_milestones() @node_arry.each do |n| n.calc_start_milestones() end end def calc_end_milestones @node_arry.each do |n| n.calc_end_milestones() end end =begin def add_event(evt) pos = evt.pos typ = evt.type if not @pos[pos] @pos[pos] = Array.new end if not @pos[pos][0] nn = BpmNode.new(@bpm_node_id, typ, evt) @pos[pos] << nn @bpm_node_id += 1 @typs_pos[typ] << nn add_prv_nxt(nn) return end # No attributes for this attribute available # => all events go into the same node if @attrs[typ] and @attrs[typ].length < 1 @pos[pos][0].add_pdj_event(evt) return end # Find most similar (i.e. equal) node for current event and attach event to # it max = 0 max_node = nil node = nil @pos[pos].each do |n| sim = n.similar(evt, @attrs[typ]) if sim == @attrs[typ].length node = n break end #if sim > max # max = sim # max_node = n #end end #if max_node # max_node.add_pdj_event(evt) # add_prv_nxt(max_node) if node node.add_pdj_event(evt) add_prv_nxt(node) else # No similar node was found. Create a new node with the current event as # first inhabitant nn = BpmNode.new(@bpm_node_id, typ, evt) @bpm_node_id += 1 @pos[pos] << nn @typs_pos[typ] << nn add_prv_nxt(nn) end end =end def add_prv_nxt(cur) #puts "add_prv_nxt, cur: #{cur}" if @prv_bpm_node if not cur.prv.include?(@prv_bpm_node) cur.prv << @prv_bpm_node end if not @prv_bpm_node.nxt.include?(cur) @prv_bpm_node.nxt << cur end end @prv_bpm_node = cur end def add_considering_step(evt) end def add_buying_step(evt) end def calc_phase_pos() # Step 1: every milestone gets position 0 @node_arry.each do |node| node.phase_pos = [] if Discover.milestone?(node.type) node.phase_pos = [0] end # Step 2: every nxt node from 'last' calculated phase_pos current_pos = 0 while current_pos <= @node_arry.length @node_arry.each do |node| if node.phase_pos.include?(current_pos) node.nxt.each do |nxt_node| next if nxt_node.phase_pos == [0] if not nxt_node.phase_pos.include?(current_pos + 1) nxt_node.phase_pos << current_pos + 1 end end end end current_pos += 1 end end end def to_s msg = "BPM " if @segment msg += "for segment id: #{@segment.segment_id}\n" end ft = false ft = true if not @typs_pos if not ft @typs_pos.each do |t| ft = true if not t or t.length < 1 end end if ft fill_typs_pos() end @typs_pos.each do |typ| next if not typ typ.each do |pos| pos.each do |node| msg += node.to_s + "\n" #node.pdj_events.each do |evt| # msg += evt.to_s + "\n" #end end end end msg += "\n" msg end def topology_to_s res = "" spaces = -3 @typs_pos.each do |typ| next if not typ next if typ.length < 1 spaces += 3 typ.each_with_index do |pos, idx2| pos.each do |bpm_node| res += bpm_node.topology_to_s(idx2 + spaces) end end end res end def calc_attrs_cnt_bpm() @attrs_cnt = calc_attrs_cnt(@node_arry) if not @attrs_cnt end def get_vis_hash return @chunks if @chunks hsh = {} @node_arry.each_with_index do |n, idx| hsh[idx] = [n.id] end hsh end def visualize(grph_obj, vis_attrs, label_id, chunks) journey_numbers = segment.length threshold = calc_max_trigger_frequency(journey_numbers, @node_arry, 3) #chunks = chunk(self, @atrrs) chunks.each_pair do |k, v| if v.length < 2 node = (@node_arry.select {|x| x.id == v[0]})[0] node.draw_node(grph_obj, vis_attrs, journey_numbers, label_id, threshold) #@node_arry[v[0]].draw_node(grph_obj, journey_numbers, label_id) else v.each do |chunk_node| chunk_node_id = Integer(chunk_node) node = (@node_arry.select {|x| x.id == chunk_node_id})[0] cknr = node.chunk_id node.draw_chunk_node(grph_obj, vis_attrs, journey_numbers, cknr, label_id, threshold) #@node_arry[chunk_node].draw_chunk_node(grph_obj, journey_numbers, cknr, label_id) end end end =begin # Draw all nodes @node_arry.each do |node| node.draw_node(grph_obj, journey_numbers) end =end # Draw all edges @node_arry.each do |node| node.draw_edge(grph_obj) end end # calculates the frequencies for all Trigger Milestones. The rank # defines, which one is used as threshold during the draw_node # method. def calc_max_trigger_frequency(journey_numbers, node_arry, rank) frequencies = [] journey_numbers = journey_numbers.to_f node_arry.each do |bpm_nodes| if bpm_nodes.type == Discover::TRIGGER num_pdj_events = bpm_nodes.pdj_events.length.to_f frequency = (num_pdj_events/journey_numbers) * 100 frequencies << frequency end end frequencies.sort!.reverse! frq = nil if rank > frequencies.length frq = frequencies.last() else frq = frequencies[rank - 1] end frq end def get_max_importance() if not @max_imp @max_imp = 0.0 @node_arry.each do |n| next if not Discover.step?(n.type) n.pdj_events.each do |evt| @max_imp = [@max_imp, evt.attributes[Discover::ALGORITHM_COLUMNS[:importance]].to_f].max end end end @max_imp end def fill_typs_pos() @typs_pos = Array.new(Discover::EVENT_TYPE_ARRAY.length) Discover::JOURNEY_EVENT_ORDER.each do |t| @typs_pos[t] = Array.new end @node_arry.each do |n| if n.type == Discover::TRIGGER if not @typs_pos[Discover::TRIGGER][0] @typs_pos[Discover::TRIGGER][0] = Array.new end @typs_pos[Discover::TRIGGER][0] << n end end end def prune(nonsig) return if nonsig <= 0.0 msg = "Bpm::prune, starting to prune. Original number of nodes: #{@node_arry.length}" $LOG.info(msg) ids_to_delete = [] @typs_pos.each do |t| next if not t t.each do |nds| nds.each do |n| next if Discover.milestone?(n.type) if n.get_frequency() <= nonsig n.prv.each do |pn| n.nxt.each do |nn| if Discover.common_user_ids?(pn, nn) ids_to_delete << n.id next if Discover.milestone?(pn.type) and Discover.milestone?(nn.type) if not pn.nxt.include?(nn) pn.nxt << nn end if not nn.prv.include?(pn) nn.prv << pn end end end end n.prv.each do |np| np.nxt.delete(n) end n.nxt.each do |nn| nn.prv.delete(n) end end end end end @typs_pos.each do |t| next if not t t.each do |pos| pos.delete_if {|n| ids_to_delete.include?(n.id)} end end @node_arry.delete_if {|n| ids_to_delete.include?(n.id)} @node_arry.each_with_index do |n, idx| next if n.id == idx n.id = idx end msg = "Bpm::prune, finished pruning. Pruned number of nodes: #{@node_arry.length}" $LOG.info(msg) end # Remove a node from a BPM. # After a node has been removed, all edges between predecessor and successor # of the removed node need to adjusted. # An edge can only be drawn between a predecessor and a successor if they # share at least one user. # # == Parameter # n:: BpmNode: Node to remove from BPM. def remove_node(n) return if not n return if not @node_arry.include?(n) n.prv.each do |pn| n.nxt.each do |nn| if Discover.common_user_ids?(pn, nn) if not pn.nxt.include?(nn) pn.nxt << nn end if not nn.prv.include?(pn) nn.prv << pn end end end end # Delete to-del-node from nxt list of to-del-node's predecessors. n.prv.each do |np| np.nxt.delete(n) end # Delete to-del-node from prv list of to-del-node's successors. n.nxt.each do |nn| nn.prv.delete(n) end # Delete to-del-node from internal structure @typs_pos.each do |t| next if not t t.each do |pos| pos.delete(n) end end # Delete to-del-node from internal structure @node_arry.delete(n) # Adjust indices of remaining nodes. @node_arry.each_with_index do |n, idx| next if n.id == idx n.id = idx end end end <file_sep>/bin/dc.rb #!/usr/bin/env ruby require 'logger' require 'optparse' require 'sqlite3' require 'graphviz' require 'pry' require 'digest' require 'yaml' require 'fileutils' require_relative './util' require_relative '../lib/consolidate_events' require_relative '../lib/bpm' require_relative '../lib/configuration' require_relative '../lib/dynamic_segmenter' require_relative '../lib/mcl' require_relative '../lib/pdj' require_relative '../lib/pdj_map' require_relative '../lib/retention' require_relative '../lib/static_segment' require_relative '../lib/visualizer' require_relative '../lib/opt_parser' require_relative '../lib/database/sqlite3_connect.rb' require_relative '../lib/json_dumper' require_relative '../lib/json_reader' VERSION = "1.1.1.3" #include Discover # Starting up the DAE, setting default values, and reading options file options = {} options[:p] = false options[:c] = "" options[:ds] = nil options[:n] = nil # <--- If we remove the possibility to set the table from the command line this block can be removed. The table will be configurable through the config only options[:e] = nil # ---> options[:o] = nil # Initialize logger and log level with infos from options initialize_logger() opt_parser = Option_Parser.new(options) initialize_logger(options) opt_parser.check_options(options) # Read ini file ini = Configuration.new(options[:i]) $LOG.debug "Main: configuration:" $LOG.debug ini # <--- connect_db loads the database into the programme. This call must not use the command line option options[:d] but the content of the ini file: # Depending on the value of ini["global"]["entry_point"] the DA must activate a different flow: # IF ini["global"]["entry_point"]==ds THEN ini["global"]["input_file"] is a standard sqlite DB and the DA initialises it and processes it. # IF ini["global"]["entry_point"]==bpm THEN ini["global"]["input_file"] is a dumpDS.js input file and the DA must extract the SQLITE table from the dump # IF ini["global"]["entry_point"]==pdjm THEN ini["global"]["input_file"] is a dumpBPM.js input file and the DA must extract the BPM table from the dump # IF ini["global"]["entry_point"]==visualisation THEN ini["global"]["input_file"] is a dumpPDJM.js input file and the DA must extract the PDJM table from the dump Entry_point = STAGES[ini["global"]["entry_point"].to_s.downcase] Exit_point = STAGES[ini["global"]["exit_point"].to_s.downcase] $base_folder = ini["global"]["base_folder"] dump = nil if Entry_point["n"] <= 2 check_folder_consistency() FileUtils::cp($base_folder+"/source.db",$base_folder+"/ds.db") input_file = $base_folder+"/" + Entry_point["name"] + ".db" msg = "Main:entry_point = 'ds'. Provided entry point for the dynamic segmentation, " msg += "'#{input_file}' database file will be loaded." $LOG.info msg if not File.exists?(input_file) msg = "Main::check_entry_point: Provided SQLite3 database file '#{input_file}' " msg += "does not exist! Aborting!" $LOG.error msg exit 1 end # Makes a backup copy of the original db db = connect_db(input_file) # ---> event_tbl_name = ini["global"]["event_table_name"] # <--- If we remove the possibility to set the table from the command line this block can be removed. The table will be configurable through the config only if options[:e] event_tbl_name = options[:e] end # ---> if not Discover.tbl_exists?(db, event_tbl_name) msg = "Main, provided table name #{event_tbl_name} does not exists!" $LOG.error(msg) msg = " ABORTING!" $LOG.error(msg) exit 1 end clean_tables(db, event_tbl_name, true) # Start compatibilty check concerning db version and attributes to be used attrs = get_attributes_for_types(ini) check_columns(db, event_tbl_name, attrs) # PHASE 1 - Extract static segments from database static_segments = extract_static_segments(db, attrs, event_tbl_name) # In case nof_res is used as an option, the static segments to be ordered by size static_segments.sort! {|s1, s2| s2.length <=> s1.length} write_static_segments(db, static_segments, event_tbl_name) # PHASE 2 - Extract dynamic segments from static segments dyn_segs = nil dyn_segment_attrs = ini.get_dynamic_segment_attributes() max_attr_vals = get_max_nof_attr_val(db, event_tbl_name, dyn_segment_attrs) if (max_attr_vals == 0 ) $LOG.error "Main: Configuration issue: There is not a single value manifestation for the attributes to be used during similarity calculations" exit(1) end nec_chars = get_nof_nec_chars(max_attr_vals) $LOG.info "Main: max number of attribute manifestations in all event types: #{max_attr_vals}" $LOG.info "Main: need #{nec_chars} a-z chars to encode #{max_attr_vals} possible values" ds_opt = ini["dynamic_segment"]["mode"] # <--- If we remove the possibility to set the dynamic segmentation mode from the command line this block can be removed. The dynamic segmentation mode will be configurable through the config only if options[:ds] ds_opt = options[:ds] end # ---> # If there is a limit to the numbers of clusters (ordered by size) process only # the relevant subset # Check INI nof_res = ini["dynamic_segment"]["number_of_results"] if nof_res if nof_res.size > 0 begin nof_res = Integer(nof_res) rescue $LOG.error "Main, provided number_of_results in config.ini is not a number" nof_res = nil end else nof_res = nil end end # <--- If we remove the possibility to set the number_of_results from the command line this block can be removed. The number_of_results will be configurable through the config only # Check command line if options[:n] nof_res = Integer(options[:n]) end # ---> # Start processing or transfer of / into dynamic segments if ds_opt == "skip" $LOG.info "Main: skipping dynamic segmentation" dyn_segs = static_segments dyn_segs.each do |s| dyn_segment = Segment.new(1) s.each do |pdj| pdj.dyn_segment = dyn_segment end end $LOG.info "Main: updating DB with static segment info as dynamic segment" else dyn_segs = extract_dynamic_segments(static_segments, nec_chars, db, ini, nof_res) $LOG.info "Main: updating DB with dynamic segment ids" end # Write IDs to the database # Discover.update_db_with_dynamic_segment_ids(db, dyn_segs, event_tbl_name) # <-------DUMP DS, ini configuration and DB dumper(phase=2,ini,db,event_tbl_name,dyn_segs,nil,nil,dump) # --------> if ds_opt == "stop" $LOG.info "Main: stopping after dynamic segmentation" close_db(db) exit 0 end if Exit_point["n"] == 2 $LOG.info "Main:exit_point = 'ds'. Stopping after dynamic segmentation" close_db(db) exit 0 end end # >>>>>>> EXIT POINT FOR DYNAMIC SEGMENTATION HERE WE MUST GENERATE THE DUMP FILE dsDump.js that contains the config variables, the results summary (dyn_segs) and the sqlite dump (db) # PHASE 3 - Start the calculation of the BPMs for each segment (each static segment might have # multiple dynamic segments. if Entry_point["n"] <= 3 check_folder_consistency() dump = dump_reader(ini,phase=3) FileUtils::cp($base_folder+"/ds.db",$base_folder+"/bpm.db") db = connect_db($base_folder+"/bpm.db") if Entry_point["n"] == 3 msg = "Main:entry_point = 'bpm'. Provided an entry point for bpm generation, " msg += "'#{ini["global"]["entry_point"]}.js' dump file will be loaded." $LOG.info msg dyn_segs= YAML.load(dump["dyn_segs"]) event_tbl_name = dump["config"]["global"]["event_table_name"] end # Just for being sure, it overwrites the dyn_segs values in the db Discover.update_db_with_dynamic_segment_ids(db, dyn_segs, event_tbl_name) bpms = calculate_bpms(dyn_segs, ini, db, event_tbl_name) write_bpm_ids_to_db(bpms, db, event_tbl_name) # >>>>>>>>>>>>>>>>>>> DUMP THE BPM <<<<<<<<<<<<<<<<<<<<<<< dumper(phase=3,ini,db,event_tbl_name,dyn_segs,bpms,nil,dump) if Exit_point["n"] == 3 $LOG.info "Main::exit_point: bpm. Stopping after bpm." exit 0 end end # PHASE 4 - Generate PDJ Maps for each BPM if Entry_point["n"] <= 4 check_folder_consistency() dump = dump_reader(ini,phase=4) FileUtils::cp($base_folder+"/bpm.db",$base_folder+"/pdjm.db") db = connect_db($base_folder+"/pdjm.db") if Entry_point["n"] == 4 msg = "Main:entry_point = 'PDJM'. Provided an entry point for PJDM generation, " msg += "'#{ini["global"]["entry_point"]}.js' dump file will be loaded." $LOG.info msg # db = connect_db(dump["config"]["global"]["db_path"]) dyn_segs = YAML.load(dump["dyn_segs"]) bpms = YAML.load(dump["bpms"]) event_tbl_name = dump["config"]["global"]["event_table_name"] end # If pdjm-method is none: ini["pdjm"]["method"] = "none" sets tmp_pdjms == bpms tmp_pdjms = calculate_pdjms(ini, bpms) write_pdjm_ids_to_db(tmp_pdjms, db, event_tbl_name) # move temporary pdj maps into the final pdj map structure pdjms = Array.new() # these lines encapsulate the bpms structure tmp_pdjms.each do |b| # in the pdjms structure, necessary to pdjms << PdjMap.new(b) # visualize the bpms/pdjms end dumper(phase=4,ini,db,event_tbl_name,dyn_segs,bpms,pdjms,dump) if Exit_point["n"] == 4 $LOG.info "Main::exit_point: pdjm. Stopping after pdjm." exit 0 end end # PHASE 5 - Visualize the resulting PDJ Maps (or BPMs if the generation of PDJMs is skipped) if Entry_point["n"] <= 5 check_folder_consistency() dump = dump_reader(ini,phase=5) if Entry_point["n"] == 5 msg = "Main:entry_point = 'Visualisation'. Provided an entry point for visualisation, " msg += "'#{ini["global"]["entry_point"]}.js' dump file will be loaded." $LOG.info msg dyn_segs = YAML.load(dump["dyn_segs"]) bpms = YAML.load(dump["bpms"]) event_tbl_name = dump["config"]["global"]["event_table_name"] pdjms = YAML.load(dump["pdjms"]) end # it's unecessary to create the db backup because the visualisation phase does not affect the .db db = connect_db($base_folder+"/pdjm.db") format = ini["visualisation"]["format"] format = format ? format : "svg" res_tbl_name = ini["visualisation"]["result_table"] res_tbl_name = res_tbl_name ? res_tbl_name : "results" # Always true, parameter is removed # path = ini["visualisation"]["file_output_path"] path = $base_folder prfx = ini["visualisation"]["file_output_prefix"] if options[:o] and options[:o].length > 0 prfx = options[:o] end vis_attrs = get_visualisation_attributes(ini) viz_object = Visualizer.new(pdjms, vis_attrs, db, res_tbl_name, format, ini, path, prfx) label_id = true graph_label = options[:c] if options[:p] viz_object.buildgraph(label_id, graph_label, ini) else viz_object.buildgraph(label_id, graph_label) end end close_db(db)<file_sep>/lib/enumerator.rb require 'set' require_relative 'constants' require_relative 'entropy' require_relative 'tools' class Enumerator ENUMERATION_NODE_THRESHOLD = 30 attr_accessor :bpm attr_reader :attrs attr_accessor :significant, :nonsignificant def initialize(bpm, ini) if bpm.node_arry.length >= ENUMERATION_NODE_THRESHOLD n = bpm.node_arry.length $LOG.error("Enumerator::new, too many nodes for enumeration (#{n} nodes > #{ENUMERATION_NODE_THRESHOLD})!") $LOG.error(" Please consider prune option, if you haven't") exit 1 end @ini = ini @bpm = bpm if @ini @attrs = @ini.get_pdjm_attributes() @importance = Discover::ALGORITHM_COLUMNS[:importance] if not @importance @importance = "importance" end end @significant = -1.0 @nonsignificant = -1.0 if @ini and @ini["bpm"] and @ini["bpm"]["significant"] @significant = @ini["bpm"]["significant"] end if @ini and @ini["bpm"] and @ini["bpm"]["nonsignificant"] @nonsignificant = @ini["bpm"]["nonsignificant"] end end def enumerate() bpm.calc_start_milestones bpm.calc_end_milestones adj_mtx = bpm.calc_adj_mtx() bpm.dst_mtx = Discover.calc_dist_mtx(adj_mtx) bpm.top_srt = Discover.bpm_topological_sort(bpm) #stps = get_events(@bpm, Discover::CONSIDERING_STEP).concat(get_events(@bpm, Discover::BUYING_STEP)) cs = Discover.get_events(@bpm, Discover::CONSIDERING_STEP) #bs = get_events(@bpm, Discover::BUYING_STEP) fct_imp = 1.0 fct_frq = 1.0 fct_ent = 1.0 fct_nnd = 1.0 if @ini["enumeration"]["factor_importance"] fct_imp = @ini["enumeration"]["factor_importance"].to_f end if @ini["enumeration"]["factor_frequency"] fct_frq = @ini["enumeration"]["factor_frequency"].to_f end if @ini["enumeration"]["factor_entropy"] fct_ent = @ini["enumeration"]["factor_entropy"].to_f end if @ini["enumeration"]["factor_number_of_nodes"] fct_nnd = @ini["enumeration"]["factor_number_of_nodes"].to_f end return enum_int(cs, bpm, bpm.dst_mtx, @attrs, fct_ent, fct_imp, fct_frq, fct_nnd, :per_attribute) end def to_s "Enumerator" end def enum_int(cs, bpm, dst_mtx, attrs, fct_entrpy = 1.0, fct_imp = 1.0, fct_frq = 1.0, fct_nnd = 1.0, nrm) if not bpm.attrs_cnt bpm.attrs_cnt = calc_attrs_cnt(bpm.node_arry) end #orig_entropy = bpm_entropy2(bpm.node_arry, attrs, bpm.attrs_cnt) orig_entropy = bpm_entropy2(bpm.node_arry, attrs, nrm) entropy_norm_factor = 1.0 if orig_entropy != 0 if orig_entropy >= 0.5 entropy_norm_factor = 1.0 / orig_entropy else entropy_norm_factor = 1.0 / (1.0 - orig_entropy) end end tbs = Discover.get_events(@bpm, Discover::BUYING_STEP) ttrg = Discover.get_events(@bpm, Discover::TRIGGER) trtp = Discover.get_events(@bpm, Discover::READY_TO_PURCHASE) tprc = Discover.get_events(@bpm, Discover::PURCHASE) $LOG.debug "Enumerator::enum_int, to enumerate BPM has #{@bpm.node_arry.length} nodes" $LOG.debug " trg: #{ttrg.length}, cs: #{cs.length}, bs: #{tbs.length}, rtp: #{trtp.length}, prc: #{tprc.length}" $LOG.debug "Enumerator::enum_int, using #{fct_entrpy} as weight for entropy" $LOG.debug "Enumerator::enum_int, using #{fct_imp} as weight for importance" $LOG.debug "Enumerator::enum_int, using #{fct_frq} as weight for frequency" $LOG.debug "Enumerator::enum_int, using #{fct_nnd} as weight for number of nodes punishment" $LOG.debug "Enumerator::enum_int, entorpy of full BPM: #{orig_entropy}" score_norm = fct_entrpy + fct_imp + fct_frq + fct_nnd res = nil iteration = 0 min_e = Float::INFINITY max_e = 0 t1 = Time.now t2 = nil cs = order_by_frq_imp(cs) mod = @ini["enumeration"]["status_every"] if not mod mod = 100000 else mod = mod.to_i end res_ary = nil if $LOG.debug? expon = (mod.to_s.length - 1).to_s msg ="iter | best_score | entropy | min diff | max diff | freq | " msg += "import | size score | " msg += " time | node ids" msg = msg % mod l = msg.length $LOG.debug msg msg = "" for i in 0..l msg += "-" end msg[9] = "+" msg[23] = "+" msg[33] = "+" msg[44] = "+" msg[55] = "+" msg[65] = "+" msg[74] = "+" msg[87] = "+" msg[96] = "+" $LOG.debug msg end sum_jrnys = 0 bpm.node_arry.each do |nd| next if Discover.milestone?(nd.type) sum_jrnys += Discover.get_user_ids_for_node(nd).length end if cs.length == 0 cs << nil end # For each member (subgraph) of the powerset of the considering steps cs.powerset.each do |c| # Get all bs steps that are connected to the current set of considering steps bs = get_bs(c, ttrg, bpm, dst_mtx) next if not bs or bs.length < 1 bs = order_by_frq_imp(bs) # For each member (subgraph) of the powerset of the buying steps bs.powerset.each do |b| # Get trigger, ready to purchase and purchase milestones trg, rtp, prc = enum_milestones(c, b, dst_mtx) trg.each do |t| rtp.each do |r| prc.each do |p| nds = Array.new if c and c[0] nds.concat(c.map {|x| x.id}) end if b and b[0] nds.concat(b.map {|x| x.id}) end if t and t[0] nds.concat(t.map {|x| x.id}) end if r and r[0] nds.concat(r.map {|x| x.id}) end if p and p[0] nds.concat(p.map {|x| x.id}) end nds_ary = get_node_arry(nds, bpm) # Score contributions #entropy = bpm_entropy2(nds_ary, attrs, bpm.attrs_cnt, nrm_fctr) entropy = bpm_entropy2(nds_ary, attrs, nrm) if entropy < 0.0 or entropy > 1.0 msg = "Enumerator::enum_int, entropy value outside allowed " msg += "range: #{entropy}" $LOG.error(msg) end ent_diff = 1.0 - ((orig_entropy - entropy).abs * entropy_norm_factor) #ent_diff = 1.0 - ((orig_entropy - entropy).abs) if ent_diff < 0 or ent_diff > 1 msg = "Enumerator::enum_int, entropy score out of range, " msg += "score: #{ent_diff}, orig_entropy: #{orig_entropy}, " msg += "current entropy: #{entropy} " #msg += "#{entropy}, entropy norm factor: " #msg += "#{entropy_norm_factor}" $LOG.error(msg) end min_e = [min_e, ent_diff].min max_e = [max_e, ent_diff].max ent_diff *= fct_entrpy frq = get_node_frequencys(nds_ary, sum_jrnys) if frq < 0 or frq > 1 $LOG.error "Enumerator::enum_int, frequency score out of range, score: #{frq}" end if frq.nan? msg = "Enumerator::enum_int, could not compute frequency! " msg += "Please check input data" $LOG.error(msg) frq = 0 end frq *= fct_frq imp = get_importance(nds_ary, @importance) if imp < 0 or imp > 1 $LOG.error "Enumerator::enum_int, importance score out of range, score: #{imp}" end if imp.nan? msg = "Enumerator::enum_int, could not compute importance " msg += "using #{@importance} as importance attribute. " msg += "Please check input data" $LOG.error(msg) frq = 0 end imp *= fct_imp nns = get_number_of_nodes_score(nds_ary, bpm) if nns < 0 or nns > 1 $LOG.error "Enumerator::enum_int, number of nodes score out of range, score: #{nns}" end nns *= fct_nnd #tmp_res = (frq + imp + nns + ent_diff) / score_norm tmp_res = frq + imp + nns + ent_diff if not res_ary or tmp_res > res_ary[0][0] res_ary = Array.new tmp = Array.new(2) tmp[0] = tmp_res tmp[1] = nds_ary res_ary << tmp elsif tmp_res == res_ary[0][0] tmp = Array.new(2) tmp[0] = tmp_res tmp[1] = nds_ary res_ary << tmp #$LOG.debug "Enumerator::enum, have for score value #{tmp_res} #{res_ary.length} BPMs" end if $LOG.debug? and iteration % mod == 0 t2 = Time.now msg = "%8d | %5.4f | %6.3f | %5.4f | %5.4f | " msg += " %5.4f | %5.4f | %5.4f | %5.1fs | %s" msg = msg % [iteration, res_ary[0][0], entropy, min_e, max_e, frq, imp, nns, t2 - t1, nds.join(', ')] $LOG.debug msg t1 = Time.now end iteration += 1 end # prc end # rtp end # trg #puts "New buying step" end # bs #puts "New considering step" end #cs $LOG.info "Enumerator::enum, enumerated #{iteration} BPMs" if res_ary $LOG.info "Enumerator::enum, enumerated #{res_ary.length} BPMs with the same highest scrore" end # No or just one iteration, returning whole bpm if iteration < 2 return Discover.build_pdjm(bpm, bpm.node_arry.map {|x| x.id}) end # Perform some checks on results scr = res_ary[0][0] sidx = Float::INFINITY res_bpm = nil res_ary.each do |r| if r[0] != scr $LOG.error "Enumerator::enum_int, final results have different scores!" end if r[1].length < sidx res_bpm = r[1] sidx = res_bpm.length elsif r[1].length == sidx $LOG.info "Enumerator::enum_int, have two result with same score and same length!" end end pdjm = Discover.build_pdjm(bpm, res_bpm.map {|x| x.id}) pdjm end def get_number_of_nodes_score(nds_ary, bpm, okay = 10) ndsl = (nds_ary.map {|x| Discover::step?(x.type) ? 1 : 0}).inject(:+) #bpml = bpm.node_arry.length if ndsl <= okay #return 1.0 - (ndsl.to_f / okay.to_f) return ndsl.to_f / okay.to_f end bpml = (bpm.node_arry.map {|x| Discover::step?(x.type) ? 1 : 0}).inject(:+) # Following if statement must never be true, but ... if bpml <= okay return 1 end ndsl -= okay bpml -= okay res = ndsl.to_f / bpml.to_f if res < 0 or res > 1 $LOG.error "Enumerator::get_number_of_nodes_score, result is not valid!!! result: #{res}" end 1 - res end def order_by_frq_imp(nd_ary, fct_frq = 1.0, fct_imp = 1.0) return nd_ary if not nd_ary or nd_ary.length < 2 nd_ary.sort {|x, y| y.get_node_frequency() * fct_frq + y.get_importance() * fct_frq <=> x.get_node_frequency() * fct_imp + x.get_importance() * fct_imp } end # Extract all buying steps, connected to a set of considering steps and # trigger milesteones. def get_bs(cs, trg, bpm, dst_mtx) bs = Array.new if cs[0] == nil cs = trg end return [] if not cs cs.flatten.uniq.each do |s| cur_row = dst_mtx.get_row(s.id) cur_row.each_with_index do |ele, idx| next if idx == s.id if ele > 0 and bpm.node_arry[idx].type == Discover::BUYING_STEP bs << bpm.node_arry[idx] end end end bs.uniq! bs end def enum_milestones(cons, buys = nil, dst_mtx) if not buys cons, buys = split_arry_according_to_typ(node_arry) end trg = Array.new rtp = Array.new prc = Array.new cons.each do |c| if c trg.concat(c.start_milestones) rtp.concat(c.end_milestones) if not buys or buys.length < 1 or not buys[0] prc.concat(c.end_milestones) end end end buys.each do |b| if b rtp.concat(b.start_milestones) prc.concat(b.end_milestones) if not cons or cons.length < 1 or not cons[0] trg.concat(b.start_milestones) end end end trg.uniq! rtp.uniq! prc.uniq! trgr = Array.new rtpr1 = Array.new rtpr2 = Array.new trg.powerset.each do |t| fa = Array.new(cons.length, false) t.each_with_index do |ms, idx| cons.each_with_index do |c, idx| next if not c if dst_mtx[ms.id][c.id] > 0 fa[idx] = true end end buys.each_with_index do |b, idx| next if not b if dst_mtx[ms.id][b.id] > 0 fa[idx] = true end end end if fa.all? trgr << t end end rtp.powerset.each do |r| fa1 = Array.new(cons.length, false) fa2 = Array.new(buys.length, false) r.each_with_index do |ms, idx| cons.each_with_index do |c, idx| next if not c if dst_mtx[c.id][ms.id] > 0 fa1[idx] = true end end buys.each_with_index do |b, idx| next if not b if dst_mtx[ms.id][b.id] > 0 fa2[idx] = true end end end if fa1.all? rtpr1 << r end if fa2.all? rtpr2 << r end end rtpr = rtpr1 & rtpr2 prcr = Array.new prc.powerset.each do |p| fa = Array.new(buys.length, false) p.each_with_index do |ms, idx| buys.each_with_index do |b, idx| next if not b if dst_mtx[b.id][ms.id] > 0 fa[idx] = true end end end if fa.all? prcr << p end end if trgr.length < 1 trgr << nil end if rtpr.length < 1 rtpr << nil end if prcr.length < 1 prcr << nil end return trgr, rtpr, prcr end def split_arry_according_to_typ(node_arry) cons = Array.new buy = Array.new node_arry.each do |n| if n.type == Discover::CONSIDERING_STEP cons << n elsif n.type == Discover::BUYING_STEP buy << n else msg = "Enumerator::split_arry_according_to_typ, expecting only " msg += "steps, found: #{Discover::ID_EVENT_MAP[n.type]}" $LOG.warn msg if $LOG end end return cons, buy end def get_node_arry(ids_ary, bpm) res = Array.new(ids_ary.length) for i in 0...res.length res[i] = bpm.node_arry[ids_ary[i]] end res end def get_node_frequencys(nd_ary, max_val) sum = 0 nd_ary.each do |nd| next if Discover.milestone?(nd.type) sum += Discover.get_user_ids_for_node(nd).length end sum.to_f / max_val.to_f =begin ids = Array.new msts = 0 frq = 0 nd_ary.each do |n| if Discover.milestone?(n.type) msts += 1 next end ids = ids + n.get_unique_user_ids #frq += n.get_frequency() end =end =begin length = 0 if nd_ary[0].pdj_events[0].pdj.dyn_segment length = nd_ary[0].pdj_events[0].pdj.dyn_segment.length.to_f else length = nd_ary[0].pdj_events[0].pdj.static_segment.length.to_f end res = frq / (length - msts) return res =end =begin ids2 = ids.uniq ids = ids2 if ids2 #ids.sort! length = 0 if nd_ary[0].pdj_events[0].pdj.dyn_segment length = nd_ary[0].pdj_events[0].pdj.dyn_segment.length.to_f else length = nd_ary[0].pdj_events[0].pdj.static_segment.length.to_f end ids.length.to_f / (length - msts) =end end def get_prv_frequencys(nd_ary) frq = 0.0 nd_ary.each do |n| frq += n.get_prv_frequency() end frq = frq.to_f / nd_ary.length.to_f frq end def get_importance(nd_ary, imp_name) imp = 0.0 msts = 0 nd_ary.each do |n| if Discover.milestone?(n.type) msts += 1 next end imp += n.get_importance(imp_name).to_f / bpm.get_max_importance().to_f end imp = imp.to_f / (nd_ary.length.to_f - msts) imp end def valid?(con_stps, con_mtx) true =begin # test whether all arry member have the same start and end_milestones con_stps.each do |n1| con_stps.each do |n2| next if n1 == n2 sm = n1.start_milestones & n2.start_milestones em = n1.end_milestones & n2.end_milestones if sm.empty? and em.empty? puts "sm and em are empty for nodes: #{n1.id} and #{n2.id}" return false end end end =end end end <file_sep>/lib/pdj_segment.rb require './Pdj.rb' class PdjSegment < Pdj attr_accessor :pdjs, :pdj_db_file :config def initialize(pdj_db_file, config) @pdj_db_file = pdj_db_file @config = config end def initialize(pdjs) @pdjs = pdjs end def get_nof_pdjs end def add_pdj(pdjs) end def split_pdj(conditions) end end <file_sep>/lib/entropy.rb module Discover def print_attrs(atrs) atrs.each_pair do |typ, typ_atrs| puts "Type: #{ID_EVENT_MAP[typ]}" typ_atrs.each_pair do |atr_nm, atr_val| puts " #{atr_nm}" atr_val.each_pair do |atr_val_nm, atr_val_mnfst| puts " #{atr_val_nm}, count: #{atr_val_mnfst}" end end end end def bpm_entropy2(node_arry, attrs, nrm = :per_attribute) atr_cnt, cnt = cnt_attr_mnfst(node_arry, attrs) #print_attrs(atr_cnt) calc_entropy(attrs, atr_cnt, nrm, node_arry.length) end def calc_entropy(attrs, atr_cnt, nrm = nil, nof_nodes = nil) cnts = 0 entryp = 0.0 atr_mnfst_cnt = 0.0 nf_attrs = 0 if nrm # calculate necessary normalizing values attrs.each_pair do |typ, atrs| atrs.each do |atr| next if not atr_cnt[typ] or not atr_cnt[typ][atr] atr_mnfst_cnt += atr_cnt[typ][atr][:cnt].to_f nf_attrs += 1 end end end attrs.each_pair do |typ, atrs| atrs.each do |atr| next if not atr_cnt[typ] or not atr_cnt[typ][atr] if nrm and nrm == :global ac = atr_mnfst_cnt else ac = atr_cnt[typ][atr][:cnt].to_f end val = 0.0 atr_cnt[typ][atr].each_pair do |atr_mnst, atr_mnst_cnt| next if atr_mnst == :cnt inf = atr_mnst_cnt.to_f / ac if inf == 1 val += 0 else val -= inf * Math.log2(inf) end end if nrm sz = 0.0 if nrm == :per_attribute sz = atr_cnt[typ][atr].size - 1 # -1 for :cnt for every attribute in # atr_cnt elsif nrm == :global sz = atr_mnfst_cnt end if val > 0.0 val /= Math.log2(sz) end end if val == Float::NAN msg = "Entropy::valc_entropy, intermediate result is NaN!!!" msg += " inf: #{inf}" mgs += " ac : #{ac}" $LOG.error(msg) exit 1 end entryp += val end end if nrm and nrm == :per_attribute entryp /= nf_attrs end entryp end def cnt_attr_mnfst(node_arry, atrs) typ = -1 atr_cnt = {} cnt = 0 node_arry.each do |nd| typ = nd.type atr_cnt[typ] = Hash.new if not atr_cnt[typ] nd.pdj_events.each do |evt| evt.attributes.each_pair do |atr_nm, atr_val| next if atr_val == "" atr_cnt[typ][atr_nm] = Hash.new if not atr_cnt[typ][atr_nm] cnt += 1 if not atr_cnt[typ][atr_nm][:cnt] atr_cnt[typ][atr_nm][:cnt] = 0 end atr_cnt[typ][atr_nm][:cnt] += 1 if not atr_cnt[typ][atr_nm][atr_val] atr_cnt[typ][atr_nm][atr_val] = Hash.new if not atr_cnt[typ][atr_nm][atr_val] atr_cnt[typ][atr_nm][atr_val] = 1 else atr_cnt[typ][atr_nm][atr_val] += 1 end end end end return [atr_cnt, cnt] end def bpm_entropy(node_arry, attrs, attrs_cnt, nrm_entropy = nil) entropy_attrs = count_attr_manifests(node_arry, attrs) calc_norm_cnts(attrs, attrs_cnt, entropy_attrs) calc_freqs(entropy_attrs) calc_entropy_values(entropy_attrs) sum_entropies = sum_entropies(entropy_attrs) if nrm_entropy and sum_entropies > nrm_entropy msg = "node_arry: #{node_arry}" msg += "attrs: #{attrs}" msg += "sum_entropy: #{sum_entropies}" mgs += "nrm_entropy: #{nrm_entropy}" $LOG.error(msg) exit 1 end normed_entropy = 0.0 if not nrm_entropy normed_entropy = norm_entropy(attrs_cnt, attrs, sum_entropies) else normed_entropy = sum_entropies / nrm_entropy end normed_entropy end # count attribute manifestations in actual bpm nodes (node_arry) def count_attr_manifests(node_arry, attrs = nil) entropy_attrs = Hash.new node_arry.each do |node| node.pdj_events.each do |event| # creating hash for current event type if not entropy_attrs[event.type] entropy_attrs[event.type] = Hash.new end event.attributes.each_pair do |attr, attr_value| next if not attr_value next if not attrs[event.type].include?(attr) # creating hash for current attribute if not entropy_attrs[event.type][attr] entropy_attrs[event.type][attr] = Hash.new end # counting manifestations # remark: empty attr_value variables are counted as a # "normal" manifestations of the attribute if not entropy_attrs[event.type][attr][attr_value] entropy_attrs[event.type][attr][attr_value] = Hash.new entropy_attrs[event.type][attr][attr_value]["cnt"] = 1 else entropy_attrs[event.type][attr][attr_value]["cnt"] += 1 end end end end entropy_attrs end # get counts for manifestations in initial bpm def calc_norm_cnts(attrs, attrs_cnt, entropy_attrs) attrs_cnt.each_pair do |type, attr| attr.each_pair do |attr_tmp, attr_value| next if not attrs[type].include? attr_tmp attr_value.each_pair do |attr_value_tmp, cnt| next if not entropy_attrs[type][attr_tmp] next if not entropy_attrs[type][attr_tmp][attr_value_tmp] entropy_attrs[type][attr_tmp][attr_value_tmp]["cnt_ges"] = cnt end end end end # calc frequencies for nodes in node_arry def calc_freqs(entropy_attrs) entropy_attrs.each_pair do |type, attr| attr.each_pair do |attr_tmp, attr_value| attr_value.each_pair do |attr_value_tmp, nrs| freq = nrs["cnt"].to_f/nrs["cnt_ges"].to_f entropy_attrs[type][attr_tmp][attr_value_tmp]["freq"] = freq end end end end def calc_entropy_values(entropy_attrs) entropy_attrs.each_pair do |type, attr| attr.each_pair do |attr_tmp, attr_value| attr_value.each_pair do |attr_value_tmp, nrs| entropy_tmp = -nrs["freq"]*Math.log(nrs["freq"], 2) entropy_attrs[type][attr_tmp][attr_value_tmp]["entropy"] = entropy_tmp end end end end def sum_entropies(entropy_attrs) sum_entropies = 0 entropy_attrs.each_pair do |type, attr| attr.each_pair do |attr_tmp, attr_value| attr_value.each_pair do |attr_value_tmp, nrs| sum_entropies += entropy_attrs[type][attr_tmp][attr_value_tmp]["entropy"] end end end sum_entropies end def norm_entropy(attrs_cnt, attrs, sum_entropies) =begin # get number of different attribute manifestations in initial bpm nof_attr_values = 0 attrs_cnt.each_pair do |event, attr| attrs_cnt[event].each_pair do |attr_tmp, attr_value| attrs_cnt[event][attr_tmp].each_key do |attr_value_tmp| next if not attr_value_tmp nof_attr_values += 1 end end end scaling_const = Math.log(nof_attr_values.to_f, 2) =end sum_entropies / norm_entropy_factor(attrs_cnt, attrs) end def norm_entropy_factor(attrs_cnt, attrs) # get number of different attribute manifestations in initial bpm nof_attr_values = 0 attrs_cnt.each_pair do |event, attr| attrs_cnt[event].each_pair do |attr_tmp, attr_value| attrs_cnt[event][attr_tmp].each_key do |attr_value_tmp| next if (not attr_value_tmp) or (not attrs[event].include?(attr_tmp)) nof_attr_values += 1 end end end Math.log(nof_attr_values.to_f, 2) end end <file_sep>/config_benchmark.ini ; General remarks: ; ================================================= ; - If an option can be set via this config file and via command line, ; the command line argument has always precedence. ; One example for this is the mode argument in the [dynamic_segment] section. [global] ; Which table to use to extract events event_table_name = _journeys_offline ; Add to all attributes in the "dynamic_segment", "bpm" and "pdjm" following ; prefix. attribute_prefix = ;--- NEW SETTINGS ; It works fine on the dump_file's md5, but on the dabase's one it doesn't track the changes done by the ; phases following the dump so it returns mismatch! For the moment the code of the db's hash ( in ;json_reader and json_dumper) is commented so the dump's md5 should work properly, if not keep it on false. input_validation = true base_folder = "./process_0" entry_point = ds exit_point = visualisation ;---- [version_check] ; What version to expect version = 1.1.1.3 ; Name of the version Table table = versions ; Name of column in which the version i s stored column = dat_adapter_version [dynamic_segment] ; Dynamic segmentation work flow control. ; If mode is set to "skip", dynamic segmentation will be skipped, i.e. BPMs are ; calculated directly on static segments. ; If mode is set to "stop", only dynamic segments will be calculated and ; stored in the DB. All following steps (BPM, PDJ-Map, ...) will not be ; executed. ; If mode is set to another value then "skip" or "stop", the normal work flow ; will be followed, i.e. dynamic segmentation, BPM, PDJ-Map, ... ; This value can also be set via command line. Command line arguments always ; have precedence over configuration file entries. mode = ; What cluster method to use for dynamic segmentation ; At the moment following cluster algorithms are supported: ; - complete_linkage ; - single_linkage cluster_method = single_linkage ; Costs for edit distance edit_distance_cost_insert = 1 edit_distance_cost_delete = 1 edit_distance_cost_substitute = 1 trigger_attributes = considering_step_attributes = jrn_step_type ready_to_purchase_attributes = buying_step_attributes = jrn_step_type purchase_attributes = print_cluster_histogram = false cluster_similarity_threshold = 0.7 ;cluster_test_runs_similarity = 0.6, 0.8, 0.1 event_similarity_threshold = -1 protected_considering_step_attributes = protected_buying_step_attributes = swap_window = 1 ; How many dynamic results should be further processed. ; If an integer N is provided for the following option, the N dynamic segments ; with the most journeys will be passed for the following steps BPM, PDJ-Map, ... ; If no number is provided, all computed dynamic segments will be passed on to ; the next phases. ; This option can be also set via command line argument "-n <N>". The command ; line argument has higher priority, if it is provided number_of_results = ;--- NEW SETTINGS ;Number of times the dynamic segmentation is repeated with a lower threshold (runs). If mode=direct this parameter is forced to 1 ;dynamic_segmentation_runs = ;Starting cluster similarity threshold. At each successive run the threshold is going to decrease by 0.1 ;cluster_similarity_threshold_init = ;Minimum acceptable size of the cluster indicated as a percentage of the static segment size (i.e. "0.1" = 10% static segment size) ;significant_cluster_size = ;--- END OF NEW SETTINGS [bpm] ; Attributes for BPM computation. trigger_attributes = considering_step_attributes = jrn_step_type ready_to_purchase_attributes = buying_step_attributes = jrn_step_type purchase_attributes = ; How many attributes need to be equal to considerer two events as identically. ; If set to 0, no attribute need to be equal. ; A negative value means all above provided attributes need to be equal. event_similarity_threshold = -1 ; What step attributes have to be equal, despite the ; "event_similarity_threshold" ; The set can be empty. protected_considering_step_attributes = protected_buying_step_attributes = swap_window = 1 ; What optimisation strategy to use. Possible values are none, average or global: ; - empty or "none" ; No optimisation. Add journeys by descending journey length. ; - average: ; Compute average journey, i.e. the journey that has highest average ; similarity to all other journeys. Use this journey as average journey. ; - global: ; If adding a new PDJ to a BPM, find the most similar of already processed ; PDJ, i.e. PDJs that are part of the BPM. Align new PDJ against the most ; similar and add it then to BPM optimise = none ; Significant threshold. Allowed values are 0 (0%) to 1 (100%). ; If a value above 0 is assigned, nodes with this frequency will be visualised, ; even if the algorithms (mcs, enumeration) have not selected them. ; This value significant = 0.2 ; Non-significant threshold. Allowed values are 0 (0%) to 1 (100%). ; This threshold is used at two occasions in the code: ; - If pruning is activated, this threshold removes all nodes from the initial ; BPM (before MCL or enumeration sees it) below this threshold. ; - After a MCL or enumeration run, all nodes that were selected by the ; algorithm and are below the threshold will be removed. nonsignificant = 0.05 ; Should the initial BPM be pruned, meaning: should all nodes be removed that ; are below the "nonsignificant" threshold. This pruning happens, before MCL or ; enumeration is performed. prune = true [pdjm] ; Method to compute a PDJ-Map. ; Possible values are: 'mcl', 'enum' or 'none' ; 'none' means, no reduction of the BPM method = mcl ; Attributes for PDJ-Map computation. trigger_attributes = considering_step_attributes = jrn_step_type ready_to_purchase_attributes = buying_step_attributes = jrn_step_type purchase_attributes = [enumeration] ; Score factor for importance factor_importance = 1 ; Score factor for frequency factor_frequency = 0.8 ; Score factor for entropy factor_entropy = 1 ; ... factor_number_of_nodes = 1 ; Print every status_every enumerations an interim result status_every = 0 [mcl] max_iterations = 200 expansion_factor = 2 inflation_factor = 3 directed = false weighted = true [chunk] ; Should resulting PDJ-Map be chunked. ; If above method is set to 'none', chunks will be computed on the original BPM chunk = false ; Necessary similarity between two bpm nodes in order to be chunked together. similarity = 0.75 pos_type = min radius = 1 chunk_level = complete chunk_crit = both considering_step_attributes = jrn_goal_type buying_step_attributes = jrn_goal_type [visualisation] ; What attribute to use as node text in visualisation. ; NOTE!!!!!!! ; If not all events in a node have the same value for the provided attribute, ; an arbitrary will be chosen! ; Attribute_prefix from [global] section will be used to prefix these ; attributes trigger_text_attribute = considering_step_text_attribute = jrn_step_type ;ready_to_purchase_text_attribute = buying_step_text_attribute = jrn_step_type ;purchase_text_attribute = ;write_to_db = true format = svg result_table = results ; If both following strings are set output PDJ-Maps are also written to the ; filesystem at corresponding locations. file_output_path = "./_outputTemp/" # Obsolete because now we have output_path in "global" section file_output_prefix = "testrun_" importance = jrn_importance [tactical_opportunities] defection_similarity_threshold = 0.8 acquisition_similarity_threshold = 0.2 connection = complete file_output_path = "./_outputTemp/" file_output_prefix = "run_tomap"
3ecb1f363331777db9ca02f592ee913c681cc309
[ "JavaScript", "Text", "Ruby", "INI" ]
42
Ruby
geometryglobal-emea/pathfinder-algorithm
ae9b3079190bb4960328935b5f25924e493a6573
afabae9c19271af9b911b226144a925348949f85
refs/heads/master
<repo_name>hebaihe55/kerry<file_sep>/lottery.php <?php /** * Created by PhpStorm. * User: hejiyuan * Date: 2015/11/26 * Time: 11:09 */ if (!isset($_COOKIE["user1"])) { setcookie(user1, time() + mt_rand(), time() + 24*60*60- (date('H')*60*60+date('m')*60) ); } ?> <!DOCTYPE html> <html lang="zh"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=750, user-scalable=no, target-densitydpi=device-dpi"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>静安嘉里中心</title> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="js/swiper.min.js"></script> <script src="js/bootstrap.min.js"></script> <!-- Bootstrap --> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/swiper.min.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> <script> function check() { var username = $('#username').val(); var mobile = $('#mobile').val(); if (username == "" || mobile == "") { alert('请输入完整!'); return false; } if (mobile.length != 11) { alert("请输入正确手机号!"); return false; } document.form1.submit(); } </script> </head> <body> <div class="container-fluid"> <header class="text-center"><a href="menu.html"><img src="img/headleft.jpg"></a><img src="img/headcenter.jpg"><a href="javascript:history.go(-1);"><img src="img/headright.jpg"></a> </header> <div class="text-center"><img src="img/daoju.jpg"></div> <div class="text-center userinfo "> <form action="code/api.php" method="post" name="form1" id="form1"> <input type="text" class="txt " placeholder="请输入姓名" id="username" name="username"> <input type="text" class="txt " placeholder="请输入手机号" id="mobile" name="mobile"> <input type="hidden" value='<?php echo $_COOKIE["user1"] ?>' id="openid" name="openid"> <img src="img/submit.png" onclick="return check()"> </form> </div> <footer class="text-center"><img src="img/footer.jpg"></footer> </div> </body> </html><file_sep>/okshear.php <?php require("code/kerry.php"); header("Content-type: text/html;charset=utf-8"); if (!isset($_COOKIE["user1"])) { setcookie(user1, time() + mt_rand(), time() + 24*60*60- (date('H')*60*60+date('m')*60) ); } $openid = $_COOKIE["user1"]; if (kerry::UserCheck($openid) == 0) { kerry::UserAdd($openid); } $aa=array(); $aa=kerry::ActiveGroup($openid); $i=count($aa); if($i==0) { kerry::ActiveAdd($openid, "剪刀"); header("Location: index.html"); exit(); } ?> <!DOCTYPE html> <html lang="zh"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=750, user-scalable=no, target-densitydpi=device-dpi"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>静安嘉里中心</title> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="js/swiper.min.js"></script> <script src="js/bootstrap.min.js"></script> <!-- Bootstrap --> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/swiper.min.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> </head> <body> <script type="text/javascript" src="http://zb.weixin.qq.com/nearbycgi/addcontact/BeaconAddContactJsBridge.js"> </script> <script type="text/javascript"> BeaconAddContactJsBridge.ready(function(){ //判断是否关注 BeaconAddContactJsBridge.invoke('checkAddContactStatus',{} ,function(apiResult){ if(apiResult.err_code == 0){ var status = apiResult.data; if(status == 1){ }else{ //跳转到关注页 BeaconAddContactJsBridge.invoke('jumpAddContact'); } }else{ alert(apiResult.err_msg) } }); }); </script> <div class="container-fluid"> <header class="text-center"><a href="menu.html"><img src="img/headleft.jpg"></a><img src="img/headcenter.jpg"><a href="javascript:history.go(-1);"><img src="img/headright.jpg"></a> </header> <div class="text-center"> <a href="collect.php"> <img src="img/okshear.jpg" class="img-responsive"></a> </div> <footer class="text-center"><img src="img/footer.jpg"></footer> </div> </body> </html><file_sep>/discount.php <?php /** * Created by PhpStorm. * User: hejiyuan * Date: 2015/11/30 * Time: 22:19 */ $flag=$_GET["flag"]; ?> <!DOCTYPE html> <html lang="zh"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=750, user-scalable=no, target-densitydpi=device-dpi"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>静安嘉里中心</title> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="js/swiper.min.js"></script> <script src="js/bootstrap.min.js"></script> <!-- Bootstrap --> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/swiper.min.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> </head> <body> <div class="container-fluid"> <header class="text-center"><a href="menu.html"><img src="img/headleft.jpg"></a><img src="img/headcenter.jpg"><a href="javascript:history.go(-1);"><img src="img/headright.jpg"></a> </header> <div class="text-center"><img src="img/discount1.jpg"></div> <div class='text-center <?php if($flag!=""){echo "show";}else{echo "hidden";}?> '> <img src="img/discount2_01.jpg"> <?php if($flag=="ESSIE NAILS"){?> <h2 style="height:48px; line-height: 34px; font-size: 3em "><?php echo $flag?></h2> <h3>凭此电子券至店铺消费即享5折优惠</h3> <?php } else { ?> <h2 style="height:48px; line-height: 4px; font-size: 3em "><?php echo $flag?></h2> <h3>凭此电子折扣券可至北区1F客服台兑换实体优惠券</h3> <h3>(仅限当天优惠使用)</h3> <?php } ?> </div> <div class='text-center <?php if($flag==""){echo "show";}else{echo "hidden";}?>'><a href="show.php?#a<?php echo rand(1,6)?>"> <img src="img/discount3.jpg"></a></div> <div style="visibility: hidden" ><img src="img/discount2_03.jpg" /> </div> <footer class="text-center"><img src="img/footer.jpg"></footer> </div> </body> </html><file_sep>/admin/conn.php <?php $conn = @mysql_connect('localhost','hejiyuan1','HJYhjy@123321'); if (!$conn) { die('Could not connect: ' . mysql_error()); } mysql_select_db('WECHAT1', $conn); ?><file_sep>/collect.php <?php require("code/kerry.php"); if (!isset($_COOKIE["user1"])) { setcookie(user1, time() + mt_rand(), time() + 24*60*60- (date('H')*60*60+date('m')*60) ); } $openid = $_COOKIE["user1"]; $userlog= kerry::Userlogin($openid); if( !is_null( $userlog) ) { header("Location:../discount.php?flag=" .$userlog); exit(); } $aa=array(); $aa=kerry::ActiveGroup($openid); $i=count($aa); ?> <!DOCTYPE html> <html lang="zh"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=750, user-scalable=no, target-densitydpi=device-dpi"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>静安嘉里中心</title> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="js/swiper.min.js"></script> <script src="js/bootstrap.min.js"></script> <!-- Bootstrap --> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/swiper.min.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> </head> <body> <div class="container-fluid"> <header class="text-center"><a href="menu.html"> <img src="img/headleft.jpg"></a><img src="img/headcenter.jpg"><a href="javascript:history.go(-1);"><img src="img/headright.jpg"></a> </header> <div class='text-center <?php if($i>=2){echo "show";}else{ echo "hidden";} ?>'> <a href="lottery.php"> <img src="img/cc1.jpg" /> </a> </div> <div class='text-center <?php if($i<2){echo "show";}else{ echo "hidden";} ?>'> <img src="img/collect1.jpg" /> </div> <footer class="text-center"><img src="img/footer.jpg"></footer> </div> </body> </html><file_sep>/README.md # kerry 嘉里中心 <file_sep>/admin/login.php <?php /** * Created by PhpStorm. * User: hejiyuan * Date: 2015/11/27 * Time: 18:32 */ ?> <!DOCTYPE html> <html> <head> <title>登陆</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> <meta name="keywords" content="Flat Dark Web Login Form Responsive Templates, Iphone Widget Template, Smartphone login forms,Login form, Widget Template, Responsive Templates, a Ipad 404 Templates, Flat Responsive Templates" /> <link href="../css/style1.css" rel='stylesheet' type='text/css' /> <!--webfonts--> <!--//webfonts--> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <script> function oncheck() { if( $("#username").val()=="" || $("#userpwd").val()=="") { alert("请输入完整"); return false; } return true; } </script> </head> <body> <!--SIGN UP--> <div class="login-form"> <div class="head-info"> <label class="lbl-1"> </label> <label class="lbl-2"> </label> <label class="lbl-3"> </label> </div> <div class="clear"> </div> <div class="avtar"> <img src="../img/avtar.png" /> </div> <form action="../code/api.php" method="get" onsubmit="return oncheck()" > <input type="text" class="text" placeholder="用户名" id="username" name="username" > <div class="key"> <input type="password" placeholder="密码" id="userpwd" name="userpwd"> </div> <input type="hidden" name="action" value="usercheck"> <div class="signin"> <input type="submit" value="Login" > </div> </form> </div> <div class="copy-rights"> </div> </body> </html><file_sep>/code/api.php <?php /** * Created by PhpStorm. * User: hejiyuan * Date: 2015/11/26 * Time: 11:04 */ require("kerry.php"); switch($_GET["action"]) { case 'usercheck': UserCheck(); break; default:UserEdit(); } function UserCheck() { if($_GET["username"]=="kerry" && $_GET["userpwd"]=="<PASSWORD>") { header("Location:../admin/index.php"); exit(); } else { header("Location:../admin/login.php"); exit(); } } function UserEdit() { $username = $_POST["username"]; $mobile = $_POST["mobile"]; $openid = $_POST["openid"]; $ext1 = ""; $ext2 = ""; $flag=0; $ticket=array(); $ticket = kerry::TicketUnused(); if (count($ticket) > 0){ if ($ticket["begintime"] < date("Y-m-d H:m:s") && $ticket["endtime"] > date("Y-m-d H:m:s")) { $ext1 = $ticket['brand']; $ext2 = $ticket["mid"]; $flag=1; } else { $ext1 = ""; $ext2 = $ticket["mid"]; $flag=1; } } $userlog= kerry::Userlogin($openid); if($userlog==null) { kerry::UserEdit($openid, $username, $mobile,$ext1,$ext2); kerry::TicketEdit($ext2); } header("Location:../discount.php?flag=" .$ext1); exit(); } ?><file_sep>/admin/index.php <?php /** * Created by PhpStorm. * User: hejiyuan * Date: 2015/11/27 * Time: 19:16 */ ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>后台</title> <link rel="stylesheet" type="text/css" href="themes/default/easyui.css"> <link rel="stylesheet" type="text/css" href="themes/icon.css"> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/jquery.easyui.min.js"></script> <script type="text/javascript" src="js/easyui-lang-zh_CN.js"></script> <style> html,body,div,table{ margin: 0; padding: 0; border: 0; text-align: center } </style> <script type="text/javascript"> function doSearch(){ $('#tt').datagrid('load',{ mobile: $('#mobile').val() }); } </script> </head> <body> <div class="demo-info" style="width: 1200px; margin: 0 auto"> <table id="tt" class="easyui-datagrid" style="width:1200px;height:600px; margin: 0 auto;" url="datagrid24_getdata.php" title="搜索" iconCls="icon-search" toolbar="#tb" rownumbers="true" pagination="true"> <thead> <tr> <th field="RelName" width="80">姓名</th> <th field="mobile" width="120">手机号</th> <th field="openid" width="80" align="right">微信号</th> <th field="ext1" width="150" align="right">折扣券</th> <th field="Createdtime" width="200">时间</th> </tr> </thead> </table> <div id="tb" style="padding:3px"> <span>手机号:</span> <input id="mobile" name="mobile" style="line-height:26px;border:1px solid #ccc"> <a href="#" class="easyui-linkbutton" plain="true" onclick="doSearch()">搜索</a> </div> </div> </body> </html><file_sep>/market.php <?php /** * Created by PhpStorm. * User: hejiyuan * Date: 2015/11/30 * Time: 15:21 */ ?> <!DOCTYPE html> <html lang="zh"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=750, user-scalable=no, target-densitydpi=device-dpi"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>静安嘉里中心</title> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="js/swiper.min.js"></script> <script src="js/bootstrap.min.js"></script> <!-- Bootstrap --> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/swiper.min.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> </head> <body> <div class="container-fluid"> <header class="text-center"><a href="menu.html"><img src="img/headleft.jpg"></a><img src="img/headcenter.jpg"><a href="javascript:history.go(-1);"><img src="img/headright.jpg"></a> </header> <div class="text-center"><img src="img/market1.jpg" class="img-responsive"></div> <div class="text-center"><a href="sos.html"> <img src="img/begin2.jpg" class="img-responsive"></a></div> <footer class="text-center"><img src="img/footer.jpg"></footer> </div> </body> </html><file_sep>/code/kerry.php <?php /** * Created by PhpStorm. * User: hejiyuan * Date: 2015/11/25 * Time: 13:47 */ header("Content-type: text/html;charset=utf-8"); class kerry { public static function test() { return "hello world"; } //判断用户是否存在 public static function UserCheck($openid) { $conn = mysqli_connect("localhost", "hejiyuan1", "HJYhjy@123321", "WECHAT1"); $conn->query("set names utf8"); // 检测连接 if (!$conn) { die("Connection failed: " . mysql_connect_error()); } $sql = " select count(openid) from users where openid='" . $openid . "'"; $result = $conn->query($sql); $rows = $result->fetch_row(); return $rows[0]; } //判断用户是否存在 public static function Userlogin($openid) { $conn = mysqli_connect("localhost", "hejiyuan1", "HJYhjy@123321", "WECHAT1"); $conn->query("set names utf8"); // 检测连接 if (!$conn) { die("Connection failed: " . mysql_connect_error()); } $sql = " select ext1 from users where openid='" . $openid . "'"; $result = $conn->query($sql); $rows = $result->fetch_row(); return $rows[0]; } //查找未使用的折扣券 public static function TicketUnused() { $conn = mysqli_connect("localhost", "hejiyuan1", "HJYhjy@123321", "WECHAT1"); $conn->query("set names utf8"); // 检测连接 if (!$conn) { die("Connection failed: " . mysql_connect_error()); } $sql = "select * from ticket where flag1=0 order by begintime limit 0,1"; $result = $conn->query($sql); $rows = $result->fetch_assoc(); return $rows; } //活动分组 public static function ActiveGroup($openid) { $conn = mysqli_connect("localhost", "hejiyuan1", "HJYhjy@123321", "WECHAT1"); $conn->query("set names utf8"); // 检测连接 if (!$conn) { die("Connection failed: " . mysql_connect_error()); } $sql = "SELECT active ,COUNT(mid) total FROM active WHERE openid='" . $openid . "' GROUP BY active"; $rs = $conn->query($sql); $result = array(); while ($row = $rs->fetch_array()) { $result[$row[0]] = $row[1]; } mysqli_close($conn); return $result; } //活动添加 public static function ActiveAdd($openid, $avtive) { $conn = mysqli_connect("localhost", "hejiyuan1", "HJYhjy@123321", "WECHAT1"); $conn->query("set names utf8"); // 检测连接 if (!$conn) { die("Connection failed: " . mysql_connect_error()); } $sql = "insert into active(openid,active) values('" . $openid . "','" . $avtive . "')"; $result = false; if (mysqli_query($conn, $sql)) { $result = true; } mysqli_close($conn); return $result; } public static function TicketEdit($mid) { $conn = mysqli_connect("localhost", "hejiyuan1", "HJYhjy@<PASSWORD>", "WECHAT1"); $conn->query("set names utf8"); // 检测连接 if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "update ticket set flag1=1 where mid=" . $mid ; echo $sql; $result = false; if (mysqli_query($conn, $sql)) { $result = true; } mysqli_close($conn); echo $result; } public static function UserEdit($openid, $userName, $mobile,$ext1,$ext2) { $conn = mysqli_connect("localhost", "hejiyuan1", "<PASSWORD>", "WECHAT1"); $conn->query("set names utf8"); // 检测连接 if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "update users set relname='" . $userName . "', mobile='" . $mobile . "', ext1='" . $ext1 . "', ext2='" . $ext2 ."' where openid='" . $openid . "'"; $result = false; if (mysqli_query($conn, $sql)) { $result = true; } mysqli_close($conn); return $result ; } //添加用户 public static function UserAdd($openid) { $conn = mysqli_connect("localhost", "hejiyuan1", "<PASSWORD>", "WECHAT1"); $conn->query("set names utf8"); // 检测连接 if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "insert into users(openid) values('" . $openid . "')"; $result = false; if (mysqli_query($conn, $sql)) { $result = true; } mysqli_close($conn); return $result; } } ?><file_sep>/i2.php <?php require("code/kerry.php"); if (!isset($_COOKIE["user1"])) { setcookie(user1, time() + mt_rand(), time() + 24*60*60- date('H')*60*60+date('m')*60 ); } $openid = $_COOKIE["user1"]; if (kerry::UserCheck($openid) == 0) { kerry::UserAdd($openid); } ?> <!DOCTYPE html> <html lang="zh"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=750, user-scalable=no, target-densitydpi=device-dpi"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>静安嘉里中心</title> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="js/swiper.min.js"></script> <script src="js/bootstrap.min.js"></script> <!-- Bootstrap --> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/swiper.min.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> </head> <body> <script type="text/javascript" src="http://zb.weixin.qq.com/nearbycgi/addcontact/BeaconAddContactJsBridge.js"> </script> <script type="text/javascript"> BeaconAddContactJsBridge.ready(function(){ //判断是否关注 BeaconAddContactJsBridge.invoke('checkAddContactStatus',{} ,function(apiResult){ if(apiResult.err_code == 0){ var status = apiResult.data; if(status == 1){ }else{ //跳转到关注页 BeaconAddContactJsBridge.invoke('jumpAddContact'); } }else{ alert(apiResult.err_msg) } }); }); </script> <div class="container-fluid"> <header class="text-center"><a href="menu.html"><img src="img/headleft.jpg"></a><img src="img/headcenter.jpg"><a href="javascript:history.go(-1);"><img src="img/headright.jpg"></a> </header> <div class="swiper-container"> <div class="swiper-wrapper"> <div class="swiper-slide"><a href="dream.php"><img src="img/banner5.jpg" class="img-responsive"></a></div> <div class="swiper-slide"><a href="map.php"><img src="img/banner1.jpg" class="img-responsive"></a></div> <div class="swiper-slide"><a href="coffee.html"><img src="img/banner2.jpg" class="img-responsive"></a></div> <div class="swiper-slide"><a href="sewing.html"><img src="img/banner4.jpg" class="img-responsive"></a></div> <div class="swiper-slide"><a href="cake.html"><img src="img/banner3.jpg" class="img-responsive"></a></div> <div class="swiper-slide"><a href="market.php"><img src="img/banner6.jpg" class="img-responsive"></a></div> <div class="swiper-slide"><a href="sos.html"><img src="img/banner7.jpg" class="img-responsive"></a></div> </div> <!-- Add Pagination --> <div class="swiper-pagination"></div> </div> <!-- Swiper JS --> <!-- Initialize Swiper --> <script> var swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', paginationClickable: true, spaceBetween: 30, autoplay: 3000 }); </script> <div class="text-center"><img src="img/logo.jpg"></div> <footer><img src="img/footer.jpg"></footer> </div> </body> </html>
e1affa9d159b74b075f61fc06c7650e3a8faaaef
[ "Markdown", "PHP" ]
12
PHP
hebaihe55/kerry
2a52a00f0d23def4c04c531f101305d8e6b22b9a
84b656cf49ff41853138f6efbf498bfe0707e2dd
refs/heads/master
<file_sep>(function () { 'use strict'; angular .module('core') .controller('ManageRequirementsController', ManageRequirementsController); function ManageRequirementsController($scope, $state, $window, Studies, Requirements) { var vm = this; $scope.findRequirements = function() { Requirements.getAll().then(function(response) { $scope.requirements = response.data; $scope.requirementsFiltered = $scope.requirements; $scope.requirementsFiltered.sort(function(a, b){ return a.requirementName.toLowerCase() > b.requirementName.toLowerCase(); }); }, function(error) { $scope.error = 'Unable to retrieve requirements!\n' + error; }); }; $scope.findStudies = function() { Studies.getAll().then(function(response) { $scope.studies = response.data; }, function(error) { $scope.error = 'Unable to retrieve requirements!\n' + error; }); }; $scope.init = function() { $scope.findStudies(); $scope.findRequirements(); } $scope.filterListOfRequirements = function() { $scope.requirementsFiltered = []; $scope.requirementsFiltered = $scope.requirements.filter(function(requirement) { return requirement.requirementName.toLowerCase().search($scope.searchEntry.toLowerCase()) > -1; }); $scope.requirementsFiltered.sort(function(a, b) { return a.requirementName.toLowerCase() > b.requirementName.toLowerCase(); }); }; $scope.deleteRequirementFromDatabase = function(requirement) { var id = requirement._id; Requirements.delete(id).then(function(response) { $window.location.reload(); }, function(error) { console.log(error); }); //deleteRequirementFromAllStudies(requirement); }; /* function deleteRequirementFromAllStudies(requirement) { //function takes id of requirement that is to be deleted //then finds all studies that were using this requirement //and converts those to removedRequirement property var id = requirement._id; for (var i in $scope.studies) { var newListOfRequirements = {}; for (var j in $scope.studies[i].requirements) { if (j == id) { console.log(j); for (var k in $scope.studies[i].requirements) { if (k != id) { newListOfRequirements[id] = $scope.studies[i].requirements[k]; var updatedStudy = $scope.studies[i]; updatedStudy.requirements = newListOfRequirements; console.log(newListOfRequirements); console.log(updatedStudy); } } } } */ /* Studies.update(updatedStudy).then(function(response) { }, function(error) { console.log(error); }); } //$window.location.reload(); }; */ } }()); <file_sep>var mongoose = require('mongoose'), Schema = mongoose.Schema; var archiveSchema = new Schema({ study_name: { type: String }, }, {strict: false, minimize: false} ); var Archive = mongoose.model('Archive', archiveSchema); module.exports = Archive; <file_sep>**- Link to Deployed Page**: https://softwareproject.herokuapp.com **- Credits:** - https://www.w3schools.com - https://jsfiddle.net - Bootstrap Link: https://angular-ui.github.io/bootstrap/ Our client was the neurology department of Shands Hospital. The clients were looking for an app to help them find any patients that came into the emergency room and matched the requirements of any of the studies they were conducting. Previously they had to look through a book that included multiple studies and had to check the requirements of each study for every patient that might have possibly met those requirements. If there was a new study that patients could qualify for or a study that was no longer being researched, the book would have to be reprinted. Our clients knew that there must be a better way, and therefore sought the help of some amazing programmers. In the short period of a semester our team was able to create a web app to streamline and simplify the process of finding matching patients as well as managing the detailed studies they were conducting. It starts with the home page where the user can choose between the study filter and the administrator page. **[Guest]{.underline}** The study filter is the focal point of the app that will be used by all of the department to quickly find patients that may match any of the studies. The page begins with all possible criteria as inputs to the filter (on the left), such as the patient's age or the type of stroke the patient had experienced. As the patient's information is entered, you will notice that the list of studies that the patient is eligible for shortens. You will also see that the number of questions about the patient will decrease because the questions dynamically change based on what studies the patient qualifies for. If none of the studies remaining require the answer of a certain question, that question will no longer be asked to save the user's time. If a study is found that matches the patient's information, the user can send an email from the app to the coordinator in charge of that study so that further research can be done on that specific patient. **[Administrator]{.underline}** This side allows all of the studies and requirements of each study to be managed. This part of the app requires coordinators to login in order to alter any of the database information. Studies can be added, edited, archived (removed from main studies list but not completely deleted), and permanently deleted from this branch. To make the app much more dynamic, administrators can make new requirements to be added to studies in the case that an unforeseen requirement must be added. This can be done on the manage requirement page. For example, if a new study needs a patient with blood type O negative, this requirement can be added to the database, which can then be added to the new study. There are three types of requirements which are Boolean (true/false), Range (specific range of numeric values), or Custom (two or more custom string options). A new study can be added to the database with a new requirement, and when any user uses the filter feature, then that new requirement will be listed as a patient question. The edit study allows any textual information involving the study to be altered, such as the lists of inclusion/exclusion principles or the coordinator's information. The archive study feature allows any study to be saved in a different collection so that if the study is no longer being researched at the time, but may return in the future, it can be recovered and transferred back into the main study collection. **- Screenshots** - **Home Page ** ![Picture1.png](media/Picture1.png) **\ ** - **View list of all client studies and Filtering studies dynamically** > ![Picture2.png](media/Picture2.png) > - **Display inclusion/exclusion criteria and Allow guest to send email to coordinator** ![Picture3.png](media/Picture3.png) - **Admin can edit client studies** ![Picture4.png](media/Picture4.png) ![Picture5.png](media/Picture5.png) - **Allow admin to Log-In** ![Picture6.png](media/Picture6.png) - **Allow admin to archive studies** ![Picture7.png](media/Picture7.png) **\ ** - **Allow admin to remove studies** ![Picture8.png](media/Picture8.png) - **Allow admin to add studies ** ![Picture9.png](media/Picture9.png) **\ ** **-Instructions for how to run the project locally** To run the project locally, a user has to run the command "npm start" while in the main directory of the project. In order for "npm start" to run, command "npm install" has to be done previously in the terminal. The project will then be found at localhost:3000. **- How to update database and server connections** The project uses MongoDB for the database. The uri for the DB can be found in /config/env/development.js. <file_sep>(function () { 'use strict'; angular .module('core') .controller('EditRequirementController', EditRequirementController); function EditRequirementController($scope, $state, $window, Requirements, $stateParams) { $scope.init = function() { $scope.requirement = $stateParams.requirement; }; $scope.save = function(requirement) { Requirements.update(requirement).then(function(response) { $window.location.href = '/manageRequirements'; }, function(error) { console.log(error); }); }; $scope.cancel = function() { $window.location.href = '/manageRequirements'; }; } }()); <file_sep>angular.module('core').factory('Archive', ['$http', '$window', function($http, $window) { var methods = { getAll: function() { return $http.get($window.location.protocol + '//' + $window.location.host + '/api/archive/'); }, create: function(study) { return $http.post($window.location.protocol + '//' + $window.location.host + '/api/archive/', study); }, delete: function(id) { return $http.delete($window.location.protocol + '//' + $window.location.host + '/api/archive/' + id); }, update: function(study) { return $http.put($window.location.protocol + '//' + $window.location.host + '/api/archive/', study); } }; return methods; } ]); <file_sep>var mongoose = require('mongoose'), Schema = mongoose.Schema; var studySchema = new Schema({ study_name: { type: String }, }, { strict: false, minimize: false } ); var Study = mongoose.model('Study', studySchema); module.exports = Study; <file_sep>(function () { 'use strict'; angular .module('core') .controller('FilterController', FilterController); function FilterController($window, $scope, Studies, Requirements, $http) { var vm = this; var requirement = {}; var sortedArrayOfAllIDssOfRequirementsPossibleFromFilteredStudies = []; var setOfAllRequirementsPossibleFromFilteredStudies = new Set(); $scope.listOfAnswersByIDs = {}; $scope.listOfAnswersByRequirement = []; $scope.sortedArrayOfAllRequirementsPossibleFromFilteredStudies = []; $scope.find = function() { Studies.getAll().then(function(response) { $scope.loading = false; //remove loader $scope.studies = response.data; $scope.studiesThatMatchFilterParameters = $scope.studies; }, function(error) { $scope.loading = false; $scope.error = 'Unable to retrieve studies!\n' + error; }); }; $scope.findRequirements = function() { Requirements.getAll().then(function(response) { $scope.loading = false; //remove loader $scope.requirements = response.data; $scope.sortedArrayOfAllRequirementsPossibleFromFilteredStudies = $scope.requirements; //sort by priority then name $scope.sortedArrayOfAllRequirementsPossibleFromFilteredStudies.sort(function(a, b) { return [a.priority, a.requirementName] > [b.priority, b.requirementName] ? 1:-1; }); }, function(error) { $scope.loading = false; $scope.error = 'Unable to retrieve requirements!\n' + error; }); }; $scope.init = function() { $scope.find(); $scope.findRequirements(); }; $scope.filterStudies = function(requirement) { $scope.noStudiesThatMatchParameters = false; $scope.listOfAnswersByRequirement = []; $scope.studiesThatMatchFilterParameters = $scope.studies; //removes all empty requirements Object.keys($scope.listOfAnswersByIDs).forEach(function(i) { if ($scope.listOfAnswersByIDs[i] === "" || $scope.listOfAnswersByIDs[i] === undefined) delete $scope.listOfAnswersByIDs[i]; }); //finds list of requirements from list of answers using database name of requirement Object.keys($scope.listOfAnswersByIDs).forEach(function(i) { $scope.listOfAnswersByRequirement = $scope.listOfAnswersByRequirement.concat($scope.requirements.filter(function(requirement) { return i === requirement._id })); }); Object.keys($scope.listOfAnswersByRequirement).forEach(function(i) { var currentRequirement = $scope.listOfAnswersByRequirement[i]; if (currentRequirement.typeOfRequirement === "Boolean") { $scope.studiesThatMatchFilterParameters = $scope.studiesThatMatchFilterParameters.filter(function(study) { var requirementFromStudyMatchingCurrentFilterParameter = study.requirements[currentRequirement._id]; if (requirementFromStudyMatchingCurrentFilterParameter != undefined) { //filters by checking if the study's requirement value is equal to the answer from the html page return requirementFromStudyMatchingCurrentFilterParameter === $scope.listOfAnswersByIDs[currentRequirement._id]; } else { return true; } }); } else if (currentRequirement.typeOfRequirement === "Range") { $scope.studiesThatMatchFilterParameters = $scope.studiesThatMatchFilterParameters.filter(function(study) { var requirementFromStudyMatchingCurrentFilterParameter = study.requirements[currentRequirement._id]; if (requirementFromStudyMatchingCurrentFilterParameter != undefined && $scope.listOfAnswersByIDs[currentRequirement._id] != "") { if (requirementFromStudyMatchingCurrentFilterParameter.lower_bound != undefined && requirementFromStudyMatchingCurrentFilterParameter.upper_bound != undefined) { return requirementFromStudyMatchingCurrentFilterParameter.lower_bound <= $scope.listOfAnswersByIDs[currentRequirement._id] && requirementFromStudyMatchingCurrentFilterParameter.upper_bound >= $scope.listOfAnswersByIDs[currentRequirement._id]; } else if (requirementFromStudyMatchingCurrentFilterParameter.lower_bound != undefined) { return requirementFromStudyMatchingCurrentFilterParameter.lower_bound <= $scope.listOfAnswersByIDs[currentRequirement._id]; } else if (requirementFromStudyMatchingCurrentFilterParameter.upper_bound != undefined) { return requirementFromStudyMatchingCurrentFilterParameter.upper_bound >= $scope.listOfAnswersByIDs[currentRequirement._id]; } } else { return true; } }); } else if (currentRequirement.typeOfRequirement === "Custom") { $scope.studiesThatMatchFilterParameters = $scope.studiesThatMatchFilterParameters.filter(function(study) { var requirementFromStudyMatchingCurrentFilterParameter = study.requirements[currentRequirement._id]; if (requirementFromStudyMatchingCurrentFilterParameter != undefined) { //filters by checking if the study's requirement value is equal to the answer from the html page return requirementFromStudyMatchingCurrentFilterParameter.toLowerCase() === $scope.listOfAnswersByIDs[currentRequirement._id].toLowerCase(); } else { return true; } }); } }); if ($scope.studiesThatMatchFilterParameters.length > 0) { findAllRequirementsAvailableInFilteredStudies(requirement); } else { $scope.noStudiesThatMatchParameters = true; } }; function findAllRequirementsAvailableInFilteredStudies(requirement) { setOfAllRequirementsPossibleFromFilteredStudies.clear(); $scope.sortedArrayOfAllRequirementsPossibleFromFilteredStudies = []; for (var i = 0; i < $scope.studiesThatMatchFilterParameters.length; i++) { angular.forEach($scope.studiesThatMatchFilterParameters[i].requirements, function(value, key) { setOfAllRequirementsPossibleFromFilteredStudies.add(key); }) } //adds list of answers angular.forEach($scope.listOfAnswersByIDs, function(value, key) { setOfAllRequirementsPossibleFromFilteredStudies.add(key); }) setOfAllRequirementsPossibleFromFilteredStudies.add(requirement._id); var arrayOfAllIDssOfRequirementsPossibleFromFilteredStudies = Array.from(setOfAllRequirementsPossibleFromFilteredStudies); var arrayOfAllRequirementsPossibleFromFilteredStudies = []; $scope.sortedArrayOfAllRequirementsPossibleFromFilteredStudies = []; arrayOfAllIDssOfRequirementsPossibleFromFilteredStudies.forEach(function(i) { $scope.sortedArrayOfAllRequirementsPossibleFromFilteredStudies = $scope.sortedArrayOfAllRequirementsPossibleFromFilteredStudies.concat($scope.requirements.filter(function(requirement) { return i === requirement._id; })); }); $scope.sortedArrayOfAllRequirementsPossibleFromFilteredStudies.sort(function(a, b) { return a.requirementName < b.requirementName; }); $scope.sortedArrayOfAllRequirementsPossibleFromFilteredStudies.sort(function(a, b) { return a.priority > b.priority; }); } $scope.postData = {}; $scope.contact = { name: "", message: "" }; $scope.postMail = function (study) { // Check form validation var contact = $scope.contact; // wrap all your input values in $scope.postData $scope.postData = angular.copy({contact,study}); $http.post('/api/contact', $scope.postData) .success(function(data) { // Show success message $window.location.href = '/filter'; }) .error(function(data) { // Show error message }); }; }; }()); <file_sep>(function () { 'use strict'; angular .module('core') .controller('EditController', EditController); function EditController($scope, $state, $window, Studies, $stateParams, Requirements) { var vm = this; $scope.init = function() { $scope.study = $stateParams.study; $scope.findRequirements(); $scope.listOfAnswersByIDs = $scope.study.requirements; $scope.searchEntry = ""; }; $scope.findRequirements = function() { Requirements.getAll().then(function(response) { $scope.requirements = response.data; findRequirementsByIDsInStudy() }, function(error) { $scope.error = 'Unable to retrieve requirements!\n' + error; }); }; function findRequirementsByIDsInStudy() { $scope.requirementsInStudy = []; $scope.requirementsNotInStudy = $scope.requirements; $scope.requirementsNotInStudyAndFiltered = $scope.requirementsNotInStudy; for (var id in $scope.listOfAnswersByIDs) { for (var j in $scope.requirements) { if (id == $scope.requirements[j]._id) { var requirement = $scope.requirements[j] $scope.requirementsInStudy.push(requirement); $scope.requirementsNotInStudy.splice(j, 1); } } } } $scope.filterListOfRequirements = function() { $scope.requirementsNotInStudyAndFiltered = []; $scope.requirementsNotInStudyAndFiltered = $scope.requirementsNotInStudy.filter(function(requirement) { return requirement.requirementName.toLowerCase().search($scope.searchEntry.toLowerCase()) > -1; }); }; $scope.addNewInclusionPrinciple = function() { $scope.study.inclusion.push(""); }; $scope.addNewExclusionPrinciple = function() { $scope.study.exclusion.push(""); }; $scope.removeCurrentInclusionPrinciple = function(index) { $scope.study.inclusion.splice(index, 1); }; $scope.removeCurrentExclusionPrinciple = function(index) { $scope.study.exclusion.splice(index, 1); }; $scope.addRequirementToStudy = function(requirement) { $scope.requirementsInStudy.push(requirement); //this function removes the requirement from the array //that has the same unique database name $scope.requirementsNotInStudy = $scope.requirementsNotInStudy.filter(function(el) { return el._id !== requirement._id; }); $scope.filterListOfRequirements(); } $scope.removeRequirementFromStudy = function(requirement) { //this function removes the requirement from the array //that has the same unique id $scope.requirementsInStudy = $scope.requirementsInStudy.filter(function(el) { return el._id !== requirement._id; }); $scope.requirementsNotInStudy.push(requirement); $scope.filterListOfRequirements(); } $scope.save = function(study) { var listOfRequirementsForUpdatedStudy = {}; var updatedStudy = $scope.study; for (var i in $scope.requirementsInStudy) { var currentRequirementID = $scope.requirementsInStudy[i]._id; if ($scope.listOfAnswersByIDs[currentRequirementID] != undefined) { listOfRequirementsForUpdatedStudy[currentRequirementID] = $scope.listOfAnswersByIDs[currentRequirementID]; } } updatedStudy.requirements = listOfRequirementsForUpdatedStudy; Studies.update(study).then(function(response) { $window.location.href = '/administrator'; }, function(error) { console.log(error); }); }; $scope.cancel = function() { $window.location.href = '/administrator'; }; } }()); <file_sep>(function () { 'use strict'; angular .module('core') .controller('AddStudyController', AddStudyController); function AddStudyController($scope, $state, $window, $sce, Requirements, Studies) { var vm = this; $scope.newStudy = {}; $scope.requirementsAddedToStudy = []; $scope.listOfAnswersByIDs = {}; $scope.searchEntry = ""; $scope.findRequirements = function() { Requirements.getAll().then(function(response) { $scope.loading = false; //remove loader $scope.requirements = response.data; $scope.requirementsNotAddedToStudy = $scope.requirements; $scope.requirementsNotAddedToStudyandFiltered = $scope.requirements; }, function(error) { $scope.loading = false; $scope.error = 'Unable to retrieve requirements!\n' + error; }); }; $scope.addRequirementToStudy = function(requirement) { $scope.requirementsAddedToStudy.push(requirement); //this function removes the requirement from the array //that has the same unique database name $scope.requirementsNotAddedToStudy = $scope.requirementsNotAddedToStudy.filter(function(el) { return el._id !== requirement._id; }); $scope.filterListOfRequirements(); } $scope.removeRequirementFromStudy = function(requirement) { //this function removes the requirement from the array //that has the same unique id $scope.requirementsAddedToStudy = $scope.requirementsAddedToStudy.filter(function(el) { return el._id !== requirement._id; }); $scope.requirementsNotAddedToStudy.push(requirement); $scope.filterListOfRequirements(); } $scope.addNewStudyToDatabase = function() { var listOfRequirementsForNewStudy = {}; for (var i in $scope.requirementsAddedToStudy) { var currentRequirementID = $scope.requirementsAddedToStudy[i]._id; if ($scope.listOfAnswersByIDs[currentRequirementID] != undefined) { listOfRequirementsForNewStudy[currentRequirementID] = $scope.listOfAnswersByIDs[currentRequirementID]; } } $scope.newStudy.requirements = listOfRequirementsForNewStudy; $scope.newStudy['inclusion'] = []; $scope.newStudy['exclusion'] = []; Studies.create($scope.newStudy).then(function(response) { $window.location.href = '/administrator'; }, function(error) { console.log(error); }); }; $scope.filterListOfRequirements = function() { $scope.requirementsNotAddedToStudyandFiltered = []; $scope.requirementsNotAddedToStudyandFiltered = $scope.requirementsNotAddedToStudy.filter(function(requirement) { return requirement.requirementName.toLowerCase().search($scope.searchEntry.toLowerCase()) > -1; }); }; } }());
d27c4f9ea2d401e279d620b45372db83b3b66995
[ "JavaScript", "Markdown" ]
9
JavaScript
SoftwareEngineering4C/ClientStudyDatabase
cc76e349929c5bcd1c1e1cbcad216ac516066b0f
526f0b07768c4ed69e4572739527ff87093ba8ce
refs/heads/master
<repo_name>MatthieuBizien/Rboost<file_sep>/rboost/benches/bench_binary.rs #![feature(core_intrinsics)] /// This is a benchmark for optimising the binary logistic loss function. /// /// The exact_naive function is quite slow: 50us per iteration, so 5s for 100k elements /// Without any precision loss, we can push it to 17.193 us with exact_factored_ln1p. /// /// Using Taylor series, we can push it to 3-4ms with an error < 1e-8. /// What is important is to be sure to remove ALL divisions. eg. x*3./4. => x*(3./4.) /// It's not clear if the optimisations for fast_mul and factorisation are worth it. /// /// We can also use Shanks methods on the Taylor series. It does works, but is slower than raw /// Taylor for the same precision. However it looks like more stable for reaching errors /// from 1e-10...1e-11 #[macro_use] extern crate criterion; extern crate lazy_static; use criterion::{Bencher, Criterion}; use lazy_static::*; use rand::prelude::*; use std::fmt::Debug; use std::fmt::Error; use std::fmt::Formatter; use std::intrinsics::{fadd_fast, fdiv_fast, fmul_fast, fsub_fast}; type Float = f64; lazy_static! { static ref LN_2: Float = (2. as Float).ln(); } // Naive formula. // f32: 26.157 us 26.194 us 26.237 us // f64: 49.944 us 50.028 us 50.127 us fn exact_naive(y: Float, x: Float) -> Float { let proba = 1. / (1. + (-x).exp()); let loss_1 = -y * proba.max(1e-8).ln(); let loss_2 = -(1. - y) * (1. - proba).max(1e-8).ln(); let loss = loss_1 + loss_2; loss } // Same formula, but reformulated // f32: 18.505 us 18.531 us 18.560 us. Precision VS exact_naive: 1e-5.7 // f64: 27.072 us 27.121 us 27.175 us. Precision VS exact_naive: 1e-14 fn exact_factored(y: Float, x: Float) -> Float { let a = (1. + (-x).exp()).ln(); let loss_ = -(1. - y) * (-x) + a; loss_ } // Use ln_1p instead of ln(1+...) // f32: 14.217 us 14.238 us 14.261 us // f64: 17.158 us 17.193 us 17.232 us fn exact_factored_ln1p(y: Float, x: Float) -> Float { let a = ((-x).exp()).ln_1p(); let loss_ = (1. - y) * x + a; loss_ } /// Long taylor series expansion around x=0. /// f64 with x**6: 2.1638 us 2.1728 us 2.1853 us. Precision 1e-4.6 /// f32 with x**8: 2.6404 us 2.6438 us 2.6476 us. Precision 1e-5.4 /// f64 with x**8: 3.4251 us 3.4326 us 3.4412 us. Precision: 1e-5.6 /// f32 with x**10: 3.1725 us 3.1769 us 3.1818 us. Precision 1e-5.7 /// f64 with x**10: 3.7915 us 3.7965 us 3.8024 us. Precision: 1e-6.7 /// f64 with x**12: 4.4420 us 4.4577 us 4.4883 us. Precision: 1e-7.8 /// f64 with x**14: 4.6436 us 4.7458 us 4.8832 us. Precision: 1e-8.9 /// f64 with x**16: 5.4314 us 5.4517 us 5.4787 us. Precision: 1e-9.9 /// f64 with x**18: 5.7089 us 5.7176 us 5.7275 us. Precision: 1e-9.6 /// /// Calculated using Sympy /// >>> from sympy import * /// >>> x, y, z, t = symbols('x y z t') /// >>> loss = -y*log(1/(1+exp(-x))) - (1-y)*log(1-1/(1+exp(-x))) /// >>> dn(l, n): /// >>> if n==0: return l.subs(x, 0) /// >>> return dn(diff(l, x), n-1) / n /// >>> dn(loss, 2) /// 1 / 8 fn taylor_naive(y: Float, x: Float) -> Float { let loss: Float = *LN_2; let loss = loss + (0.5 - y) * x; let x2 = x * x; let x4 = x2 * x2; let x6 = x2 * x4; let x8 = x4 * x4; let x10 = x4 * x6; let x12 = x6 * x6; let x14 = x6 * x8; let x16 = x8 * x8; let x18 = x10 * x8; let loss = loss + x2 / 8.; let loss = loss - x4 / 192.; let loss = loss + x6 / 2880.; let loss = loss - x8 * (17. / 645120.); let loss = loss + x10 * (31. / 14515200.); let loss = loss - x12 * (691. / 3832012800.); let loss = loss + x14 * (5461. / 348713164800.); let loss = loss - x16 * (929569. / 669529276416000.); let loss = loss - x18 * (3202291. / 25609494822912000.); loss } /// Same as above, but optimised with less multiplications. Faster and more precise. /// f32 with x**6: 1.6010 us 1.6033 us 1.6058 us. Precision 1e-4.7 /// f32 with x**8: 1.9207 us 1.9233 us 1.9264 us. Precision 1e-5.8 /// f64 with x**8: 1.9214 us 1.9237 us 1.9262 us. Precision: 1e-5.8 /// f64 with x**10: 2.1146 us 2.1175 us 2.1207 us. Precision: 1e-6.8 /// f64 with x**12: 3.3194 us 3.3236 us 3.3282 us. Precision: 1e-7.8 /// f64 with x**14: 3.7556 us 3.7814 us 3.8317 us. Precision: 1e-8.9 fn taylor_optimised(y: Float, x: Float) -> Float { let loss: Float = *LN_2; let loss = loss + (0.5 - y) * x; let x2 = x * x; let loss = loss + x2 * ((1. / 8.) // x**2 + x2 * ((-1. / 192.) // x**4 + x2 * ((1. / 2880. )// x**6 + x2 * ((-17. / 645120.) // x**8 + x2 * ((31. / 14515200.) // x**10 + x2 * ((-691. / 3832012800.) // x**12 + x2 * (5461. / 348713164800.) // x**14 )))))); loss } // What if we use fmul_fast? It's faster, but not stable yet. // f64 with x**14: 3.0418 us 3.0492 us 3.0603 us. Precision: 1e-8.9 fn taylor_fast_mul(y: Float, x: Float) -> Float { unsafe { let loss: Float = *LN_2; let loss = loss + fmul_fast(0.5 - y, x); let x2 = fmul_fast(x, x); loss + fmul_fast( x2, 1. / 8. // x**2 + fmul_fast(x2 , (-1. / 192.) // x**4 + fmul_fast(x2 , (1. / 2880.) // x**6 + fmul_fast(x2 , (-17. / 645120.) // x**8 + fmul_fast(x2 , (31. / 14515200. )// x**10 + fmul_fast(x2 , (-691. / 3832012800.) // x**12 + fmul_fast(x2 , 5461. / 348713164800. // x**14 )))))), ) } } fn _shanks(prec: Float, current: Float, next: Float) -> Float { (next * prec - current.powi(2)) / (next + prec - 2. * current) } /// Shanks derivative /// f64 with x**10: 5.8229 us 5.8437 us 5.8732 us. Precision: 1e-8.3 /// f64 with x**12: 6.6162 us 6.6332 us 6.6527 us. Precision: 1e-9.5 /// f64 with x**14: 8.1196 us 8.1410 us 8.1638 us. Precision: 1e-10.7 fn shanks_naive(y: Float, x: Float) -> Float { let x2 = x * x; let x4 = x2 * x2; let x6 = x2 * x4; let x8 = x4 * x4; let x10 = x4 * x6; let x12 = x6 * x6; let x14 = x8 * x6; let a2 = x2 / 8.; let a4 = a2 - x4 / 192.; let a6 = a4 + x6 / 2880.; let a8 = a6 - x8 * 17. / 645120.; let a10 = a8 + x10 * 31. / 14515200.; let a12 = a10 - x12 * 691. / 3832012800.; let a14 = a12 + x14 * 5461. / 348713164800.; //let shank_val = shanks(a6, a8, a10); //let shank_val = shanks(a8, a10, a12); let shank_val = _shanks(a10, a12, a14); let loss: Float = *LN_2; let loss = loss + (0.5 - y) * x; let loss = loss + shank_val; loss } /// Optimised Shanks derivative /// f64 with x**14: 7.8129 us 7.9778 us 8.2055 us. Precision: 1e-10.7 fn shanks_optimised(y: Float, x: Float) -> Float { let x2 = x * x; let x12 = x2.powi(6); let x14 = x2.powi(7); let a10 = x2 * (1. / 8. // x**2 + x2 * (-1. / 192. // x**4 + x2 * (1. / 2880. // x**6 + x2 * (-17. / 645120. // x**8 + x2 * 31. / 14515200. // x**10 )))); let a12 = a10 - x12 * 691. / 3832012800.; let a14 = a12 + x14 * 5461. / 348713164800.; let shank_val = _shanks(a10, a12, a14); let loss: Float = *LN_2; let loss = loss + (0.5 - y) * x; let loss = loss + shank_val; loss } fn _shanks_fast_mul(prec: Float, current: Float, next: Float) -> Float { unsafe { let top = fsub_fast(fmul_fast(next, prec), fmul_fast(current, current)); let bottom = fadd_fast(next, fsub_fast(prec, fmul_fast(current, 2.))); fdiv_fast(top, bottom) } } /// f64 with x**14: 6.3917 us 6.4321 us 6.4819 us. Precision 1e-10.6 /// f64 with x**14: 7.3272 us 7.3686 us 7.4282 us. Precision 1e-11.1 fn shanks_fast_mul(y: Float, x: Float) -> Float { unsafe { let x2 = fmul_fast(x, x); let x4 = fmul_fast(x2, x2); let x8 = fmul_fast(x4, x4); let x12 = fmul_fast(x8, x4); let x14 = fmul_fast(x12, x2); let z12 = fmul_fast(x2, -691. / 3832012800.); let z10 = fmul_fast(x2, fadd_fast(31. / 14515200., z12)); let z8 = fmul_fast(x2, fadd_fast(-17. / 645120., z10)); let z6 = fmul_fast(x2, fadd_fast(1. / 2880., z8)); let z4 = fmul_fast(x2, fadd_fast(-1. / 192., z6)); let z2 = fmul_fast(x2, fadd_fast(1. / 8., z4)); let a12 = z2; let a14 = fadd_fast(a12, fmul_fast(x12, 5461. / 348713164800.)); let a16 = fsub_fast(a14, fmul_fast(x14, 929569. / 669529276416000.)); let shank_val = _shanks_fast_mul(a12, a14, a16); let loss: Float = *LN_2; let loss = fadd_fast(loss, fmul_fast(0.5 - y, x)); let loss = fadd_fast(loss, shank_val); loss } } /// Shanks derivative at order 2. /// f64 with x**14: 14.127 us 14.145 us 14.167 us. Precision: 1e-9.7 fn shanks2_naive(y: Float, x: Float) -> Float { let x2 = x * x; let x4 = x2 * x2; let x6 = x2 * x4; let x8 = x4 * x4; let x10 = x4 * x6; let x12 = x6 * x6; let x14 = x6 * x8; let a2 = x2 / 8.; let a4 = a2 - x4 / 192.; let a6 = a4 + x6 / 2880.; let a8 = a6 - x8 * 17. / 645120.; let a10 = a8 + x10 * 31. / 14515200.; let a12 = a10 - x12 * 691. / 3832012800.; let a14 = a12 + x14 * 5461. / 348713164800.; let shank_val_8 = _shanks(a6, a8, a10); let shank_val_10 = _shanks(a8, a10, a12); let shank_val_12 = _shanks(a10, a12, a14); let shank_val = _shanks(shank_val_8, shank_val_10, shank_val_12); let loss: Float = *LN_2; let loss = loss + (0.5 - y) * x; let loss = loss + shank_val; loss } // This function have a better precision than shanks2, which indicates some numerical errors // f64 with x**14: 10.567 us 10.656 us 10.742 us. Precision: 1e-10.3 fn shanks2_fast_mul(y: Float, x: Float) -> Float { unsafe { let x2 = fmul_fast(x, x); let x4 = fmul_fast(x2, x2); let x6 = fmul_fast(x2, x4); let x8 = fmul_fast(x4, x4); let x10 = fmul_fast(x4, x6); let x12 = fmul_fast(x6, x6); let x14 = fmul_fast(x6, x8); let a2 = fmul_fast(x2, 1. / 8.); let a4 = fsub_fast(a2, fmul_fast(x4, 1. / 192.)); let a6 = fadd_fast(a4, fmul_fast(x6, 1. / 2880.)); let a8 = fsub_fast(a6, fmul_fast(x8, 17. / 645120.)); let a10 = fadd_fast(a8, fmul_fast(x10, 31. / 14515200.)); let a12 = fsub_fast(a10, fmul_fast(x12, 691. / 3832012800.)); let a14 = fadd_fast(a12, fmul_fast(x14, 5461. / 348713164800.)); let shank_val_8 = _shanks_fast_mul(a6, a8, a10); let shank_val_10 = _shanks_fast_mul(a8, a10, a12); let shank_val_12 = _shanks_fast_mul(a10, a12, a14); let shank_val = _shanks_fast_mul(shank_val_8, shank_val_10, shank_val_12); let loss: Float = *LN_2; let loss = fadd_fast(loss, fmul_fast(0.5 - y, x)); let loss = fadd_fast(loss, shank_val); loss } } struct Fn_ { f: &'static (Fn(f64, f64) -> f64), name: &'static str, } impl Fn_ { fn new(name: &'static str, f: &'static Fn(f64, f64) -> f64) -> Self { Self { f, name } } } impl Debug for Fn_ { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { f.write_str(self.name) } } fn get_functions() -> Vec<Fn_> { vec![ Fn_::new("exact_naive", &exact_naive), Fn_::new("exact_factored", &exact_factored), Fn_::new("exact_factored_ln1p", &exact_factored_ln1p), Fn_::new("taylor_naive", &taylor_naive), Fn_::new("taylor_optimised", &taylor_optimised), Fn_::new("taylor_fast_mul", &taylor_fast_mul), Fn_::new("shanks_naive", &shanks_naive), Fn_::new("shanks_optimised", &shanks_optimised), Fn_::new("shanks_fast_mul", &shanks_fast_mul), Fn_::new("shanks2_naive", &shanks2_naive), Fn_::new("shanks2_fast_mul", &shanks2_fast_mul), ] } fn get_proba_target() -> (Vec<Float>, Vec<Float>) { let seed = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; // byte array let mut rng = SmallRng::from_seed(seed); let n = 1000; let probas: Vec<_> = (0..n) .map(|_| (rng.gen::<Float>() * 2. - 1.) * 20.) .collect(); let target: Vec<_> = (0..n) .map(|_| if rng.gen::<Float>() > 0.5 { 1. } else { 0. }) .collect(); (probas, target) } fn bench_tree(b: &mut Bencher, f: &Fn_) { let (probas, target) = get_proba_target(); b.iter(|| { let mut sum = 0.; for (&a, &b) in probas.iter().zip(&target) { sum += (f.f)(a, b); } sum }) } fn criterion_benchmark(c: &mut Criterion) { let (probas, target) = get_proba_target(); for f in get_functions() { let mut max_diff: Float = 0.; for (&a, &b) in probas.iter().zip(&target) { max_diff = max_diff.max(((f.f)(a, b) - exact_naive(a, b)).abs()); } println!("max_diff for {} = e{:.1}", f.name, max_diff.log10()); } c.bench_function_over_inputs("binary", bench_tree, get_functions()); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches); <file_sep>/rboost/examples/example_tree.rs extern crate cpuprofiler; extern crate csv; extern crate rboost; extern crate serde_json; use rboost::{parse_csv, rmse, BinaryLogLoss, DecisionTree, TreeParams}; fn main() -> Result<(), Box<::std::error::Error>> { // Load the data let train = include_str!("../data/regression.train"); let train = parse_csv(train, "\t")?; let test = include_str!("../data/regression.test"); let test = parse_csv(test, "\t")?; let n_bins = 128; for max_depth in 0..8 { let mut tree_params = TreeParams::default(); tree_params.max_depth = max_depth; tree_params.min_split_gain = 0.; println!("\nParams tree{:?} n_bins={}", tree_params, n_bins); let mut predictions = vec![0.; train.target.len()]; let tree = DecisionTree::build( &mut train.as_prepared_data(n_bins)?, &mut predictions, &tree_params, BinaryLogLoss::default(), )?; let yhat_train: Vec<f64> = (0..train.features.n_rows()) .map(|i| tree.predict(&train.features.row(i))) .collect(); println!("RMSE train {:.8}", rmse(&train.target, &yhat_train)); let yhat_test: Vec<f64> = (0..test.features.n_rows()) .map(|i| tree.predict(&test.features.row(i))) .collect(); println!("RMSE Test {:.8}", rmse(&test.target, &yhat_test)); } Ok(()) } <file_sep>/rboost/examples/example_boost_binary.rs /// WARNING: boosting is NOT ready, do NOT use it for real work extern crate cpuprofiler; extern crate csv; extern crate rboost; extern crate serde_json; use cpuprofiler::PROFILER; use rand::prelude::{SeedableRng, SmallRng}; use rboost::duration_as_f64; use rboost::{ accuracy_score, parse_csv, roc_auc_score, BinaryLogLoss, BoosterParams, TreeParams, GBT, }; use std::time::Instant; fn main() -> Result<(), Box<::std::error::Error>> { let train = include_str!("../data/binary.train"); let train = parse_csv(train, "\t")?; let test = include_str!("../data/binary.test"); let test = parse_csv(test, "\t")?; let seed = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; // byte array let mut rng = SmallRng::from_seed(seed); let booster_params = BoosterParams { learning_rate: 0.1, colsample_bytree: 1., }; let mut tree_params = TreeParams::default(); tree_params.max_depth = 8; tree_params.min_split_gain = 0.3; let n_bins = 2048; println!( "Params booster={:?} tree{:?} n_bins={}", booster_params, tree_params, n_bins ); println!("Profiling to example_boost_binary.profile"); PROFILER.lock()?.start("./example_boost_binary.profile")?; let train_start_time = Instant::now(); let gbt = GBT::build( &booster_params, &tree_params, &mut train.as_prepared_data(n_bins)?, 1000, Some(&test), 10000, BinaryLogLoss::default(), &mut rng, )?; println!( "Training of {} trees finished. Elapsed: {:.2} secs", gbt.n_trees(), duration_as_f64(&train_start_time.elapsed()), ); PROFILER.lock()?.stop()?; let yhat_train: Vec<f64> = (0..train.features.n_rows()) .map(|i| gbt.predict(&train.features.row(i))) .collect(); println!( "TRAIN: ROC AUC {:.8}, accuracy {:.8}", roc_auc_score(&train.target, &yhat_train)?, accuracy_score(&train.target, &yhat_train)?, ); let yhat_test: Vec<f64> = (0..test.features.n_rows()) .map(|i| gbt.predict(&test.features.row(i))) .collect(); println!( "TEST: ROC AUC {:.8}, accuracy {:.8}", roc_auc_score(&test.target, &yhat_test)?, accuracy_score(&test.target, &yhat_test)?, ); Ok(()) } <file_sep>/rboost/src/matrix/dense.rs use core::ops::Index; use std::ops::IndexMut; /// Slice of data with a stride. pub struct StridedVecView<'a, A: 'a> { pub data: &'a [A], pub start: usize, pub stride: usize, } impl<'a, A: 'a> StridedVecView<'a, A> { pub fn new(data: &'a [A], start: usize, stride: usize) -> Self { Self { data, start, stride, } } pub fn from_slice(data: &'a [A]) -> Self { Self { data, start: 0, stride: 1, } } } impl<'a, A: 'a> Index<usize> for StridedVecView<'a, A> { type Output = A; fn index(&self, pos: usize) -> &A { &self.data[self.start + pos * self.stride] } } impl<'a, A: 'a> StridedVecView<'a, A> { pub fn iter(&'a self) -> impl Iterator<Item = &A> { let n_iter = self.data.len() / self.stride; //(0..n_iter).map(move |pos| &self[pos]) (0..n_iter).map(move |pos| &self[pos]) } } /// Store a dense matrix in a column-major way. pub struct ColumnMajorMatrix<A> { /// Number of rows in the matrix n_rows: usize, /// Number of columns in the matrix n_cols: usize, /// Values used by the algorithm. Format is row first values: Vec<A>, } impl<A> ColumnMajorMatrix<A> { pub fn from_columns(columns: Vec<Vec<A>>) -> Self { let (n_cols, n_rows) = (columns.len(), columns[0].len()); let mut values = Vec::with_capacity(n_rows * n_cols); for column in columns { for item in column { values.push(item) } } assert_eq!(n_rows * n_cols, values.len()); Self { n_rows, n_cols, values, } } pub fn from_rows(rows: Vec<Vec<A>>) -> Self { let (n_rows, n_cols) = (rows.len(), rows[0].len()); let mut values: Vec<A> = Vec::with_capacity(n_rows * n_cols); let mut rows: Vec<_> = rows.into_iter().map(|c| c.into_iter()).collect(); loop { let mut n_ko = 0; for row in &mut rows { if let Some(item) = row.next() { values.push(item) } else { n_ko += 1; } } if n_ko > 0 { assert_eq!(n_ko, n_rows); break; } } assert_eq!(n_rows * n_cols, values.len()); Self { n_rows, n_cols, values, } } pub fn from_function(n_rows: usize, n_cols: usize, f: impl Fn(usize, usize) -> A) -> Self { let mut values = Vec::new(); for col in 0..n_cols { for row in 0..n_rows { values.push(f(row, col)); } } Self { n_rows, n_cols, values, } } pub fn column(&self, col: usize) -> &[A] { let start = col * self.n_rows; &self.values.as_slice()[start..start + self.n_rows] } pub fn column_mut(&mut self, col: usize) -> &mut [A] { let start = col * self.n_rows; &mut self.values.as_mut_slice()[start..start + self.n_rows] } pub fn columns(&self) -> impl Iterator<Item = &[A]> { self.values.chunks(self.n_rows) } pub fn row(&self, row: usize) -> StridedVecView<A> { StridedVecView::new(&self.values, row, self.n_rows) } pub fn flat(&self) -> &Vec<A> { &self.values } pub fn n_rows(&self) -> usize { self.n_rows } pub fn n_cols(&self) -> usize { self.n_cols } } impl<A> Index<(usize, usize)> for ColumnMajorMatrix<A> { type Output = A; fn index(&self, (row, col): (usize, usize)) -> &A { // No need to check for col because it fill be out of the buffer assert!(row < self.n_rows); &self.values[row + col * self.n_rows] } } impl<A> IndexMut<(usize, usize)> for ColumnMajorMatrix<A> { fn index_mut(&mut self, (row, col): (usize, usize)) -> &mut A { &mut self.values[row + col * self.n_rows] } } #[cfg(test)] mod tests { use super::*; #[test] fn test_column_major() { // 1 4 // 2 5 // 3 6 let col0 = vec![1., 2., 3.]; let col1 = vec![4., 5., 6.]; let columns = vec![col0.clone(), col1.clone()]; let matrix = ColumnMajorMatrix::from_columns(columns.clone()); assert_eq!(matrix[(0, 0)], 1.); assert_eq!(matrix[(1, 0)], 2.); assert_eq!(matrix[(2, 0)], 3.); assert_eq!(matrix[(0, 1)], 4.); assert_eq!(matrix[(1, 1)], 5.); assert_eq!(matrix[(2, 1)], 6.); assert_eq!(col0, matrix.column(0)); assert_eq!(col1, matrix.column(1)); assert_eq!(columns, matrix.columns().collect::<Vec<_>>()); assert_eq!(matrix.row(0)[0], 1.); assert_eq!(matrix.row(1)[0], 2.); assert_eq!(matrix.row(2)[0], 3.); assert_eq!(matrix.row(0)[1], 4.); assert_eq!(matrix.row(1)[1], 5.); assert_eq!(matrix.row(2)[1], 6.); let row0: Vec<f64> = matrix.row(0).iter().map(|&e| e.clone()).collect(); let row1: Vec<f64> = matrix.row(1).iter().map(|&e| e.clone()).collect(); let row2: Vec<f64> = matrix.row(2).iter().map(|&e| e.clone()).collect(); assert_eq!(row0, vec![1., 4.]); assert_eq!(row1, vec![2., 5.]); assert_eq!(row2, vec![3., 6.]); } #[test] fn test_column_major_from_rows() { // 1 4 // 2 5 // 3 6 let row0 = vec![1., 4.]; let row1 = vec![2., 5.]; let row2 = vec![3., 6.]; let rows = vec![row0.clone(), row1.clone(), row2.clone()]; let matrix = ColumnMajorMatrix::from_rows(rows); assert_eq!(matrix[(0, 0)], 1.); assert_eq!(matrix[(1, 0)], 2.); assert_eq!(matrix[(2, 0)], 3.); assert_eq!(matrix[(0, 1)], 4.); assert_eq!(matrix[(1, 1)], 5.); assert_eq!(matrix[(2, 1)], 6.); } } <file_sep>/rboost/examples/example_dart_binary.rs extern crate cpuprofiler; extern crate csv; extern crate rboost; extern crate serde_json; use cpuprofiler::PROFILER; use rand::prelude::{SeedableRng, SmallRng}; use rboost::duration_as_f64; use rboost::{ accuracy_score, parse_csv, roc_auc_score, BinaryLogLoss, Dart, DartParams, TreeParams, }; use std::time::Instant; fn main() -> Result<(), Box<::std::error::Error>> { let train = include_str!("../data/binary.train"); let train = parse_csv(train, "\t")?; let test = include_str!("../data/binary.test"); let test = parse_csv(test, "\t")?; let seed = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; // byte array let mut rng = SmallRng::from_seed(seed); let mut booster_params = DartParams::default(); booster_params.colsample_bytree = 0.95; booster_params.dropout_rate = 0.5; booster_params.learning_rate = 0.3; let mut tree_params = TreeParams::default(); tree_params.max_depth = 5; tree_params.min_split_gain = 10.; let n_bins = 256; println!( "Params booster={:?} tree{:?} n_bins={}", booster_params, tree_params, n_bins ); println!("Profiling to example_dart_binary.profile"); PROFILER.lock()?.start("./example_dart_binary.profile")?; let train_start_time = Instant::now(); let gbt = Dart::build( &booster_params, &tree_params, &mut train.as_prepared_data(n_bins)?, 100, Some(&test), 100, BinaryLogLoss::default(), &mut rng, )?; println!( "Training of {} trees finished. Elapsed: {:.2} secs", gbt.n_trees(), duration_as_f64(&train_start_time.elapsed()), ); PROFILER.lock()?.stop()?; let yhat_train: Vec<f64> = (0..train.features.n_rows()) .map(|i| gbt.predict(&train.features.row(i))) .collect(); println!( "TRAIN: ROC AUC {:.8}, accuracy {:.8}", roc_auc_score(&train.target, &yhat_train)?, accuracy_score(&train.target, &yhat_train)?, ); let yhat_test: Vec<f64> = (0..test.features.n_rows()) .map(|i| gbt.predict(&test.features.row(i))) .collect(); println!( "TEST: ROC AUC {:.8}, accuracy {:.8}", roc_auc_score(&test.target, &yhat_test)?, accuracy_score(&test.target, &yhat_test)?, ); Ok(()) } <file_sep>/rboost/src/gbt.rs use crate::math::add; use crate::math::mul_add; use crate::math::sample_indices_ratio; use crate::{ Dataset, FitResult, Loss, Node, PreparedDataset, StridedVecView, TreeParams, DEFAULT_COLSAMPLE_BYTREE, DEFAULT_LEARNING_RATE, SHOULD_NOT_HAPPEN, }; use rand::prelude::Rng; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct BoosterParams { pub learning_rate: f64, pub colsample_bytree: f64, } impl BoosterParams { pub fn new() -> Self { BoosterParams { learning_rate: DEFAULT_LEARNING_RATE, colsample_bytree: DEFAULT_COLSAMPLE_BYTREE, } } } impl Default for BoosterParams { fn default() -> Self { Self::new() } } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct GBT<L: Loss> { models: Vec<Node>, booster_params: BoosterParams, tree_params: TreeParams, best_iteration: usize, loss: L, initial_prediction: f64, } impl<L: Loss> GBT<L> { pub fn build( booster_params: &BoosterParams, tree_params: &TreeParams, train_set: &mut PreparedDataset, num_boost_round: usize, valid: Option<&Dataset>, early_stopping_rounds: usize, loss: L, rng: &mut impl Rng, ) -> FitResult<GBT<L>> { let mut models = Vec::new(); let booster_params = (*booster_params).clone(); let tree_params = (*tree_params).clone(); let mut train = train_set.as_train_data(&loss); train.check_data()?; let initial_prediction = loss.get_initial_prediction(&train.target); let mut best_iteration = 0; let mut best_val_loss = None; let size_train = train.target.len(); let size_val = valid.map(|e| e.target.len()); // Indices and weights per tree. We create it before so we don't have to allocate a new vector at // each iteration let indices: Vec<usize> = (0..train.target.len()).collect(); let sample_weights = vec![1.; size_train]; let mut train_scores = vec![initial_prediction; size_train]; let mut val_scores = size_val.map(|size_val| vec![initial_prediction; size_val]); let mut train_cache_score = vec![0.; size_train]; let mut val_cache_score = size_val.map(|size_val| vec![0.; size_val]); for iter_cnt in 0..(num_boost_round) { train.update_grad_hessian(&loss, &train_scores, &sample_weights); if booster_params.colsample_bytree < 1. { train.columns = sample_indices_ratio( rng, train.features.n_cols(), booster_params.colsample_bytree, ); } let mut learner = Node::build_from_train_data(&train, &indices, &mut train_cache_score, &tree_params); mul_add( &train_cache_score, booster_params.learning_rate, &mut train_scores, ); learner.apply_shrinking(booster_params.learning_rate); if let Some(valid) = valid { let val_cache_score = val_cache_score.as_mut().expect(SHOULD_NOT_HAPPEN); val_cache_score.clone_from_slice(&learner.par_predict(&valid.features)); let val_scores = val_scores.as_mut().expect(SHOULD_NOT_HAPPEN); add(&val_cache_score, val_scores); let val_loss = loss.calc_loss(&valid.target, &val_scores) / (valid.target.len() as f64); let val_loss = val_loss.sqrt(); if iter_cnt == 0 { best_val_loss = Some(val_loss) } else if let Some(best_val_loss_) = best_val_loss { if val_loss < best_val_loss_ { best_val_loss = Some(val_loss); best_iteration = iter_cnt; } if iter_cnt - best_iteration >= early_stopping_rounds { for _ in best_iteration..(iter_cnt - 1) { models.pop(); } break; } } models.push(learner); }; } Ok(Self { models, booster_params, tree_params, best_iteration, loss, initial_prediction, }) } fn _predict(&self, features: &StridedVecView<f64>, models: &[Node]) -> f64 { let o: f64 = models.iter().map(|model| model.predict(features)).sum(); if o.is_nan() { panic!("NAN in output of prediction"); } self.loss.get_target(o + self.initial_prediction) } pub fn predict(&self, features: &StridedVecView<f64>) -> f64 { self._predict(&features, &self.models) } pub fn n_trees(&self) -> usize { self.models.len() } } <file_sep>/rboost/src/tree_bin.rs use crate::tree_direct::build_direct; use crate::{ sum_indices, weighted_mean, LeafNode, NanBranch, Node, SplitNode, TrainDataset, TreeParams, }; use ord_subset::OrdSubsetIterExt; use std::f64::INFINITY; /// Store the result of a successful split on a node struct SplitResult { feature_id: usize, best_val: f64, best_gain: f64, left_indices: Vec<usize>, right_indices: Vec<usize>, nan_branch: NanBranch, } /// Just a range function that can works in reverse: /// range(0, 5) = [0, 1, 2, 3, 4] /// range(5, 0) = [5, 4, 3, 2, 1] fn range(start: usize, end: usize) -> Box<Iterator<Item = usize>> { if start < end { Box::new(start..end) } else { Box::new((end..start).map(move |e| start - e)) } } fn calc_gain_bins( train: &TrainDataset, indices: &[usize], feature_id: usize, sum_grad: f64, sum_hessian: f64, params: &TreeParams, ) -> Option<(usize, f64, usize, NanBranch)> { let n_bins = train.n_bins[feature_id]; // First we compute the values of the bins on the dataset let mut grads: Vec<_> = (0..n_bins).map(|_| 0.).collect(); let mut hessians: Vec<_> = (0..n_bins).map(|_| 0.).collect(); let mut min_bin = grads.len(); // placeholder value: if it don't change we have no data let mut max_bin = 0; let mut n_nan = 0; // We iterate over all the indices. We currently don't have a fast path for sparse values. for &i in indices { match train.bins[(i, feature_id)] { Some(bin) => { let bin = bin as usize; min_bin = min_bin.min(bin); max_bin = max_bin.max(bin); grads[bin] += train.grad[i]; hessians[bin] += train.hessian[i]; } None => { // NAN values are implicitly in sum_grad and sum_hessian n_nan += 1; } }; } if max_bin == min_bin || max_bin == 0 { // Not possible to split if there is just one bin return None; } // Compute the gain by looping over let compute_gain = |start, end| { // We initialize at the first value let mut grad_left = 0.; let mut hessian_left = 0.; let mut best_gain = -INFINITY; let mut best_bin = 0; for bin in range(start, end) { grad_left += grads[bin]; hessian_left += hessians[bin]; let current_gain = Node::_calc_split_gain( sum_grad, sum_hessian, grad_left, hessian_left, params.lambda, params.gamma, ); if current_gain > best_gain { best_gain = current_gain; best_bin = bin; } } (best_gain, best_bin) }; // First pass: we loop over all the bins left to right. let (best_gain, best_bin) = compute_gain(min_bin, max_bin); if n_nan == 0 { // Short path if there is no NAN return Some((feature_id, best_gain, best_bin, NanBranch::None)); } // If there is NAN, we try to get the best path in the reverse order, so we can choose if the // default path for NAN should be in the right branch or the left branch. let (best_gain_rev, best_bin_rev) = compute_gain(max_bin, min_bin); if best_gain > best_gain_rev { // For the "left to right" order, the NAN are implicitly in the left branch. Some((feature_id, best_gain, best_bin, NanBranch::Right)) } else { // It's the opposite for the "right to left" order Some((feature_id, best_gain_rev, best_bin_rev, NanBranch::Left)) } } fn get_best_split_bins( train: &TrainDataset, indices: &[usize], sum_grad: f64, sum_hessian: f64, params: &TreeParams, ) -> Option<SplitResult> { let results: Vec<_> = train .columns .iter() .filter_map(|&feature_id| { calc_gain_bins(&train, &indices, feature_id, sum_grad, sum_hessian, &params) }) .collect(); let best = results.into_iter().ord_subset_max_by_key(|result| result.1); let (feature_id, best_gain, best_bin, nan_branch) = match best { None => return None, Some(e) => e, }; let mut left_indices = Vec::new(); let mut right_indices = Vec::new(); for &i in indices { match train.bins[(i, feature_id)] { Some(bin) => { let bin = bin as usize; if bin <= best_bin { left_indices.push(i); } else { right_indices.push(i); } } None => { match nan_branch { NanBranch::Left => left_indices.push(i), NanBranch::Right => right_indices.push(i), NanBranch::None => {} // We drop the indices if there is no preferred branch } } }; } let best_val = train.threshold_vals[feature_id][best_bin]; Some(SplitResult { feature_id, best_val, best_gain, left_indices, right_indices, nan_branch, }) } pub(crate) struct SplitBinReturn { pub(crate) node: Box<Node>, pub(crate) mean_val: f64, } /// Exact Greedy Algorithm for Split Finding /// (Refer to Algorithm1 of Reference[1]) pub(crate) fn build_bins( train: &TrainDataset, indices: &[usize], predictions: &mut [f64], depth: usize, params: &TreeParams, ) -> SplitBinReturn { // If the number of indices is too small it's faster to just use the direct algorithm if indices.len() <= params.min_rows_for_binning { let out = build_direct(train, indices, predictions, depth, params); return SplitBinReturn { node: out.node, mean_val: out.mean_val, }; } macro_rules! return_leaf { () => {{ let mean_val = Node::_calc_leaf_weight(&train.grad, &train.hessian, params.lambda, indices); for &i in indices { predictions[i] = mean_val; } let node = Box::new(Node::Leaf(LeafNode { val: mean_val, n_obs: indices.len(), })); return SplitBinReturn { node, mean_val }; }}; } if depth >= params.max_depth { return_leaf!(); } let sum_grad = sum_indices(&train.grad, indices); let sum_hessian = sum_indices(&train.hessian, indices); let best_result = get_best_split_bins(train, indices, sum_grad, sum_hessian, params); let best_result: SplitResult = match best_result { Some(e) => e, None => return_leaf!(), }; if best_result.best_gain < params.min_split_gain { return_leaf!(); } let left_child = build_bins( &train, &best_result.left_indices, predictions, depth + 1, &params, ); let right_child = build_bins( &train, &best_result.right_indices, predictions, depth + 1, &params, ); let mean_val = weighted_mean( right_child.mean_val, best_result.right_indices.len(), left_child.mean_val, best_result.left_indices.len(), ); let node = Box::new(Node::Split(SplitNode { left_child: left_child.node, right_child: right_child.node, split_feature_id: best_result.feature_id, split_val: best_result.best_val, val: mean_val, nan_branch: best_result.nan_branch, n_obs: indices.len(), })); SplitBinReturn { node, mean_val } } <file_sep>/rboost/examples/example_tree_binary.rs /// WARNING: boosting is NOT ready, do NOT use it for real work extern crate cpuprofiler; extern crate csv; extern crate rboost; extern crate serde_json; use rboost::{accuracy_score, parse_csv, roc_auc_score, BinaryLogLoss, DecisionTree, TreeParams}; fn main() -> Result<(), Box<::std::error::Error>> { let train = include_str!("../data/binary.train"); let train = parse_csv(train, "\t")?; let test = include_str!("../data/binary.test"); let test = parse_csv(test, "\t")?; let n_bins = 2048; for max_depth in 2..10 { let mut tree_params = TreeParams::default(); tree_params.max_depth = max_depth; tree_params.min_split_gain = 0.; println!("\nParams tree{:?} n_bins={}", tree_params, n_bins); let mut predictions = vec![0.; train.target.len()]; let tree = DecisionTree::build( &mut train.as_prepared_data(n_bins)?, &mut predictions, &tree_params, BinaryLogLoss::default(), )?; let yhat_train: Vec<f64> = (0..train.features.n_rows()) .map(|i| tree.predict(&train.features.row(i))) .collect(); println!( "TRAIN: ROC AUC {:.8}, accuracy {:.8}", roc_auc_score(&train.target, &yhat_train)?, accuracy_score(&train.target, &yhat_train)?, ); let yhat_test: Vec<f64> = (0..test.features.n_rows()) .map(|i| tree.predict(&test.features.row(i))) .collect(); println!( "TEST: ROC AUC {:.8}, accuracy {:.8}", roc_auc_score(&test.target, &yhat_test)?, accuracy_score(&test.target, &yhat_test)?, ); } Ok(()) } <file_sep>/rboost/src/lib.rs #[macro_use] extern crate serde_derive; mod dart; mod data; mod error; mod gbt; mod losses; mod math; mod matrix; mod rf; mod tree; mod tree_all; mod tree_bin; mod tree_direct; pub use crate::dart::*; pub use crate::data::*; pub use crate::error::*; #[doc(hidden)] // TODO implements boosting correctly pub use crate::gbt::*; pub use crate::losses::*; pub use crate::math::*; pub use crate::matrix::dense::*; pub use crate::rf::*; pub use crate::tree::*; pub(crate) static DEFAULT_GAMMA: f64 = 0.; pub(crate) static DEFAULT_LAMBDA: f64 = 1.; pub(crate) static DEFAULT_LEARNING_RATE: f64 = 0.1; pub(crate) static DEFAULT_MAX_DEPTH: usize = 3; pub(crate) static DEFAULT_MIN_SPLIT_GAIN: f64 = 0.1; pub(crate) static DEFAULT_COLSAMPLE_BYTREE: f64 = 1.; pub(crate) static DEFAULT_N_TREES: usize = 1000; #[doc(hidden)] /// Transform a duration to the number of sec in float. /// Useful for the examples while duration_float is not stable. pub fn duration_as_f64(duration: &::std::time::Duration) -> f64 { let nano = duration.subsec_nanos() as f64; let sec = duration.as_secs() as f64; sec + nano / 1_000_000_000. } <file_sep>/rboost/src/losses.rs use crate::sum; /// General interface for a loss. pub trait Loss: std::marker::Sync { fn calc_gradient_hessian(&self, target: &[f64], predictions: &[f64]) -> (Vec<f64>, Vec<f64>); fn calc_loss(&self, target: &[f64], predictions: &[f64]) -> f64; /// Transform from latent variables (eg. odd for logistic regression) to the target (eg. proba) fn get_target(&self, latent: f64) -> f64; /// Initial value for the prediction. Useful for limiting bias in regression and unbalanced /// classes for classification. fn get_initial_prediction(&self, target: &[f64]) -> f64; } /// L2 Loss, ie the usual loss for a regression. #[derive(Debug, Serialize, Deserialize, Clone)] pub struct RegLoss { // Nothing inside } impl Default for RegLoss { fn default() -> Self { RegLoss {} } } impl Loss for RegLoss { fn calc_gradient_hessian(&self, target: &[f64], predictions: &[f64]) -> (Vec<f64>, Vec<f64>) { let hessian: Vec<f64> = (0..target.len()).map(|_| 2.).collect(); let grad = (0..target.len()) .map(|i| 2. * (target[i] - predictions[i])) .collect(); (grad, hessian) } fn calc_loss(&self, target: &[f64], predictions: &[f64]) -> f64 { let mut errors = Vec::new(); for (n_row, &target) in target.iter().enumerate() { let diff = target - predictions[n_row]; errors.push(diff.powi(2)); } sum(&errors) } fn get_target(&self, latent: f64) -> f64 { latent } fn get_initial_prediction(&self, target: &[f64]) -> f64 { target.iter().sum::<f64>() / (target.len() as f64) } } /// Binary log loss, for two-class classification #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] pub struct BinaryLogLoss { // Nothing inside } impl Default for BinaryLogLoss { fn default() -> Self { BinaryLogLoss {} } } impl Loss for BinaryLogLoss { fn calc_gradient_hessian(&self, target: &[f64], predictions: &[f64]) -> (Vec<f64>, Vec<f64>) { let mut hessian: Vec<f64> = Vec::with_capacity(target.len()); let mut grad = Vec::with_capacity(target.len()); for (&target, &latent) in target.iter().zip(predictions.iter()) { let proba = self.get_target(-latent); grad.push(proba - target); hessian.push(proba * (1. - proba)); } (grad, hessian) } // Targets must be 0 or 1 exactly - for the moment. This loss function could generalize to // y in [0,1] #[allow(clippy::float_cmp)] fn calc_loss(&self, target: &[f64], predictions: &[f64]) -> f64 { // target y = 0 or 1 // proba p = 1 / (1 + exp(-x)) // -Loss = - y * log(p) - (1-y) * log(1-p) // = y * log(1+exp(-x)) - (1-y) * log(exp(-x)) + (1-y) * log(1+exp(-x)) // = log(1+exp(-x)) + (1-y) * x // See https://play.rust-lang.org/?edition=2015&gist=1b59228c7a9ceea83a769b644927f192 // for benchmarks (including Taylor series) let mut errors = Vec::new(); for (&y, &x) in target.iter().zip(predictions.iter()) { assert!((y == 0.) | (y == 1.), "Target must be 0 or 1, got {}", y); let loss = (1. - y) * x + (-x).exp().ln_1p(); errors.push(loss); } sum(&errors) } fn get_target(&self, latent: f64) -> f64 { 1. / (1. + latent.exp()) } fn get_initial_prediction(&self, target: &[f64]) -> f64 { let mean_val = (target.iter().sum::<f64>()) / (target.len() as f64); let mean_val = mean_val.max(1e-8).min(1. - 1e-8); (mean_val / (1. - mean_val)).ln() } } #[cfg(test)] mod tests { use super::*; /// Clone the vector and increase a given index fn inc_vec(v: &Vec<f64>, i: usize, eps: f64) -> Vec<f64> { let mut v = v.clone(); v[i] += eps; v } macro_rules! assert_close { ($a : expr, $b: expr, $delta: expr) => {{ let (a, b, delta) = ($a, $b, $delta); assert!( (a - b).abs() <= delta, "Difference = {:.6} > {:.6} too important between {:.6} and {:.6}", a - b, delta, a, b ); }}; } #[test] fn test_reg_loss() { let target = vec![0.1, 0.4, 1.3, 0.2]; let predictions = vec![0.1, 0.4, 1.0, 0.0]; let eps = 1e-5; let loss_reg = RegLoss::default(); let loss = loss_reg.calc_loss(&target, &predictions); let (grad, hessian) = loss_reg.calc_gradient_hessian(&target, &predictions); for i in 0..target.len() { // Test gradient // f'(x) = (f(x+eps) - f(x-eps)) / (2*eps) let l_plus = loss_reg.calc_loss(&inc_vec(&target, i, eps), &predictions); let l_minus = loss_reg.calc_loss(&inc_vec(&target, i, -eps), &predictions); let grad_emp = (l_plus - l_minus) / (2. * eps); assert_close!(grad[i], grad_emp, 1e-5); // Test hessian // f"(x) = (f'(x+eps/2) - f'(x-eps/2)) / (2*eps/2) // = (f(x+eps)-f(x) - f(x) + f(x-eps)) / (eps*eps) let hessian_emp = (l_plus + l_minus - 2. * loss) / eps.powi(2); assert_close!(hessian[i], hessian_emp, 1e-5); } } //noinspection RsApproxConstant #[test] fn test_binary_loss() { let target = vec![1., 1., 0., 1.]; let predictions = vec![0.1, 0.4, 0.9, 0.3]; let eps = 1e-5; let loss_reg = BinaryLogLoss::default(); let loss = loss_reg.calc_loss(&target, &predictions); let expected = 2.9529210316741383; assert_close!(loss, expected, 1e-3); let (grad, hessian) = loss_reg.calc_gradient_hessian(&target, &predictions); for i in 0..target.len() { // Test gradient // f'(x) = (f(x+eps) - f(x-eps)) / (2*eps) let l_plus = loss_reg.calc_loss(&target, &inc_vec(&predictions, i, eps)); let l_minus = loss_reg.calc_loss(&target, &inc_vec(&predictions, i, -eps)); let grad_emp = (l_plus - l_minus) / (2. * eps); assert_close!(grad[i], grad_emp, 1e-5); // Test hessian // f"(x) = (f'(x+eps/2) - f'(x-eps/2)) / (2*eps/2) // = (f(x+eps)-f(x) - f(x) + f(x-eps)) / (eps*eps) let hessian_emp = (l_plus + l_minus - 2. * loss) / eps.powi(2); assert_close!(hessian[i], hessian_emp, 1e-5); } } } <file_sep>/rboost/src/data.rs use crate::losses::Loss; use crate::{prod_vec, ColumnMajorMatrix, FitResult}; use ordered_float::OrderedFloat; use rayon::prelude::{IntoParallelIterator, ParallelIterator}; use std::error::Error; use std::f64::INFINITY; use std::ops::Deref; // TODO use NonMaxX type BinType = u32; /// Util for parsing a CSV without headers into a dataset. /// /// The first column of the CSV must be the target. pub fn parse_csv(data: &str, sep: &str) -> Result<Dataset, Box<Error>> { let mut target: Vec<f64> = Vec::new(); let mut features: Vec<Vec<f64>> = Vec::new(); for l in data.split('\n') { if l.is_empty() { continue; } let mut items = l.split(sep); target.push(items.next().ok_or("no_target")?.parse()?); let c_features: Result<_, Box<Error>> = items.map(|item| Ok(item.parse()?)).collect(); features.push(c_features?); } let features = ColumnMajorMatrix::from_rows(features); Ok(Dataset { features, target }) } /// Store the raw data. pub struct Dataset { /// Predictor for the learning pub features: ColumnMajorMatrix<f64>, /// Target, used for the learning pub target: Vec<f64>, } impl Dataset { pub fn features(&self) -> &ColumnMajorMatrix<f64> { &self.features } pub fn target(&self) -> &[f64] { &self.target } pub fn n_rows(&self) -> usize { self.features.n_rows() } pub fn n_cols(&self) -> usize { self.features.n_cols() } /// Rank per columns: the smallest value will have the rank 1, /// two equals values will have the same rank. /// NAN values will have the rank 0. /// // Because we use strict float ranking, we have to use exact float comparison. #[allow(clippy::float_cmp)] fn rank_features(&self) -> ColumnMajorMatrix<usize> { let columns = self .features .columns() .map(|column| { // Give the position in the column of the indices // First we sort the index according to the positions let mut sorted_indices: Vec<usize> = (0..column.len()).collect(); sorted_indices.sort_by_key(|&row_id| OrderedFloat::from(column[row_id])); // Then we create the histogram of the features let mut w: Vec<usize> = (0..column.len()).map(|_| 0).collect(); let nan_value = 0; let mut current_order = 1; let mut current_val = column[sorted_indices[0]]; for idx in sorted_indices { let val = column[idx]; if val.is_nan() { w[idx] = nan_value; } else { if val != current_val { if !current_val.is_nan() { current_order += 1; } current_val = val; } w[idx] = current_order; } } for &e in &w { assert_ne!(e, 0); } w }) .collect(); ColumnMajorMatrix::from_columns(columns) } /// Bin values: the smallest value will have the bin 0, the biggest n_bins. /// NAN values will be None. /// Vec<usize> is the effective number of bins we have at the end. fn bin_features( features_rank: &ColumnMajorMatrix<usize>, n_bins: usize, ) -> FitResult<(ColumnMajorMatrix<Option<BinType>>, Vec<usize>)> { let x: FitResult<Vec<_>> = features_rank .columns() .map(|column| { let max: usize = 1 + *column.iter().max().ok_or("No data")?; let n_bins: usize = max.min(n_bins); assert!(n_bins < (BinType::max_value()) as usize); // Then we bins the features let bins: Vec<_> = column .iter() .map(|&e| Some((e * n_bins / max) as BinType)) .collect(); Ok((bins, n_bins)) }) .collect(); let x = x?; let mut columns = Vec::with_capacity(x.len()); let mut n_bins = Vec::with_capacity(x.len()); for (col, n_bin) in x.into_iter() { columns.push(col); n_bins.push(n_bin); } let columns = ColumnMajorMatrix::from_columns(columns); Ok((columns, n_bins)) } /// Pre-compute the thresholds when we split between two bins. fn get_threshold_between_bins( values: &[f64], bins: &[Option<BinType>], n_bin: usize, ) -> Vec<f64> { if n_bin == 0 { return Vec::new(); } let mut min_vals = vec![INFINITY; n_bin]; let mut max_vals = vec![-INFINITY; n_bin]; for (&val, &bin) in values.iter().zip(bins.iter()) { let bin = match bin { None => continue, Some(e) => e as usize, }; min_vals[bin] = min_vals[bin].min(val); max_vals[bin] = max_vals[bin].max(val); } // TODO what happens if a bin is empty? max_vals .into_iter() .zip(min_vals.into_iter().skip(1)) .map(|(a, b)| (a / 2. + b / 2.)) .collect() } /// Prepare the dataset for the training. /// * `n_bins` - Number of bins we want to use. Set it to 0 for exact training /// Exact training is slower and more prone to over-fit. pub fn as_prepared_data(&self, n_bins: usize) -> FitResult<PreparedDataset> { let features_rank = self.rank_features(); let (bins, n_bins) = Dataset::bin_features(&features_rank, n_bins)?; let threshold_vals: Vec<_> = self .features .columns() .zip(bins.columns()) .zip(n_bins.iter()) .collect(); let threshold_vals = threshold_vals .into_par_iter() .map(|((values, bins), &n_bin)| Self::get_threshold_between_bins(values, bins, n_bin)) .collect(); Ok(PreparedDataset { features: &self.features, target: &self.target, features_rank, bins, n_bins, threshold_vals, }) } } /// Dataset pre-computed for the training. pub struct PreparedDataset<'a> { pub(crate) features: &'a ColumnMajorMatrix<f64>, pub(crate) target: &'a Vec<f64>, // Rank inside the dataset of a feature. Can contains duplicates if the values are equals. pub(crate) features_rank: ColumnMajorMatrix<usize>, pub(crate) bins: ColumnMajorMatrix<Option<BinType>>, pub(crate) n_bins: Vec<usize>, pub(crate) threshold_vals: Vec<Vec<f64>>, } impl<'a> PreparedDataset<'a> { pub fn target(&'a self) -> &'a [f64] { self.target } pub fn features(&'a self) -> &'a ColumnMajorMatrix<f64> { self.features } pub fn n_rows(&self) -> usize { self.features.n_rows() } pub fn n_cols(&self) -> usize { self.features.n_cols() } pub(crate) fn as_train_data(&'a self, loss: &impl Loss) -> TrainDataset<'a> { let zero_vec = vec![0.; self.n_rows()]; let weights = vec![1.; self.n_rows()]; let columns: Vec<_> = (0..self.features.n_cols()).collect(); let mut train = TrainDataset { grad: zero_vec.clone(), hessian: zero_vec.clone(), columns, data: self, }; train.update_grad_hessian(loss, &zero_vec, &weights); train } /// Check we have no NAN in input pub(crate) fn check_data(&self) -> FitResult<()> { for &x in self.features.flat() { if x.is_nan() { Err("Found NAN in the features")?; } } for &x in self.target { if x.is_nan() { Err("Found NAN in the target")?; } } Ok(()) } } pub(crate) struct TrainDataset<'a> { pub(crate) grad: Vec<f64>, pub(crate) hessian: Vec<f64>, // Columns that we want to train on pub(crate) columns: Vec<usize>, pub(crate) data: &'a PreparedDataset<'a>, } // With Deref we can use train_data_set.X if X is an attribute of PreparedDataset impl<'a> Deref for TrainDataset<'a> { type Target = PreparedDataset<'a>; fn deref(&self) -> &Self::Target { self.data } } impl<'a> TrainDataset<'a> { pub(crate) fn update_grad_hessian( &mut self, loss: &impl Loss, predictions: &[f64], sample_weights: &[f64], ) { assert_eq!(predictions.len(), sample_weights.len()); let (grad, hessian) = loss.calc_gradient_hessian(&self.target, &predictions); self.grad = prod_vec(&grad, sample_weights); self.hessian = prod_vec(&hessian, sample_weights); } } <file_sep>/rboost/src/tree_direct.rs use crate::{ sum_indices, weighted_mean, LeafNode, NanBranch, Node, SplitNode, TrainDataset, TreeParams, SHOULD_NOT_HAPPEN, }; use ord_subset::OrdSubsetIterExt; //use rayon::prelude::{IntoParallelIterator, ParallelIterator}; use std::f64::INFINITY; /// Store the result of a successful split on a node struct SplitResult { feature_id: usize, best_val: f64, best_gain: f64, left_indices: Vec<usize>, right_indices: Vec<usize>, nan_branch: NanBranch, } // Because we use strict float ranking, we have to use exact float comparison. #[allow(clippy::float_cmp)] fn calc_gain_direct( train: &TrainDataset, indices: &[usize], sum_grad: f64, sum_hessian: f64, params: &TreeParams, feature_id: usize, ) -> Option<SplitResult> { // sorted_instance_ids = instances[:, feature_id].argsort() let mut sorted_instance_ids = indices.to_vec(); sorted_instance_ids.sort_unstable_by_key(|&row_id| train.features_rank[(row_id, feature_id)]); for &idx in &sorted_instance_ids { assert!(!train.features[(idx, feature_id)].is_nan()); assert_ne!(train.features_rank[(idx, feature_id)], 0); } // Number of NAN. We use the fact that the rank is 0 iif the value is NAN. let n_nan = sorted_instance_ids .iter() .enumerate() .filter(|(_, &idx)| train.features_rank[(idx, feature_id)] != 0) .map(|(n, _)| n) .next(); let n_nan = match n_nan { None => return None, // We only have NAN values Some(e) => e, }; // We check a trivial cases: the feature is constant. // Because the rank of the NAN is always smaller than the rank of the other values, at n_nan // we have the smallest not-nan value let first_rank = train.features_rank[(sorted_instance_ids[n_nan], feature_id)]; let last_rank = train.features_rank[( *sorted_instance_ids.last().expect(SHOULD_NOT_HAPPEN), feature_id, )]; if first_rank == last_rank { return None; } let grad_nan: f64 = (0..n_nan).map(|n| train.grad[sorted_instance_ids[n]]).sum(); let hessian_nan: f64 = (0..n_nan) .map(|n| train.hessian[sorted_instance_ids[n]]) .sum(); // We initialize at the first value let mut grad_left = train.grad[sorted_instance_ids[n_nan]]; let mut hessian_left = train.hessian[sorted_instance_ids[n_nan]]; let mut best_gain = -INFINITY; let mut best_idx = 0; let mut best_val = ::std::f64::NAN; let mut last_val = train.features[(sorted_instance_ids[n_nan], feature_id)]; let mut best_nan_branch = NanBranch::None; // The potential split is before the current value, so we have to skip the first for (idx, &nrow) in sorted_instance_ids[n_nan..sorted_instance_ids.len()] .iter() .enumerate() .skip(1) { // We can only split when the value change let val = train.features[(nrow, feature_id)]; if val != last_val { let current_gain = Node::_calc_split_gain( sum_grad, sum_hessian, grad_left, hessian_left, params.lambda, params.gamma, ); if current_gain > best_gain { best_gain = current_gain; best_idx = idx; best_val = (val + last_val) / 2.; best_nan_branch = if n_nan > 0 { // If there is NAN they are implicitly in the right branch NanBranch::Right } else { // If there is no NAN we don't know what to do NanBranch::None }; } if n_nan > 0 { // We evaluate what happens if we push all the NAN values to the left branch let current_gain = Node::_calc_split_gain( sum_grad, sum_hessian, grad_left + grad_nan, hessian_left + hessian_nan, params.lambda, params.gamma, ); if current_gain > best_gain { best_gain = current_gain; best_idx = idx; best_val = (val + last_val) / 2.; best_nan_branch = NanBranch::Left; } } } last_val = val; grad_left += train.grad[nrow]; hessian_left += train.hessian[nrow]; } // Sanity check assert!(!best_val.is_nan()); let (left_indices, right_indices) = sorted_instance_ids.split_at(best_idx); Some(SplitResult { feature_id, best_val, best_gain, left_indices: left_indices.to_vec(), right_indices: right_indices.to_vec(), nan_branch: best_nan_branch, }) } fn get_best_split_direct( train: &TrainDataset, indices: &[usize], sum_grad: f64, sum_hessian: f64, params: &TreeParams, ) -> Option<SplitResult> { let results: Vec<_> = train .columns .iter() .filter_map(|&feature_id| { calc_gain_direct(&train, indices, sum_grad, sum_hessian, &params, feature_id) }) .collect(); results .into_iter() .ord_subset_max_by_key(|result| result.best_gain) } pub(crate) struct DirectReturn { pub(crate) node: Box<Node>, pub(crate) mean_val: f64, } /// Exact Greedy Algorithm for Split Findincg /// (Refer to Algorithm1 of Reference[1]) pub(crate) fn build_direct( train: &TrainDataset, indices: &[usize], predictions: &mut [f64], depth: usize, params: &TreeParams, ) -> DirectReturn { macro_rules! return_leaf { () => {{ let mean_val = Node::_calc_leaf_weight(&train.grad, &train.hessian, params.lambda, indices); for &i in indices { predictions[i] = mean_val; } let node = Box::new(Node::Leaf(LeafNode { val: mean_val, n_obs: indices.len(), })); return DirectReturn { node, mean_val }; }}; } if depth >= params.max_depth { return_leaf!(); } let sum_grad = sum_indices(&train.grad, indices); let sum_hessian = sum_indices(&train.hessian, indices); let best_result = get_best_split_direct(train, indices, sum_grad, sum_hessian, params); let best_result = match best_result { Some(e) => e, None => return_leaf!(), }; if best_result.best_gain < params.min_split_gain { return_leaf!(); } let left_child = build_direct( &train, &best_result.left_indices, predictions, depth + 1, &params, ); let right_child = build_direct( &train, &best_result.right_indices, predictions, depth + 1, &params, ); let mean_val = weighted_mean( right_child.mean_val, best_result.right_indices.len(), left_child.mean_val, best_result.left_indices.len(), ); let node = Box::new(Node::Split(SplitNode { left_child: left_child.node, right_child: right_child.node, split_feature_id: best_result.feature_id, split_val: best_result.best_val, val: mean_val, nan_branch: best_result.nan_branch, n_obs: indices.len(), })); DirectReturn { node, mean_val } } <file_sep>/rboost/examples/example_dart.rs extern crate cpuprofiler; extern crate csv; extern crate rboost; extern crate serde_json; use cpuprofiler::PROFILER; use rand::prelude::{SeedableRng, SmallRng}; use rboost::duration_as_f64; use rboost::{parse_csv, rmse, Dart, DartParams, RegLoss, TreeParams}; use std::fs::File; use std::io::Write; use std::time::Instant; fn main() -> Result<(), Box<::std::error::Error>> { let train = include_str!("../data/regression.train"); let train = parse_csv(train, "\t")?; let test = include_str!("../data/regression.test"); let test = parse_csv(test, "\t")?; let seed = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; // byte array let mut rng = SmallRng::from_seed(seed); let booster_params = DartParams { colsample_bytree: 0.95, dropout_rate: 0.97, learning_rate: 0.8, }; let mut tree_params = TreeParams::default(); tree_params.max_depth = 4; tree_params.min_split_gain = 1.; let n_bins = 256; println!( "Params booster={:?} tree{:?} n_bins={}", booster_params, tree_params, n_bins ); println!("Profiling to example_dart.profile"); PROFILER.lock()?.start("./example_dart.profile")?; let train_start_time = Instant::now(); let gbt = Dart::build( &booster_params, &tree_params, &mut train.as_prepared_data(n_bins)?, 1000, Some(&test), 1000, RegLoss::default(), &mut rng, )?; println!( "Training of {} trees finished. Elapsed: {:.2} secs", gbt.n_trees(), duration_as_f64(&train_start_time.elapsed()), ); PROFILER.lock()?.stop()?; let n_preds = 10; let predict_start_time = Instant::now(); let mut predictions = vec![0.; train.n_rows()]; for _ in 0..n_preds { for (i, pred) in predictions.iter_mut().enumerate() { *pred += gbt.predict(&train.features.row(i)); } } println!( "{} Predictions. Elapsed: {:.2} secs", n_preds, duration_as_f64(&predict_start_time.elapsed()), ); for pred in predictions.iter_mut() { *pred /= n_preds as f64; } let yhat_train: Vec<f64> = (0..train.features.n_rows()) .map(|i| gbt.predict(&train.features.row(i))) .collect(); println!("RMSE train {:.8}", rmse(&train.target, &yhat_train)); let yhat_test: Vec<f64> = (0..test.features.n_rows()) .map(|i| gbt.predict(&test.features.row(i))) .collect(); println!("RMSE Test {:.8}", rmse(&test.target, &yhat_test)); println!("Serializing model to example_dart.json"); let serialized: String = serde_json::to_string(&gbt)?; let mut file = File::create("example_dart.json")?; file.write_all(serialized.as_bytes())?; println!("Writing predictions to example_dart.csv"); let file = File::create("example_dart.csv")?; let mut wtr = csv::Writer::from_writer(file); wtr.write_record(&["dataset", "true_val", "yhat"])?; for (true_val, yhat) in train.target.iter().zip(yhat_train.iter()) { wtr.write_record(&["train", &true_val.to_string(), &yhat.to_string()])?; } for (true_val, yhat) in test.target.iter().zip(yhat_test.iter()) { wtr.write_record(&["test", &true_val.to_string(), &yhat.to_string()])?; } wtr.flush()?; Ok(()) } <file_sep>/rboost/src/error.rs use std::{error, fmt}; #[derive(Debug, Clone, Serialize, Deserialize)] /// Generic error type on fitting error. /// /// We have to define a specific type because the generic dyn Error is not Sync, so it can't be used /// with Rayon. pub struct FitError { msg: String, } impl FitError { fn new(msg: String) -> FitError { FitError { msg } } } impl fmt::Display for FitError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("invalid first item to double") } } // This is important for other errors to wrap this one. impl error::Error for FitError { fn description(&self) -> &str { &self.msg } fn cause(&self) -> Option<&error::Error> { // Generic error, underlying cause isn't tracked. None } } impl std::convert::From<&str> for FitError { fn from(msg: &str) -> Self { FitError::new(msg.to_string()) } } impl std::convert::From<String> for FitError { fn from(msg: String) -> Self { FitError::new(msg) } } pub type FitResult<T> = Result<T, FitError>; pub(crate) static SHOULD_NOT_HAPPEN: &str = "There is an unexpected error in Rboost. Please raise a bug."; <file_sep>/rboost/src/matrix/mod.rs pub mod dense; //pub mod sparse; <file_sep>/rboost/src/tree_all.rs use crate::{ weighted_mean, ColumnMajorMatrix, LeafNode, NanBranch, Node, SplitNode, TrainDataset, TreeParams, SHOULD_NOT_HAPPEN, }; use either::Either; use itertools::izip; use rayon::prelude::*; use std::f64::INFINITY; #[derive(Debug)] pub(crate) struct Bin2Return { pub(crate) node: Node, pub(crate) mean_val: f64, pub(crate) n_obs: usize, } /// Just a range function that can works in reverse: /// range(0, 5) = [0, 1, 2, 3, 4] /// range(5, 0) = [5, 4, 3, 2, 1] fn range(start: usize, end: usize) -> Box<Iterator<Item = usize>> { if start < end { Box::new(start..end) } else { Box::new((end..start).map(move |e| start - e)) // TODO check -1 } } /// Compute the best gain for every possible split between bins fn compute_gain( grads: &[f64], hessians: &[f64], start: usize, end: usize, sum_grad: f64, sum_hessian: f64, params: &TreeParams, ) -> (f64, usize) { // We initialize at the first value let mut grad_left = 0.; let mut hessian_left = 0.; let mut best_gain = -INFINITY; let mut best_bin = 0; for bin in range(start, end) { grad_left += grads[bin]; hessian_left += hessians[bin]; let current_gain = Node::_calc_split_gain( sum_grad, sum_hessian, grad_left, hessian_left, params.lambda, params.gamma, ); if current_gain > best_gain { best_gain = current_gain; best_bin = bin; } } (best_gain, best_bin) } /// Get the index of the node if the node is between min_node and max_node, or None otherwise fn get_node_idx(node: usize, min_node: usize, max_node: usize) -> Option<usize> { if (node >= min_node) & (node < max_node) { Some(node - min_node) } else { None } } #[derive(Clone, Debug)] struct GainResult { feature_id: usize, gain: f64, bin: usize, nan_branch: NanBranch, } /// Compute the gain if we split for this feature on all the nodes. fn calc_gains_bin( train: &TrainDataset, nodes_of_rows: &[usize], sums_grad: &[f64], sums_hessian: &[f64], params: &TreeParams, feature_id: usize, (min_node, max_node): (usize, usize), ) -> Vec<Option<GainResult>> { let n_bins = train.n_bins[feature_id]; let n_nodes = max_node - min_node; let mut grads = ColumnMajorMatrix::from_function(n_bins, n_nodes, |_, _| 0.); let mut hessians = ColumnMajorMatrix::from_function(n_bins, n_nodes, |_, _| 0.); let mut n_nan = vec![0; n_nodes]; for (bin, &node, &grad, &hessian) in izip!( train.bins.column(feature_id), nodes_of_rows, &train.grad, &train.hessian ) { if let Some(node) = get_node_idx(node, min_node, max_node) { match bin { Some(bin) => { let bin = *bin as usize; grads[(bin, node)] += grad; hessians[(bin, node)] += hessian; } None => { n_nan[node] += 1; } } } } (0..n_nodes) .map(|node| { // Helper function let compute_gain = |start, end| { compute_gain( grads.column(node), hessians.column(node), start, end, sums_grad[node], sums_hessian[node], params, ) }; // First pass: we loop over all the bins left to right. let (best_gain, best_bin) = compute_gain(0, n_bins); // Short path if there is no NAN if n_nan[node] == 0 { // Short path if there is no NAN return Some(GainResult { feature_id, gain: best_gain, bin: best_bin, nan_branch: NanBranch::None, }); } // If there is NAN, we try to get the best path in the reverse order, so we can choose if the // default path for NAN should be in the right branch or the left branch. let (best_gain_rev, best_bin_rev) = compute_gain(n_bins, 0); if best_gain > best_gain_rev { // For the "left to right" order, the NAN are implicitly in the left branch. Some(GainResult { feature_id, gain: best_gain, bin: best_bin, nan_branch: NanBranch::Right, }) } else { // It's the opposite for the "right to left" order Some(GainResult { feature_id, gain: best_gain_rev, bin: best_bin_rev, nan_branch: NanBranch::Left, }) } }) .collect() } fn get_best_splits_bin( train: &TrainDataset, nodes_of_rows: &[usize], sums_grad: &[f64], sums_hessian: &[f64], params: &TreeParams, (min_node, max_node): (usize, usize), ) -> Box<Iterator<Item = Option<GainResult>>> { // Per node and per feature, what is the best split let best_split_per_node_and_feature: Vec<Vec<_>> = train .columns .par_iter() .map(|&feature_id| { calc_gains_bin( &train, nodes_of_rows, sums_grad, sums_hessian, &params, feature_id, (min_node, max_node), ) }) .collect(); // We concatenate: per node, what is the best split Box::new((0..(max_node - min_node)).map(move |node| { let mut best_result: Option<GainResult> = None; for col in &best_split_per_node_and_feature { if let Some(result) = &col[node] { if let Some(best_) = &best_result { if result.gain >= best_.gain { best_result = Some(result.clone()); } } else { // Default behaviour for the first iteration best_result = Some(result.clone()); } } } best_result })) } /// Exact Greedy Algorithm for Split Finding pub(crate) fn build_bins2( train: &TrainDataset, nodes_of_rows: &mut [usize], predictions: &mut [f64], depth: usize, params: &TreeParams, min_node: usize, max_node: usize, ) -> Vec<Bin2Return> { debug_assert!(max_node > min_node); let mut sums_grad = vec![0.; max_node - min_node]; let mut sums_hessian = vec![0.; max_node - min_node]; let mut n_obs_per_node = vec![0; max_node - min_node]; for (&node, grad, hessian) in izip!(nodes_of_rows.iter(), &train.grad, &train.hessian) { if let Some(node) = get_node_idx(node, min_node, max_node) { sums_grad[node] += grad; sums_hessian[node] += hessian; n_obs_per_node[node] += 1; } } let best_splits = if depth >= params.max_depth { // Fast path if nothing to do Box::new((min_node..max_node).map(|_| None)) } else { // Per node, what is the best split get_best_splits_bin( train, nodes_of_rows, &sums_grad, &sums_hessian, params, (min_node, max_node), ) }; // Add an index to every node that we will split. // We pre-compute for the leaf the final value let mut n_with_child = 0; let nodes: Vec<_> = best_splits .zip(sums_grad) .zip(sums_hessian) .map(|((split, sum_grad), sum_hessian)| { if let Some(split) = split { if split.gain >= params.min_split_gain { let o = Either::Left((n_with_child, split)); n_with_child += 1; return o; } } return Either::Right(sum_grad / (sum_hessian + params.lambda)); }) .collect(); // Update the predictions for nodes that will not be split if n_with_child != nodes.len() { for (node, prediction) in nodes_of_rows.iter().zip(predictions.iter_mut()) { if let Some(node) = get_node_idx(*node, min_node, max_node) { if let Either::Right(val) = nodes[node] { *prediction = val; } } } } // Fast path if nothing can be split if n_with_child == 0 { return n_obs_per_node .into_iter() .zip(nodes) .map(|(n_obs, node)| { let mean_val = node.right().expect(SHOULD_NOT_HAPPEN); let node = LeafNode { val: mean_val, n_obs, }; Bin2Return { node: Node::Leaf(node), mean_val, n_obs, } }) .collect(); } // For every node, put them either on the left or on the right. // The indices of the new nodes starts at max_node and goes up 2 by 2 when we have a split. for (i, node) in nodes_of_rows.iter_mut().enumerate() { if let Some(node_idx) = get_node_idx(*node, min_node, max_node) { //let node_idx = nodes_of_rows[i] - min_node; if let Either::Left((n_node_with_child, split)) = &nodes[node_idx] { if let Some(bin) = train.bins[(i, split.feature_id)] { let n_node_with_child = *n_node_with_child; if bin as usize <= split.bin { // Left child *node = n_node_with_child * 2 + max_node } else { // Right child *node = n_node_with_child * 2 + max_node + 1 } } } } } // We iterate again to compute the children let children = build_bins2( train, nodes_of_rows, predictions, depth + 1, params, max_node, max_node + n_with_child * 2, ); debug_assert_eq!(children.len(), n_with_child * 2); let mut children = children.into_iter(); // We add back the children to the parents and return let o = nodes .into_iter() .zip(n_obs_per_node) .map(|(e, n_obs)| match e { Either::Left((_, split)) => { let left_child = children.next().unwrap(); debug_assert!(left_child.n_obs > 0); let right_child = children.next().unwrap(); debug_assert!(right_child.n_obs > 0); debug_assert_eq!(left_child.n_obs + right_child.n_obs, n_obs); let mean_val = weighted_mean( right_child.mean_val, right_child.n_obs, left_child.mean_val, left_child.n_obs, ); let node = SplitNode { left_child: Box::new(left_child.node), right_child: Box::new(right_child.node), split_feature_id: split.feature_id, split_val: train.threshold_vals[split.feature_id][split.bin], val: mean_val, nan_branch: split.nan_branch, n_obs, }; Bin2Return { node: Node::Split(node), mean_val, n_obs, } } Either::Right(mean_val) => { let node = LeafNode { val: mean_val, n_obs, }; Bin2Return { node: Node::Leaf(node), mean_val, n_obs, } } }) .collect(); debug_assert!(children.next().is_none()); o } <file_sep>/build-travis.sh #!/usr/bin/env bash set -ev cd rboost # Build and fails on warning cargo rustc -- -D warnings # Check the formatting time cargo fmt -- --check # Run all the test (in debug mode so it catch more potential errors) time cargo test --all # Run all the examples (release mode because it's too slow otherwise) for f in examples/*; do echo "'$f'" echo cargo run --example $(basename "$f" | sed 's/.rs//') --release time cargo run --example $(basename "$f" | sed 's/.rs//') --release done<file_sep>/rboost/benches/bench_trees.rs #![feature(duration_as_u128)] extern crate csv; extern crate rboost; extern crate serde_json; #[macro_use] extern crate criterion; use criterion::{Bencher, Criterion}; use rboost::{parse_csv, DecisionTree, RegLoss, TreeParams}; fn bench_tree(b: &mut Bencher, n_bins: &&usize) { let train = include_str!("../data/regression.train"); let train = parse_csv(train, "\t").expect("Train data"); let train = train.as_prepared_data(**n_bins).expect("Preparing data"); b.iter(|| { let loss = RegLoss::default(); let tree_params = TreeParams { gamma: 1., lambda: 10., max_depth: 10, min_split_gain: 1., }; let mut predictions: Vec<_> = (0..train.features().n_rows()).map(|_| 0.).collect(); let tree = DecisionTree::build(&train, &mut predictions, &tree_params, loss); tree.expect("Error while creating tree"); }) } fn criterion_benchmark(c: &mut Criterion) { c.bench_function_over_inputs("tree", bench_tree, &[0, 256]); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches); <file_sep>/rboost/src/rf.rs use crate::math::sample_indices_ratio; use crate::{ FitResult, Loss, Node, PreparedDataset, StridedVecView, TreeParams, DEFAULT_COLSAMPLE_BYTREE, DEFAULT_N_TREES, SHOULD_NOT_HAPPEN, }; use rand::prelude::Rng; use rayon::prelude::*; use std::sync::Arc; use std::sync::Mutex; /// Parameters for constructing a random forest. #[derive(Debug, Serialize, Deserialize, Clone)] pub struct RFParams { pub n_trees: usize, pub colsample_bytree: f64, } impl RFParams { pub fn new() -> Self { Self { n_trees: DEFAULT_N_TREES, colsample_bytree: DEFAULT_COLSAMPLE_BYTREE, } } } impl Default for RFParams { fn default() -> Self { Self::new() } } /// Random Forest implementation. /// /// The trees are constructed independently by sub-sampling with resample. /// It's parallelized using rayon. #[derive(Debug, Serialize, Deserialize, Clone)] pub struct RandomForest<L: Loss> { models: Vec<Node>, rf_params: RFParams, tree_params: TreeParams, loss: L, initial_prediction: f64, } impl<L: Loss + std::marker::Sync> RandomForest<L> { pub fn build( train: &PreparedDataset, rf_params: &RFParams, tree_params: &TreeParams, loss: L, rng: &mut impl Rng, ) -> FitResult<(RandomForest<L>, Vec<f64>)> { train.check_data()?; let initial_prediction = loss.get_initial_prediction(&train.target); // We have to compute the weights first because they depends on &mut rng let random_init: Vec<_> = (0..rf_params.n_trees) .map(|_| { let mut weights = vec![0.; train.n_rows()]; let indices: Vec<_> = (0..train.target.len()).collect(); for _ in train.target { weights[*rng.choose(&indices).expect(SHOULD_NOT_HAPPEN)] += 1.; } let columns = sample_indices_ratio(rng, train.features.n_cols(), rf_params.colsample_bytree); (weights, columns) }) .collect(); // We don't do boosting so the initial value is just the default one let train_scores = vec![initial_prediction; train.n_rows()]; // Store the sum of the cross-validated predictions and the number of predictions done let predictions = vec![(0., 0); train.n_rows()]; let predictions = Arc::new(Mutex::new(predictions)); let models: Vec<_> = random_init .into_par_iter() .map(|(sample_weights, columns)| { // TODO: can we remove the allocations inside the hot loop? // We update the data set to a train set according to the weights. let mut train = train.as_train_data(&loss); train.update_grad_hessian(&loss, &train_scores, &sample_weights); train.columns = columns; let mut tree_predictions = vec![0.; train.n_rows()]; // We filter the indices with non-null weights let (mut train_indices, mut test_indices) = (Vec::new(), Vec::new()); for (indice, &weight) in sample_weights.iter().enumerate() { if weight > 0. { train_indices.push(indice) } else { test_indices.push(indice) } } // Let's build it! let node = Node::build_from_train_data( &train, &train_indices, &mut tree_predictions, &tree_params, ); // Predict and write back the predictions to the result let predictions = predictions.clone(); let mut predictions = predictions.lock().expect("Poisoned mutex"); for i in test_indices { predictions[i].0 += node.predict(&train.features.row(i)); predictions[i].1 += 1; } node }) .collect(); // We divide the cross-validated predictions by the number of trees used let predictions = predictions.lock().expect("Poisoned mutex"); let predictions = predictions .iter() .map(|(pred, n)| *pred / (*n as f64)) .map(|latent| loss.get_target(latent + initial_prediction)) .collect(); let rf = RandomForest { models, rf_params: (*rf_params).clone(), tree_params: (*tree_params).clone(), loss, initial_prediction, }; Ok((rf, predictions)) } pub fn predict(&self, features: &StridedVecView<f64>) -> f64 { let o: f64 = self .models .iter() .map(|model| model.predict(features)) .sum(); if o.is_nan() { panic!("NAN in output of prediction"); } let o = o / self.models.len() as f64; self.loss.get_target(o + self.initial_prediction) } } <file_sep>/rboost/src/tree.rs use crate::{ sum_indices, ColumnMajorMatrix, FitResult, PreparedDataset, StridedVecView, TrainDataset, DEFAULT_GAMMA, DEFAULT_LAMBDA, DEFAULT_MAX_DEPTH, DEFAULT_MIN_SPLIT_GAIN, }; //use rayon::prelude::ParallelIterator; use crate::losses::Loss; use crate::tree_all::build_bins2; use crate::tree_direct::build_direct; /// Parameters for building the tree. /// /// They are the same than Xgboost <https://xgboost.readthedocs.io/en/latest/parameter.html> #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] pub struct TreeParams { pub gamma: f64, pub lambda: f64, pub max_depth: usize, pub min_split_gain: f64, pub recursive_split: bool, pub min_rows_for_binning: usize, } impl TreeParams { pub fn new() -> Self { TreeParams { gamma: DEFAULT_GAMMA, lambda: DEFAULT_LAMBDA, max_depth: DEFAULT_MAX_DEPTH, min_split_gain: DEFAULT_MIN_SPLIT_GAIN, recursive_split: false, min_rows_for_binning: 0, } } } impl Default for TreeParams { fn default() -> Self { Self::new() } } #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] pub(crate) enum NanBranch { None, Left, Right, } #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] pub(crate) struct SplitNode { pub(crate) split_feature_id: usize, pub(crate) n_obs: usize, pub(crate) split_val: f64, pub(crate) val: f64, pub(crate) nan_branch: NanBranch, pub(crate) left_child: Box<Node>, pub(crate) right_child: Box<Node>, } #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] pub(crate) struct LeafNode { pub(crate) val: f64, pub(crate) n_obs: usize, } #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] pub(crate) enum Node { Split(SplitNode), Leaf(LeafNode), } impl Node { /// Loss reduction /// (Refer to Eq7 of Reference[1]) pub(crate) fn _calc_split_gain( g: f64, h: f64, g_l: f64, h_l: f64, lambda: f64, gamma: f64, ) -> f64 { fn calc_term(g: f64, h: f64, lambda: f64) -> f64 { g.powi(2) / (h + lambda) } let g_r = g - g_l; let h_r = h - h_l; calc_term(g_l, h_l, lambda) + calc_term(g_r, h_r, lambda) - calc_term(g, h, lambda) - gamma } /// Calculate the optimal weight of this leaf node. /// (Refer to Eq5 of Reference[1]) pub(crate) fn _calc_leaf_weight( grad: &[f64], hessian: &[f64], lambda: f64, indices: &[usize], ) -> f64 { sum_indices(grad, indices) / (sum_indices(hessian, indices) + lambda) } pub(crate) fn build_from_train_data( train: &TrainDataset, indices: &[usize], predictions: &mut [f64], params: &TreeParams, ) -> Node { assert_eq!( train .grad .iter() .map(|f| f.is_nan() as usize) .sum::<usize>(), 0 ); assert_eq!( train .hessian .iter() .map(|f| f.is_nan() as usize) .sum::<usize>(), 0 ); let depth = 0; let has_bins = train.n_bins.iter().any(|&n_bins| n_bins > 0); if has_bins { if params.recursive_split { return *crate::tree_bin::build_bins(train, indices, predictions, depth, params) .node; } let mut nodes_of_rows = vec![::std::usize::MAX; train.n_rows()]; for &i in indices { nodes_of_rows[i] = 0; } let out = build_bins2(train, &mut nodes_of_rows, predictions, depth, params, 0, 1); assert_eq!(out.len(), 1); let out = match out.into_iter().next() { Some(e) => e.node, _ => panic!(), }; out } else { let out = build_direct(train, indices, predictions, depth, params); *(out.node) } } pub fn apply_shrinking(&mut self, shrinkage_rate: f64) { match self { Node::Leaf(ref mut node) => node.val *= shrinkage_rate, Node::Split(ref mut node) => { Node::apply_shrinking(&mut node.left_child, shrinkage_rate); Node::apply_shrinking(&mut node.right_child, shrinkage_rate); } } } pub fn predict(&self, features: &StridedVecView<f64>) -> f64 { match &self { Node::Split(split) => { let val = features[split.split_feature_id]; if val.is_nan() { match split.nan_branch { NanBranch::Left => split.left_child.predict(&features), NanBranch::Right => split.right_child.predict(&features), // If we didn't see any NAN in the train branch NanBranch::None => split.val, } } else if val <= split.split_val { split.left_child.predict(&features) } else { split.right_child.predict(&features) } } Node::Leaf(leaf) => leaf.val, } } pub fn par_predict(&self, features: &ColumnMajorMatrix<f64>) -> Vec<f64> { (0..features.n_rows()) .map(|i| { let row = features.row(i); self.predict(&row) }) .collect() } } /// Decision Tree implementation. #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] pub struct DecisionTree<L: Loss> { root: Node, loss: L, } impl<L: Loss> DecisionTree<L> { pub fn build( train: &PreparedDataset, predictions: &mut [f64], params: &TreeParams, loss: L, ) -> FitResult<Self> { let indices: Vec<_> = (0..train.target.len()).collect(); let train = train.as_train_data(&loss); let node = Node::build_from_train_data(&train, &indices, predictions, params); Ok(Self { root: node, loss }) } pub fn predict(&self, features: &StridedVecView<f64>) -> f64 { let o = self.root.predict(features); self.loss.get_target(o) } pub fn par_predict(&self, features: &ColumnMajorMatrix<f64>) -> Vec<f64> { self.root .par_predict(features) .iter() .map(|&o| self.loss.get_target(o)) .collect() } } #[cfg(test)] mod tests { use crate::*; #[test] fn test_regression_bins() -> Result<(), Box<::std::error::Error>> { let train = include_str!("../data/regression.train"); let train = parse_csv(train, "\t")?; let test = include_str!("../data/regression.test"); let test = parse_csv(test, "\t")?; let loss = RegLoss::default(); let train = train.as_prepared_data(3_000)?; let mut predictions = vec![::std::f64::NAN; train.n_rows()]; let mut params = TreeParams::new(); params.max_depth = 6; let tree = DecisionTree::build(&train, &mut predictions, &params, loss)?; let pred2 = tree.par_predict(&train.features); assert_eq!(predictions.len(), pred2.len()); let diffs: Vec<_> = predictions .iter() .zip(&pred2) .filter(|(&a, &b)| a != b) .collect(); assert_eq!( diffs.len(), 0, "{} different predictions out of {}, eg. {:?}", diffs.len(), predictions.len(), diffs.into_iter().take(100).collect::<Vec<_>>() ); let loss_train = rmse(&train.target, &predictions); let loss_test = rmse(&test.target, &tree.par_predict(&test.features)); assert!( loss_train <= 0.433, "Train loss too important, expected 0.43062595, got {} (test {})", loss_train, loss_test ); assert!( loss_test <= 0.446, "Test loss too important, expected 0.44403195, got {}", loss_test ); Ok(()) } #[test] fn test_regression_bins_recursive() -> Result<(), Box<::std::error::Error>> { let train = include_str!("../data/regression.train"); let train = parse_csv(train, "\t")?; let test = include_str!("../data/regression.test"); let test = parse_csv(test, "\t")?; let loss = RegLoss::default(); let train = train.as_prepared_data(3_000)?; let mut predictions = vec![::std::f64::NAN; train.n_rows()]; let mut params = TreeParams::new(); params.max_depth = 6; params.recursive_split = true; let tree = DecisionTree::build(&train, &mut predictions, &params, loss)?; let pred2 = tree.par_predict(&train.features); assert_eq!(predictions.len(), pred2.len()); for i in 0..predictions.len() { assert_eq!(predictions[i], pred2[i]); } let loss_train = rmse(&train.target, &predictions); let loss_test = rmse(&test.target, &tree.par_predict(&test.features)); assert!( loss_train <= 0.433, "Train loss too important, expected 0.43062595, got {} (test {})", loss_train, loss_test ); assert!( loss_test <= 0.446, "Test loss too important, expected 0.44403195, got {}", loss_test ); Ok(()) } #[test] fn test_regression_direct() -> Result<(), Box<::std::error::Error>> { let train = include_str!("../data/regression.train"); let train = parse_csv(train, "\t")?; let test = include_str!("../data/regression.test"); let test = parse_csv(test, "\t")?; let loss = RegLoss::default(); let train = train.as_prepared_data(0)?; let mut predictions = vec![::std::f64::NAN; train.n_rows()]; let mut params = TreeParams::new(); params.max_depth = 6; let tree = DecisionTree::build(&train, &mut predictions, &params, loss)?; let pred2 = tree.par_predict(&train.features); assert_eq!(predictions.len(), pred2.len()); for i in 0..predictions.len() { assert_eq!(predictions[i], pred2[i]); } let loss_train = rmse(&train.target, &predictions); let loss_test = rmse(&test.target, &tree.par_predict(&test.features)); assert!( loss_train <= 0.433, "Train loss too important, expected 0.43062595, got {} (test {})", loss_train, loss_test ); assert!( loss_test <= 0.446, "Test loss too important, expected 0.44403195, got {}", loss_test ); Ok(()) } } <file_sep>/rboost/Cargo.toml [package] name = "rboost" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] edition = "2018" [dependencies] classifier-measures = "0.4" either = "1" itertools = "0.8" # Git dependency until https://github.com/Emerentius/ord_subset/issues/4 is resolved ord_subset = {"git"="https://github.com/expenses/ord_subset.git"} ordered-float = "1.0" rand = "0.5.5" rayon = "1.0" serde = "1.0" serde_derive = "1.0" [dev-dependencies] cpuprofiler = "0.0.3" criterion = "0.2" lazy_static = "1.2.0" serde_json = "1.0" csv = "1" [[bench]] name = "bench_trees" harness = false [[bench]] name = "bench_binary" harness = false <file_sep>/rboost/src/dart.rs use crate::math::sample_indices_ratio; use crate::{ ColumnMajorMatrix, Dataset, FitResult, Loss, Node, PreparedDataset, StridedVecView, TreeParams, DEFAULT_COLSAMPLE_BYTREE, SHOULD_NOT_HAPPEN, }; use rand::prelude::Rng; use rayon::current_num_threads; use rayon::prelude::*; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct DartParams { pub colsample_bytree: f64, pub dropout_rate: f64, pub learning_rate: f64, } impl DartParams { pub fn new() -> Self { DartParams { colsample_bytree: DEFAULT_COLSAMPLE_BYTREE, dropout_rate: 0.5, learning_rate: 1.0, } } } impl Default for DartParams { fn default() -> Self { Self::new() } } /// Dart Booster. Boosting with dropout. /// /// Based on <https://arxiv.org/abs/1505.01866> #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Dart<L: Loss> { models: Vec<Node>, booster_params: DartParams, tree_params: TreeParams, best_iteration: usize, loss: L, initial_prediction: f64, } /// Compute the prediction for multiple trees of a DART fn calc_full_prediction( predictions: &ColumnMajorMatrix<f64>, tree_weights: &[f64], filter: &[bool], dest: &mut [f64], learning_rate: f64, initial_prediction: f64, ) { let chunk_size = predictions.n_rows() / current_num_threads(); // We split the dataset by rows dest.par_chunks_mut(chunk_size) .enumerate() .for_each(|(n_chunk, dest)| { // Initialization of the dataset at the initial prediction dest.iter_mut().for_each(|e| *e = initial_prediction); let first_original_idx = chunk_size * n_chunk; // We add the trees to the current chunk for ((predictions, &weight), &keep) in predictions.columns().zip(tree_weights).zip(filter) { // Dropout: we only keep parts of the trees if !keep { continue; } let predictions = &predictions[first_original_idx..]; for (dest, prediction) in dest.iter_mut().zip(predictions) { *dest += prediction * weight * learning_rate; } } }) } impl<L: Loss> Dart<L> { pub fn build( booster_params: &DartParams, tree_params: &TreeParams, train_set: &mut PreparedDataset, num_boost_round: usize, valid: Option<&Dataset>, early_stopping_rounds: usize, loss: L, rng: &mut impl Rng, ) -> FitResult<Dart<L>> { let mut models = Vec::new(); let booster_params = (*booster_params).clone(); let tree_params = (*tree_params).clone(); let mut train = train_set.as_train_data(&loss); train.check_data()?; let initial_prediction = loss.get_initial_prediction(&train.target); let mut best_iteration = 0; let mut best_val_loss = None; let size_train = train.target.len(); let size_val = valid.map(|e| e.target.len()); // Predictions per tree. let mut train_preds = ColumnMajorMatrix::from_function(size_train, num_boost_round, |_, _| 0.); let mut val_predictions = size_val .map(|size_val| ColumnMajorMatrix::from_function(size_val, num_boost_round, |_, _| 0.)); // Weights of every trees let mut tree_weights = Vec::new(); // Indices and weights per tree. We create it before so we don't have to allocate a new vector at // each iteration let indices: Vec<usize> = (0..train.target.len()).collect(); let sample_weights = vec![1.; size_train]; let mut train_scores = vec![0.; size_train]; let mut val_scores = size_val.map(|size_val| vec![0.; size_val]); let mut active_tree = vec![true; num_boost_round]; for iter_cnt in 0..(num_boost_round) { // Skip some trees for predictions for e in active_tree.iter_mut().take(iter_cnt) { if rng.gen::<f64>() > booster_params.dropout_rate { *e = false; } else { *e = true } } if active_tree.iter().all(|&e| e) & (booster_params.dropout_rate < 1.0) { *rng.choose_mut(&mut active_tree).expect(SHOULD_NOT_HAPPEN) = true; } let n_removed: usize = active_tree.iter().map(|&e| (!e) as usize).sum(); let normalizer = (n_removed as f64) / (1. + n_removed as f64); for (&e, weight) in active_tree.iter().zip(tree_weights.iter_mut()) { if !e { *weight *= normalizer; } } calc_full_prediction( &train_preds, &tree_weights, &active_tree, &mut train_scores, booster_params.learning_rate, initial_prediction, ); train.update_grad_hessian(&loss, &train_scores, &sample_weights); if booster_params.colsample_bytree < 1. { train.columns = sample_indices_ratio( rng, train.features.n_cols(), booster_params.colsample_bytree, ); } let learner = Node::build_from_train_data( &train, &indices, train_preds.column_mut(iter_cnt), &tree_params, ); tree_weights.push(1. / (1. + n_removed as f64)); if let Some(valid) = valid { let val_predictions = val_predictions.as_mut().expect(SHOULD_NOT_HAPPEN); let mut val_scores = val_scores.as_mut().expect(SHOULD_NOT_HAPPEN); let dest = val_predictions.column_mut(iter_cnt); dest.clone_from_slice(&learner.par_predict(&valid.features)); active_tree.iter_mut().for_each(|e| *e = true); calc_full_prediction( &val_predictions, &tree_weights, &active_tree, &mut val_scores, 1., initial_prediction, ); let val_loss = loss.calc_loss(&valid.target, &val_scores) / (valid.target.len() as f64); let val_loss = val_loss.sqrt(); if iter_cnt == 0 { best_val_loss = Some(val_loss) } else if let Some(best_val_loss_) = best_val_loss { if val_loss < best_val_loss_ { best_val_loss = Some(val_loss); best_iteration = iter_cnt; } if iter_cnt - best_iteration >= early_stopping_rounds { for _ in best_iteration..(iter_cnt - 1) { models.pop(); } break; } } models.push(learner); }; } for (tree, &weight) in models.iter_mut().zip(&tree_weights) { tree.apply_shrinking(weight); } Ok(Self { models, booster_params, tree_params, best_iteration, loss, initial_prediction, }) } fn _predict(&self, features: &StridedVecView<f64>, models: &[Node]) -> f64 { let o: f64 = models.iter().map(|model| model.predict(features)).sum(); if o.is_nan() { panic!("NAN in output of prediction"); } self.loss.get_target(o + self.initial_prediction) } pub fn predict(&self, features: &StridedVecView<f64>) -> f64 { self._predict(&features, &self.models) } pub fn n_trees(&self) -> usize { self.models.len() } } <file_sep>/rboost/src/matrix/sparse.rs use std::ops::Index; /// List of list format for sparse matrix. Allows fast creation and access. pub struct LILColumnMajorMatrix<A> { /// Number of rows in the matrix n_rows: usize, /// Number of columns in the matrix n_cols: usize, /// Position of the data. The first level is the columns, the second is the rows indices: Vec<Vec<usize>>, /// Values of the data. The first level is the columns, the second is the rows values: Vec<Vec<A>>, /// Null value implicitly encoded by an absence of data null_value: A, } pub struct SparseListView<'a, A: 'a> { /// Number of elements in the list len: usize, // Position of the data indices: &'a [usize], // Values of the data values: &'a [A], null_value: &'a A, } impl<A: PartialEq> LILColumnMajorMatrix<A> { pub fn from_columns(columns: Vec<Vec<A>>, null_value: A) -> Self { let (n_cols, n_rows) = (columns.len(), columns[0].len()); let mut values = Vec::with_capacity(n_cols); let mut indices = Vec::with_capacity(n_cols); for column in columns { let mut col_values = Vec::new(); let mut col_indices = Vec::new(); for (n_row, item) in column.into_iter().enumerate() { if item != null_value { col_indices.push(n_row); col_values.push(item); } } values.push(col_values); indices.push(col_indices); } Self { n_rows, n_cols, values, indices, null_value, } } pub fn from_rows(rows: Vec<Vec<A>>, null_value: A) -> Self { let (n_rows, n_cols) = (rows.len(), rows[0].len()); let mut indices: Vec<Vec<usize>> = (0..n_cols).map(|_| Vec::new()).collect(); let mut values: Vec<Vec<A>> = (0..n_cols).map(|_| Vec::new()).collect(); for (n_row, row) in rows.into_iter().enumerate() { for (n_col, elem) in row.into_iter().enumerate() { if elem != null_value { indices[n_col].push(n_row); values[n_col].push(elem); } } } Self { n_rows, n_cols, values, indices, null_value, } } } impl<A> LILColumnMajorMatrix<A> { pub fn column(&self, n_col: usize) -> SparseListView<A> { SparseListView { indices: &self.indices[n_col], values: &self.values[n_col], len: self.n_rows, null_value: &self.null_value, } } pub fn columns(&self) -> Vec<SparseListView<A>> { self.indices .iter() .zip(&self.values) .map(|(indices, values)| SparseListView { indices, values, len: self.n_rows, null_value: &self.null_value, }) .collect() } pub fn n_rows(&self) -> usize { self.n_rows } pub fn n_cols(&self) -> usize { self.n_cols } pub fn null_value(&self) -> &A { &self.null_value } } impl<'a, A: 'a> SparseListView<'a, A> { pub fn iter(&self) -> impl Iterator<Item = (&usize, &A)> { self.indices.iter().zip(self.values) } pub fn iter_all(&self) -> impl Iterator<Item = &A> { (0..self.len).map(move |idx| &self[idx]) } pub fn len(&self) -> usize { self.len } pub fn null_value(&self) -> &A { &self.null_value } } impl<'a, A: 'a> Index<usize> for SparseListView<'a, A> { type Output = A; fn index(&self, n: usize) -> &A { if let Ok(idx) = self.indices.binary_search(&n) { &self.values[idx] } else { &self.null_value } } } impl<A> Index<(usize, usize)> for LILColumnMajorMatrix<A> { type Output = A; fn index(&self, (row, col): (usize, usize)) -> &A { if let Ok(idx) = self.indices[col].binary_search(&row) { &self.values[col][idx] } else { &self.null_value } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_column_major() { // 1 4 // 2 5 // 3 6 let col0: Vec<f64> = vec![1., 2., 3.]; let col1: Vec<f64> = vec![4., 5., 6.]; let columns = vec![col0.clone(), col1.clone()]; let matrix = LILColumnMajorMatrix::from_columns(columns.clone(), 1.); assert_eq!(matrix[(0, 0)], 1.); assert_eq!(matrix[(1, 0)], 2.); assert_eq!(matrix[(2, 0)], 3.); assert_eq!(matrix[(0, 1)], 4.); assert_eq!(matrix[(1, 1)], 5.); assert_eq!(matrix[(2, 1)], 6.); let col0_: Vec<f64> = matrix.column(0).iter_all().map(|e| *e).collect(); let col1_: Vec<f64> = matrix.column(1).iter_all().map(|e| *e).collect(); assert_eq!(col0, col0_); assert_eq!(col1, col1_); let tuple0: Vec<(usize, f64)> = vec![(1, 2.), (2, 3.)]; let tuple0_: Vec<(usize, f64)> = matrix.column(0).iter().map(|(a, b)| (*a, *b)).collect(); assert_eq!(tuple0, tuple0_); } #[test] fn test_column_major_from_rows() { // 1 4 // 2 5 // 3 6 let row0 = vec![1., 4.]; let row1 = vec![2., 5.]; let row2 = vec![3., 6.]; let rows = vec![row0.clone(), row1.clone(), row2.clone()]; let matrix = LILColumnMajorMatrix::from_rows(rows, 1.); assert_eq!(matrix[(0, 0)], 1.); assert_eq!(matrix[(1, 0)], 2.); assert_eq!(matrix[(2, 0)], 3.); assert_eq!(matrix[(0, 1)], 4.); assert_eq!(matrix[(1, 1)], 5.); assert_eq!(matrix[(2, 1)], 6.); } } <file_sep>/rboost/examples/example_rf_binary.rs // Example of a regression with a random forest. extern crate cpuprofiler; extern crate csv; extern crate rboost; extern crate serde_json; use cpuprofiler::PROFILER; use rand::prelude::{SeedableRng, SmallRng}; use rboost::duration_as_f64; use rboost::{ accuracy_score, parse_csv, roc_auc_score, BinaryLogLoss, RFParams, RandomForest, TreeParams, }; use std::time::Instant; fn main() -> Result<(), Box<::std::error::Error>> { // Load the data let train = include_str!("../data/binary.train"); let train = parse_csv(train, "\t")?; let test = include_str!("../data/binary.test"); let test = parse_csv(test, "\t")?; // Random forest is a stochastic algorithm. For better control you can set the seed before // or use `let mut rng = ::rand::thread_rng()` let seed = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; // byte array let mut rng = SmallRng::from_seed(seed); // We set the params for the RF and the trees let mut rf_params = RFParams::new(); rf_params.colsample_bytree = 0.9; rf_params.n_trees = 100; let mut tree_params = TreeParams::default(); tree_params.gamma = 1.; tree_params.lambda = 1.; tree_params.max_depth = 10; tree_params.min_split_gain = 1.; // We use binning so the training is much faster. let n_bins = 256; println!( "Params rf={:?} tree{:?} n_bins={}", rf_params, tree_params, n_bins ); // cpuprofiler allows us to profile the hot loop let profile_path = "./example_rf.profile"; println!("Profiling to {}", profile_path); PROFILER.lock()?.start(profile_path)?; let predict_start_time = Instant::now(); let (rf, yhat_cv) = RandomForest::build( // Important: we have to transform the dataset to a PreparedDataset. // This step could be done just once if you want to train multiple RF. &mut train.as_prepared_data(n_bins)?, &rf_params, &tree_params, BinaryLogLoss::default(), &mut rng, )?; println!( "{} RF fit. Elapsed: {:.2} secs", rf_params.n_trees, duration_as_f64(&predict_start_time.elapsed()), ); PROFILER.lock()?.stop()?; // RF gives us direct cross-validated predictions. It's usually a little bit worse than test // because we use only 1-1/e = 63% of the train set. println!( "TRAIN CV: ROC AUC {:.8}, accuracy {:.8}", roc_auc_score(&train.target, &yhat_cv)?, accuracy_score(&train.target, &yhat_cv)?, ); let predict_start_time = Instant::now(); let yhat_train: Vec<f64> = (0..train.features.n_rows()) .map(|i| rf.predict(&train.features.row(i))) .collect(); println!( "Predictions done in {:.2} secs", duration_as_f64(&predict_start_time.elapsed()), ); println!( "TRAIN: ROC AUC {:.8}, accuracy {:.8}", roc_auc_score(&train.target, &yhat_train)?, accuracy_score(&train.target, &yhat_train)?, ); let yhat_test: Vec<f64> = (0..test.features.n_rows()) .map(|i| rf.predict(&test.features.row(i))) .collect(); println!( "TEST: ROC AUC {:.8}, accuracy {:.8}", roc_auc_score(&test.target, &yhat_test)?, accuracy_score(&test.target, &yhat_test)?, ); Ok(()) } <file_sep>/rboost/src/math.rs use rand::seq::sample_indices; use rand::Rng; pub(crate) fn sum(v: &[f64]) -> f64 { let mut o = 0.; for e in v.iter() { o += *e; } o } pub(crate) fn prod_vec(a: &[f64], b: &[f64]) -> Vec<f64> { a.iter().zip(b).map(|(&a, &b)| a * b).collect() } pub fn rmse(target: &[f64], yhat: &[f64]) -> f64 { let rmse: f64 = yhat .iter() .zip(target.iter()) .map(|(&a, &b)| (a - b).powi(2)) .sum(); (rmse / target.len() as f64).sqrt() } pub(crate) fn sum_indices(v: &[f64], indices: &[usize]) -> f64 { // A sum over a null set is not possible there, and this catch bugs. // The speed difference is negligible assert_ne!(indices.len(), 0); let mut o = 0.; for &i in indices { o += v[i]; } o } #[allow(dead_code)] pub(crate) fn sub_vec(a: &mut [f64], b: &[f64]) { assert_eq!(a.len(), b.len()); for (a, b) in a.iter_mut().zip(b.iter()) { *a -= b; } } #[allow(dead_code)] pub(crate) fn mul_add(a: &[f64], b: f64, out: &mut [f64]) { assert_eq!(a.len(), out.len()); out.iter_mut().zip(a).for_each(|(out, a)| *out += a * b); } #[allow(dead_code)] pub(crate) fn add(a: &[f64], out: &mut [f64]) { assert_eq!(a.len(), out.len()); out.iter_mut().zip(a).for_each(|(out, a)| *out += a); } pub(crate) fn sample_indices_ratio(rng: &mut impl Rng, length: usize, ratio: f64) -> Vec<usize> { let n_cols_f64 = ratio * (length as f64); let mut n_cols = n_cols_f64.floor() as usize; // Randomly select N or N+1 column proportionally to the difference if (n_cols_f64 - n_cols as f64) > rng.gen() { n_cols += 1; } sample_indices(rng, length, n_cols) } pub(crate) fn weighted_mean(val_1: f64, n_1: usize, val_2: f64, n_2: usize) -> f64 { let n = (n_1 + n_2) as f64; let (n_1, n_2) = (n_1 as f64, n_2 as f64); (val_1 * n_1 + val_2 * n_2) / n } pub fn roc_auc_score(y_true: &[f64], y_hat: &[f64]) -> Result<f64, Box<::std::error::Error>> { if y_hat.len() != y_true.len() { Err("Size of inputs are not the same for ROC AUC")?; } if y_hat.len() == 0 { Err("No input for ROC AUC")?; } let mut v: Vec<_> = y_true .iter() .zip(y_hat) .map(|(&y_true, &y_hat)| (y_true > 0.5, y_hat)) .collect(); let auc = classifier_measures::roc_auc_mut(&mut v).ok_or("Error on computation of ROC AUC"); Ok(auc?) } pub fn accuracy_score(y_true: &[f64], y_hat: &[f64]) -> Result<f64, Box<::std::error::Error>> { let mut n_ok = 0; for (&a, &b) in y_true.iter().zip(y_hat) { let a = if a == 0. { false } else if a == 1. { true } else { Err("Label must be 0 or 1")?; unreachable!() }; if a == (b > 0.5) { n_ok += 1; } } Ok((n_ok as f64) / (y_true.len() as f64)) } #[cfg(test)] mod tests { //use crate::*; // macro_rules! assert_almost_eq { // ($a : expr, $b:expr) => { // let (a, b) = ($a, $b); // let eps = 1e-5; // let diff = (a - b).abs(); // if diff > eps { // panic!("{} != {} at +-{}", a, b, eps) // } // }; // } }
58b6c917de12e33576cf39f920c1864e4976ea1c
[ "TOML", "Rust", "Shell" ]
25
Rust
MatthieuBizien/Rboost
91b53204015f5b2e5a6be593d310140185d0eb14
df585b17684f7558e46bd1e0a27717a3776b842c
refs/heads/master
<repo_name>0-Tal-do-Script/Tempo-de-Reuniao<file_sep>/README.md # Tempo de Reunião Você faz muitas reuniões?! Sim ?! Tem ideia de quantas já fez esse ano ou esse mês ou quanto tempo reservou para elas? Esse código é muito simples de rodar no google Planilhas, para ajudar segue um passo a passo: 1. Criar uma planilha do Google: - *Dica: Digite no seu browser "Sheets.new" e uma nova planilha se abrirá*; 2. Na barra superior *(menu Arquivo)* clique em `Ferramentas -> Editor de script`, uma nova se abrirá; 3. Apague todo o conteúdo e cole o código do arquivo `code.js`; 4. Volte para a planilha e atualize a página, aguarde tudo carregar; 5. Na barra superior *(menu Arquivo)*, você verá um novo item chamado **CALENDÁRIO**: - Clique em `CALENDÁRIO -> Configurar (1º uso)`; - Conceda as autorizações necessárias: - Após selecionar sua conta na nova janela que se abrirá, clique em `Avançado` e então em `Acessar ... (não seguro)` que fica na parte inferior. - Preencha os campos em amarelo com os valores desejados; - Clique em `CALENDÁRIO -> Importar Dados`.<file_sep>/code.js /** * Tempo de Reunião * @version 0.2.0 * @license MIT * @author https://github.com/Apps-script/Tempo-de-Reuniao */ /** Função automática do App Script que é executada assim que o usuário abre a planilha */ function onOpen() { // Crio um item no menu "arquivo" para facilitar a usabilidade SpreadsheetApp.getUi() .createMenu('CALENDÁRIO') .addItem('Configurar (1º uso)', 'setup') .addItem('Importar Dados', 'importCalendar') .addToUi(); } /** Função que faz a configuração inicial da aba, que basicamente é adicionar os campos de data, email e título das colunas */ function setup() { const sheet = SpreadsheetApp.getActiveSheet(); // Campos de data sheet.getRange('A1').setValue('Data inicial'); sheet.getRange('A2').setValue('Data final'); const dateCells = sheet.getRange('B1:B2'); dateCells.setBackground('#FFFBCE'); // Colorindo o fundo da célula em amarelo dateCells.setNumberFormat('dd/mm/yy'); // Definindo o formato das células como "data e hora" // Datas de exemplo let now = new Date(); now.setHours(0, 0, 0, 0); let pastDate = new Date(); pastDate.setMonth(pastDate.getMonth() - 3); pastDate.setHours(0, 0, 0, 0); sheet.getRange('B1').setValue(pastDate); sheet.getRange('B2').setValue(now); // Campo de email sheet.getRange('A3').setValue('Seu email'); sheet.getRange('B3').setValue('<EMAIL>').setBackground('#FFFBCE'); // Título das colunas sheet.getRange('A5:F5') .setValues([ ['Título do evento', 'Início', 'Término', 'Criado por', 'Convidados','Tempo de reunião'] ]) .setBackground('#B5BBFF'); } /** Função que importa os dados do calendário após a configuração inicial */ function importCalendar() { const sheet = SpreadsheetApp.getActiveSheet(); const calendar = CalendarApp.getCalendarById(sheet.getRange('B3').getValue()); const myEvents = calendar.getEvents(sheet.getRange('B1').getValue(), sheet.getRange('B2').getValue()); // Limpando os dados da planilha antes de importar dados novos sheet.getRange('A6:E').clearContent(); // Gerando a lista de eventos const rows = []; myEvents.forEach(event => { const guests = event.getGuestList().map(guest => guest.getEmail()); rows.push([ event.getTitle(), event.getStartTime(), event.getEndTime(), event.getCreators(), guests.sort().join(', '), ]); }); // Inserindo as linhas na planilha sheet.getRange(6, 1, rows.length, 5).setValues(rows); // fazendo calculo var spreadsheet = SpreadsheetApp.getActive(); spreadsheet.getRange('F6').activate(); var currentCell = spreadsheet.getCurrentCell(); spreadsheet.getSelection().getNextDataRange(SpreadsheetApp.Direction.DOWN).activate(); currentCell.activateAsCurrentCell(); spreadsheet.getActiveRange().setFormula('=IF(C6>0;C6-B6;" ")').setNumberFormat('[h]:mm:ss'); // Alinhar var spreadsheet = SpreadsheetApp.getActive(); spreadsheet.getRange('A:F').activate(); spreadsheet.getActiveRangeList().setHorizontalAlignment('center'); }
5605644741fbca00ae971a92e82bbd66c0d7fda2
[ "Markdown", "JavaScript" ]
2
Markdown
0-Tal-do-Script/Tempo-de-Reuniao
6cf090b59bfb3d56cc9877beb5ffb91b8523c30f
7f3b5fc56d18e5d0839a4144e8887388caa2f735
refs/heads/main
<repo_name>fatemehh1376/Maktab_44_2<file_sep>/fatemeh.py def func1(): print("Hi every body")<file_sep>/README.md # Maktab_44_2 for group
2a7f0056d3d2ec603deec16f7587a4c43f8ccc5c
[ "Markdown", "Python" ]
2
Python
fatemehh1376/Maktab_44_2
6b51d957c156e451f19918038b1cbc4884c092ce
c30fcd389242405d62284c11b1a5517d7b270a1b
refs/heads/master
<file_sep>class Review < ApplicationRecord belongs_to :reservation belongs_to :user validates :content, presence: true validates :rate, numericality: { less_than_or_equal_to: 5, greater_than_or_equal_to: 1 }, presence: true end <file_sep>class UsersController < ApplicationController def show @user = User.find(params[:id]) @users = User.all @rooms = @user.rooms.where(is_active: true).paginate(page: params[:page], per_page: 6) @reviews = Review.all @num1 = 0 @num2 = 0 @rooms.each do |room| @num1 += room.guest_reviews.count @num2 += room.host_reviews.count end end end <file_sep>class Room < ApplicationRecord belongs_to :user has_many :photos, dependent: :destroy has_many :reservations, dependent: :destroy has_many :reviews, through: :reservations validates :home_type, presence: true validates :room_type, presence: true validates :guest_count, presence: true validates :bedroom_count, presence: true validates :bathroom_count, presence: true geocoded_by :address after_validation :geocode, if: :address_changed? def average_rating ids = reservations.pluck(:user_id)# pluck all the user_id from the reservations # add a condition to return 0 if the reviews from guests is 0 if reviews.where(user_id: ids).any? reviews.where(user_id: ids).average(:rate).round(2).to_i else return 1 end end def guest_reviews ids = reservations.pluck(:user_id) reviews.where(user_id: ids) end def host_reviews ids = reservations.pluck(:user_id) reviews.where.not(user_id: ids) end end <file_sep>module RoomsHelper def is_ready?(room) !room.price.blank? && !room.photos.blank? && !room.room_name.blank? && !room.address.blank? end end <file_sep>class ReservationsController < ApplicationController def create room = Room.find(params[:room_id]) if current_user == room.user flash[:alert] = "You cannot book your own property!" elsif current_user == nil flash[:alert] = "Please log in!" else start_date = Date.parse(reservation_params[:start_date]) end_date = Date.parse(reservation_params[:end_date]) nights = end_date == start_date ? 1 : (end_date - start_date).to_i @reservation = current_user.reservations.new(reservation_params) @reservation.room = room @reservation.price = room.price @reservation.total_price = nights * room.price @reservation.save flash[:notice] = "Booked Successfully!" end redirect_to room_url(room) end def your_reservations @rooms = current_user.rooms.all @review = Review.new end def your_trips @users = User.all @reservations = current_user.reservations.all @review = Review.new end private def reservation_params params.require(:reservation).permit(:start_date, :end_date) end end <file_sep>class RoomsController < ApplicationController before_action :get_room, except: [:new, :create, :index] def index @rooms = current_user.rooms.paginate(page: params[:page], per_page: 10) end def new @room = Room.new end def create @room = current_user.rooms.new(room_params) if @room.save redirect_to room_room_url(@room) else render 'new' end end def show @reservation = @room.reservations.new end def update @final_params = is_ready?(@room) ? room_params.merge(is_active: true) : room_params if @room.update(@final_params) redirect_to request.referrer else render 'room' end end def room end def price end def description end def photos @photos = @room.photos end def amenities end def location end def preload today = Date.today reservations = @room.reservations.where("start_date >= ? OR end_date >= ?",today,today) render json: reservations end def preview start_date = Date.parse(params[:start_date]) end_date = Date.parse(params[:end_date]) output = { conflict: is_conflict(start_date, end_date, @room) } render json: output end private def room_params params.require(:room).permit(:home_type, :room_type, :guest_count, :bedroom_count, :bathroom_count, :price, :room_name, :summary, :address, :has_tv, :has_kitchen, :has_internet, :has_heating, :has_air_conditioning) end def get_room @room = Room.find(params[:id]) end def is_conflict(start_date, end_date, room) check = room.reservations.where("? < start_date AND end_date < ?", start_date, end_date) check.size > 0 ? true : false end end <file_sep>class Reservation < ApplicationRecord belongs_to :user belongs_to :room has_many :reviews end <file_sep>module ReservationsHelper end <file_sep>class ReviewsController < ApplicationController def create @review = Review.new(review_params) @reservation = Reservation.find_by(id: @review.reservation_id) if @reservation.reviews.where(user_id: @review.user_id, host_id: @review.host_id, guest_id: @review.guest_id).any? flash[:alert] = "You already reviewed this reservation." redirect_to request.referrer else if @review.save flash[:notice] = "Reviewed Successfully!" redirect_to request.referrer end end end private def review_params params.require(:review).permit(:user_id, :host_id, :guest_id, :content, :rate, :reservation_id) end end
66778fac9535349437e5044868b612a2774836cb
[ "Ruby" ]
9
Ruby
ren0715/airbnb
d48cbad2038cd36f1f3a1b51dbcb85c7bc66f685
a33608943aa09f2af90dc7918d50af63e0f3c3bd
refs/heads/master
<file_sep>export { ModalProps } from './Modal'; export { ModalBaseProps } from './ModalBase'; <file_sep>export { Image, BackgroundImage } from './Image'; <file_sep>export { ToggleProps } from './Toggle'; <file_sep>export { LoadingWrapperProps } from './LoadingWrapper'; <file_sep>declare module 'elementz-ui'; <file_sep>import { getButtonColor } from '../buttonHelpers'; import { defaultTheme } from '../../../utilities/ThemeProvider'; describe('getButtonColor', () => { it('should return primary color when type is `primary`', () => { expect(getButtonColor({ type: 'primary', theme: defaultTheme })).toEqual( defaultTheme.primary, ); }); it('should return default color when type is not available', () => { expect(getButtonColor({ type: null, theme: defaultTheme })).toEqual( defaultTheme.default, ); }); }); <file_sep>export { ImageProps, BackgroundImageProps } from './Image'; <file_sep>export const setDimensions = (width: string, height: string) => { return ` width: ${width}; height: ${height}; `; }; export const setAbsoluteCenter = (size: string) => { return ` position: absolute; top: 50%; left: 50%; margin-top: -${parseFloat(size.replace(/\D/g, '')) / 2}px; margin-left: -${parseFloat(size.replace(/\D/g, '')) / 2}px; `; }; export const alignVertical = () => { return ` display: flex; align-items: center; justify-content: center; `; }; export const setDisabled = () => { return ` opacity: 0.7; pointer-events: none; `; }; <file_sep>#!/bin/bash npm install npm run build npm run build:storybook npm run test:coverage coveralls < ./coverage/lcov.info <file_sep>export { Modal } from './Modal'; export { ModalBase } from './ModalBase'; <file_sep>export { default, Props } from './Grid'; <file_sep>export { Text } from './Text'; export { Button, LoadingButton } from './Button'; export { Spinner } from './Spinner'; export { Image, BackgroundImage } from './Image'; export { ModalBase, Modal } from './Modal'; <file_sep>module.exports = { setupTestFrameworkScriptFile: require.resolve('./jest.setup.js'), preset: 'ts-jest', moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'], testPathIgnorePatterns: ['/node_modules/'], transform: { '.(ts|tsx)': 'ts-jest', }, }; <file_sep>import React from 'react'; import { ThemeProvider } from '../src/components/utilities'; export const WrapperDecorator = storyFn => ( <ThemeProvider>{storyFn()}</ThemeProvider> ); <file_sep>// defaults for all stories export const infoConfig = { info: { inline: true, header: false, styles: { infoBody: { marginTop: '50px', padding: '20px', lineHeight: '2', }, source: { h1: { margin: '0', }, }, }, }, }; <file_sep>export * from './elements'; export * from './layout'; export * from './wrappers'; export * from './utilities'; <file_sep>export { ThemeProvider, defaultTheme } from './ThemeProvider'; export { Toggle } from './Toggle'; <file_sep>export { ClickOutsideWrapperProps } from './ClickOutsideWrapper'; <file_sep>export const getButtonColor = ({ type, theme }: { type: any; theme: any }) => type ? theme[type] : theme.default; <file_sep>export { LoadingWrapper } from './LoadingWrapper'; <file_sep>export const get = (obj: any, ...paths: any) => paths .join('.') .split('.') .reduce((a: any, b: any) => (a && a[b] ? a[b] : null), obj); export const themeGet = (paths: string, fallback?: string) => (props: any) => get(props.theme, paths) || fallback; <file_sep># elementz-ui ✨ [![Build Status](https://travis-ci.org/savalazic/elementz-ui.svg?branch=master)](https://travis-ci.org/savalazic/elementz-ui) [![Coverage Status](https://coveralls.io/repos/github/savalazic/elementz-ui/badge.svg?branch=master)](https://coveralls.io/github/savalazic/elementz-ui?branch=master) [![license](https://img.shields.io/github/license/mashape/apistatus.svg?maxAge=2592000)](https://github.com/savalazic/elementz-ui/blob/master/LICENSE) <!-- [![npm downloads](https://img.shields.io/npm/dm/repo-name.svg)](https://www.npmjs.com/package/repo-name) --> <!-- [![npm version](https://img.shields.io/npm/v/repo-name.svg)](https://www.npmjs.com/package/repo-name) --> Set of React components that are highly customizable so you can configure the base styles of all the components as well as modify each one of them individually. ### WIP... 👨🏻‍💻 ## Licence elementz-ui is released under the MIT license. Copyright © 2018 <NAME>. <file_sep>export { SpinnerProps } from './Spinner'; <file_sep>import React from 'react'; import { storiesOf } from '@storybook/react'; const stories = storiesOf('Welcome', module); stories.addParameters({ info: { disable: true, }, }); stories.add('to elementz-ui', () => ( <div> <h1>Welcome to elementz-ui</h1> <p> This is a storybook environment for the{' '} <a href="http://github.com/savalazic/elementz-ui/" target="_blank"> elementz-ui </a> </p> </div> )); <file_sep>export { ButtonProps, LoadingButtonProps } from './Button'; <file_sep>export { ThemeProps } from './ThemeProvider'; <file_sep>import resolve from 'rollup-plugin-node-resolve'; import babel from 'rollup-plugin-babel'; import replace from 'rollup-plugin-replace'; import typescript from 'rollup-plugin-typescript'; import { terser } from 'rollup-plugin-terser'; const dev = 'development'; const prod = 'production'; const env = process.env.NODE_ENV === prod || process.env.NODE_ENV === dev ? process.env.NODE_ENV : dev; const config = { input: 'src/index.ts', output: { file: 'dist/index.js', format: 'cjs', globals: { react: 'React', 'react-dom': 'ReactDOM', 'styled-components': 'styled', }, }, plugins: [ replace({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV), }), resolve(), babel({ exclude: 'node_modules/**', // only transpile our source code externalHelpers: true, }), typescript(), ], external: ['react', 'react-dom', 'styled-components'], }; if (env === 'production') { config.plugins.push(terser()); } export default config; <file_sep>export { ClickOutsideWrapper } from './ClickOutsideWrapper'; <file_sep>export { TextProps } from './Text'; <file_sep>export { ClickOutsideWrapper } from './ClickOutsideWrapper'; export { LoadingWrapper } from './LoadingWrapper';
124165381af0ccf152f267a072dbd9c5f733ce86
[ "JavaScript", "TypeScript", "Markdown", "Shell" ]
30
TypeScript
savalazic/elementz-ui
f1b013f4c3e8a7b2e96e0fc8299569896892b515
7ded8874564920a8fbc30d313627776ec3e48419
refs/heads/master
<repo_name>Disi77/Basnicka<file_sep>/README.md # Program na přeházení pořadí slov, řádků a slok v básničce Program vznikl v rámci kurzu PyLadies "Začátečnický kurz PyLadies – Ostrava - podzim 2018" <file_sep>/basnicka.py from random import shuffle def hlavicka(string): ''' Vytiskne hlavičku se zadaným stringem ''' print() print(50*'-') print(string.upper()) print() # Původní básnička hlavicka('Původní básnička:') with open('basnicka.txt', encoding='utf-8') as soubor: for radek in soubor.readlines(): print(radek.rstrip()) # Načíst básničku ze souboru a vrátit zpátky řádky v obráceném pořadí hlavicka('Básnička - řádky v obráceném pořadí:') with open('basnicka.txt', encoding='utf-8') as soubor: for radek in reversed(list(soubor.readlines())): print(radek.rstrip()) # Orátit pořadí slov ve verších hlavicka('Básnička - slova v řádku v obráceném pořadí:') seznam = [] with open('basnicka.txt', encoding='utf-8') as soubor: for radek in soubor.readlines(): seznam.append(radek.rstrip()) for zaznam in seznam: radek = zaznam.split() radek.reverse() novy_radek = ' '.join(radek) print(novy_radek) # Obrátit pořadí slok (sloky oddělené prázdným řádkem) hlavicka('Soubor s básničkou - sloky v obráceném pořadí:') seznam = [] with open('basnicka.txt', encoding='utf-8') as soubor: text = soubor.read() zacatek = 0 for x in range(text.count('\n\n')): konec = text.index('\n\n', zacatek+1) seznam.append(text[zacatek:konec].strip()) zacatek = konec seznam.append(text[zacatek:].strip()) seznam.reverse() for sloka in seznam: print(sloka) print() # Slova náhodně se zachováním původní struktury básně hlavicka('Soubor s básničkou - přeházená slova:') radky = [] with open('basnicka.txt', encoding='utf-8') as soubor: for radek in soubor.readlines(): radky.append(radek.rstrip()) # nejdříve zkoumám strukturu textu delka_radek = [] seznam_0 = [] for radek in radky: delka = len(radek) delka_radek.append(delka) seznam_0.extend(radek.split()) seznam = [] for slovo in seznam_0: slovo = slovo.replace(',', '').replace('.', '').lower() seznam.append(slovo) shuffle(seznam) # pak z přeházených slov znovu tvořím báseň nova_basnicka = [] pocet_radku = len(delka_radek) pocet_mezer = delka_radek.count(0) pocet_slov_na_radek, zbytek = divmod(len(seznam), (pocet_radku - pocet_mezer)) for kolo in range(pocet_radku): if delka_radek[kolo] != 0: radek = '' for x in range(pocet_slov_na_radek): radek += ' ' + seznam.pop() nova_basnicka.append(radek.strip()) else: nova_basnicka.append('\n') try: for zaznam in nova_basnicka: if len(zaznam) > 1: radek = zaznam radek = zaznam + ' ' + seznam.pop() nova_basnicka[nova_basnicka.index(zaznam)] = radek except IndexError: pass # Nastavím správný syntax - velké písmeno na začátku sloky apod. index_mezery_odstavec = [] for i, x in enumerate(delka_radek): if x == 0: index_mezery_odstavec.append(i) nova_basnicka[0] = nova_basnicka[0].capitalize() for index in index_mezery_odstavec: nova_basnicka[index+1] = nova_basnicka[index+1].capitalize() for i, radek in enumerate(nova_basnicka): if i == pocet_radku-1: nova_basnicka[i] += '.' elif (i+1) in index_mezery_odstavec: nova_basnicka[i] += '.' elif i in index_mezery_odstavec: pass else: nova_basnicka[i] += ',' for x in nova_basnicka: print(x)
02f99b233f4d18bcec8c8c3c5c791c4c490885d7
[ "Markdown", "Python" ]
2
Markdown
Disi77/Basnicka
139c4ef593f02501865c1567f64ece9907c56b20
124d53d17916138a701b2c9d35fc3a436770fa89
refs/heads/master
<repo_name>syshen/RACSwift-HackerNews<file_sep>/Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/Swift/PropertySpec.swift // // PropertySpec.swift // ReactiveCocoa // // Created by <NAME> on 2015-01-23. // Copyright (c) 2015 GitHub. All rights reserved. // import Result import Nimble import Quick import ReactiveCocoa private let initialPropertyValue = "InitialValue" private let subsequentPropertyValue = "SubsequentValue" class PropertySpec: QuickSpec { override func spec() { describe("ConstantProperty") { it("should have the value given at initialization") { let constantProperty = ConstantProperty(initialPropertyValue) expect(constantProperty.value).to(equal(initialPropertyValue)) } it("should yield a producer that sends the current value then completes") { let constantProperty = ConstantProperty(initialPropertyValue) var sentValue: String? var signalCompleted = false constantProperty.producer.start(next: { value in sentValue = value }, completed: { signalCompleted = true }) expect(sentValue).to(equal(initialPropertyValue)) expect(signalCompleted).to(beTruthy()) } } describe("MutableProperty") { it("should have the value given at initialization") { let mutableProperty = MutableProperty(initialPropertyValue) expect(mutableProperty.value).to(equal(initialPropertyValue)) } it("should yield a producer that sends the current value then all changes") { let mutableProperty = MutableProperty(initialPropertyValue) var sentValue: String? mutableProperty.producer.start(next: { value in sentValue = value }) expect(sentValue).to(equal(initialPropertyValue)) mutableProperty.value = subsequentPropertyValue expect(sentValue).to(equal(subsequentPropertyValue)) } it("should complete its producer when deallocated") { var mutableProperty: MutableProperty? = MutableProperty(initialPropertyValue) var signalCompleted = false mutableProperty?.producer.start(completed: { signalCompleted = true }) mutableProperty = nil expect(signalCompleted).to(beTruthy()) } } describe("PropertyOf") { it("should pass through behaviors of the input property") { let constantProperty = ConstantProperty(initialPropertyValue) let propertyOf = PropertyOf(constantProperty) var sentValue: String? var producerCompleted = false propertyOf.producer.start(next: { value in sentValue = value }, completed: { producerCompleted = true }) expect(sentValue).to(equal(initialPropertyValue)) expect(producerCompleted).to(beTruthy()) } } describe("DynamicProperty") { var object: ObservableObject! var property: DynamicProperty! let propertyValue: () -> Int? = { if let value: AnyObject = property?.value { return value as? Int } else { return nil } } beforeEach { object = ObservableObject() expect(object.rac_value).to(equal(0)) property = DynamicProperty(object: object, keyPath: "rac_value") } afterEach { object = nil } it("should read the underlying object") { expect(propertyValue()).to(equal(0)) object.rac_value = 1 expect(propertyValue()).to(equal(1)) } it("should write the underlying object") { property.value = 1 expect(object.rac_value).to(equal(1)) expect(propertyValue()).to(equal(1)) } it("should observe changes to the property and underlying object") { var values: [Int] = [] property.producer.start(next: { value in expect(value).notTo(beNil()) values.append((value as? Int) ?? -1) }) expect(values).to(equal([ 0 ])) property.value = 1 expect(values).to(equal([ 0, 1 ])) object.rac_value = 2 expect(values).to(equal([ 0, 1, 2 ])) } it("should complete when the underlying object deallocates") { var completed = false property = { // Use a closure so this object has a shorter lifetime. let object = ObservableObject() let property = DynamicProperty(object: object, keyPath: "rac_value") property.producer.start(completed: { completed = true }) expect(completed).to(beFalsy()) expect(property.value).notTo(beNil()) return property }() expect(completed).toEventually(beTruthy()) expect(property.value).to(beNil()) } it("should retain property while DynamicProperty's object is retained"){ weak var dynamicProperty: DynamicProperty? = property property = nil expect(dynamicProperty).toNot(beNil()) object = nil expect(dynamicProperty).to(beNil()) } } describe("binding") { describe("from a Signal") { it("should update the property with values sent from the signal") { let (signal, observer) = Signal<String, NoError>.pipe() let mutableProperty = MutableProperty(initialPropertyValue) mutableProperty <~ signal // Verify that the binding hasn't changed the property value: expect(mutableProperty.value).to(equal(initialPropertyValue)) sendNext(observer, subsequentPropertyValue) expect(mutableProperty.value).to(equal(subsequentPropertyValue)) } it("should tear down the binding when disposed") { let (signal, observer) = Signal<String, NoError>.pipe() let mutableProperty = MutableProperty(initialPropertyValue) let bindingDisposable = mutableProperty <~ signal bindingDisposable.dispose() sendNext(observer, subsequentPropertyValue) expect(mutableProperty.value).to(equal(initialPropertyValue)) } it("should tear down the binding when bound signal is completed") { let (signal, observer) = Signal<String, NoError>.pipe() let mutableProperty = MutableProperty(initialPropertyValue) let bindingDisposable = mutableProperty <~ signal expect(bindingDisposable.disposed).to(beFalsy()) sendCompleted(observer) expect(bindingDisposable.disposed).to(beTruthy()) } it("should tear down the binding when the property deallocates") { let (signal, observer) = Signal<String, NoError>.pipe() var mutableProperty: MutableProperty<String>? = MutableProperty(initialPropertyValue) let bindingDisposable = mutableProperty! <~ signal mutableProperty = nil expect(bindingDisposable.disposed).to(beTruthy()) } } describe("from a SignalProducer") { it("should start a signal and update the property with its values") { let signalValues = [initialPropertyValue, subsequentPropertyValue] let signalProducer = SignalProducer<String, NoError>(values: signalValues) let mutableProperty = MutableProperty(initialPropertyValue) mutableProperty <~ signalProducer expect(mutableProperty.value).to(equal(signalValues.last!)) } it("should tear down the binding when disposed") { let signalValues = [initialPropertyValue, subsequentPropertyValue] let signalProducer = SignalProducer<String, NoError>(values: signalValues) let mutableProperty = MutableProperty(initialPropertyValue) let disposable = mutableProperty <~ signalProducer disposable.dispose() // TODO: Assert binding was teared-down? } it("should tear down the binding when bound signal is completed") { let signalValues = [initialPropertyValue, subsequentPropertyValue] let (signalProducer, observer) = SignalProducer<String, NoError>.buffer(1) let mutableProperty = MutableProperty(initialPropertyValue) let disposable = mutableProperty <~ signalProducer expect(disposable.disposed).to(beFalsy()) sendCompleted(observer) expect(disposable.disposed).to(beTruthy()) } it("should tear down the binding when the property deallocates") { let signalValues = [initialPropertyValue, subsequentPropertyValue] let signalProducer = SignalProducer<String, NoError>(values: signalValues) var mutableProperty: MutableProperty<String>? = MutableProperty(initialPropertyValue) let disposable = mutableProperty! <~ signalProducer mutableProperty = nil expect(disposable.disposed).to(beTruthy()) } } describe("from another property") { it("should take the source property's current value") { let sourceProperty = ConstantProperty(initialPropertyValue) let destinationProperty = MutableProperty("") destinationProperty <~ sourceProperty.producer expect(destinationProperty.value).to(equal(initialPropertyValue)) } it("should update with changes to the source property's value") { let sourceProperty = MutableProperty(initialPropertyValue) let destinationProperty = MutableProperty("") destinationProperty <~ sourceProperty.producer destinationProperty.value = subsequentPropertyValue expect(destinationProperty.value).to(equal(subsequentPropertyValue)) } it("should tear down the binding when disposed") { let sourceProperty = MutableProperty(initialPropertyValue) let destinationProperty = MutableProperty("") let bindingDisposable = destinationProperty <~ sourceProperty.producer bindingDisposable.dispose() sourceProperty.value = subsequentPropertyValue expect(destinationProperty.value).to(equal(initialPropertyValue)) } it("should tear down the binding when the source property deallocates") { var sourceProperty: MutableProperty<String>? = MutableProperty(initialPropertyValue) let destinationProperty = MutableProperty("") let bindingDisposable = destinationProperty <~ sourceProperty!.producer sourceProperty = nil expect(bindingDisposable.disposed).to(beTruthy()) } it("should tear down the binding when the destination property deallocates") { let sourceProperty = MutableProperty(initialPropertyValue) var destinationProperty: MutableProperty<String>? = MutableProperty("") let bindingDisposable = destinationProperty! <~ sourceProperty.producer destinationProperty = nil expect(bindingDisposable.disposed).to(beTruthy()) } } } } } private class ObservableObject: NSObject { dynamic var rac_value: Int = 0 } <file_sep>/Carthage/Checkouts/LlamaKit/LlamaKitTests/ResultTests.swift // // LlamaKitTests.swift // LlamaKitTests // // Created by <NAME> on 9/9/14. // Copyright (c) 2014 <NAME>. All rights reserved. // import Foundation import LlamaKit import XCTest class ResultTests: XCTestCase { let err = NSError(domain: "", code: 11, userInfo: nil) let err2 = NSError(domain: "", code: 12, userInfo: nil) func testSuccessIsSuccess() { let s: Result<Int,NSError> = success(42) XCTAssertTrue(s.isSuccess) } func testFailureIsNotSuccess() { let f: Result<Bool, NSError> = failure() XCTAssertFalse(f.isSuccess) } func testSuccessReturnsValue() { let s: Result<Int,NSError> = success(42) XCTAssertEqual(s.value!, 42) } func testSuccessReturnsNoError() { let s: Result<Int,NSError> = success(42) XCTAssertNil(s.error) } func testFailureReturnsError() { let f: Result<Int, NSError> = failure(self.err) XCTAssertEqual(f.error!, self.err) } func testFailureReturnsNoValue() { let f: Result<Int, NSError> = failure(self.err) XCTAssertNil(f.value) } func testMapSuccessUnaryOperator() { let x: Result<Int, NSError> = success(42) let y = x.map(-) XCTAssertEqual(y.value!, -42) } func testMapFailureUnaryOperator() { let x: Result<Int, NSError> = failure(self.err) let y = x.map(-) XCTAssertNil(y.value) XCTAssertEqual(y.error!, self.err) } func testMapSuccessNewType() { let x: Result<String, NSError> = success("abcd") let y = x.map { count($0) } XCTAssertEqual(y.value!, 4) } func testMapFailureNewType() { let x: Result<String, NSError> = failure(self.err) let y = x.map { count($0) } XCTAssertEqual(y.error!, self.err) } func doubleSuccess(x: Int) -> Result<Int, NSError> { return success(x * 2) } func doubleFailure(x: Int) -> Result<Int, NSError> { return failure(self.err) } func testFlatMapSuccessSuccess() { let x: Result<Int, NSError> = success(42) let y = x.flatMap(doubleSuccess) XCTAssertEqual(y.value!, 84) } func testFlatMapSuccessFailure() { let x: Result<Int, NSError> = success(42) let y = x.flatMap(doubleFailure) XCTAssertEqual(y.error!, self.err) } func testFlatMapFailureSuccess() { let x: Result<Int, NSError> = failure(self.err2) let y = x.flatMap(doubleSuccess) XCTAssertEqual(y.error!, self.err2) } func testFlatMapFailureFailure() { let x: Result<Int, NSError> = failure(self.err2) let y = x.flatMap(doubleFailure) XCTAssertEqual(y.error!, self.err2) } func testDescriptionSuccess() { let x: Result<Int, NSError> = success(42) XCTAssertEqual(x.description, "Success: 42") } func testDescriptionFailure() { let x: Result<String, NSError> = failure() XCTAssert(x.description.hasPrefix("Failure: Error Domain= Code=0 ")) } func testCoalesceSuccess() { let r: Result<Int, NSError> = success(42) let x = r ?? 43 XCTAssertEqual(x, 42) } func testCoalesceFailure() { let x = failure() ?? 43 XCTAssertEqual(x, 43) } private func makeTryFunction<T>(x: T, _ succeed: Bool = true)(error: NSErrorPointer) -> T { if !succeed { error.memory = NSError(domain: "domain", code: 1, userInfo: [:]) } return x } func testTryTSuccess() { XCTAssertEqual(try(makeTryFunction(42 as Int?)) ?? 43, 42) } func testTryTFailure() { let result = try(makeTryFunction(nil as String?, false)) XCTAssertEqual(result ?? "abc", "abc") XCTAssert(result.description.hasPrefix("Failure: Error Domain=domain Code=1 ")) } func testTryBoolSuccess() { XCTAssert(try(makeTryFunction(true)).isSuccess) } func testTryBoolFailure() { let result = try(makeTryFunction(false, false)) XCTAssertFalse(result.isSuccess) XCTAssert(result.description.hasPrefix("Failure: Error Domain=domain Code=1 ")) } func testSuccessEquality() { let result: Result<String, NSError> = success("result") let otherResult: Result<String, NSError> = success("result") XCTAssert(result == otherResult) } func testFailureEquality() { let result: Result<String, NSError> = failure(err) let otherResult: Result<String, NSError> = failure(err) XCTAssert(result == otherResult) } func testSuccessInequality() { let result: Result<String, NSError> = success("result") let otherResult: Result<String, NSError> = success("different result") XCTAssert(result != otherResult) } func testFailureInequality() { let result: Result<String, NSError> = failure(err) let otherResult: Result<String, NSError> = failure(err2) XCTAssert(result != otherResult) } } <file_sep>/Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/Swift/SignalProducerNimbleMatchers.swift // // SignalProducerNimbleMatchers.swift // ReactiveCocoa // // Created by <NAME> on 1/25/15. // Copyright (c) 2015 GitHub. All rights reserved. // import Foundation import ReactiveCocoa import Nimble public func sendValue<T: Equatable, E: Equatable>(value: T?, #sendError: E?, #complete: Bool) -> NonNilMatcherFunc<SignalProducer<T, E>> { return sendValues(value.map { [$0] } ?? [], sendError: sendError, complete: complete) } public func sendValues<T: Equatable, E: Equatable>(values: [T], sendError maybeSendError: E?, #complete: Bool) -> NonNilMatcherFunc<SignalProducer<T, E>> { return NonNilMatcherFunc { actualExpression, failureMessage in precondition(maybeSendError == nil || !complete, "Signals can't both send an error and complete") failureMessage.postfixMessage = "Send values \(values). Send error \(maybeSendError). Complete: \(complete)" let maybeProducer = actualExpression.evaluate() if let signalProducer = maybeProducer { var sentValues: [T] = [] var sentError: E? var signalCompleted = false signalProducer.start(next: { value in sentValues.append(value) }, error: { error in sentError = error }, completed: { signalCompleted = true }) if sentValues != values { return false } if sentError != maybeSendError { return false } return signalCompleted == complete } else { return false } } }<file_sep>/Carthage/Checkouts/LlamaKit/LlamaKit.podspec Pod::Spec.new do |s| s.name = "LlamaKit" s.version = "0.5.0" s.summary = "Collection of must-have functional Swift tools." s.description = "Collection of must-have functional tools. Trying to be as lightweight as possible, hopefully providing a simple foundation that more advanced systems can build on. LlamaKit is very Cocoa-focused. It is designed to work with common Cocoa paradigms, use names that are understandable to Cocoa devs, integrate with Cocoa tools like GCD, and in general strive for a low-to-modest learning curve for devs familiar with ObjC and Swift rather than Haskell and ML." s.homepage = "https://github.com/LlamaKit/LlamaKit" s.license = "MIT" s.author = { "<NAME>" => "<EMAIL>" } s.social_media_url = "http://twitter.com/cocoaphony" s.ios.deployment_target = "8.0" s.osx.deployment_target = "10.10" s.source = { :git => "https://github.com/LlamaKit/LlamaKit.git", :tag => "v#{s.version}" } s.source_files = "LlamaKit/*.swift" end <file_sep>/Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/Swift/TestError.swift // // TestError.swift // ReactiveCocoa // // Created by <NAME> on 1/26/15. // Copyright (c) 2015 GitHub. All rights reserved. // import Foundation import ReactiveCocoa enum TestError: Int { case Default = 0 case Error1 = 1 case Error2 = 2 } extension TestError: ErrorType { static var domain: String { return "org.reactivecocoa.ReactiveCocoa.Tests" } var nsError: NSError { return NSError(domain: TestError.domain, code: rawValue, userInfo: nil) } } <file_sep>/Carthage/Checkouts/ReactiveCocoa/Carthage/Checkouts/Box/BoxTests/BoxTypeTests.swift // Copyright (c) 2014 <NAME>. All rights reserved. import Box import XCTest class BoxTypeTests: XCTestCase { func testEquality() { let (a, b, c) = (Box(1), Box(1), Box(2)) XCTAssertTrue(a == b) XCTAssertFalse(b == c) } func testInequality() { let (a, b, c) = (Box(1), Box(1), Box(2)) XCTAssertFalse(a != b) XCTAssertTrue(b != c) } func testMap() { let a = Box(1) let b: Box<String> = map(a, toString) XCTAssertEqual(b.value, "1") } } <file_sep>/Carthage/Checkouts/ReactiveCocoa/ReactiveCocoa/Swift/Bag.swift // // Bag.swift // ReactiveCocoa // // Created by <NAME> on 2014-07-10. // Copyright (c) 2014 GitHub. All rights reserved. // /// A uniquely identifying token for removing a value that was inserted into a /// Bag. internal struct RemovalToken { private let extract: () -> UInt? } /// An unordered, non-unique collection of values of type T. internal struct Bag<T>: SequenceType { private var next: UInt = 0 private var elements = [UInt: T]() /// Inserts the given value in the collection, and returns a token that can /// later be passed to removeValueForToken(). internal mutating func insert(value: T) -> RemovalToken { let start = next while elements[next] != nil { next = next &+ 1 assert(next != start) } elements[next] = value var key = Optional(next) return RemovalToken { let k = key key = nil return k } } /// Removes a value, given the token returned from insert(). /// /// If the value has already been removed, nothing happens. internal mutating func removeValueForToken(token: RemovalToken) { if let key = token.extract() { self.elements.removeValueForKey(key) } } internal func generate() -> GeneratorOf<T> { var values: [T] = [] var index = next + 1 while index > 0 { --index if let value = elements[index] { values.append(value) } } return GeneratorOf(values.generate()) } } <file_sep>/Carthage/Checkouts/ReactiveCocoa/Carthage/Checkouts/Nimble/NimbleTests/Matchers/RaisesExceptionTest.swift import XCTest import Nimble class RaisesExceptionTest: XCTestCase { var exception = NSException(name: "laugh", reason: "Lulz", userInfo: ["key": "value"]) func testPositiveMatches() { expect { self.exception.raise() }.to(raiseException()) expect { self.exception.raise() }.to(raiseException(named: "laugh")) expect { self.exception.raise() }.to(raiseException(named: "laugh", reason: "Lulz")) expect { self.exception.raise() }.to(raiseException(named: "laugh", reason: "Lulz", userInfo: ["key": "value"])) } func testPositiveMatchesWithSubMatchers() { expect { self.exception.raise() }.to(raiseException(named: equal("laugh"))) expect { self.exception.raise() }.to(raiseException(reason: beginWith("Lu"))) expect { self.exception.raise() }.to(raiseException(userInfo:equal(["key": "value"]))) expect { self.exception.raise() }.to(raiseException(named: equal("laugh"), reason: beginWith("Lu"))) expect { self.exception.raise() }.to( raiseException(named: equal("laugh"), reason: beginWith("Lu"), userInfo:equal(["key": "value"]))) expect { self.exception.raise() }.toNot(raiseException(named: equal("smile"))) expect { self.exception.raise() }.toNot(raiseException(reason: beginWith("Lut"))) expect { self.exception.raise() }.toNot(raiseException(userInfo:equal(["key": "no value"]))) expect { self.exception.raise() }.toNot(raiseException(named: equal("laugh"), reason: beginWith("Lut"))) expect { self.exception }.toNot(raiseException(named: equal("laugh"), reason: beginWith("Lu"))) } func testNegativeMatches() { failsWithErrorMessage("expected to raise exception with name equal <foo>") { expect { self.exception.raise() }.to(raiseException(named: "foo")) } failsWithErrorMessage("expected to raise exception with name equal <laugh> with reason equal <bar>") { expect { self.exception.raise() }.to(raiseException(named: "laugh", reason: "bar")) } failsWithErrorMessage( "expected to raise exception with name equal <laugh> with reason equal <Lulz> with userInfo equal <{k = v;}>") { expect { self.exception.raise() }.to(raiseException(named: "laugh", reason: "Lulz", userInfo: ["k": "v"])) } failsWithErrorMessage("expected to raise any exception") { expect { self.exception }.to(raiseException()) } failsWithErrorMessage("expected to not raise any exception") { expect { self.exception.raise() }.toNot(raiseException()) } failsWithErrorMessage("expected to raise exception with name equal <laugh> with reason equal <Lulz>") { expect { self.exception }.to(raiseException(named: "laugh", reason: "Lulz")) } failsWithErrorMessage("expected to raise exception with name equal <bar> with reason equal <Lulz>") { expect { self.exception.raise() }.to(raiseException(named: "bar", reason: "Lulz")) } failsWithErrorMessage("expected to not raise exception with name equal <laugh>") { expect { self.exception.raise() }.toNot(raiseException(named: "laugh")) } failsWithErrorMessage("expected to not raise exception with name equal <laugh> with reason equal <Lulz>") { expect { self.exception.raise() }.toNot(raiseException(named: "laugh", reason: "Lulz")) } failsWithErrorMessage("expected to not raise exception with name equal <laugh> with reason equal <Lulz> with userInfo equal <{key = value;}>") { expect { self.exception.raise() }.toNot(raiseException(named: "laugh", reason: "Lulz", userInfo: ["key": "value"])) } } func testNegativeMatchesWithSubMatchers() { failsWithErrorMessage("expected to raise exception with name equal <foo> with reason begin with <bar>") { expect { self.exception.raise() }.to(raiseException(named: equal("foo"), reason: beginWith("bar"))) } failsWithErrorMessage("expected to raise exception with name equal <foo>") { expect { self.exception.raise() }.to(raiseException(named: equal("foo"))) } failsWithErrorMessage("expected to raise exception with reason begin with <bar>") { expect { self.exception.raise() }.to(raiseException(reason: beginWith("bar"))) } failsWithErrorMessage("expected to raise exception with userInfo equal <{k = v;}>") { expect { self.exception.raise() }.to(raiseException(userInfo: equal(["k": "v"]))) } failsWithErrorMessage("expected to not raise exception with name equal <laugh> with reason begin with <Lu>") { expect { self.exception.raise() }.toNot(raiseException(named: equal("laugh"), reason: beginWith("Lu"))) } failsWithErrorMessage("expected to not raise exception with name equal <laugh>") { expect { self.exception.raise() }.toNot(raiseException(named: equal("laugh"))) } failsWithErrorMessage("expected to not raise exception with reason begin with <Lu>") { expect { self.exception.raise() }.toNot(raiseException(reason: beginWith("Lu"))) } failsWithErrorMessage("expected to raise exception with name equal <laugh> with reason begin with <Lu>") { expect { self.exception }.to(raiseException(named: equal("laugh"), reason: beginWith("Lu"))) } } } <file_sep>/Carthage/Checkouts/LlamaKit/LlamaKit/README.md LlamaKit ======== Collection of must-have functional tools. Trying to be as lightweight as possible, hopefully providing a simple foundation that more advanced systems can build on. LlamaKit is very Cocoa-focused. It is designed to work with common Cocoa paradigms, use names that are understandable to Cocoa devs, integrate with Cocoa tools like GCD, and in general strive for a low-to-modest learning curve for devs familiar with ObjC and Swift rather than Haskell and ML. There are more functionally beautiful toolkits out there (see [Swiftz](https://github.com/maxpow4h/swiftz) and [Swift-Extras](https://github.com/CodaFi/Swift-Extras) for some nice examples). LlamaKit intentionally is much less full-featured, and is focused only on things that come up commonly in Cocoa development. (Within those restrictions, it hopes to be based as much as possible on the lessons of other FP languages, and I welcome input from folks with deeper FP experience.) Currently has a `Result` object, which is the most critical. (And in the end, it may be the *only* thing in the main module.) LlamaKit should be considered highly experimental, pre-alpha, in development, I promise I will break you. But the `Result` object is kind of nice already if you want to go ahead and use it. :D (Note that I've moved the async objects, Future, Promise, Task, out of this repo. I'm working on them further, but they'll go into some other repo like LlamaKit-async. This repo is meant to be very, very core stuff that almost everyone will want. Async is too big for that.) <file_sep>/RACSwift-HackerNews/ViewController.swift // // ViewController.swift // RACSwift // // Created by syshen on 5/6/15. // Copyright (c) 2015 Intelligent Gadget. All rights reserved. // import UIKit import ReactiveCocoa import Alamofire class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var indicator:UIActivityIndicatorView? @IBOutlet weak var tableView:UITableView? var action:Action<(), [NSNumber], NSError>? var cocoaAction:CocoaAction? let client = HNClient() var items:[NSNumber] = [] override func prefersStatusBarHidden() -> Bool { return true } override func viewDidLoad() { super.viewDidLoad() let refreshControl = UIRefreshControl() self.tableView?.registerClass(UITableViewCell.self, forCellReuseIdentifier: "tableViewCell") self.action = Action { self.client.topStories() } self.action!.executing.producer |> start(next:{ x in let executing = x as Bool if executing { self.indicator?.startAnimating() } else { self.indicator?.stopAnimating() } }) self.action!.values.observe(error: {error->() in let alert = UIAlertView() alert.title = "Error" alert.message = "Failed due to \(error)" alert.show() }, next: { [unowned self] nums -> () in self.items = nums refreshControl.endRefreshing() // End refreshing when done self.tableView?.reloadData() }) self.action!.apply().start() self.cocoaAction = CocoaAction(self.action!, {$0 as AnyObject?}) refreshControl.addTarget(self.cocoaAction!, action: CocoaAction.selector, forControlEvents: .ValueChanged) self.tableView!.addSubview(refreshControl) // client.topStories() // |> on(started: { [unowned self] in // self.indicator!.startAnimating() // }, error: { [unowned self] error in // self.indicator!.stopAnimating() // }, completed: { [unowned self] in // self.indicator!.stopAnimating() // } // ) // |> start(next: { [unowned self] nums -> Void in // self.items = nums // self.tableView?.reloadData() // }) } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("tableViewCell", forIndexPath: indexPath) as! UITableViewCell let identity:NSNumber = self.items[indexPath.row] // self.client.item(identity) |> start(next: { dict->() in // if let story = dict as NSDictionary! { // if let text = story["title"] as? String { // cell.textLabel!.text = text // } // } // }) cell.textLabel!.text = "" let prepareReuseProducer = cell.rac_prepareForReuseSignal.toSignalProducer() |> map { _ in () } |> catch { _ in SignalProducer<(), NoError>.empty } let storyTitleProducer = self.client.item(identity) |> map { dict in dict["title"] as! String } |> catch { _ in SignalProducer<String, NoError>(value: "") } |> takeUntil(prepareReuseProducer) |> observeOn(UIScheduler()) DynamicProperty(object: cell.textLabel!, keyPath: "text") <~ storyTitleProducer |> map { $0 as AnyObject? } return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } <file_sep>/RACSwift-HackerNews/HNClient.swift // // RHCClient.swift // RACSwift // // Created by syshen on 5/6/15. // Copyright (c) 2015 Intelligent Gadget. All rights reserved. // import UIKit import ReactiveCocoa import Alamofire class HNClient: NSObject { var test = "Hello World" func maxItemIdentity() -> SignalProducer<NSNumber, NSError> { return SignalProducer{ observer, _ in self.requestManager.request( .GET, "https://hacker-news.firebaseio.com/v0/maxitem.json" ).responseJSON(options: .AllowFragments, completionHandler: { (_, _, JSON, error) -> Void in if let error = error { sendError(observer, error) } else { if let maxitem = JSON as? NSNumber { sendNext(observer, maxitem) } sendCompleted(observer) } }) return } } func topStories() -> SignalProducer<[NSNumber], NSError> { return SignalProducer{ observer, _ in self.requestManager.request( .GET, "https://hacker-news.firebaseio.com/v0/topstories.json" ).responseJSON(options: .AllowFragments, completionHandler: { (_, _, JSON, error) -> Void in if let error = error { sendError(observer, error) } else { if let nums = JSON as? [NSNumber] { sendNext(observer, nums) } sendCompleted(observer) } }) return } } func item(identity:NSNumber) -> SignalProducer<NSDictionary, NSError> { return SignalProducer { observer, _ in self.requestManager.request( .GET, "https://hacker-news.firebaseio.com/v0/item/\(identity).json" ).responseJSON(options: .AllowFragments, completionHandler: { (_, _, JSON, error) -> Void in if let error = error { sendError(observer, error) } else { if let dict = JSON as? NSDictionary { sendNext(observer, dict) } sendCompleted(observer) } }) return } } private let requestManager = Alamofire.Manager(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) } <file_sep>/Carthage/Checkouts/LlamaKit/README.md LlamaKit ======== Collection of must-have functional tools. Trying to be as lightweight as possible, hopefully providing a simple foundation that more advanced systems can build on. LlamaKit is very Cocoa-focused. It is designed to work with common Cocoa paradigms, use names that are understandable to Cocoa devs, integrate with Cocoa tools like GCD, and in general strive for a low-to-modest learning curve for devs familiar with ObjC and Swift rather than Haskell and ML. There are more functionally beautiful toolkits out there (see [Swiftz](https://github.com/maxpow4h/swiftz) and [Swift-Extras](https://github.com/CodaFi/Swift-Extras) for some nice examples). LlamaKit intentionally is much less full-featured, and is focused only on things that come up commonly in Cocoa development. (Within those restrictions, it hopes to be based as much as possible on the lessons of other FP languages, and I welcome input from folks with deeper FP experience.) Currently has a `Result` object, which is the most critical. (And in the end, it may be the *only* thing in the main module.) `Result` is mostly done except for documentation (in progress). Tests are built. `Future` is in progress. It's heavily inspired by [Scala's approach](http://docs.scala-lang.org/overviews/core/futures.html), though there are some small differences. I haven't decided if a `Promise` ISA `Future` or HASA `Future`. The Scala approach is a weird hybrid. It technically HASA `Future`, but in the main implementation, the `Promise` is its own `Future`, so it's kind of ISA, too. Still a work in progress there. I'm considering pulling `Future` out; it already makes this module too complicated (did I mention that LlamaKit wants to be really, really simple?) LlamaKit should be considered highly experimental, pre-alpha, in development, I promise I will break you. But the `Result` object is kind of nice already if you want to go ahead and use it. :D Current Thinkings on Structure ============================== (This is highly in progress and subject to change, like everything. Comments welcome.) I want LlamaKit to provide several important tools to simplify functional composition. But LlamaKit doesn't intend to be a programming approach (vs. [ReactiveCocoa](https://github.com/ReactiveCocoa) or [TypeLift](https://github.com/typelift) which provide powerful ways to think about problems). LlamaKit is just a bag of tools. If you want to borrow my hammer, you don't have to take my circular saw, too. So LlamaKit is split up into several small frameworks so you can pick-and-choose. <table> <tr><td colspan=2 align="center">LlamaKit (umbrella)</td></tr> <tr><td>LlamaFuture</td><td>Llama... (?)</td><td>LlamaOps</td></tr> <tr><td colspan=3 align="center">LlamaCore</td></tr> </table> LlamaCore : The absolute basics. If it's in LlamaCore, I believe that the majority of Swift developers should be using it. I think other libraries should bulid on top of it. I think Apple should put it into stdlib. This is the stuff that I worry *many* developers will reinvent, and that will cause collisions between code bases. LlamaCore strives to be incredibly non-impacting. It avoids creating top-level functions that might conflict with consuming code. It declares no new opeartors. The bar is very high to be in LlamaCore. It currently contains just two types: `Result` (which I think Apple should put into stdlib) and `Box` (which only exists because of Swift compiler limitations). In the ideal LlamaKit, LlamaCore would be empty. LlamaFuture : Concurrency primitives, most notably `Future`. In my current design, `Future` is actually stand-alone and doesn't require LlamaCore, but I think that most developers will want a failable `Future<Result>>` (which I am tentatively calling `Task`). I also expect this to hold `Promise`, which is a future that the caller manually completes. (This is still under very heavy consideration; I'm not sure exactly what I want yet.) LlamaFuture is tightly coupled to GCD, and is intended as a nicer interface to common Cocoa concurrency primitives, not a replacement for them. LlamaOps : Functional composition with operators like `>>=` and `|>` is a beautiful thing. But it carries with it a lot of overhead. Not only are there cognative loads (the code is not obvious at all to the uninitiated), there are non-trivial compiler and language impacts. Operators are declared globally (specifically precedence and associativity). The Swift compiler has some serious performance problems building code with complex operator usage. And in the case of operator conflict, the resulting errors are very confusing. Widely used libraries should strongly avoid bringing in new operators implicitly. My intention is that you would always have to import LlamaOps explicitly, even if you import the umbrella LlamaKit. LlamaKit : I do expect most of the things in LlamaKit to be useful to many, if not most, Cocoa devs. I don't want to force you to take everything, but I do want to make it easy to take everything (except operators). So hopefully I can provide an umbrella framework. I don't know if that actually works in Xcode, but we'll see. Llama... : At this point I'm not expecting a ton more stuff, but this is where it would go. While I'm evangelizing functional programming, I want most people to use Swift to achieve that, not lots of layers on top of Swift. So for instance, I'm not particularly sold on an `Either` right now. In most cases I'd rather you use an enum directly. And I don't want to create a full functor-applicative-monad hierarchy (TypeLift is covering that for us). I probabaly do want somewhere to put `sequence()`, `lift()`, `pure()`, and `flip()` and maybe that could become LlamaLambda (LlamaLamb? LlamaFunc?) But I want to go slow there and see what needs arrise in real projects.<file_sep>/Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/Swift/BagSpec.swift // // BagSpec.swift // ReactiveCocoa // // Created by <NAME> on 2014-07-13. // Copyright (c) 2014 GitHub. All rights reserved. // import Nimble import Quick import ReactiveCocoa class BagSpec: QuickSpec { override func spec() { var bag = Bag<String>() beforeEach { bag = Bag() } it("should insert values") { let a = bag.insert("foo") let b = bag.insert("bar") let c = bag.insert("buzz") expect(contains(bag, "foo")).to(beTruthy()) expect(contains(bag, "bar")).to(beTruthy()) expect(contains(bag, "buzz")).to(beTruthy()) expect(contains(bag, "fuzz")).to(beFalsy()) expect(contains(bag, "foobar")).to(beFalsy()) } it("should remove values given the token from insertion") { let a = bag.insert("foo") let b = bag.insert("bar") let c = bag.insert("buzz") bag.removeValueForToken(b) expect(contains(bag, "foo")).to(beTruthy()) expect(contains(bag, "bar")).to(beFalsy()) expect(contains(bag, "buzz")).to(beTruthy()) bag.removeValueForToken(a) expect(contains(bag, "foo")).to(beFalsy()) expect(contains(bag, "bar")).to(beFalsy()) expect(contains(bag, "buzz")).to(beTruthy()) bag.removeValueForToken(c) expect(contains(bag, "foo")).to(beFalsy()) expect(contains(bag, "bar")).to(beFalsy()) expect(contains(bag, "buzz")).to(beFalsy()) } } } <file_sep>/Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/Swift/SchedulerSpec.swift // // SchedulerSpec.swift // ReactiveCocoa // // Created by <NAME> on 2014-07-13. // Copyright (c) 2014 GitHub. All rights reserved. // import Foundation import Nimble import Quick import ReactiveCocoa class SchedulerSpec: QuickSpec { override func spec() { describe("ImmediateScheduler") { it("should run enqueued actions immediately") { var didRun = false ImmediateScheduler().schedule { didRun = true } expect(didRun).to(beTruthy()) } } describe("UIScheduler") { func dispatchSyncInBackground(action: () -> ()) { let group = dispatch_group_create() dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), action) dispatch_group_wait(group, DISPATCH_TIME_FOREVER) } it("should run actions immediately when on the main thread") { let scheduler = UIScheduler() var values: [Int] = [] expect(NSThread.isMainThread()).to(beTruthy()) scheduler.schedule { values.append(0) } expect(values).to(equal([ 0 ])) scheduler.schedule { values.append(1) } scheduler.schedule { values.append(2) } expect(values).to(equal([ 0, 1, 2 ])) } it("should enqueue actions scheduled from the background") { let scheduler = UIScheduler() var values: [Int] = [] dispatchSyncInBackground { scheduler.schedule { expect(NSThread.isMainThread()).to(beTruthy()) values.append(0) } return } expect(values).to(equal([])) expect(values).toEventually(equal([ 0 ])) dispatchSyncInBackground { scheduler.schedule { expect(NSThread.isMainThread()).to(beTruthy()) values.append(1) } scheduler.schedule { expect(NSThread.isMainThread()).to(beTruthy()) values.append(2) } return } expect(values).to(equal([ 0 ])) expect(values).toEventually(equal([ 0, 1, 2 ])) } it("should run actions enqueued from the main thread after those from the background") { let scheduler = UIScheduler() var values: [Int] = [] dispatchSyncInBackground { scheduler.schedule { expect(NSThread.isMainThread()).to(beTruthy()) values.append(0) } return } scheduler.schedule { expect(NSThread.isMainThread()).to(beTruthy()) values.append(1) } scheduler.schedule { expect(NSThread.isMainThread()).to(beTruthy()) values.append(2) } expect(values).to(equal([])) expect(values).toEventually(equal([ 0, 1, 2 ])) } } describe("QueueScheduler") { it("should run enqueued actions on a global queue") { var didRun = false QueueScheduler().schedule { didRun = true expect(NSThread.isMainThread()).to(beFalsy()) } expect{didRun}.toEventually(beTruthy()) } describe("on a given queue") { var queue: dispatch_queue_t! var scheduler: QueueScheduler! beforeEach { queue = dispatch_queue_create("", DISPATCH_QUEUE_CONCURRENT) dispatch_suspend(queue) scheduler = QueueScheduler(queue) } it("should run enqueued actions serially on the given queue") { var value = 0 for i in 0..<5 { scheduler.schedule { expect(NSThread.isMainThread()).to(beFalsy()) value++ } } expect(value).to(equal(0)) dispatch_resume(queue) expect{value}.toEventually(equal(5)) } it("should run enqueued actions after a given date") { var didRun = false scheduler.scheduleAfter(NSDate()) { didRun = true expect(NSThread.isMainThread()).to(beFalsy()) } expect(didRun).to(beFalsy()) dispatch_resume(queue) expect{didRun}.toEventually(beTruthy()) } it("should repeatedly run actions after a given date") { let disposable = SerialDisposable() var count = 0 let timesToRun = 3 disposable.innerDisposable = scheduler.scheduleAfter(NSDate(), repeatingEvery: 0.01, withLeeway: 0) { expect(NSThread.isMainThread()).to(beFalsy()) if ++count == timesToRun { disposable.dispose() } } expect(count).to(equal(0)) dispatch_resume(queue) expect{count}.toEventually(equal(timesToRun)) } } } describe("TestScheduler") { var scheduler: TestScheduler! var startInterval: NSTimeInterval! // How much dates are allowed to differ when they should be "equal." let dateComparisonDelta = 0.00001 beforeEach { let startDate = NSDate() startInterval = startDate.timeIntervalSinceReferenceDate scheduler = TestScheduler(startDate: startDate) expect(scheduler.currentDate).to(equal(startDate)) } it("should run immediately enqueued actions upon advancement") { var string = "" scheduler.schedule { string += "foo" expect(NSThread.isMainThread()).to(beTruthy()) } scheduler.schedule { string += "bar" expect(NSThread.isMainThread()).to(beTruthy()) } expect(string).to(equal("")) scheduler.advance() expect(scheduler.currentDate.timeIntervalSinceReferenceDate).to(beCloseTo(startInterval)) expect(string).to(equal("foobar")) } it("should run actions when advanced past the target date") { var string = "" scheduler.scheduleAfter(15) { string += "bar" expect(NSThread.isMainThread()).to(beTruthy()) } scheduler.scheduleAfter(5) { string += "foo" expect(NSThread.isMainThread()).to(beTruthy()) } expect(string).to(equal("")) scheduler.advanceByInterval(10) expect(scheduler.currentDate.timeIntervalSinceReferenceDate).to(beCloseTo(startInterval + 10, within: dateComparisonDelta)) expect(string).to(equal("foo")) scheduler.advanceByInterval(10) expect(scheduler.currentDate.timeIntervalSinceReferenceDate).to(beCloseTo(startInterval + 20, within: dateComparisonDelta)) expect(string).to(equal("foobar")) } it("should run all remaining actions in order") { var string = "" scheduler.scheduleAfter(15) { string += "bar" expect(NSThread.isMainThread()).to(beTruthy()) } scheduler.scheduleAfter(5) { string += "foo" expect(NSThread.isMainThread()).to(beTruthy()) } scheduler.schedule { string += "fuzzbuzz" expect(NSThread.isMainThread()).to(beTruthy()) } expect(string).to(equal("")) scheduler.run() expect(scheduler.currentDate).to(equal(NSDate.distantFuture() as? NSDate)) expect(string).to(equal("fuzzbuzzfoobar")) } } } } <file_sep>/README.md ##A really simple example of a Hacker News client with RAC3.0.## I have used ReactiveCocoa 2.0 for half of an year. But to me, RAC3.0 is still not an easy thing to understand and learn. If you guys also want a simple example of how to use RAC3.0 with Swift, I hope this repo is helpful to you. And I also recommend you can visit some other articles like: - http://blog.scottlogic.com/2015/04/28/reactive-cocoa-3-continued.html - http://nomothetis.svbtle.com/an-introduction-to-reactivecocoa - http://blog.scottlogic.com/2015/04/24/first-look-reactive-cocoa-3.html ##Build## 1. Install Carthage 2. % carthage update 3. Launch the project file and build <file_sep>/Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/Swift/SignalSpec.swift // // SignalSpec.swift // ReactiveCocoa // // Created by <NAME> on 2015-01-23. // Copyright (c) 2015 GitHub. All rights reserved. // import Box import Result import Nimble import Quick import ReactiveCocoa class SignalSpec: QuickSpec { override func spec() { describe("init") { var testScheduler: TestScheduler! beforeEach { testScheduler = TestScheduler() } it("should run the generator immediately") { var didRunGenerator = false Signal<AnyObject, NoError> { observer in didRunGenerator = true return nil } expect(didRunGenerator).to(beTruthy()) } it("should not keep signal alive indefinitely") { weak var signal: Signal<AnyObject, NoError>? = Signal.never expect(signal).to(beNil()) } it("should deallocate after erroring") { weak var signal: Signal<AnyObject, TestError>? = Signal { observer in testScheduler.schedule { sendError(observer, TestError.Default) } return nil } var errored = false signal?.observe(error: { _ in errored = true }) expect(errored).to(beFalsy()) expect(signal).toNot(beNil()) testScheduler.run() expect(errored).to(beTruthy()) expect(signal).to(beNil()) } it("should deallocate after completing") { weak var signal: Signal<AnyObject, NoError>? = Signal { observer in testScheduler.schedule { sendCompleted(observer) } return nil } var completed = false signal?.observe(completed: { completed = true }) expect(completed).to(beFalsy()) expect(signal).toNot(beNil()) testScheduler.run() expect(completed).to(beTruthy()) expect(signal).to(beNil()) } it("should deallocate after interrupting") { weak var signal: Signal<AnyObject, NoError>? = Signal { observer in testScheduler.schedule { sendInterrupted(observer) } return nil } var interrupted = false signal?.observe(interrupted: { interrupted = true }) expect(interrupted).to(beFalsy()) expect(signal).toNot(beNil()) testScheduler.run() expect(interrupted).to(beTruthy()) expect(signal).to(beNil()) } it("should forward events to observers") { let numbers = [ 1, 2, 5 ] let signal: Signal<Int, NoError> = Signal { observer in testScheduler.schedule { for number in numbers { sendNext(observer, number) } sendCompleted(observer) } return nil } var fromSignal: [Int] = [] var completed = false signal.observe(next: { number in fromSignal.append(number) }, completed: { completed = true }) expect(completed).to(beFalsy()) expect(fromSignal).to(beEmpty()) testScheduler.run() expect(completed).to(beTruthy()) expect(fromSignal).to(equal(numbers)) } it("should dispose of returned disposable upon error") { let disposable = SimpleDisposable() let signal: Signal<AnyObject, TestError> = Signal { observer in testScheduler.schedule { sendError(observer, TestError.Default) } return disposable } var errored = false signal.observe(error: { _ in errored = true }) expect(errored).to(beFalsy()) expect(disposable.disposed).to(beFalsy()) testScheduler.run() expect(errored).to(beTruthy()) expect(disposable.disposed).to(beTruthy()) } it("should dispose of returned disposable upon completion") { let disposable = SimpleDisposable() let signal: Signal<AnyObject, NoError> = Signal { observer in testScheduler.schedule { sendCompleted(observer) } return disposable } var completed = false signal.observe(completed: { completed = true }) expect(completed).to(beFalsy()) expect(disposable.disposed).to(beFalsy()) testScheduler.run() expect(completed).to(beTruthy()) expect(disposable.disposed).to(beTruthy()) } it("should dispose of returned disposable upon interrupted") { let disposable = SimpleDisposable() let signal: Signal<AnyObject, NoError> = Signal { observer in testScheduler.schedule { sendInterrupted(observer) } return disposable } var interrupted = false signal.observe(interrupted: { interrupted = true }) expect(interrupted).to(beFalsy()) expect(disposable.disposed).to(beFalsy()) testScheduler.run() expect(interrupted).to(beTruthy()) expect(disposable.disposed).to(beTruthy()) } } describe("Signal.pipe") { it("should not keep signal alive indefinitely") { weak var signal = Signal<(), NoError>.pipe().0 expect(signal).to(beNil()) } it("should deallocate after erroring") { let testScheduler = TestScheduler() weak var weakSignal: Signal<(), TestError>? // Use an inner closure to help ARC deallocate things as we // expect. let test: () -> () = { let (signal, observer) = Signal<(), TestError>.pipe() weakSignal = signal testScheduler.schedule { sendError(observer, TestError.Default) } } test() expect(weakSignal).toNot(beNil()) testScheduler.run() expect(weakSignal).to(beNil()) } it("should deallocate after completing") { let testScheduler = TestScheduler() weak var weakSignal: Signal<(), TestError>? // Use an inner closure to help ARC deallocate things as we // expect. let test: () -> () = { let (signal, observer) = Signal<(), TestError>.pipe() weakSignal = signal testScheduler.schedule { sendCompleted(observer) } } test() expect(weakSignal).toNot(beNil()) testScheduler.run() expect(weakSignal).to(beNil()) } it("should deallocate after interrupting") { let testScheduler = TestScheduler() weak var weakSignal: Signal<(), NoError>? let test: () -> () = { let (signal, observer) = Signal<(), NoError>.pipe() weakSignal = signal testScheduler.schedule { sendInterrupted(observer) } } test() expect(weakSignal).toNot(beNil()) testScheduler.run() expect(weakSignal).to(beNil()) } it("should forward events to observers") { let (signal, observer) = Signal<Int, NoError>.pipe() var fromSignal: [Int] = [] var completed = false signal.observe(next: { number in fromSignal.append(number) }, completed: { completed = true }) expect(fromSignal).to(beEmpty()) expect(completed).to(beFalsy()) sendNext(observer, 1) expect(fromSignal).to(equal([ 1 ])) sendNext(observer, 2) expect(fromSignal).to(equal([ 1, 2 ])) expect(completed).to(beFalsy()) sendCompleted(observer) expect(completed).to(beTruthy()) } } describe("observe") { var testScheduler: TestScheduler! beforeEach { testScheduler = TestScheduler() } it("should stop forwarding events when disposed") { let disposable = SimpleDisposable() let signal: Signal<Int, NoError> = Signal { observer in testScheduler.schedule { for number in [ 1, 2 ] { sendNext(observer, number) } sendCompleted(observer) sendNext(observer, 4) } return disposable } var fromSignal: [Int] = [] signal.observe(next: { number in fromSignal.append(number) }) expect(disposable.disposed).to(beFalsy()) expect(fromSignal).to(beEmpty()) testScheduler.run() expect(disposable.disposed).to(beTruthy()) expect(fromSignal).to(equal([ 1, 2 ])) } it("should not trigger side effects") { var runCount = 0 let signal: Signal<(), NoError> = Signal { observer in runCount += 1 return nil } expect(runCount).to(equal(1)) signal.observe() expect(runCount).to(equal(1)) } it("should release observer after termination") { weak var testStr: NSMutableString? let (signal, sink) = Signal<Int, NoError>.pipe() let test: () -> () = { var innerStr: NSMutableString = NSMutableString() signal.observe(next: { value in innerStr.appendString("\(value)") }) testStr = innerStr } test() sendNext(sink, 1) expect(testStr).to(equal("1")) sendNext(sink, 2) expect(testStr).to(equal("12")) sendCompleted(sink) expect(testStr).to(beNil()) } it("should release observer after interruption") { weak var testStr: NSMutableString? let (signal, sink) = Signal<Int, NoError>.pipe() let test: () -> () = { var innerStr: NSMutableString = NSMutableString() signal.observe(next: { value in innerStr.appendString("\(value)") }) testStr = innerStr } test() sendNext(sink, 1) expect(testStr).to(equal("1")) sendNext(sink, 2) expect(testStr).to(equal("12")) sendInterrupted(sink) expect(testStr).to(beNil()) } describe("trailing closure") { it("receives next values") { var values = [Int]() let (signal, sink) = Signal<Int, NoError>.pipe() signal.observe { next in values.append(next) } sendNext(sink, 1) sendNext(sink, 2) sendNext(sink, 3) sendCompleted(sink) expect(values).to(equal([1, 2, 3])) } } } describe("map") { it("should transform the values of the signal") { let (signal, sink) = Signal<Int, NoError>.pipe() let mappedSignal = signal |> map { String($0 + 1) } var lastValue: String? mappedSignal.observe(next: { lastValue = $0 return }) expect(lastValue).to(beNil()) sendNext(sink, 0) expect(lastValue).to(equal("1")) sendNext(sink, 1) expect(lastValue).to(equal("2")) } } describe("mapError") { it("should transform the errors of the signal") { let (signal, sink) = Signal<Int, TestError>.pipe() let producerError = NSError(domain: "com.reactivecocoa.errordomain", code: 100, userInfo: nil) var error: NSError? signal |> mapError { _ in producerError } |> observe(next: { _ in return }, error: { error = $0 }) expect(error).to(beNil()) sendError(sink, TestError.Default) expect(error).to(equal(producerError)) } } describe("filter") { it("should omit values from the signal") { let (signal, sink) = Signal<Int, NoError>.pipe() let mappedSignal = signal |> filter { $0 % 2 == 0 } var lastValue: Int? mappedSignal.observe(next: { lastValue = $0 }) expect(lastValue).to(beNil()) sendNext(sink, 0) expect(lastValue).to(equal(0)) sendNext(sink, 1) expect(lastValue).to(equal(0)) sendNext(sink, 2) expect(lastValue).to(equal(2)) } } describe("ignoreNil") { it("should forward only non-nil values") { let (signal, sink) = Signal<Int?, NoError>.pipe() let mappedSignal = signal |> ignoreNil var lastValue: Int? mappedSignal.observe(next: { lastValue = $0 }) expect(lastValue).to(beNil()) sendNext(sink, nil) expect(lastValue).to(beNil()) sendNext(sink, 1) expect(lastValue).to(equal(1)) sendNext(sink, nil) expect(lastValue).to(equal(1)) sendNext(sink, 2) expect(lastValue).to(equal(2)) } } describe("scan") { it("should incrementally accumulate a value") { let (baseSignal, sink) = Signal<String, NoError>.pipe() let signal = baseSignal |> scan("", +) var lastValue: String? signal.observe(next: { lastValue = $0 }) expect(lastValue).to(beNil()) sendNext(sink, "a") expect(lastValue).to(equal("a")) sendNext(sink, "bb") expect(lastValue).to(equal("abb")) } } describe("reduce") { it("should accumulate one value") { let (baseSignal, sink) = Signal<Int, NoError>.pipe() let signal = baseSignal |> reduce(1, +) var lastValue: Int? var completed = false signal.observe(next: { lastValue = $0 }, completed: { completed = true }) expect(lastValue).to(beNil()) sendNext(sink, 1) expect(lastValue).to(beNil()) sendNext(sink, 2) expect(lastValue).to(beNil()) expect(completed).to(beFalse()) sendCompleted(sink) expect(completed).to(beTrue()) expect(lastValue).to(equal(4)) } it("should send the initial value if none are received") { let (baseSignal, sink) = Signal<Int, NoError>.pipe() let signal = baseSignal |> reduce(1, +) var lastValue: Int? var completed = false signal.observe(next: { lastValue = $0 }, completed: { completed = true }) expect(lastValue).to(beNil()) expect(completed).to(beFalse()) sendCompleted(sink) expect(lastValue).to(equal(1)) expect(completed).to(beTrue()) } } describe("skip") { it("should skip initial values") { let (baseSignal, sink) = Signal<Int, NoError>.pipe() let signal = baseSignal |> skip(1) var lastValue: Int? signal.observe(next: { lastValue = $0 }) expect(lastValue).to(beNil()) sendNext(sink, 1) expect(lastValue).to(beNil()) sendNext(sink, 2) expect(lastValue).to(equal(2)) } it("should not skip any values when 0") { let (baseSignal, sink) = Signal<Int, NoError>.pipe() let signal = baseSignal |> skip(0) var lastValue: Int? signal.observe(next: { lastValue = $0 }) expect(lastValue).to(beNil()) sendNext(sink, 1) expect(lastValue).to(equal(1)) sendNext(sink, 2) expect(lastValue).to(equal(2)) } } describe("skipRepeats") { it("should skip duplicate Equatable values") { let (baseSignal, sink) = Signal<Bool, NoError>.pipe() let signal = baseSignal |> skipRepeats var values: [Bool] = [] signal.observe(next: { values.append($0) }) expect(values).to(equal([])) sendNext(sink, true) expect(values).to(equal([ true ])) sendNext(sink, true) expect(values).to(equal([ true ])) sendNext(sink, false) expect(values).to(equal([ true, false ])) sendNext(sink, true) expect(values).to(equal([ true, false, true ])) } it("should skip values according to a predicate") { let (baseSignal, sink) = Signal<String, NoError>.pipe() let signal = baseSignal |> skipRepeats { count($0) == count($1) } var values: [String] = [] signal.observe(next: { values.append($0) }) expect(values).to(equal([])) sendNext(sink, "a") expect(values).to(equal([ "a" ])) sendNext(sink, "b") expect(values).to(equal([ "a" ])) sendNext(sink, "cc") expect(values).to(equal([ "a", "cc" ])) sendNext(sink, "d") expect(values).to(equal([ "a", "cc", "d" ])) } } describe("skipWhile") { var signal: Signal<Int, NoError>! var sink: Signal<Int, NoError>.Observer! var lastValue: Int? beforeEach { let (baseSignal, observer) = Signal<Int, NoError>.pipe() signal = baseSignal |> skipWhile { $0 < 2 } sink = observer lastValue = nil signal.observe(next: { lastValue = $0 }) } it("should skip while the predicate is true") { expect(lastValue).to(beNil()) sendNext(sink, 1) expect(lastValue).to(beNil()) sendNext(sink, 2) expect(lastValue).to(equal(2)) sendNext(sink, 0) expect(lastValue).to(equal(0)) } it("should not skip any values when the predicate starts false") { expect(lastValue).to(beNil()) sendNext(sink, 3) expect(lastValue).to(equal(3)) sendNext(sink, 1) expect(lastValue).to(equal(1)) } } describe("take") { it("should take initial values") { let (baseSignal, sink) = Signal<Int, NoError>.pipe() let signal = baseSignal |> take(2) var lastValue: Int? var completed = false signal.observe(next: { lastValue = $0 }, completed: { completed = true }) expect(lastValue).to(beNil()) expect(completed).to(beFalse()) sendNext(sink, 1) expect(lastValue).to(equal(1)) expect(completed).to(beFalse()) sendNext(sink, 2) expect(lastValue).to(equal(2)) expect(completed).to(beTrue()) } it("should complete immediately after taking given number of values") { let numbers = [ 1, 2, 4, 4, 5 ] var testScheduler = TestScheduler() var signal: Signal<Int, NoError> = Signal { observer in testScheduler.schedule { for number in numbers { sendNext(observer, number) } } return nil } var completed = false signal = signal |> take(numbers.count) signal.observe(completed: { completed = true }) expect(completed).to(beFalsy()) testScheduler.run() expect(completed).to(beTruthy()) } it("should interrupt when 0") { let numbers = [ 1, 2, 4, 4, 5 ] var testScheduler = TestScheduler() let signal: Signal<Int, NoError> = Signal { observer in testScheduler.schedule { for number in numbers { sendNext(observer, number) } } return nil } var result: [Int] = [] var interrupted = false signal |> take(0) |> observe(next: { number in result.append(number) }, interrupted: { interrupted = true }) expect(interrupted).to(beTruthy()) testScheduler.run() expect(result).to(beEmpty()) } } describe("collect") { it("should collect all values") { let (original, sink) = Signal<Int, NoError>.pipe() let signal = original |> collect let expectedResult = [ 1, 2, 3 ] var result: [Int]? signal.observe(next: { value in expect(result).to(beNil()) result = value }) for number in expectedResult { sendNext(sink, number) } expect(result).to(beNil()) sendCompleted(sink) expect(result).to(equal(expectedResult)) } it("should complete with an empty array if there are no values") { let (original, sink) = Signal<Int, NoError>.pipe() let signal = original |> collect var result: [Int]? signal.observe(next: { result = $0 }) expect(result).to(beNil()) sendCompleted(sink) expect(result).to(equal([])) } it("should forward errors") { let (original, sink) = Signal<Int, TestError>.pipe() let signal = original |> collect var error: TestError? signal.observe(error: { error = $0 }) expect(error).to(beNil()) sendError(sink, .Default) expect(error).to(equal(TestError.Default)) } } describe("takeUntil") { var signal: Signal<Int, NoError>! var sink: Signal<Int, NoError>.Observer! var triggerSink: Signal<(), NoError>.Observer! var lastValue: Int? = nil var completed: Bool = false beforeEach { let (baseSignal, observer) = Signal<Int, NoError>.pipe() let (triggerSignal, triggerObserver) = Signal<(), NoError>.pipe() signal = baseSignal |> takeUntil(triggerSignal) sink = observer triggerSink = triggerObserver lastValue = nil completed = false signal.observe( next: { lastValue = $0 }, completed: { completed = true } ) } it("should take values until the trigger fires") { expect(lastValue).to(beNil()) sendNext(sink, 1) expect(lastValue).to(equal(1)) sendNext(sink, 2) expect(lastValue).to(equal(2)) expect(completed).to(beFalse()) sendNext(triggerSink, ()) expect(completed).to(beTrue()) } it("should complete if the trigger fires immediately") { expect(lastValue).to(beNil()) expect(completed).to(beFalse()) sendNext(triggerSink, ()) expect(completed).to(beTrue()) expect(lastValue).to(beNil()) } } describe("takeUntilReplacement") { var signal: Signal<Int, NoError>! var sink: Signal<Int, NoError>.Observer! var replacementSink: Signal<Int, NoError>.Observer! var lastValue: Int? = nil var completed: Bool = false beforeEach { let (baseSignal, observer) = Signal<Int, NoError>.pipe() let (replacementSignal, replacementObserver) = Signal<Int, NoError>.pipe() signal = baseSignal |> takeUntilReplacement(replacementSignal) sink = observer replacementSink = replacementObserver lastValue = nil completed = false signal.observe( next: { lastValue = $0 }, completed: { completed = true } ) } it("should take values from the original then the replacement") { expect(lastValue).to(beNil()) expect(completed).to(beFalse()) sendNext(sink, 1) expect(lastValue).to(equal(1)) sendNext(sink, 2) expect(lastValue).to(equal(2)) sendNext(replacementSink, 3) expect(lastValue).to(equal(3)) expect(completed).to(beFalse()) sendNext(sink, 4) expect(lastValue).to(equal(3)) expect(completed).to(beFalse()) sendNext(replacementSink, 5) expect(lastValue).to(equal(5)) expect(completed).to(beFalse()) sendCompleted(replacementSink) expect(completed).to(beTrue()) } } describe("takeWhile") { var signal: Signal<Int, NoError>! var observer: Signal<Int, NoError>.Observer! beforeEach { let (baseSignal, sink) = Signal<Int, NoError>.pipe() signal = baseSignal |> takeWhile { $0 <= 4 } observer = sink } it("should take while the predicate is true") { var latestValue: Int! var completed = false signal.observe(next: { value in latestValue = value }, completed: { completed = true }) for value in -1...4 { sendNext(observer, value) expect(latestValue).to(equal(value)) expect(completed).to(beFalse()) } sendNext(observer, 5) expect(latestValue).to(equal(4)) expect(completed).to(beTrue()) } it("should complete if the predicate starts false") { var latestValue: Int? var completed = false signal.observe(next: { value in latestValue = value }, completed: { completed = true }) sendNext(observer, 5) expect(latestValue).to(beNil()) expect(completed).to(beTrue()) } } describe("observeOn") { it("should send events on the given scheduler") { let testScheduler = TestScheduler() let (signal, observer) = Signal<Int, NoError>.pipe() var result: [Int] = [] signal |> observeOn(testScheduler) |> observe(next: { result.append($0) }) sendNext(observer, 1) sendNext(observer, 2) expect(result).to(beEmpty()) testScheduler.run() expect(result).to(equal([ 1, 2 ])) } } describe("delay") { it("should send events on the given scheduler after the interval") { let testScheduler = TestScheduler() var signal: Signal<Int, NoError> = Signal { observer in testScheduler.schedule { sendNext(observer, 1) } testScheduler.scheduleAfter(5, action: { sendNext(observer, 2) sendCompleted(observer) }) return nil } var result: [Int] = [] var completed = false signal |> delay(10, onScheduler: testScheduler) |> observe(next: { number in result.append(number) }, completed: { completed = true }) testScheduler.advanceByInterval(4) // send initial value expect(result).to(beEmpty()) testScheduler.advanceByInterval(10) // send second value and receive first expect(result).to(equal([ 1 ])) expect(completed).to(beFalsy()) testScheduler.advanceByInterval(10) // send second value and receive first expect(result).to(equal([ 1, 2 ])) expect(completed).to(beTruthy()) } it("should schedule errors immediately") { let testScheduler = TestScheduler() var signal: Signal<Int, TestError> = Signal { observer in testScheduler.schedule { sendError(observer, TestError.Default) } return nil } var errored = false signal |> delay(10, onScheduler: testScheduler) |> observe(error: { _ in errored = true }) testScheduler.advance() expect(errored).to(beTruthy()) } } describe("throttle") { var scheduler: TestScheduler! var observer: Signal<Int, NoError>.Observer! var signal: Signal<Int, NoError>! beforeEach { scheduler = TestScheduler() let (baseSignal, baseObserver) = Signal<Int, NoError>.pipe() observer = baseObserver signal = baseSignal |> throttle(1, onScheduler: scheduler) expect(signal).notTo(beNil()) } it("should send values on the given scheduler at no less than the interval") { var values: [Int] = [] signal.observe(next: { value in values.append(value) }) expect(values).to(equal([])) sendNext(observer, 0) expect(values).to(equal([])) scheduler.advance() expect(values).to(equal([ 0 ])) sendNext(observer, 1) sendNext(observer, 2) expect(values).to(equal([ 0 ])) scheduler.advanceByInterval(1.5) expect(values).to(equal([ 0, 2 ])) scheduler.advanceByInterval(3) expect(values).to(equal([ 0, 2 ])) sendNext(observer, 3) expect(values).to(equal([ 0, 2 ])) scheduler.advance() expect(values).to(equal([ 0, 2, 3 ])) sendNext(observer, 4) sendNext(observer, 5) scheduler.advance() expect(values).to(equal([ 0, 2, 3 ])) scheduler.run() expect(values).to(equal([ 0, 2, 3, 5 ])) } it("should schedule completion immediately") { var values: [Int] = [] var completed = false signal.observe(next: { value in values.append(value) }, completed: { completed = true }) sendNext(observer, 0) scheduler.advance() expect(values).to(equal([ 0 ])) sendNext(observer, 1) sendCompleted(observer) expect(completed).to(beFalsy()) scheduler.run() expect(values).to(equal([ 0 ])) expect(completed).to(beTruthy()) } } describe("sampleOn") { var sampledSignal: Signal<Int, NoError>! var observer: Signal<Int, NoError>.Observer! var samplerObserver: Signal<(), NoError>.Observer! beforeEach { let (signal, sink) = Signal<Int, NoError>.pipe() let (sampler, samplesSink) = Signal<(), NoError>.pipe() sampledSignal = signal |> sampleOn(sampler) observer = sink samplerObserver = samplesSink } it("should forward the latest value when the sampler fires") { var result: [Int] = [] sampledSignal.observe(next: { result.append($0) }) sendNext(observer, 1) sendNext(observer, 2) sendNext(samplerObserver, ()) expect(result).to(equal([ 2 ])) } it("should do nothing if sampler fires before signal receives value") { var result: [Int] = [] sampledSignal.observe(next: { result.append($0) }) sendNext(samplerObserver, ()) expect(result).to(beEmpty()) } it("should send lates value multiple times when sampler fires multiple times") { var result: [Int] = [] sampledSignal.observe(next: { result.append($0) }) sendNext(observer, 1) sendNext(samplerObserver, ()) sendNext(samplerObserver, ()) expect(result).to(equal([ 1, 1 ])) } it("should complete when both inputs have completed") { var completed = false sampledSignal.observe(completed: { completed = true }) sendCompleted(observer) expect(completed).to(beFalsy()) sendCompleted(samplerObserver) expect(completed).to(beTruthy()) } } describe("combineLatestWith") { var combinedSignal: Signal<(Int, Double), NoError>! var observer: Signal<Int, NoError>.Observer! var otherObserver: Signal<Double, NoError>.Observer! beforeEach { let (signal, sink) = Signal<Int, NoError>.pipe() let (otherSignal, otherSink) = Signal<Double, NoError>.pipe() combinedSignal = signal |> combineLatestWith(otherSignal) observer = sink otherObserver = otherSink } it("should forward the latest values from both inputs") { var latest: (Int, Double)? combinedSignal.observe(next: { latest = $0 }) sendNext(observer, 1) expect(latest).to(beNil()) // is there a better way to test tuples? sendNext(otherObserver, 1.5) expect(latest?.0).to(equal(1)) expect(latest?.1).to(equal(1.5)) sendNext(observer, 2) expect(latest?.0).to(equal(2)) expect(latest?.1).to(equal(1.5)) } it("should complete when both inputs have completed") { var completed = false combinedSignal.observe(completed: { completed = true }) sendCompleted(observer) expect(completed).to(beFalsy()) sendCompleted(otherObserver) expect(completed).to(beTruthy()) } } describe("zipWith") { var leftSink: Signal<Int, NoError>.Observer! var rightSink: Signal<String, NoError>.Observer! var zipped: Signal<(Int, String), NoError>! beforeEach { let (leftSignal, leftObserver) = Signal<Int, NoError>.pipe() let (rightSignal, rightObserver) = Signal<String, NoError>.pipe() leftSink = leftObserver rightSink = rightObserver zipped = leftSignal |> zipWith(rightSignal) } it("should combine pairs") { var result: [String] = [] zipped.observe(next: { (left, right) in result.append("\(left)\(right)") }) sendNext(leftSink, 1) sendNext(leftSink, 2) expect(result).to(equal([])) sendNext(rightSink, "foo") expect(result).to(equal([ "1foo" ])) sendNext(leftSink, 3) sendNext(rightSink, "bar") expect(result).to(equal([ "1foo", "2bar" ])) sendNext(rightSink, "buzz") expect(result).to(equal([ "1foo", "2bar", "3buzz" ])) sendNext(rightSink, "fuzz") expect(result).to(equal([ "1foo", "2bar", "3buzz" ])) sendNext(leftSink, 4) expect(result).to(equal([ "1foo", "2bar", "3buzz", "4fuzz" ])) } it("should complete when the shorter signal has completed") { var result: [String] = [] var completed = false zipped.observe(next: { (left, right) in result.append("\(left)\(right)") }, completed: { completed = true }) expect(completed).to(beFalsy()) sendNext(leftSink, 0) sendCompleted(leftSink) expect(completed).to(beFalsy()) expect(result).to(equal([])) sendNext(rightSink, "foo") expect(completed).to(beTruthy()) expect(result).to(equal([ "0foo" ])) } } describe("materialize") { it("should reify events from the signal") { let (signal, observer) = Signal<Int, TestError>.pipe() var latestEvent: Event<Int, TestError>? signal |> materialize |> observe(next: { latestEvent = $0 }) sendNext(observer, 2) expect(latestEvent).toNot(beNil()) if let latestEvent = latestEvent { switch latestEvent { case let .Next(box): expect(box.value).to(equal(2)) default: fail() } } sendError(observer, TestError.Default) if let latestEvent = latestEvent { switch latestEvent { case .Error(_): () default: fail() } } } } describe("dematerialize") { typealias IntEvent = Event<Int, TestError> var sink: Signal<IntEvent, NoError>.Observer! var dematerialized: Signal<Int, TestError>! beforeEach { let (signal, observer) = Signal<IntEvent, NoError>.pipe() sink = observer dematerialized = signal |> dematerialize } it("should send values for Next events") { var result: [Int] = [] dematerialized.observe(next: { result.append($0) }) expect(result).to(beEmpty()) sendNext(sink, IntEvent.Next(Box(2))) expect(result).to(equal([ 2 ])) sendNext(sink, IntEvent.Next(Box(4))) expect(result).to(equal([ 2, 4 ])) } it("should error out for Error events") { var errored = false dematerialized.observe(error: { _ in errored = true }) expect(errored).to(beFalsy()) sendNext(sink, IntEvent.Error(Box(TestError.Default))) expect(errored).to(beTruthy()) } it("should complete early for Completed events") { var completed = false dematerialized.observe(completed: { completed = true }) expect(completed).to(beFalsy()) sendNext(sink, IntEvent.Completed) expect(completed).to(beTruthy()) } } describe("takeLast") { var sink: Signal<Int, TestError>.Observer! var lastThree: Signal<Int, TestError>! beforeEach { let (signal, observer) = Signal<Int, TestError>.pipe() sink = observer lastThree = signal |> takeLast(3) } it("should send the last N values upon completion") { var result: [Int] = [] lastThree.observe(next: { result.append($0) }) sendNext(sink, 1) sendNext(sink, 2) sendNext(sink, 3) sendNext(sink, 4) expect(result).to(beEmpty()) sendCompleted(sink) expect(result).to(equal([ 2, 3, 4 ])) } it("should send less than N values if not enough were received") { var result: [Int] = [] lastThree.observe(next: { result.append($0) }) sendNext(sink, 1) sendNext(sink, 2) sendCompleted(sink) expect(result).to(equal([ 1, 2 ])) } it("should send nothing when errors") { var result: [Int] = [] var errored = false lastThree.observe( next: { result.append($0) }, error: { _ in errored = true } ) sendNext(sink, 1) sendNext(sink, 2) sendNext(sink, 3) expect(errored).to(beFalsy()) sendError(sink, TestError.Default) expect(errored).to(beTruthy()) expect(result).to(beEmpty()) } } describe("timeoutWithError") { var testScheduler: TestScheduler! var signal: Signal<Int, TestError>! var sink: Signal<Int, TestError>.Observer! beforeEach { testScheduler = TestScheduler() let (baseSignal, observer) = Signal<Int, TestError>.pipe() signal = baseSignal |> timeoutWithError(TestError.Default, afterInterval: 2, onScheduler: testScheduler) sink = observer } it("should complete if within the interval") { var completed = false var errored = false signal.observe(completed: { completed = true }, error: { _ in errored = true }) testScheduler.scheduleAfter(1) { sendCompleted(sink) } expect(completed).to(beFalsy()) expect(errored).to(beFalsy()) testScheduler.run() expect(completed).to(beTruthy()) expect(errored).to(beFalsy()) } it("should error if not completed before the interval has elapsed") { var completed = false var errored = false signal.observe(completed: { completed = true }, error: { _ in errored = true }) testScheduler.scheduleAfter(3) { sendCompleted(sink) } expect(completed).to(beFalsy()) expect(errored).to(beFalsy()) testScheduler.run() expect(completed).to(beFalsy()) expect(errored).to(beTruthy()) } } describe("try") { it("should forward original values upon success") { let (baseSignal, sink) = Signal<Int, TestError>.pipe() var signal = baseSignal |> try { _ in return .success() } var current: Int? signal.observe(next: { value in current = value }) for value in 1...5 { sendNext(sink, value) expect(current).to(equal(value)) } } it("should error if an attempt fails") { let (baseSignal, sink) = Signal<Int, TestError>.pipe() var signal = baseSignal |> try { _ in return .failure(.Default) } var error: TestError? signal.observe(error: { err in error = err }) sendNext(sink, 42) expect(error).to(equal(TestError.Default)) } } describe("tryMap") { it("should forward mapped values upon success") { let (baseSignal, sink) = Signal<Int, TestError>.pipe() var signal = baseSignal |> tryMap { num -> Result<Bool, TestError> in return .success(num % 2 == 0) } var even: Bool? signal.observe(next: { value in even = value }) sendNext(sink, 1) expect(even).to(equal(false)) sendNext(sink, 2) expect(even).to(equal(true)) } it("should error if a mapping fails") { let (baseSignal, sink) = Signal<Int, TestError>.pipe() var signal = baseSignal |> tryMap { _ -> Result<Bool, TestError> in return .failure(.Default) } var error: TestError? signal.observe(error: { err in error = err }) sendNext(sink, 42) expect(error).to(equal(TestError.Default)) } } describe("combinePrevious") { var sink: Signal<Int, NoError>.Observer! let initialValue: Int = 0 var latestValues: (Int, Int)? beforeEach { latestValues = nil let (signal, baseSink) = Signal<Int, NoError>.pipe() sink = baseSink signal |> combinePrevious(initialValue) |> observe(next: { latestValues = $0 }) } it("should forward the latest value with previous value") { expect(latestValues).to(beNil()) sendNext(sink, 1) expect(latestValues?.0).to(equal(initialValue)) expect(latestValues?.1).to(equal(1)) sendNext(sink, 2) expect(latestValues?.0).to(equal(1)) expect(latestValues?.1).to(equal(2)) } } describe("combineLatest") { var sinkA: Signal<Int, NoError>.Observer! var sinkB: Signal<Int, NoError>.Observer! var sinkC: Signal<Int, NoError>.Observer! var combinedValues: [Int]? var completed: Bool! beforeEach { combinedValues = nil completed = false let (signalA, baseSinkA) = Signal<Int, NoError>.pipe() let (signalB, baseSinkB) = Signal<Int, NoError>.pipe() let (signalC, baseSinkC) = Signal<Int, NoError>.pipe() sinkA = baseSinkA sinkB = baseSinkB sinkC = baseSinkC combineLatest(signalA, signalB, signalC) |> observe(next: { combinedValues = [$0, $1, $2] }, completed: { completed = true }) } it("should forward the latest values from all inputs"){ expect(combinedValues).to(beNil()) sendNext(sinkA, 0) sendNext(sinkB, 1) sendNext(sinkC, 2) expect(combinedValues).to(equal([0, 1, 2])) sendNext(sinkA, 10) expect(combinedValues).to(equal([10, 1, 2])) } it("should not forward the latest values before all inputs"){ expect(combinedValues).to(beNil()) sendNext(sinkA, 0) expect(combinedValues).to(beNil()) sendNext(sinkB, 1) expect(combinedValues).to(beNil()) sendNext(sinkC, 2) expect(combinedValues).to(equal([0, 1, 2])) } it("should complete when all inputs have completed"){ expect(completed).to(beFalsy()) sendCompleted(sinkA) sendCompleted(sinkB) expect(completed).to(beFalsy()) sendCompleted(sinkC) expect(completed).to(beTruthy()) } } describe("zip") { var sinkA: Signal<Int, NoError>.Observer! var sinkB: Signal<Int, NoError>.Observer! var sinkC: Signal<Int, NoError>.Observer! var zippedValues: [Int]? var completed: Bool! beforeEach { zippedValues = nil completed = false let (signalA, baseSinkA) = Signal<Int, NoError>.pipe() let (signalB, baseSinkB) = Signal<Int, NoError>.pipe() let (signalC, baseSinkC) = Signal<Int, NoError>.pipe() sinkA = baseSinkA sinkB = baseSinkB sinkC = baseSinkC zip(signalA, signalB, signalC) |> observe(next: { zippedValues = [$0, $1, $2] }, completed: { completed = true }) } it("should combine all set"){ expect(zippedValues).to(beNil()) sendNext(sinkA, 0) expect(zippedValues).to(beNil()) sendNext(sinkB, 1) expect(zippedValues).to(beNil()) sendNext(sinkC, 2) expect(zippedValues).to(equal([0, 1, 2])) sendNext(sinkA, 10) expect(zippedValues).to(equal([0, 1, 2])) sendNext(sinkA, 20) expect(zippedValues).to(equal([0, 1, 2])) sendNext(sinkB, 11) expect(zippedValues).to(equal([0, 1, 2])) sendNext(sinkC, 12) expect(zippedValues).to(equal([10, 11, 12])) } it("should complete when the shorter signal has completed"){ expect(completed).to(beFalsy()) sendNext(sinkB, 1) sendNext(sinkC, 2) sendCompleted(sinkB) sendCompleted(sinkC) expect(completed).to(beFalsy()) sendNext(sinkA, 0) expect(completed).to(beTruthy()) } } } }
476417b4f817afbd8c1a0af8e5ef5422f7316c77
[ "Swift", "Ruby", "Markdown" ]
16
Swift
syshen/RACSwift-HackerNews
76bd396b5dfdf247e0cbb867ff8f0740230b160c
134447d91126ff92fd68d2af33af148e1fd97d3e
refs/heads/master
<repo_name>chrisjsherm/region<file_sep>/README.md # Overview Domain model for a geographic region.<file_sep>/src/Region.js const ConfigService = require('./services/configuration.service'); /** * Geographic region. */ module.exports = class Region { /** * * @param {string} name Name of the region. * @param {Set<string>} zipCodes Set of zip codes. */ constructor(name, zipCodes) { validateName(name); this.name = name; validateZipCodes(zipCodes); this.zipCodes = zipCodes; } /** * For a given object with a zip code property, determine if it matches any * of a list of Regions. If it does, return the matching Region. * * @param {Object} obj Object to compare against. * @param {string} zipCodeProperty Property on the obj parameter that holds a * zip code value. * @param {Array<Region>} regionsToMatch List of Region objects to match against. * * @returns {Region | null} Matching Region or null if no match. * * @throws {TypeError} If a parameter's type does not match the type specified * above. */ static getMatchingRegion(obj, zipCodeProperty, regionsToMatch) { if (typeof obj !== 'object' || obj === null) { throw new TypeError( 'Parameter obj must be a JavaScript object. Invalid value: ' + JSON.stringify(obj) + '.', ); } // Ensure zipCodeProperty is a string before using it. if (typeof zipCodeProperty !== 'string') { throw new TypeError( 'Parameter zipCodeProperty must be a string. Invalid value: ' + JSON.stringify(zipCodeProperty) + '.', ); } if (!obj.hasOwnProperty(zipCodeProperty)) { throw new Error( `Parameter obj must have a property named ${zipCodeProperty}.`, ); } isValidZipCode(obj[zipCodeProperty], true); if (!Array.isArray(regionsToMatch)) { throw new TypeError( 'regionsToMatch must be an Array. Invalid ' + `value: ${JSON.stringify(regionsToMatch)}.`, ); } for (let i = 0, length = regionsToMatch.length; i < length; i++) { if (regionsToMatch[i].zipCodes.has(obj[zipCodeProperty])) { return regionsToMatch[i]; } } return null; } }; /** * Throw an error if the name is invalid. * * @param {string} name Name of the region to validate. * * @returns {boolean} True if the name is valid. * * @throws {TypeError} If the name is not a string. */ function validateName(name) { if (typeof name !== 'string') { throw new TypeError(`Name must be a string. Invalid value: ${name}.`); } return true; } /** * Throw an error if the list of zip codes is not valid. * * param {Set<string>} zipCodes Set of numeric zip codes. * * @returns {boolean} True if the zip codes are valid. * * @throws {TypeError} If the zip codes parameter is not a set of numeric * strings. * @throws {RangeError} If the zip code is not five characters in length. */ function validateZipCodes(zipCodes) { if (!(zipCodes instanceof Set)) { throw new TypeError( 'zipCodes must be a Set of numeric strings. ' + `Invalid value: ${JSON.stringify(zipCodes)}.`, ); } zipCodes.forEach(zipCode => { isValidZipCode(zipCode, true); }); return true; } /** * Test a zip code for validity and throw an Error on failure. * * @param {string} zipCode Zip code to test. * @param {boolean} throwOnInvalid Throw an error if the zip code fails validation. * * @returns {boolean} True if the zip code passes validation. * * @throws {Error} If the zip code fails validation and throwOnInvalid is true. */ function isValidZipCode(zipCode, throwOnInvalid = false) { if (typeof zipCode !== 'string') { if (throwOnInvalid) { throw new TypeError( 'Paramter zipCode must be of type string. ' + `Invalid value: ${JSON.stringify(zipCode)}`, ); } return false; } if (!ConfigService.regexZipCodePattern.test(zipCode)) { if (throwOnInvalid) { throw new Error( 'Paramter zipCode must be either five digits or ' + 'five digits with a dash followed by four digits. ' + `Invalid value: ${zipCode}`, ); } return false; } return true; } <file_sep>/src/services/configuration.service.js const configuration = { // Zip codes with five digits or {five digits}-{four digits}. regexZipCodePattern: /(^\d{5}$)|(^\d{5}-\d{4}$)/, }; module.exports = configuration; <file_sep>/src/Region.spec.js const assert = require('chai').assert; const Region = require('./Region'); describe('Region class', () => { it('should throw when a non-string name is passed to its constructor', () => { assert.throws(() => { new Region(true, new Set()); }, TypeError); assert.throws(() => { new Region(123, new Set()); }, TypeError); }); it('should throw when a non-Array region list is passed to the constructor', () => { assert.throws(() => { new Region('New River Valley', '12222'); }); }); it('should pass when a valid Region is instantiated', () => { assert.strictEqual( new Region( 'New River Valley', new Set(['24068', '24073', '24061', '24060', '24141', '24142', '24143']) ).name, 'New River Valley' ); }); }); describe('Region.getMatchingRegion static method', () => { it('should throw when a non-object is passed for obj to getMatchingRegion', () => { assert.throws(() => { Region.getMatchingRegion('New River Valley', 'zipCode', []); }); }); it('should throw when a non-string is passed for zipCodeProperty to getMatchingRegion', () => { assert.throws(() => { Region.getMatchingRegion({}, 12345, []); }); try { Region.getMatchingRegion({}, 12345, []); } catch (e) { assert.match(e.message, new RegExp(/zipCodeProperty must be a string.*/)); } }); it('should throw if the obj parameter does not have a property matching ' + 'the zipCodeProperty', () => { try { Region.getMatchingRegion( { name: 'New River Valley' }, 'zipCode', [] ); } catch (e) { assert.match(e.message, new RegExp(/obj must have a property named.*/)); } }); it('should throw if regionsToMatch is not an array', () => { try { Region.getMatchingRegion( { zipCode: '24060' }, 'zipCode', 'New River Valley', ); } catch (e) { assert.match(e.message, new RegExp(/regionsToMatch must be an Array.*/)); } }); it('should return a matching region', () => { const matchingRegion1 = new Region( 'New River Valley', new Set(['24060', '24061', '24073'])); assert.deepStrictEqual(Region.getMatchingRegion( { zipCode: '24060' }, 'zipCode', [matchingRegion1] ), matchingRegion1); const matchingRegion2 = new Region( 'Northern Virginia', new Set(['22201', '22152']) ); assert.deepStrictEqual(Region.getMatchingRegion( { zipCode: '22152' }, 'zipCode', [matchingRegion1, matchingRegion2] ), matchingRegion2); }); });
b51966bce914a55d5f40664f1bab7c1a7063c549
[ "Markdown", "JavaScript" ]
4
Markdown
chrisjsherm/region
245b0b7f8be6a1ab18f58db26119507b21e7f6ea
4e47c9b958d08ca3ccf35c30e06e5935d4e47793
refs/heads/master
<file_sep>const axios = require("axios"); /** * Component * * @param {String} apiKey * @param {Object} opts options * @param {String} [opts.hostname] * @param {String} [opts.accessToken] */ var Component = function () { }; // ----------------------------------------------------- // Misc // ----------------------------------------------------- /** * .getHeaders() * * @returns {Array} */ Component.prototype.getHeaders = function (extra = {}) { var headers = {}; if (this.apiKey) headers["X-Api-Token"] = this.apiKey; if (this.accessToken) headers["Authorization"] = "Bearer " + this.accessToken; return Object.assign(extra, headers); }; // ----------------------------------------------------- // COMPONENTS // ----------------------------------------------------- /** * GET /components * * @param {Object} opts * @param {String} [opts.page] * @returns {Promise} */ Component.prototype.latest = function (opts = {}) { return new Promise((resolve, reject) => { axios .get(`${this.hostname}/components`, { headers: this.getHeaders(), params: { page: opts.page || 1 } }) .then(({ data }) => resolve(data)) .catch(err => reject(err)); }); }; /** * GET /components/starred * * @param {Object} opts * @param {String} [opts.page] * @returns {Promise} */ Component.prototype.starred = function (opts = {}) { return new Promise((resolve, reject) => { axios .get(`${this.hostname}/components/starred`, { headers: this.getHeaders(), params: { page: opts.page || 1 } }) .then(({ data }) => resolve(data)) .catch(err => reject(err)); }); }; /** * GET /components/search/{query} * * @param {String} query * @param {Object} opts * @param {String} [opts.page] * @returns {Promise} */ Component.prototype.search = function (query, opts = {}) { return new Promise((resolve, reject) => { axios .get(`${this.hostname}/components/search/${query}`, { headers: this.getHeaders(), params: { page: opts.page || 1 } }) .then(({ data }) => resolve(data)) .catch(err => reject(err)); }); }; /** * /components/create * * @param {FormData} component Options * @param {String} [component.user_id] * @param {String} [component.group_id] * @returns {Promise} */ Component.prototype.create = function (component) { var extraHeaders = {} if (!component.raw) { var formData = this.fromData(component); component = formData.getBuffer() extraHeaders = formData.getHeaders() } return new Promise((resolve, reject) => { axios .post(`${this.hostname}/components/create`, component, { headers: this.getHeaders(extraHeaders) }) .then(({ data }) => resolve(data)) .catch(err => reject(err)); }); }; /** * GET /components/group/{groupID} * * @param {String} groupID * @param {Object} opts * @param {String} [opts.page] * @returns {Promise} */ Component.prototype.getByGroupID = function (groupID, opts = {}) { return new Promise((resolve, reject) => { axios .get(`${this.hostname}/components/group/${groupID}`, { headers: this.getHeaders(), params: { page: opts.page || 1 } }) .then(({ data }) => resolve(data)) .catch(err => reject(err)); }); }; /** * GET /components/:component_id * * @param {String} componentID * @returns {Promise} */ Component.prototype.get = function (componentID) { return new Promise((resolve, reject) => { axios .get(`${this.hostname}/components/${componentID}`, { headers: this.getHeaders() }) .then(({ data }) => resolve(data)) .catch(err => reject(err)); }); }; /** * POST /components/:component_id * * @param {String} componentID * @param {Object} component * @param {String} [component.user_id] * @param {String} [component.group_id] * @returns {Promise} */ Component.prototype.update = function (componentID, component) { return new Promise((resolve, reject) => { axios .post(`${this.hostname}/components/${componentID}`, component, { headers: this.getHeaders() }) .then(({ data }) => resolve(data)) .catch(err => reject(err)); }); }; /** * GET /components/:component_id/download/:stl_id * * @param {String} componentID * @returns {Promise} */ Component.prototype.downloadSTL = function (componentID, stlID) { return new Promise((resolve, reject) => { axios .get( `${ this.hostname }/components/${componentID}/download/${stlID}`, { headers: this.getHeaders() } ) .then(({ data }) => resolve(data)) .catch(err => reject(err)); }); }; /** * POST /components/{component_id}/stl * * @param {String} componentID * @param {FormData} formData * @returns {Promise} */ Component.prototype.newSTL = function (componentID, formData) { var extraHeaders = {} if (typeof formData.getHeaders === 'function') { extraHeaders = formData.getHeaders() } return new Promise((resolve, reject) => { axios .post(`${this.hostname}/components/${componentID}/stl/`, formData, { headers: this.getHeaders(extraHeaders), }) .then(({ data }) => resolve(data)) .catch(err => reject(err)); }); }; /** * DEL /components/{component_id}/stl/{stl_id}/delete * * @param {String} componentID * @param {String} stlID * @returns {Promise} */ Component.prototype.deleteSTL = function (componentID, stlID) { return new Promise((resolve, reject) => { axios .delete(`${this.hostname}/components/${componentID}/stl/${stlID}/delete`, { headers: this.getHeaders() } ) .then(({ data }) => resolve(data)) .catch(err => reject(err)); }); }; /** * POST /components/{component_id}/stl/{stl_id}/estimate * * @param {String} componentID * @param {String} stlID * @param {Object} estimate * @param {String} estimate.scale * @param {String} estimate.layer_height * @param {String} estimate.infill * @returns {Promise} */ Component.prototype.estimateSTL = function (componentID, stlID, estimate) { return new Promise((resolve, reject) => { axios .post(`${this.hostname}/components/${componentID}/stl/${stlID}/estimate`, estimate, { headers: this.getHeaders(), }) .then(({ data }) => resolve(data)) .catch(err => reject(err)); }); }; /** * DEL /components/:component_id/delete * * @param {String} componentID * @returns {Promise} */ Component.prototype.delete = function (componentID) { return new Promise((resolve, reject) => { axios .delete(`${this.hostname}/components/${componentID}/delete`, { headers: this.getHeaders() }) .then(({ data }) => resolve(data)) .catch(err => reject(err)); }); }; /** * POST /components/:component_id/star * * @param {String} componentID * @param {String} userId * @returns {Promise} */ Component.prototype.star = function (componentID) { return new Promise((resolve, reject) => { axios .post( `${this.hostname}/components/${componentID}/star`, {}, { headers: this.getHeaders() } ) .then(({ data }) => resolve(data)) .catch(err => reject(err)); }); }; /** * DEL /components/:component_id/un-star * * @param {String} componentID * @returns {Promise} */ Component.prototype.unStar = function (componentID) { return new Promise((resolve, reject) => { axios .delete(`${this.hostname}/components/${componentID}/un-star`, { headers: this.getHeaders() }) .then(({ data }) => resolve(data)) .catch(err => reject(err)); }); }; /** * POST /components/:component_id/add-tag * * @param {String} componentID * @param {String} tag * @returns {Promise} */ Component.prototype.addTag = function (componentID, tag) { return new Promise((resolve, reject) => { axios .post( `${this.hostname}/components/${componentID}/add-tag`, { tag }, { headers: this.getHeaders() } ) .then(({ data }) => resolve(data)) .catch(err => reject(err)); }); }; /** * DEL /components/:component_id/un-star * * @param {String} componentID * @param {String} tagID * @returns {Promise} */ Component.prototype.removeTag = function (componentID, tagID) { return new Promise((resolve, reject) => { axios .delete( `${ this.hostname }/components/${componentID}/remove-tag/${tagID}`, { headers: this.getHeaders() } ) .then(({ data }) => resolve(data)) .catch(err => reject(err)); }); }; module.exports = Component; <file_sep>const axios = require("axios"); /** * Job * * @param {String} apiKey * @param {Object} opts options * @param {String} [opts.hostname] * @param {String} [opts.accessToken] */ var Job = function () { }; // ----------------------------------------------------- // Misc // ----------------------------------------------------- /** * .getHeaders() * * @returns {Array} */ Job.prototype.getHeaders = function () { var headers = {}; if (this.apiKey) headers["X-Api-Token"] = this.apiKey; if (this.accessToken) headers["Authorization"] = "Bearer " + this.accessToken; return headers; }; // ----------------------------------------------------- // JOBS // ----------------------------------------------------- /** * POST /jobs/create * * @param {Object} job * @param {String} [component.user_id] * @returns {Promise} */ Job.prototype.create = function (job) { return new Promise((resolve, reject) => { axios .post(`${this.hostname}/jobs/create`, job, { headers: this.getHeaders() }) .then(({ data }) => resolve(data)) .catch(err => reject(err)); }); }; /** * GET /jobs/group/:group_id * * @param {String} groupID * @returns {Promise} */ Job.prototype.getByGroupID = function (groupID) { return new Promise((resolve, reject) => { axios .get(`${this.hostname}/jobs/group/${groupID}`, { headers: this.getHeaders() }) .then(({ data }) => resolve(data)) .catch(err => reject(err)); }); }; /** * GET /jobs/:job_id * * @param {String} jobID * @returns {Promise} */ Job.prototype.get = function (jobID) { return new Promise((resolve, reject) => { axios .get(`${this.hostname}/jobs/${jobID}`, { headers: this.getHeaders() }) .then(({ data }) => resolve(data)) .catch(err => reject(err)); }); }; /** * DELETE /jobs/:job_id/cancel * * @param {String} jobID * @returns {Promise} */ Job.prototype.cancel = function (jobID) { return new Promise((resolve, reject) => { axios .delete(`${this.hostname}/jobs/${jobID}/cancel`, { headers: this.getHeaders() }) .then(({ data }) => resolve(data)) .catch(err => reject(err)); }); }; /** * POST /jobs/demo-print * * @param {Object} demoPrint * @param {String} [demoPrint.group_id] * @param {String} [demoPrint.component_id] * @param {String} [demoPrint.address_line_1] * @param {String} [demoPrint.address_line_2] * @param {String} [demoPrint.zipcode] * @param {String} [demoPrint.city] * @param {String} [demoPrint.state] * @param {String} [demoPrint.country] * @param {String} [demoPrint.delivery_instructions] * @returns {Promise} */ Job.prototype.demoPrint = function (demoPrint) { return new Promise((resolve, reject) => { axios .post(`${this.hostname}/jobs/demo-print`, demoPrint, { headers: this.getHeaders() }) .then(({ data }) => resolve(data)) .catch(err => reject(err)); }); }; // ----------------------------------------------------- // Events // ----------------------------------------------------- /** * GET /jobs/:job_id/events * * @param {String} jobID * @returns {Promise} */ Job.prototype.getEvents = function (jobID) { return new Promise((resolve, reject) => { axios .get(`${this.hostname}/jobs/${jobID}/events`, { headers: this.getHeaders() }) .then(({ data }) => resolve(data)) .catch(err => reject(err)); }); }; /** * POST /jobs/:job_id/events/create * * @param {String} jobID * @param {Object} event * @returns {Promise} */ Job.prototype.createJobEvent = function (jobID, event) { return new Promise((resolve, reject) => { axios .post(`${this.hostname}/jobs/${jobID}/events/create`, event, { headers: this.getHeaders() }) .then(({ data }) => resolve(data)) .catch(err => reject(err)); }); }; module.exports = Job;
0c8c7b110285ff5e6f45b2f73b043f18cd364f12
[ "JavaScript" ]
2
JavaScript
Ideea-inc/3ps-node
18610549fde46c74d9e4e26563fbb55aa0a7d4c1
31c93620426a70a0d7591111cd24c2f7e12dce39
refs/heads/master
<repo_name>coci315/vue_scrabble<file_sep>/src/common/js/scrabble.js const VOWELS = 'aeiou' const CONSONANTS = 'bcdfghjklmnpqrstvwxyz' // const HAND_SIZE = 7 const SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 } // function getFrequencyDict (sequence) { // const freq = {} // for (let x in sequence) { // if (typeof (freq[x]) === 'undefined') { // freq[x] = 0 // } // freq[x] += 1 // } // return freq // } export function getWordScore (word, n) { let score = 0 if (word === '') return 0 for (let i in word) { score += SCRABBLE_LETTER_VALUES[word[i]] } score *= word.length if (word.length === n) { score += 50 } return score } export function dealHand (n) { const hand = [] const numVowels = Math.floor(n / 3) for (let i = 0; i < numVowels; i++) { const letter = VOWELS[Math.floor(Math.random() * VOWELS.length)] hand.push(letter) } for (let i = 0; i < n - numVowels; i++) { const letter = CONSONANTS[Math.floor(Math.random() * CONSONANTS.length)] hand.push(letter) } return hand } export function wordToIndex (word, hand) { const arr = [] for (let i in word) { let index = hand.indexOf(word[i]) while (arr.indexOf(index) !== -1) { index = hand.indexOf(word[i], index + 1) } arr.push(index) } return arr } <file_sep>/src/common/js/store.js export function saveToLocal (key, value) { let scrabble = window.localStorage.__scrabble__ if (!scrabble) { scrabble = {} } else { scrabble = JSON.parse(scrabble) } scrabble[key] = value window.localStorage.__scrabble__ = JSON.stringify(scrabble) } export function loadFromLocal (key, def) { let scrabble = window.localStorage.__scrabble__ if (!scrabble) { return def } scrabble = JSON.parse(scrabble) let ret = scrabble[key] return ret === undefined ? def : ret }
bdd4ed26ef79b24d8865f6f84dfa259dc4c94880
[ "JavaScript" ]
2
JavaScript
coci315/vue_scrabble
7e9681006e50484d86f986094a5d9a4b62f775ce
6b1b46053bb8263438211e56921c4219abda42de
refs/heads/master
<repo_name>sgrodzicki/runtimes.bref.sh<file_sep>/README.md This repository contains the code for [runtimes.bref.sh](https://runtimes.bref.sh/). It is implemented as a serverless PHP application using [Bref](https://bref.sh/). <file_sep>/Makefile preview: sam local start-api --region=us-east-1 deploy: sam package \ --output-template-file .stack.yaml \ --region us-east-1 \ --s3-bucket bref-runtime-versions-website sam deploy \ --template-file .stack.yaml \ --capabilities CAPABILITY_IAM \ --region us-east-1 \ --stack-name bref-runtime-versions-website <file_sep>/index.php <?php declare(strict_types=1); use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use GuzzleHttp\Client; use Symfony\Component\Cache\Adapter\FilesystemAdapter; use Symfony\Contracts\Cache\ItemInterface; require_once __DIR__ . '/vendor/autoload.php'; $app = new \Slim\App([ 'settings' => [ 'displayErrorDetails' => false, ], ]); $container = $app->getContainer(); $container['view'] = function () { return new \Slim\Views\Twig(__DIR__ . '/templates'); }; $regions = [ 'ca-central-1', 'eu-central-1', 'eu-north-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-south-1', 'sa-east-1', 'us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'af-south-1', 'ap-south-1', 'ap-northeast-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', ]; $app->get('/', function (ServerRequestInterface $request, ResponseInterface $response) use ($regions) { $selectedRegion = $request->getQueryParams()['region'] ?? 'us-east-1'; if (!in_array($selectedRegion, $regions)) { $response->getBody()->write('Unknown region'); return $response; } $versions = listVersions(); $selectedVersion = $request->getQueryParams()['version'] ?? $versions[array_key_first($versions)]; if (!in_array($selectedVersion, $versions)) { $response->getBody()->write('Unknown version'); return $response; } return $this->view->render($response, 'index.html.twig', [ 'layers' => listLayers($selectedVersion, $selectedRegion), 'versions' => $versions, 'regions' => $regions, 'selectedRegion' => $selectedRegion, 'selectedVersion' => $selectedVersion, ]); }); $app->get('/embedded', function (ServerRequestInterface $request, ResponseInterface $response) use ($regions) { $selectedRegion = $request->getQueryParams()['region'] ?? 'us-east-1'; if (!in_array($selectedRegion, $regions)) { $response->getBody()->write('Unknown region'); return $response; } $versions = listVersions(); $latestVersion = $versions[array_key_first($versions)]; return $this->view->render($response, 'embedded.html.twig', [ 'layers' => listLayers($latestVersion, $selectedRegion), 'regions' => $regions, 'selectedRegion' => $selectedRegion, ]); }); $app->run(); function listLayers(string $version, string $region): array { $cache = new FilesystemAdapter(); // Caching network calls to improve performance $data = $cache->get('layers_' . $version, function (ItemInterface $item) use ($version) { $item->expiresAfter(3600); $client = new Client(); $url = 'https://raw.githubusercontent.com/brefphp/bref/' . $version . '/layers.json'; $response = $client->get($url); $json = $response->getBody()->getContents(); $data = json_decode($json, true); return $data; }); $layers = []; $accountId = '209497400698'; foreach ($data as $name => $regions) { if (!isset($regions[$region])) { continue; } $layers[] = [ 'name' => $name, 'arn' => sprintf('arn:aws:lambda:%s:%s:layer:%s:%s', $region, $accountId, $name, $regions[$region]), 'version' => $regions[$region], ]; } return $layers; } function listVersions(): array { $cache = new FilesystemAdapter(); // Caching network call as GitHub's API is rate limited $releases = $cache->get('releases', function (ItemInterface $item) { $item->expiresAfter(3600); $client = new Client(); $url = 'https://api.github.com/repos/brefphp/bref/releases'; $response = $client->get($url); $json = $response->getBody()->getContents(); $releases = json_decode($json, true); return $releases; }); $versions = []; foreach ($releases as $release) { // Skip prereleases (e.g., 0.5.14-beta1) if ($release['prerelease']) { continue; } // Skip releases prior to 0.5.0 as that's when layers.json was added if (\Composer\Semver\Comparator::lessThan($release['name'], '0.5.0')) { continue; } $versions[] = $release['name']; } // Sorting is needed as minor/patch releases can be published after major/minor releases $versions = \Composer\Semver\Semver::rsort($versions); return $versions; }
226502ac6ac31f3e3a95ea749b37e7c14e5cc41e
[ "Markdown", "Makefile", "PHP" ]
3
Markdown
sgrodzicki/runtimes.bref.sh
00bf975f2a03f2df040846f10a7ca26822757462
9b427f37c84c004608c63c0922922f0123e93626
refs/heads/master
<repo_name>CLAMP-IT/moodle-blocks_filtered_course_list<file_sep>/settings.php <?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * This file defines the admin settings available for the Filtered course list block. * * @package block_filtered_course_list * @copyright 2016 CLAMP * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die; require_once(dirname(__FILE__) . '/locallib.php'); if ($ADMIN->fulltree) { $filterfiles = block_filtered_course_list_lib::get_filter_files(); if (count($filterfiles) > 0) { foreach ($filterfiles as $file) { require_once($file); } } $exfilters = block_filtered_course_list_lib::get_filter_classes(); foreach ($exfilters as $classname) { $shortname = $classname::getshortname(); $fullname = $classname::getfullname(); $component = $classname::getcomponent(); $versionsyncnum = $classname::getversionsyncnum(); $path = (new ReflectionClass($classname))->getFileName(); $dirroot = preg_quote($CFG->dirroot, '/'); $relpath = preg_replace("/^$dirroot/", '', $path); // Check that path exists, that plugin is installed, that this filter is from the plugin's code, and that versions sync. $pluginmanager = \core_plugin_manager::instance(); $plugininfo = $pluginmanager->get_plugin_info($component); if (file_exists($path) && $plugininfo && strpos($path, $plugininfo->rootdir) === 0 && $versionsyncnum === BLOCK_FILTERED_COURSE_LIST_FILTER_VERSION_SYNC_NUMBER) { $val = "$shortname|$component|$relpath"; $label = "$fullname ($shortname) from $component"; $options[$val] = $label; } } if (empty($options)) { set_config('externalfilters', '', 'block_filtered_course_list'); } else { $settings->add(new admin_setting_configmulticheckbox('block_filtered_course_list/externalfilters', get_string('externalfilters', 'block_filtered_course_list'), get_string('configexternalfilters', 'block_filtered_course_list'), array(), $options )); } $settings->add(new admin_setting_configtextarea('block_filtered_course_list/filters', get_string('filters', 'block_filtered_course_list'), get_string('configfilters', 'block_filtered_course_list'), get_string('defaultfilters', 'block_filtered_course_list'), PARAM_RAW)); $settings->add(new admin_setting_configcheckbox('block_filtered_course_list/hideallcourseslink', get_string('hideallcourseslink', 'block_filtered_course_list'), get_string('confighideallcourseslink', 'block_filtered_course_list'), BLOCK_FILTERED_COURSE_LIST_FALSE)); $settings->add(new admin_setting_configcheckbox('block_filtered_course_list/hidefromguests', get_string('hidefromguests', 'block_filtered_course_list'), get_string('confighidefromguests', 'block_filtered_course_list'), BLOCK_FILTERED_COURSE_LIST_FALSE)); $settings->add(new admin_setting_configcheckbox('block_filtered_course_list/hideothercourses', get_string('hideothercourses', 'block_filtered_course_list'), get_string('confighideothercourses', 'block_filtered_course_list'), BLOCK_FILTERED_COURSE_LIST_FALSE)); $settings->add(new admin_setting_configcheckbox('block_filtered_course_list/persistentexpansion', get_string('persistentexpansion', 'block_filtered_course_list'), get_string('configpersistentexpansion', 'block_filtered_course_list'), BLOCK_FILTERED_COURSE_LIST_TRUE)); $settings->add(new admin_setting_configtext('block_filtered_course_list/maxallcourse', get_string('maxallcourse', 'block_filtered_course_list'), get_string('configmaxallcourse', 'block_filtered_course_list'), 10, '/^\d{1,3}$/', 3)); $settings->add(new admin_setting_configtext('block_filtered_course_list/coursenametpl', get_string('coursenametpl', 'block_filtered_course_list'), get_string('configcoursenametpl', 'block_filtered_course_list'), 'FULLNAME')); $settings->add(new admin_setting_configtext('block_filtered_course_list/catrubrictpl', get_string('catrubrictpl', 'block_filtered_course_list'), get_string('configcatrubrictpl', 'block_filtered_course_list'), 'NAME')); $settings->add(new admin_setting_configtext('block_filtered_course_list/catseparator', get_string('catseparator', 'block_filtered_course_list'), get_string('configcatseparator', 'block_filtered_course_list'), ' / ')); $managerviews = array( BLOCK_FILTERED_COURSE_LIST_ADMIN_VIEW_ALL => get_string('allcourses', 'block_filtered_course_list'), BLOCK_FILTERED_COURSE_LIST_ADMIN_VIEW_OWN => get_string('owncourses', 'block_filtered_course_list') ); $settings->add(new admin_setting_configselect('block_filtered_course_list/managerview', get_string('managerview', 'block_filtered_course_list'), get_string('configmanagerview', 'block_filtered_course_list'), BLOCK_FILTERED_COURSE_LIST_ADMIN_VIEW_ALL, $managerviews)); $sortablefields = array( 'fullname' => get_string('fullname'), 'shortname' => get_string('shortname'), 'sortorder' => get_string('sort_sortorder', 'core_admin'), 'idnumber' => get_string('idnumber'), 'startdate' => get_string('startdate'), 'none' => get_string('none'), ); $sortvectors = array( 'ASC' => get_string('asc'), 'DESC' => get_string('desc'), ); $settings->add(new admin_setting_configselect('block_filtered_course_list/primarysort', get_string('primarysort', 'block_filtered_course_list'), get_string('configprimarysort', 'block_filtered_course_list'), 'fullname', $sortablefields)); $settings->add(new admin_setting_configselect('block_filtered_course_list/primaryvector', get_string('primaryvector', 'block_filtered_course_list'), '', 'ASC', $sortvectors)); $settings->add(new admin_setting_configselect('block_filtered_course_list/secondarysort', get_string('secondarysort', 'block_filtered_course_list'), get_string('configsecondarysort', 'block_filtered_course_list'), 'none', $sortablefields)); $settings->add(new admin_setting_configselect('block_filtered_course_list/secondaryvector', get_string('secondaryvector', 'block_filtered_course_list'), '', 'ASC', $sortvectors)); } <file_sep>/locallib.php <?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * This file defines constants and classes used by the Filtered course list block. * * @package block_filtered_course_list * @copyright 2016 CLAMP * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); define('BLOCK_FILTERED_COURSE_LIST_ADMIN_VIEW_ALL', 'all'); define('BLOCK_FILTERED_COURSE_LIST_ADMIN_VIEW_OWN', 'own'); define('BLOCK_FILTERED_COURSE_LIST_DEFAULT_LABELSCOUNT', 2); define('BLOCK_FILTERED_COURSE_LIST_DEFAULT_CATEGORY', 0); define('BLOCK_FILTERED_COURSE_LIST_EMPTY', ''); define('BLOCK_FILTERED_COURSE_LIST_FALSE', 0); define('BLOCK_FILTERED_COURSE_LIST_FILTER_VERSION_SYNC_NUMBER', '1.0.0'); define('BLOCK_FILTERED_COURSE_LIST_TRUE', 1); define('BLOCK_FILTERED_COURSE_LIST_GENERIC_CONFIG', 'generic|e'); /** * Get the name of the filter corresponding to a configuration line. * * @param string $name Putative filter name * @param array $exfilters List of external filters designated in config * @return string Filtername or null */ function get_filter($name, $exfilters) { global $CFG; if (empty($name)) { return null; } // Assume base filter. $classname = "\\block_filtered_course_list\\{$name}_filter"; // If not base filter, look for external filter. if (!class_exists($classname)) { // Find the filter we're looking for. $exfilters = array_filter(explode(',', $exfilters), function($info) use($name) { return strpos($info, "$name|") === 0; }); // Abort if filter not found. if (empty($exfilters)) { return null; } // Split out filter info. $filterinfo = explode('|', $exfilters[0]); $path = $CFG->dirroot . $filterinfo[2]; // Check that path exists. if (file_exists($path)) { // Set class name. $classname = "{$name}_fcl_filter"; // Require path. require_once($path); } else { $classname = false; } } return $classname; } /** * A class to structure rubrics regardless of their config type * * @package block_filtered_course_list * @copyright 2016 CLAMP * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class block_filtered_course_list_rubric { /** @var string The rubric's title */ public $title; /** @var array The subset of enrolled courses that match the filter criteria */ public $courses = array(); /** @var string Indicates whether the rubric is expanded or collapsed by default */ public $expanded; /** @var array Config settings */ public $config; /** * Constructor * * @param string $title The display title of the rubric * @param array $courses Courses the user is enrolled in that match the Filtered * @param array $config Block configuration * @param string $expanded Indicates the rubrics initial state: expanded or collapsed */ public function __construct($title, $courses, $config, $expanded = false) { $this->title = format_string(htmlspecialchars($title)); $this->courses = $courses; $this->config = $config; $this->expanded = $expanded; } } /** * Utility functions * * @package block_filtered_course_list * @copyright 2017 CLAMP * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class block_filtered_course_list_lib { public static function get_filter_files() { global $CFG; $files = []; $dir = new RecursiveDirectoryIterator($CFG->dirroot); $flt = new RecursiveCallbackFilterIterator($dir, function($current, $key, $iterator) { if ($current->getFilename()[0] === '.') { return false; } return true; }); $itr = new RecursiveIteratorIterator($flt); foreach ($itr as $file) { if (preg_match('/.*fcl_filter\.php$/', $file)) { $files[] = $file; } } return $files; } public static function get_filter_classes() { $exfilters = array_filter(get_declared_classes(), function($class) { return preg_match('/.*fcl_filter/', $class); }); return $exfilters; } /** * Display a coursename according to the template * * @param object $course An object with all of the course attributes * @param string $tpl The coursename display template */ public static function coursedisplaytext($course, $tpl) { if ($tpl == '') { $tpl = 'FULLNAME'; } $cat = core_course_category::get($course->category, IGNORE_MISSING); $catname = (is_object($cat)) ? $cat->name : ''; $replacements = array( 'FULLNAME' => $course->fullname, 'SHORTNAME' => $course->shortname, 'IDNUMBER' => $course->idnumber, 'CATEGORY' => $catname, ); // If we have limits defined, apply them. static::apply_template_limits($replacements, $tpl); $displaytext = str_replace(array_keys($replacements), $replacements, $tpl); return format_string(strip_tags($displaytext)); } /** * Apply length limits to a template string. TOKEN{#} in the template string * is replaced by TOKEN, and the replacement value for TOKEN is truncated to * # characters. * * @param object $replacements an array of pattern => replacement * @param string $tpl the template string (coursename or category) */ public static function apply_template_limits(&$replacements, &$tpl) { $limitpattern = "{(\d+)}"; foreach ($replacements as $pattern => $replace) { $limit = array(); if (preg_match("/$pattern$limitpattern/", $tpl, $limit)) { $replacements[$pattern] = static::truncate($replace, (int) $limit[1]); } } $tpl = preg_replace("/$limitpattern/", "", $tpl); } /** * Ellipsis truncate the given string to $length characters. * * @param string $string the string to be truncated * @param int $length the number of characters to truncate to * @return $string the truncated string */ public static function truncate($string, $length) { if ($length > 0 && \core_text::strlen($string) > $length) { $string = \core_text::substr($string, 0, $length); $string = trim($string); $string .= "…"; } return $string; } } <file_sep>/block_filtered_course_list.php <?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * This file contains the class used to display a Filtered course list block. * * @package block_filtered_course_list * @copyright 2016 CLAMP * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); require_once($CFG->dirroot . '/course/lib.php'); require_once(dirname(__FILE__) . '/locallib.php'); /** * The Filtered course list block class * * @package block_filtered_course_list * @copyright 2016 CLAMP * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class block_filtered_course_list extends block_base { /** @var array Admin settings for the FCL block */ private $fclconfig; /** @var array A list of rubric objects for display */ private $rubrics = array(); /** @var arrray A list of courses for the current user */ private $mycourses = array(); /** @var string A type of user for purposes of list display, should be 'user', 'manager' or 'guest' */ private $usertype; /** @var string Type of list: 'generic_list', 'filtered_list' or 'empty_block' */ private $liststyle; /** * Set the initial properties for the block */ public function init() { $this->title = get_string('blockname', 'block_filtered_course_list'); $this->fclconfig = get_config('block_filtered_course_list'); } /** * The FCL block uses a settings.php file * * @return bool Returns true */ public function has_config() { return true; } /** * Set the instance title and merge instance config as soon as nstance data is loaded */ public function specialization() { if (isset($this->config->title) && $this->config->title != '') { $this->title = format_string($this->config->title, true, ['context' => $this->context]); } if (isset($this->config->filters) && $this->config->filters != '') { $this->fclconfig->filters = $this->config->filters; } } /** * Allow multiple instances * * @return bool Returns true */ public function instance_allow_multiple() { return true; } /** * Returns the role that best describes the block... 'region' * * @return string 'region' */ public function get_aria_role() { return 'region'; } /** * Returns the rubrics data * * We provide this function to facilitate forks that render the block for the mobile app. * * @return array */ public function get_rubrics() { return $this->rubrics; } /** * Return the block contents * * @return stdClass The block contents */ public function get_content($page=null) { // We allow unit tests to pass in the global $PAGE object. if ($page !== null) { $this->page = $page; } if ($this->content !== null) { return $this->content; } $this->content = new stdClass; $this->content->text = ''; $this->content->footer = ''; $sortsettings = array( array( $this->fclconfig->primarysort, $this->fclconfig->primaryvector, ), array( $this->fclconfig->secondarysort, $this->fclconfig->secondaryvector, ), ); $sortstring = "visible DESC"; foreach ($sortsettings as $sortsetting) { if ($sortsetting[0] == 'none') { continue; } else { $sortstring .= ", " . $sortsetting[0] . " " . $sortsetting[1]; } } $this->mycourses = enrol_get_my_courses(null, "$sortstring"); $this->_calculate_usertype(); $this->liststyle = $this->_set_liststyle(); if ($this->liststyle != 'empty_block') { if ($this->liststyle == 'generic_list') { $this->fclconfig->filters = BLOCK_FILTERED_COURSE_LIST_GENERIC_CONFIG; } $this->_process_filtered_list(); } $output = $this->page->get_renderer('block_filtered_course_list'); $params = array( 'usertype' => $this->usertype, 'liststyle' => $this->liststyle, 'hideallcourseslink' => $this->fclconfig->hideallcourseslink, ); $footer = new \block_filtered_course_list\output\footer($params); $this->content->footer = $output->render($footer); return $this->content; } /** * Set the usertype for purposes of the course list display */ private function _calculate_usertype() { global $USER; if (empty($USER->id) || isguestuser()) { $this->usertype = 'guest'; } else if (has_capability('moodle/course:view', context_system::instance())) { $this->usertype = 'manager'; } else { $this->usertype = 'user'; } } /** * Set the list style */ private function _set_liststyle() { global $CFG; // The default liststyle is 'filtered_list' but ... $liststyle = 'filtered_list'; if (!empty($CFG->disablemycourses) && $this->usertype != 'manager') { $liststyle = 'generic_list'; } if ($this->usertype == 'manager' && $this->fclconfig->managerview != BLOCK_FILTERED_COURSE_LIST_ADMIN_VIEW_OWN) { $liststyle = "generic_list"; } if ($this->fclconfig->hidefromguests == BLOCK_FILTERED_COURSE_LIST_TRUE && $this->usertype == 'guest') { $liststyle = "empty_block"; } return $liststyle; } /** * Build a user-specific Filtered course list block */ private function _process_filtered_list() { $output = $this->page->get_renderer('block_filtered_course_list'); // Parse the textarea settings into an array of arrays. $filterconfigs = array_map(function($line) { return array_map(function($item) { return trim($item); }, explode('|', $line, 2)); }, explode("\n", $this->fclconfig->filters)); // Get the arrays of rubrics based on the config lines, filter out failures, and merge them into one array. $this->rubrics = array_reduce( array_filter( array_map(function($config) { $classname = get_filter($config[0], $this->fclconfig->externalfilters); if (class_exists($classname)) { $item = new $classname($config, $this->mycourses, $this->fclconfig); return $item->get_rubrics(); } return null; }, $filterconfigs), function($item) { return is_array($item); } ), 'array_merge', array()); if ($this->fclconfig->hideothercourses == BLOCK_FILTERED_COURSE_LIST_FALSE && $this->liststyle != 'generic_list') { $mentionedcourses = array_unique(array_reduce(array_map(function($item) { return $item->courses; }, $this->rubrics), 'array_merge', array()), SORT_REGULAR); $othercourses = array_udiff($this->mycourses, $mentionedcourses, function($a, $b) { return $a->id - $b->id; }); if (!empty($othercourses)) { $otherrubric = new block_filtered_course_list_rubric(get_string('othercourses', 'block_filtered_course_list'), $othercourses, $this->fclconfig); $this->rubrics[] = $otherrubric; } } if (count($this->rubrics) > 0) { $content = new \block_filtered_course_list\output\content($this->instance->id, $this->rubrics); $this->content->text = $output->render($content); } else if ($this->fclconfig->filters != BLOCK_FILTERED_COURSE_LIST_GENERIC_CONFIG) { $this->liststyle = 'generic_list'; $this->fclconfig->filters = 'generic|e'; $this->_process_filtered_list(); } } } <file_sep>/tests/block_test.php <?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * This file defines PHPUnit tests for the Filtered course list block. * * @package block_filtered_course_list * @copyright 2016 CLAMP * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace block_filtered_course_list; use advanced_testcase; use moodle_page; use block_filtered_course_list; use block_filtered_course_list_lib; use stdClass; use DOMDocument; use DOMElement; use completion_completion; defined('MOODLE_INTERNAL') || die(); global $CFG; require_once($CFG->dirroot . '/blocks/moodleblock.class.php'); require_once($CFG->dirroot . '/lib/pagelib.php'); require_once(dirname(__FILE__) . '/../block_filtered_course_list.php'); require_once(dirname(__FILE__) . '/../renderer.php'); /** * PHPUnit tests * * @package block_filtered_course_list * @copyright 2016 CLAMP * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class block_test extends advanced_testcase { /** @var int The admin user's id number */ private $adminid; /** @var object A test user */ private $user1; /** @var object A test user */ private $user2; /** @var array A list of course objects to be used in several tests */ private $courses = array(); /** @var array A list of categories into which the test courses can be grouped */ private $categories = array(); /** * General setup for PHPUnit testing */ protected function setUp(): void { global $CFG; unset ( $CFG->maxcategorydepth ); $this->resetAfterTest(true); $this->_setupusers(); $this->_setupfilter(); } protected function tearDown(): void { $rmpath = __DIR__ . '/behat/data/fcl_filter.php'; if (file_exists($rmpath)) { unlink($rmpath); } } /** * Text external filter detection. */ public function test_external_filter_detection() { $files = block_filtered_course_list_lib::get_filter_files(); $this->assertCount(1, $files); $this->assertEquals('fcl_filter.php', $files[0]->getFilename()); require_once($files[0]->getPathname()); $classes = block_filtered_course_list_lib::get_filter_classes(); $this->assertCount(1, $classes); $this->assertEquals('test_fcl_filter', reset($classes)); } /** * Test that the default settings are applying as expected */ public function test_default_settings() { // Confirm expected defaults. // We omit the multiline default for the 'filters' setting. $fclconfig = get_config('block_filtered_course_list'); $configdefaults = array ( 'hideallcourseslink' => 0, 'hidefromguests' => 0, 'hideothercourses' => 0, 'maxallcourse' => 10, 'coursenametpl' => 'FULLNAME', 'catrubrictpl' => 'NAME', 'catseparator' => ' / ', 'managerview' => 'all', 'persistentexpansion' => 1, 'primarysort' => 'fullname', 'primaryvector' => 'ASC', 'secondarysort' => 'none', 'secondaryvector' => 'ASC', ); foreach ($configdefaults as $name => $value) { $expected = $configdefaults[$name]; $actual = $fclconfig->$name; $this->assertEquals($expected, $actual, "$actual should be set to $expected"); } } /** * Test a site that has no courses */ public function test_site_with_no_courses() { // On a site with no courses, no users should see a block. $this->_noblock ( array ( 'none' => true, 'guest' => true, 'user1' => true, 'admin' => true )); } /** * Test a site that has only one category and no enrollments */ public function test_single_category_site_with_no_enrollments() { // Create 8 courses in the default category: Category 1. $this->_create_misc_courses( 1, 8 ); // Everyone should see all courses. $this->_courselistincludes ( array ( 'none' => array ( 'Course 1' , 'Course 8' ), 'guest' => array ( 'Course 1' , 'Course 8' ), 'admin' => array ( 'Course 1' , 'Course 8' ), 'user1' => array ( 'Course 1' , 'Course 8' ), )); } /** * Test a small site with one category and some enrollments */ public function test_small_single_category_site_with_enrollments() { // Create 8 courses in the default category: Category 1. $this->_create_misc_courses( 1, 8 ); // Enroll user1 as a teacher in course 1 and a student in courses 3 and 5. $this->getDataGenerator()->enrol_user( $this->user1->id , $this->courses['c_1']->id , 3 ); $this->getDataGenerator()->enrol_user( $this->user1->id , $this->courses['c_3']->id ); $this->getDataGenerator()->enrol_user( $this->user1->id , $this->courses['c_5']->id ); // Anonymous, Guest and Admin should see all courses. $this->_courselistincludes ( array ( 'none' => array ( 'Course 1' , 'Course 8' ), 'guest' => array ( 'Course 1' , 'Course 8' ), 'admin' => array ( 'Course 1' , 'Course 8' ) )); // User1 should see courses 1, 3 and 5. $this->_courselistincludes ( array ( 'user1' => array ( 'Course 1' , 'Course 3' , 'Course 5' ) )); // User1 should not see course 2 or course 6. $this->_courselistexcludes ( array ( 'user1' => array ( 'Course 2' , 'Course 6' ) )); // We should also check the generic filter while we have this configuration. set_config('filters', 'generic|e', 'block_filtered_course_list'); // User1 should now see all courses. $this->_courselistincludes ( array ( 'user1' => array ( 'Course 1' , 'Course 2', 'Course 3' , 'Course 5', 'Course 6' ), )); } /** * Test a larger site with enrollments in one category */ public function test_larger_single_category_site_with_enrollments() { // Create 12 courses in the default category: Category 1. $this->_create_misc_courses( 1, 12 ); // Enroll user1 as a teacher in course 1 and a student in courses 3 and 5. $this->getDataGenerator()->enrol_user( $this->user1->id , $this->courses['c_1']->id , 3 ); $this->getDataGenerator()->enrol_user( $this->user1->id , $this->courses['c_3']->id ); $this->getDataGenerator()->enrol_user( $this->user1->id , $this->courses['c_5']->id ); // The block should not display individual courses to anonymous, guest, or admin. $this->_courselistexcludes ( array ( 'none' => array ( 'Course 1' ), 'guest' => array ( 'Course 1' ), 'admin' => array ( 'Course 1' ) )); // The block should offer a category link to anonymous, guest, and admin. $this->_courselistincludes ( array ( 'none' => array ( 'Category 1' ), 'guest' => array ( 'Category 1' ), 'admin' => array ( 'Category 1' ) )); // User1 should still see courses 1, 3 and 5. $this->_courselistincludes ( array ( 'user1' => array ( 'Course 1' , 'Course 3' , 'Course 5' ) )); // User1 should not see course 2 or course 6. $this->_courselistexcludes ( array ( 'user1' => array ( 'Course 2' , 'Course 6' ) )); } /** * Test a rich site with several courses in various categories */ public function test_rich_site_with_defaults() { $this->_create_rich_site(); // With no special settings, the behavior should be as for a larger single-category site. set_config('filters', '', 'block_filtered_course_list'); // The block should not display individual courses to anonymous, guest, or admin. // The block should not display links to categories below the top level. $this->_courselistexcludes ( array ( 'none' => array ( 'Course 1', 'Child', 'Grandchild' ), 'guest' => array ( 'Course 1', 'Child', 'Grandchild' ), 'admin' => array ( 'Course 1', 'Child', 'Grandchild' ) )); // The block should offer top-level category links to anonymous, guest, admin or an unenrolled user. $this->_courselistincludes ( array ( 'none' => array ( 'Category 1', 'Sibling' ), 'guest' => array ( 'Category 1', 'Sibling' ), 'admin' => array ( 'Category 1', 'Sibling' ), 'user3' => array ( 'Category 1', 'Sibling' ), )); // Regular users should see links to visible courses in visible categories under 'Other courses'. // This includes visible courses in visible categories in hidden categories. // Teachers should see links to all their courses, visible or hidden, and under hidden categories. // Students should see links to visible courses in hidden categories under 'Other courses'. $this->_courseunderrubric( array( 'user1' => array( 'c_1' => 'Other courses', 'cc1_2' => 'Other courses', 'gc1_1' => 'Other courses', 'sc_2' => 'Other courses', 'øthér' => 'Other courses', 'hcvc_1' => 'Other courses', ), 'user2' => array( 'c_1' => 'Other courses', 'cc1_3' => 'Other courses', 'gc1_1' => 'Other courses', 'hc_1' => 'Other courses', 'hcc_2' => 'Other courses', 'hcc_3' => 'Other courses', 'sc_2' => 'Other courses', ) )); // Students should not see links to hidden courses or visible courses under hidden categories. $this->_courselistexcludes( array( 'user1' => array( 'cc1_3', 'gc1_3' ) )); } /** * Test a complicated site filtered by category */ public function test_rich_site_filtered_by_category() { $this->_create_rich_site(); // Change setting to filter by categories. $filterconfig = <<<EOF category | c | 0 EOF; set_config('filters', $filterconfig, 'block_filtered_course_list'); // The block should not display individual courses to anonymous, guest, or admin. // The block should not display links to categories below the top level. $this->_courselistexcludes ( array ( 'none' => array ( 'Course 1', 'Child', 'Grandchild' ), 'guest' => array ( 'Course 1', 'Child', 'Grandchild' ), 'admin' => array ( 'Course 1', 'Child', 'Grandchild' ) )); // The block should offer top-level category links to anonymous, guest, and admin. // A user not enrolled in any visible courses should see the same. $this->_courselistincludes ( array ( 'none' => array ( 'Category 1', 'Sibling' ), 'guest' => array ( 'Category 1', 'Sibling' ), 'admin' => array ( 'Category 1', 'Sibling' ), 'user3' => array ( 'Category 1', 'Sibling' ), )); // Regular users should see links to visible courses under corresponding visible categories. // Teachers should see links to all their courses, visible or hidden, and under hidden categories. // Courses under a hidden category will appear under "Other courses" to those who can't see the category. // With admins_sees_own an admin should see hidden courses under hidden categories. // Change the managerview setting to 'own'. set_config('managerview', 'own', 'block_filtered_course_list'); // Enroll admin in 'hc_1'. $this->getDataGenerator()->enrol_user( $this->adminid, $this->courses['hc_1']->id, 3 ); $this->_courseunderrubric( array( 'user1' => array( 'c_1' => 'Category 1', 'cc1_2' => 'Child category 1', 'gc1_1' => 'Grandchild category 1', 'sc_2' => 'Sibling category', 'hc_1' => 'Other courses', 'hcc_2' => 'Other courses', ), 'user2' => array( 'c_1' => 'Category 1', 'cc1_3' => 'Child category 1', 'gc1_1' => 'Grandchild category 1', 'hc_1' => 'Other courses', 'hcc_3' => 'Other courses', 'sc_2' => 'Sibling category', 'øthér' => 'Sibling category', ), 'admin' => array( 'hc_1' => 'Hidden category' ) )); // Courses should appear only under immediate parents. $this->_courseunderrubric ( array ( 'user1' => array ( 'gc1_1' => 'Category 1' ), 'user2' => array ( 'gc1_1' => 'Child category 1' ) ) , 'not' ); // Students should not see links to hidden courses. // Students shoudl see links to visible courses even if they are in hidden categories. $this->_courselistexcludes( array( 'user1' => array( 'cc1_3', 'gc1_3' ) )); // Now try switching the root category setting. $cc2id = $this->categories['cc2']->id; $filterconfig = <<<EOF category | collapsed | $cc2id EOF; set_config('filters', $filterconfig, 'block_filtered_course_list'); // There should be no rubric for Category 1. $this->_courselistexcludes( array ( 'user1' => array ( 'Category 1' ) )); // Courses directly under Category 1 should continue to appear in 'Other courses'. $this->_courseunderrubric( array( 'user1' => array( 'c_1' => 'Other courses', 'cc1_2' => 'Other courses', 'cc2_1' => 'Child category 2', 'gc1_1' => 'Grandchild category 1', 'sc_2' => 'Other courses', ) )); // Test the ability to set recursion depth on top-level category filter. // Confirm also that comments in the category and depth fields will be ignored. $filterconfig = <<<EOF category | collapsed | 0 (Top level) | 1 deep EOF; set_config('filters', $filterconfig, 'block_filtered_course_list'); $this->_courseunderrubric( array( 'user1' => array( 'c_1' => 'Category 1', 'cc1_2' => 'Other courses', 'gc1_1' => 'Other courses', 'sc_2' => 'Sibling category', ), )); $this->_sectionexpanded ( array( 'Category 1' => 'collapsed', 'Sibling category' => 'collapsed', )); // Test the ability to set recursion depth on specific categories. $cc1id = $this->categories['cc1']->id; $scid = $this->categories['sc']->id; $filterconfig = <<<EOF category | expanded | $cc1id | 1 category | collapsed | $scid | 1 EOF; set_config('filters', $filterconfig, 'block_filtered_course_list'); $this->_courseunderrubric( array( 'user1' => array( 'c_1' => 'Other courses', 'cc1_2' => 'Child category 1', 'gc1_1' => 'Other courses', 'sc_2' => 'Sibling category', ), )); $this->_sectionexpanded ( array( 'Child category 1' => 'expanded', 'Sibling category' => 'collapsed', )); // Test the behavior of hidden categories and their potentially visible descendants. // Set the filter target to the be the visible child of the hidden category. // It should behave like any other visible category. $hcvcid = $this->categories['hcvc']->id; $filterconfig = <<<EOF category | expanded | $hcvcid | 0 EOF; set_config('filters', $filterconfig, 'block_filtered_course_list'); $this->_courseunderrubric( array( 'user1' => array( 'hcvc_1' => 'Hidden category visible child', ), 'user2' => array( 'hcvc_1' => 'Hidden category visible child', 'hcvc_3' => 'Hidden category visible child', ), )); $this->_courselistexcludes( array( 'user1' => array( 'hcvc_3', ), )); // Test the behavior of hidden categories and their potentially visible descendants. // Set the filter target to the be the hidden category itself. // We should get a rubric for the visible child. // We should get no rubric for the hidden category. // Accessible courses in the hidden category should appear under "Other courses". $hcid = $this->categories['hc']->id; $filterconfig = <<<EOF category | expanded | $hcid | 0 EOF; set_config('filters', $filterconfig, 'block_filtered_course_list'); $this->_courseunderrubric( array( 'user1' => array( 'hcvc_1' => 'Hidden category visible child', 'hc_1' => 'Other courses', ), 'user2' => array( 'hcvc_1' => 'Hidden category visible child', 'hcvc_3' => 'Hidden category visible child', 'hc_1' => 'Other courses', 'hc_3' => 'Other courses', ), )); $this->_courselistexcludes( array( 'user1' => array( 'hcvc_3', ), )); // Test that we can display a visible child category of a hidden parent category. // We can do this by pointing directly to the top-level category. $filterconfig = <<<EOF category | expanded | 0 | 0 EOF; set_config('filters', $filterconfig, 'block_filtered_course_list'); $this->_courseunderrubric( array( 'user1' => array( 'hcvc_1' => 'Hidden category visible child' ), )); } /** * Test shortname filtering */ public function test_shortnames() { $this->_shared_test('shortname'); } /** * Test idnumber filtering */ public function test_idnumbers() { $this->_shared_test('idnumber'); } /** * Generic test for shortname or idnumber filters * * @param string $filter 'shortname' or 'idnumber' */ public function _shared_test($filter) { $this->_create_rich_site(); // We'll need to use uppercase for the idnumber_filter. $transformation = ($filter == 'idnumber') ? 'mb_strtoupper' : 'mb_strtolower'; // Set up some idnumber filters. $filterconfig = <<<EOF $filter | expanded | Current courses | _1 $filter | expanded | Future courses | _2 $filter | expanded | Non-ascii | {$transformation('ø')} $filter | expanded | Child courses | {$transformation('cc')} $filter | expanded | Unnumbered categories | {$transformation('c_')} EOF; set_config('filters', $filterconfig, 'block_filtered_course_list'); // The block should not display individual courses to anonymous, guest, or admin. // The block should not display links to categories below the top level. $this->_courselistexcludes ( array ( 'none' => array ( 'Course 1', 'Child', 'Grandchild' ), 'guest' => array ( 'Course 1', 'Child', 'Grandchild' ), 'admin' => array ( 'Course 1', 'Child', 'Grandchild' ) )); // The block should offer top-level category links to anonymous, guest, and admin. $this->_courselistincludes ( array ( 'none' => array ( 'Category 1', 'Sibling' ), 'guest' => array ( 'Category 1', 'Sibling' ), 'admin' => array ( 'Category 1', 'Sibling' ) )); // The block should list'Current', 'Future', and 'Other courses'. $this->_courseunderrubric( array( 'user1' => array( 'c_1' => 'Current courses', 'cc1_1' => 'Current courses', 'cc2_1' => 'Current courses', 'gc1_1' => 'Current courses', 'sc_1' => 'Current courses', 'øthér' => 'Non-ascii', 'cc1_2' => 'Child courses', 'cc2_1' => 'Child courses', 'sc_2' => 'Unnumbered categories', ), 'user2' => array( 'c_2' => 'Future courses', 'cc1_2' => 'Future courses', 'cc2_2' => 'Future courses', 'gc1_2' => 'Future courses', 'sc_2' => 'Future courses', 'hc_2' => 'Future courses', 'hc_3' => 'Unnumbered categories', 'c_3' => 'Unnumbered categories', 'cc2_2' => 'Child courses', 'cc2_2' => 'Future courses', 'gc1_3' => 'Other courses' ) )); } /** * Test shortnames with regex */ public function test_regex_shortnames() { $this->_create_rich_site(); // Use regex for shortname matches. $filterconfig = <<<EOF regex | exp | All but default | ^[a-zø]{2} EOF; set_config('filters', $filterconfig, 'block_filtered_course_list'); // This new rubric should exclude courses with a shortname like 'c_1'. // It does not begin with two lowercase letters. $this->_courseunderrubric ( array ( 'user1' => array ( 'c_1' => 'All but default', ) ), 'not'); // Courses under any other category should be listed. $this->_courseunderrubric ( array ( 'user1' => array ( 'cc1_1' => 'All but default', 'cc2_1' => 'All but default', 'gc1_1' => 'All but default', 'sc_1' => 'All but default', 'øthér' => 'All but default', ), )); } /** * Test generic filters */ public function test_generic_filters() { $this->_create_rich_site(); // Set up the generic filter. set_config('filters', 'generic | exp | Courses | Course categories', 'block_filtered_course_list'); // Change the managerview setting to 'own'. set_config('managerview', 'own', 'block_filtered_course_list'); // Hide the catch-all 'Other courses' rubric. set_config('hideothercourses', 1, 'block_filtered_course_list'); // The block should offer top-level category links to all users including logged-in user enrolled in no courses. $this->_courselistincludes ( array ( 'admin' => array ( 'Course categories' ), 'user1' => array ( 'Course categories' ), 'user2' => array ( 'Course categories' ), 'none' => array ( 'Course categories' ), 'guest' => array ( 'Course categories' ), 'user3' => array ( 'Course categories' ), )); } /** * Test a site with mixed filters */ public function test_mixed_filters() { $this->_create_rich_site(); // Set up mixed filters. $cc2id = $this->categories['cc2']->id; $scid = $this->categories['sc']->id; $filterconfig = <<<EOF shortname | expanded | Ones | _1 category | expanded | $cc2id | 0 category | expanded | $scid | 0 shortname | expanded | Twos | _2 EOF; set_config('filters', $filterconfig, 'block_filtered_course_list'); // Users should see relevant courses under all rubrics. $this->_courseunderrubric( array( 'user1' => array( 'c_1' => 'Ones', 'sc_1' => 'Ones', 'cc2_1' => 'Ones', 'cc2_1' => 'Child category 2', 'cc2_2' => 'Child category 2', 'sc_1' => 'Sibling category', 'sc_2' => 'Sibling category', 'sc_2' => 'Twos', ), )); } /** * Test the ability to use the admin settings to hide the link to 'All courses' */ public function test_setting_hideallcourseslink() { $this->_create_rich_site(); // Set up simple matching. $filterconfig = <<<EOF shortname | e | Courses | _ EOF; set_config('filters', $filterconfig, 'block_filtered_course_list'); // Any user who sees the block should also see the "All courses" link. $this->_allcourseslink ( array ( 'none' => 'Search courses', 'guest' => 'Search courses', 'user1' => 'All courses', 'admin' => 'Search courses', 'user3' => false )); // Hide the All-courses link from all but admins. set_config('hideallcourseslink', 1, 'block_filtered_course_list'); // Only an admin should see the "All courses" link. $this->_allcourseslink ( array ( 'none' => false, 'guest' => false, 'user1' => false, 'admin' => 'Search courses', )); } /** * Test whether an admin can hide the block from guests */ public function test_setting_hidefromguests() { $this->_create_rich_site(); // Set up simple matching. $filterconfig = <<<EOF shortname | expanded | Courses | _ EOF; set_config('filters', $filterconfig, 'block_filtered_course_list'); // All users should see the block. $this->_noblock ( array ( 'none' => false, 'guest' => false, 'user1' => false, 'admin' => false, 'user3' => false, )); // Change the setting to hide the block from guests and anonymous visitors. set_config('hidefromguests', 1, 'block_filtered_course_list'); // Now only admins and logged-in users should see the block. $this->_noblock ( array ( 'none' => true, 'guest' => true, 'user1' => false, 'admin' => false, 'user3' => false, )); } /** * Test whether an admin can choose whether or not to display a link to 'Other courses' * not covered by the filter */ public function test_setting_hideothercourses() { $this->_create_rich_site(); $filterconfig = <<<EOF shortname | e | Current courses | gc EOF; set_config('filters', $filterconfig, 'block_filtered_course_list'); // Enrollments that do not match appear under 'Other courses'. $this->_courseunderrubric ( array ( 'user1' => array ( 'sc_1' => 'Other courses', ), )); // Hide the catch-all 'Other courses' rubric. set_config('hideothercourses', 1, 'block_filtered_course_list'); // No other courses are listed. $this->_courselistexcludes ( array ( 'user1' => array( 'Other courses' ), )); } /** * Test that aria attributes are added for collapsible rubrics */ public function test_aria_attributes() { $this->_create_rich_site(); // Set up simple matching. $filterconfig = <<<EOF shortname | exp | Courses | _ EOF; set_config('filters', $filterconfig, 'block_filtered_course_list'); // For users enrolled in courses the various rubrics are collapsible. $this->_courselistincludes ( array ( 'user1' => array ( 'collapsible', 'aria-multiselectable', 'aria-controls', 'aria-expanded', 'aria-selected', 'aria-labelledby', 'aria-hidden', ), )); } /** * Test whether an admin can designate particular rubrics to be expanded automatically */ public function test_setting_expanded_section() { $this->_create_rich_site(); // Set up some rubrics. $filterconfig = <<<EOF shortname | collapsed | Current courses | _1 shortname | collapsed | Future courses | _2 shortname | collapsed | Child courses | cc shortname | collapsed | Unnumbered categories | c_ category | collapsed | 0 | 0 EOF; set_config('filters', $filterconfig, 'block_filtered_course_list'); // All sections should be collapsed. $this->_sectionexpanded ( array( 'Current courses' => 'collapsed', 'Future courses' => 'collapsed', 'Child courses' => 'collapsed', 'Unnumbered categories' => 'collapsed', 'Category 1' => 'collapsed', 'Child category' => 'collapsed', )); // Now set a couple sections to be expanded by default. $filterconfig = <<<EOF shortname | expanded | Current courses | _1 shortname | collapsed | Future courses | _2 shortname | collapsed | Child courses | cc shortname | expanded | Unnumbered categories | c_ category | expanded | 0 | 0 EOF; set_config('filters', $filterconfig, 'block_filtered_course_list'); // The corresponding sections should be expanded. $this->_sectionexpanded ( array( 'Current courses' => 'expanded', 'Future courses' => 'collapsed', 'Child courses' => 'collapsed', 'Unnumbered categories' => 'expanded', 'Category 1' => 'expanded', 'Child category' => 'expanded', )); // Now test config lines that do not set expansion state or use invalid values. $filterconfig = <<<EOF shortname | | Current courses | _1 shortname | invalid value | Future courses | _2 EOF; set_config('filters', $filterconfig, 'block_filtered_course_list'); // All sections should be collapsed. $this->_sectionexpanded ( array( 'Current courses' => 'collapsed', 'Future courses' => 'collapsed', )); } /** * Test that rubric titles pass through htmlentities() */ public function test_rubric_title_htmlentities() { $this->_create_rich_site(); // Set up a shortname rubrics. $filterconfig = <<<EOF shortname | col | Current <br />courses | _1 EOF; set_config('filters', $filterconfig, 'block_filtered_course_list'); // We should see the course under the original text. // This test would fail if the line break were interpreted. $this->_courseunderrubric ( array ( 'user1' => array ( 'c_1' => 'Current <br />courses', ) )); } /** * Test whether an admin can choose whether to see all courses or only her own */ public function test_setting_managerview() { $this->_create_rich_site(); set_config('filters', '', 'block_filtered_course_list'); // The block should not display links to categories below the top level. $this->_courselistexcludes ( array ( 'admin' => array ( 'Course 1', 'Child', 'Grandchild' ) )); // The block should offer top-level category links to anonymous, guest, and admin. $this->_courselistincludes ( array ( 'admin' => array ( 'Category 1', 'Sibling' ) )); // Change the managerview setting to 'own'. set_config('managerview', 'own', 'block_filtered_course_list'); // An admin enrolled in no courses should still see only the top level. $this->_courselistexcludes ( array ( 'admin' => array ( 'Course 1', 'Child', 'Grandchild' ) )); $this->_courselistincludes ( array ( 'admin' => array ( 'Category 1', 'Sibling' ) )); // Put the admin in a course. $this->getDataGenerator()->enrol_user( $this->adminid, $this->courses['gc1_1']->id ); // Admin should see the course listing as a regular user would. $this->_courselistexcludes ( array ( 'admin' => array ( 'Category 1', 'Sibling' ) )); $this->_courseunderrubric ( array ( 'admin' => array ( 'gc1_1' => 'Other courses' ) )); } /** * Test some display template settings */ public function test_setting_tpls() { $this->_create_rich_site(); set_config('coursenametpl', 'FULLNAME (SHORTNAME) : IDNUMBER < <b>CATEGORY</b>', 'block_filtered_course_list'); set_config('catrubrictpl', 'NAME - IDNUMBER - <b>PARENT</b> - ANCESTRY', 'block_filtered_course_list'); set_config('catseparator', ' :: ', 'block_filtered_course_list'); // Any tags should be stripped. $longrubric = 'Grandchild category 1 - gc1 - Child category 2 - Category 1 :: Child category 2 :: Grandchild category 1'; $htmlentities = '&uuml;&amp;: HTML Entities (&uuml;&amp;shortname) : &uuml;&amp;IDNUMBER &lt; Sibling category'; $this->_courselistincludes ( array ( 'user1' => array( 'Non-ascii matching (øthér) : ØTHÉR &lt; Sibling category', 'Category 1 - - Top - Category 1', $longrubric, $htmlentities, ), )); $this->_courselistexcludes ( array ( 'user1' => array( '&amp;uuml;', '&amp;amp;' ) )); } /** * Ensure that the block honors a possible 'disablemycourses' setting */ public function test_setting_cfg_disablemycourses() { global $CFG; $this->_create_rich_site(); set_config('filters', '', 'block_filtered_course_list'); $CFG->disablemycourses = 1; // Enrolled users, like guests, should see a generic list of categories. $this->_courselistincludes ( array ( 'user1' => array ( 'Category 1', 'Sibling' ) )); // Enrolled users, like guests, should not see subcategories or specific courses. $this->_courselistexcludes ( array ( 'user1' => array ( 'Course 1', 'Child', 'Grandchild' ) )); // On the other hand, managerview = own trumps disablemycourses. set_config('managerview', 'own', 'block_filtered_course_list'); // Enroll admin in 'hc_1'. $this->getDataGenerator()->enrol_user( $this->adminid, $this->courses['hc_1']->id, 3 ); $this->_courseunderrubric ( array ( 'admin' => array ( 'hc_1' => 'Other courses' ) )); } /** * Test that we are applying the correct CSS completion classes */ public function test_css_completion_classes() { global $CFG, $DB; // Create a course. $this->_create_misc_courses( 1, 1 ); // Enroll user1 as a student in course 1. $this->getDataGenerator()->enrol_user( $this->user1->id , $this->courses['c_1']->id ); // While completion is not enabled site-wide. $this->_courselistexcludes ( array ( 'user1' => array ( 'complete' ), )); // While completion is enabled site-wide, but not on the course. $CFG->enablecompletion = true; $this->_courselistexcludes ( array ( 'user1' => array ( 'complete' ), )); // Enable completion on the course. $record = new stdClass(); $record->id = $this->courses['c_1']->id; $record->enablecompletion = 1; $DB->update_record('course', $record); $this->_courselistincludes ( array ( 'user1' => array ( 'incomplete' ), )); // Finally, mark the completion. $completion = new completion_completion(array( 'course' => $this->courses['c_1']->id, 'userid' => $this->user1->id )); $completion->mark_complete(); $this->_courselistincludes ( array ( 'user1' => array ( 'complete' ), )); $this->_courselistexcludes ( array ( 'user1' => array ( 'incomplete' ), )); } /** * Test enrolment filter. */ public function test_enrolment_filter() { $this->_create_rich_site(); // Include courses with guest access enabled. $filterconfig = <<<EOF enrolment | c | guest | Open to guests EOF; set_config('filters', $filterconfig, 'block_filtered_course_list'); $this->_courselistincludes(array( 'user1' => array('Open to guests', 'Guest enrolment'), 'user3' => array('Open to guests', 'Guest enrolment'), 'none' => array('Open to guests', 'Guest enrolment'), )); $this->_courselistexcludes(array( 'user3' => array('Self enrolment'), )); // Include courses with self enrolment enabled. $filterconfig = <<<EOF enrolment | c | self | Allowing self enrolment EOF; set_config('filters', $filterconfig, 'block_filtered_course_list'); $this->_courselistincludes(array( 'user1' => array('Allowing self enrolment', 'Self enrolment'), 'user3' => array('Allowing self enrolment', 'Self enrolment'), 'none' => array('Allowing self enrolment', 'Self enrolment'), )); $this->_courselistexcludes(array( 'user3' => array('Guest enrolment'), )); // Include courses with either self or guest enrolment enabled. $filterconfig = <<<EOF enrolment | c | self, guest | Self-serve EOF; set_config('filters', $filterconfig, 'block_filtered_course_list'); $this->_courselistincludes(array( 'user1' => array('Self-serve', 'Self enrolment'), 'user2' => array('Self-serve', 'Guest enrolment'), 'user3' => array('Self-serve', 'Self enrolment'), 'user3' => array('Self-serve', 'Guest enrolment'), 'none' => array('Self-serve', 'Self enrolment'), 'none' => array('Self-serve', 'Guest enrolment'), )); } /** * Generate some users to test against */ private function _setupusers() { global $USER; // Get the admin id. $this->setAdminUser(); $this->adminid = $USER->id; // Set up 3 regular users. $this->user1 = $this->getDataGenerator()->create_user(array( 'username' => 'user1', 'firstname' => 'User', 'lastname' => 'One', 'email' => '<EMAIL>' )); $this->user2 = $this->getDataGenerator()->create_user(array( 'username' => 'user2', 'firstname' => 'User', 'lastname' => 'Two', 'email' => '<EMAIL>' )); $this->user3 = $this->getDataGenerator()->create_user(array( 'username' => 'user3', 'firstname' => 'User', 'lastname' => 'Three', 'email' => '<EMAIL>' )); } /** * Copy the test filter so that settings will detect it. */ private function _setupfilter() { $frompath = __DIR__ . '/behat/data/external_filter.php'; $topath = __DIR__ . '/behat/data/fcl_filter.php'; if (file_exists($frompath)) { copy($frompath, $topath); } } /** * Generate some courses in the Category 1 category * * @param int $start A first value to apply incrementally to several courses * @param int $end The value at which to stop generating courses */ private function _create_misc_courses( $start=1, $end=8 ) { for ($i = $start; $i <= $end; $i++) { $this->courses["c_$i"] = $this->getDataGenerator()->create_course(array( 'fullname' => "Course $i in Misc", 'shortname' => "c_$i", 'idnumber' => strtoupper("c_$i"), )); } } /** * Build a more complicated site for more intresting testing * Use the following structure * * Category 1 * Course 1, c_1 * ... * Course 12, c_12 * Child category 1 * Course 1 in Child category 1, cc1_1 * ... * Course 3 in Child category 1, cc1_3, hidden * Child category 2 * Course 1 in Child category 2, cc2_1 * ... * Course 3 in Child category 2, cc2_3, hidden * Grandchild category 1 * Course 1 in Grandchild category, gc1_1 * ... * Course 3 in Grandchild category, gc1_3, hidden * Hidden category * Course 1 in Hidden category, hc_1 * ... * Course 3 in Hidden category, hc_3, hidden * Hidden category child * Course 1 in Hidden category child, hcc_1 * ... * Course 3 in Hidden category child, hcc_3, hidden * Hidden category visible Child * Course 1 in Hidden category child, hcvc_1 * ... * Course 3 in Hidden category child, hcvc_3, hidden * Sibling category * Course 1 in Sibling category, sc_1 * ... * Course 3 in Sibling category, sc_3, hidden * Non-ascii matching, øthér */ private function _create_rich_site() { global $DB; // Add some courses under Category 1. $this->_create_misc_courses ( 1, 3 ); // Create categories. $this->categories['cc1'] = $this->getDataGenerator()->create_category( array( 'name' => 'Child category 1', 'parent' => 1, 'idnumber' => 'cc1' )); $this->categories['cc2'] = $this->getDataGenerator()->create_category( array( 'name' => 'Child category 2', 'parent' => 1, 'idnumber' => 'cc2' )); $cc2id = $this->categories['cc2']->id; $this->categories['gc1'] = $this->getDataGenerator()->create_category( array( 'name' => 'Grandchild category 1', 'parent' => $cc2id, 'idnumber' => 'gc1' )); $this->categories['hc'] = $this->getDataGenerator()->create_category( array( 'name' => 'Hidden category', 'parent' => 1, 'idnumber' => 'hc', 'visible' => 0 )); $hcid = $this->categories['hc']->id; $this->categories['hcc'] = $this->getDataGenerator()->create_category( array( 'name' => 'Hidden category child', 'parent' => $hcid, 'idnumber' => 'hcc' )); $this->categories['hcvc'] = $this->getDataGenerator()->create_category( array( 'name' => 'Hidden category visible child', 'parent' => $hcid, 'idnumber' => 'hcvc', )); $this->categories['hcvc']->show(); $this->categories['sc'] = $this->getDataGenerator()->create_category( array( 'name' => 'Sibling category', 'idnumber' => 'sc' )); // Create three courses in each category, the third of which is hidden. foreach ($this->categories as $id => $category) { for ($i = 1; $i <= 3; $i++) { $shortname = "{$id}_$i"; $params = array ( 'fullname' => "Course $i in $category->name", 'shortname' => $shortname, 'idnumber' => strtoupper($shortname), 'category' => $category->id ); if ( $i % 3 == 0 ) { $params['visible'] = 0; } else { $params['visible'] = 1; } $this->courses[$shortname] = $this->getDataGenerator()->create_course( $params ); } } // Create a course with a non-ascii shortname in the Sibling category. $params = array ( 'fullname' => 'Non-ascii matching', 'shortname' => 'øthér', 'idnumber' => 'ØTHÉR', 'category' => $this->categories['sc']->id ); $this->courses['øthér'] = $this->getDataGenerator()->create_course( $params ); // Create a course with HTML entities in the fullname and shortname. $params = array( 'fullname' => '&uuml;&amp;: HTML Entities', 'shortname' => '&uuml;&amp;shortname', 'idnumber' => '&uuml;&amp;IDNUMBER', 'category' => $this->categories['sc']->id ); $this->courses['&uuml;&amp;shortname'] = $this->getDataGenerator()->create_course( $params ); // Create a course with guest enrolment enabled in the Sibling category. $params = array( 'fullname' => 'Guest enrolment enabled', 'shortname' => 'guestenrolment', 'idnumber' => 'GUESTENROLMENT', 'category' => $this->categories['sc']->id ); $this->courses['guestenrolment'] = $this->getDataGenerator()->create_course($params); $guestplugin = enrol_get_plugin('guest'); $studentrole = $DB->get_record('role', array('shortname' => 'student')); $instance = $guestplugin->add_instance($this->courses['guestenrolment'], array('status' => ENROL_INSTANCE_ENABLED, 'name' => 'Test instance', 'customint6' => 1, 'roleid' => $studentrole->id)); // Create a course with self enrolment enabled in the Sibling category. $params = array( 'fullname' => 'Self enrolment enabled', 'shortname' => 'selfenrolment', 'idnumber' => 'SELFENROLMENT', 'category' => $this->categories['sc']->id ); $this->courses['selfenrolment'] = $this->getDataGenerator()->create_course($params); $selfplugin = enrol_get_plugin('self'); $instanceid1 = $selfplugin->add_instance($this->courses['selfenrolment'], array('status' => ENROL_INSTANCE_ENABLED, 'name' => 'Test instance', 'customint6' => 1, 'roleid' => $studentrole->id)); // Enroll user1 as a student in all courses. foreach ($this->courses as $course) { $this->getDataGenerator()->enrol_user( $this->user1->id, $course->id ); } // Enroll user2 as a teacher in all courses. foreach ($this->courses as $course) { $this->getDataGenerator()->enrol_user( $this->user2->id, $course->id, 3 ); } } /** * Test the get_rubrics method that facilitates mobile rendering */ public function test_get_rubrics() { // Create 8 courses in the default category: Category 1. $this->_create_misc_courses( 1, 8 ); $page = new moodle_page; $this->_switchuser( 'admin' ); $bi = new block_filtered_course_list; $bi->instance = new StdClass; $bi->instance->id = 17; $bi->get_content( $page ); $this->assertEquals( 8, count( $bi->get_rubrics()[0]->courses )); } /** * Test whether given users see any block at all * * @param array $expectations A list of users and whether or not they should see any block */ private function _noblock ( $expectations=array() ) { $page = new moodle_page; foreach ($expectations as $user => $result) { $this->_switchuser ( $user ); $bi = new block_filtered_course_list; $bi->instance = new StdClass; $bi->instance->id = 17; if ( $result === true ) { if ( isset ( $bi->get_content($page)->text ) ) { // In some cases the text exists but is empty. $this->assertEmpty ( $bi->get_content($page)->text , "$user should not see a block, but ... " . $bi->get_content($page)->text); } else { // In other cases the text will not have been set at all. $this->assertFalse ( isset ( $bi->get_content($page)->text ) ); } } else { $this->assertNotEmpty ( $bi->get_content($page)->text , "$user should see a block." ); } } } /** * Test whether given users can see a link to 'All courses' * * @param array $expectations A list of users and whether or not they should see the link */ private function _allcourseslink ( $expectations=array() ) { $page = new moodle_page; foreach ($expectations as $user => $result) { $this->_switchuser ( $user ); $bi = new block_filtered_course_list; $bi->instance = new StdClass; $bi->instance->id = 17; $footer = $bi->get_content($page)->footer; if ( $result ) { $this->assertStringContainsString ( $result , $footer , "$user should see the All-courses link." ); } else { $this->assertStringNotContainsString ( 'All courses' , $footer , "$user should not see the All-courses link." ); } } } /** * Test whether the course listing includes a particular course for a given user * * @param array $expectations A list of users and courses they should see */ private function _courselistincludes ( $expectations=array() ) { $page = new moodle_page; foreach ($expectations as $user => $courses) { $this->_switchuser ( $user ); $bi = new block_filtered_course_list; $bi->instance = new StdClass; $bi->instance->id = 17; foreach ($courses as $course) { $this->assertStringContainsString ( $course , $bi->get_content($page)->text , "$user should see $course." ); } } } /** * Test whether the course listing includes a particular course for a given user * * @param array $expectations A list of users and courses they should not see */ private function _courselistexcludes ( $expectations=array() ) { $page = new moodle_page; foreach ($expectations as $user => $courses) { $this->_switchuser ( $user ); $bi = new block_filtered_course_list; $bi->instance = new StdClass; $bi->instance->id = 17; foreach ($courses as $course) { $this->assertStringNotContainsString ( $course , $bi->get_content($page)->text , "$user should not see $course." ); } } } /** * Change the current user * * @param mixed $user Can be a user type or a specific user object */ private function _switchuser ( $user ) { if ( $user == 'none' ) { $this->setUser( null ); } else if ( $user == 'guest' ) { $this->setGuestUser(); } else if ( $user == 'admin' ) { $this->setAdminUser(); } else { $this->setUser( $this->$user ); } } /** * Test whether the course listing includes a particular course for a given user under a particular heading * * @param array $expectations A list of users and courses they should or should not see * @param string $relation 'under' indicates that the user should see the course, otherwise not */ private function _courseunderrubric ( $expectations=array() , $relation='under' ) { $page = new moodle_page; foreach ($expectations as $user => $courses) { $this->_switchuser ( $user ); $bi = new block_filtered_course_list; $bi->instance = new StdClass; $bi->instance->id = 17; $html = new DOMDocument; $html->loadHTML( mb_convert_encoding( $bi->get_content($page)->text, 'HTML-ENTITIES', 'UTF-8' )); $rubrics = $html->getElementsByTagName('div'); foreach ($courses as $course => $rubricmatch) { $hits = 0; foreach ($rubrics as $rubric) { $rubrictitle = $rubric->nodeValue; if ( trim($rubrictitle) != $rubricmatch || $rubric->getAttribute('class') == 'tablist') { continue; } $ul = $rubric->nextSibling; while (!($ul instanceof DOMElement)) { $ul = $ul->nextSibling; } $anchors = $ul->getElementsByTagName('a'); foreach ($anchors as $anchor) { $anchorclass = $anchor->attributes->getNamedItem('class')->nodeValue; if ( strpos( $anchorclass, 'block-fcl__list__link' ) !== false ) { $anchortitle = $anchor->attributes->getNamedItem('title')->nodeValue; if ( $anchortitle == $course ) { $hits++; } } } } if ( $relation == 'not' ) { $this->assertEquals( 0, $hits, "$user should not see $course under $rubricmatch" ); } else { $this->assertGreaterThan( 0, $hits, "$user should see $course under $rubricmatch" ); } } } } /** * Test whether a given rubric is expanded or not * * @param array $expectations A list of rubric titles * @param string $operator Indicates whether to expect expanded or collapsed */ private function _sectionexpanded ( $expectations=array(), $operator='' ) { $page = new moodle_page; $this->_switchuser('user1'); $bi = new block_filtered_course_list; $bi->instance = new StdClass; $bi->instance->id = 17; $html = new DOMDocument; $html->loadHTML( $bi->get_content($page)->text ); $rubrics = $html->getElementsByTagName('div'); foreach ($rubrics as $rubric) { $title = $rubric->textContent; if (!(array_key_exists($title, $expectations))) { continue; } $state = $expectations[$title]; $class = $rubric->getAttribute('class'); if ($operator == 'not') { $this->assertNotContains ( $state , $class, "The class attribute of '$title' should not contain $state."); } else { $this->assertContains ( $state , $class, "The class attribute of '$title' should contain $state."); } } } } <file_sep>/db/upgrade.php <?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * This file keeps track of upgrades to the filtered course list block * * @since 2.5 * @package block_filtered_course_list * @copyright 2016 CLAMP * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); /** * Upgrade code for the section links block. * * @param int $oldversion * @return bool */ function xmldb_block_filtered_course_list_upgrade($oldversion) { // Moodle v2.3.0 release upgrade line // Put any upgrade step following this. // Moodle v2.4.0 release upgrade line // Put any upgrade step following this. // Moodle v2.5.0 release upgrade line // Put any upgrade step following this. if ($oldversion < 2014010601) { $oldfiltertype = get_config('moodle', 'block_filtered_course_list/filtertype'); if ($oldfiltertype == 'term') { set_config('block_filtered_course_list/filtertype', 'shortname'); } $oldtermcurrent = get_config('moodle', 'block_filtered_course_list_termcurrent'); if (!empty($oldtermcurrent)) { set_config('block_filtered_course_list_currentshortname', $oldtermcurrent); unset_config('block_filtered_course_list_termcurrent'); } $oldtermfuture = get_config('moodle', 'block_filtered_course_list_termfuture'); if (!empty($oldtermfuture)) { set_config('block_filtered_course_list_futureshortname', $oldtermfuture); unset_config('block_filtered_course_list_termfuture'); } // Main savepoint reached. upgrade_block_savepoint(true, 2014010601, 'filtered_course_list'); } // Moodle v2.6.0 release upgrade line. // Put any upgrade step following this. if ($oldversion < 2015102002) { $fclsettings = array( 'filtertype', 'hideallcourseslink', 'hidefromguests', 'hideothercourses', 'useregex', 'currentshortname', 'currentexpanded', 'futureshortname', 'futureexpanded', 'labelscount', 'categories', 'adminview', 'maxallcourse', 'collapsible', ); $customrubrics = array( 'customlabel', 'customshortname', 'labelexpanded', ); foreach ($fclsettings as $name) { $value = get_config('moodle', 'block_filtered_course_list_' . $name); set_config($name, $value, 'block_filtered_course_list'); unset_config('block_filtered_course_list_' . $name); } for ($i = 1; $i <= 10; $i++) { foreach ($customrubrics as $setting) { $name = $setting . $i; $value = get_config('moodle', 'block_filtered_course_list_' . $name); if (!empty($value)) { set_config($name, $value, 'block_filtered_course_list'); unset_config('block_filtered_course_list_' . $name); } } } // Main savepoint reached. upgrade_block_savepoint(true, 2015102002, 'filtered_course_list'); } if ($oldversion < 2016080801) { $fclcnf = get_config('block_filtered_course_list'); $newcnf = ''; $disabled = ($fclcnf->filtertype == 'categories') ? '' : 'DISABLED '; $expanded = ($fclcnf->collapsible == 0) ? 'expanded' : 'collapsed'; $newcnf = "{$disabled}category | $expanded | $fclcnf->categories (catID) | 0 (depth) \n"; $type = ($fclcnf->useregex) ? 'regex' : 'shortname'; $disabled = ($fclcnf->filtertype == 'shortname') ? '' : 'DISABLED '; if ($fclcnf->currentshortname != '') { $expanded = ($fclcnf->currentexpanded || $fclcnf->collapsible == 0) ? 'expanded' : 'collapsed'; $newcnf .= "{$disabled}$type | $expanded | Current courses | $fclcnf->currentshortname \n"; } if ($fclcnf->futureshortname != '') { $expanded = ($fclcnf->futureexpanded || $fclcnf->collapsible == 0) ? 'expanded' : 'collapsed'; $newcnf .= "{$disabled}$type | $expanded | Future courses | $fclcnf->futureshortname \n"; } for ($i = 1; $i <= 10; $i++) { $labelvarname = "customlabel$i"; $shortnamevarname = "customshortname$i"; $expandedvarname = "labelexpanded$i"; if (property_exists($fclcnf, $labelvarname) && $fclcnf->$labelvarname != '') { $label = $fclcnf->$labelvarname; $label = str_replace('|', '-', $label); $shortname = $fclcnf->$shortnamevarname; $expanded = ($fclcnf->$expandedvarname || $fclcnf->collapsible == 0) ? 'expanded' : 'collapsed'; $disabled = ($i > $fclcnf->labelscount) ? 'DISABLED ' : $disabled; $newcnf .= "{$disabled}$type | $expanded | $label | $shortname \n"; } } set_config('filters', $newcnf, 'block_filtered_course_list'); set_config('managerview', $fclcnf->adminview, 'block_filtered_course_list'); upgrade_block_savepoint(true, 2016080801, 'filtered_course_list'); } return true; } <file_sep>/renderer.php <?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * This file defines the renderer for the Filtered course list block. * * @package block_filtered_course_list * @copyright 2016 CLAMP * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace block_filtered_course_list\output; defined('MOODLE_INTERNAL') || die; require_once(dirname(__FILE__) . '/locallib.php'); /** * Helper class for list items. * * @package block_filtered_course_list * @copyright 2016 CLAMP * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class list_item implements \renderable, \templatable { /** @var array of CSS classes for the list item */ public $classes = array('block-fcl__list__item'); /** @var string Display text for the list item link */ public $displaytext; /** @var array of CSS classes for the list item link */ public $linkclasses = array('block-fcl__list__link'); /** @var string Text to display when the list item link is hovered */ public $title; /** @var moodle_url object The destination for the list item link */ public $url; /** @var mixed Empty string or link to course summary URL */ public $summaryurl; /** @var icon object The icon to display */ public $icon; /** * Class constructor * * @param mixed $itemobject A object from which to derive the class properties * @param object $config The plugin options object */ public function __construct($itemobject, $config) { global $USER; $type = (get_class($itemobject) == 'core_course_category') ? 'category' : 'course'; switch ($type){ case 'course': $this->classes[] = 'block-fcl__list__item--course'; $completionclass = $this->completion_class($itemobject, $USER->id); if (!empty($completionclass)) { $this->classes[] = $completionclass; } $this->displaytext = \block_filtered_course_list_lib::coursedisplaytext($itemobject, $config->coursenametpl); if (!$itemobject->visible) { $this->linkclasses[] = 'dimmed'; } $this->title = format_string($itemobject->shortname); $this->url = new \moodle_url('/course/view.php?id=' . $itemobject->id); $this->summaryurl = new \moodle_url('/course/info.php?id=' . $itemobject->id); if (isloggedin($USER)) { $usercontext = \context_user::instance($USER->id); $userservice = \core_favourites\service_factory::get_service_for_user_context($usercontext); $isfave = $userservice->favourite_exists( 'core_course', 'courses', $itemobject->id, \context_course::instance($itemobject->id)); $fastring = ($isfave) ? 'fa-star' : 'fa-graduation-cap'; $srtitle = ($isfave) ? get_string('favourite', 'core_course') : get_string('course', 'core'); $this->icon = new icon($itemobject->id, $isfave, $fastring, $srtitle); } else { $this->icon = new icon($itemobject->id, false, 'fa-graduation-cap', get_string('course', 'core')); } break; case 'category': $this->classes[] = 'block-fcl__list__item--category'; $this->displaytext = format_string($itemobject->name); if (!$itemobject->visible) { $this->linkclasses[] = 'dimmed'; } $this->title = ''; $this->url = new \moodle_url('/course/index.php?categoryid=' . $itemobject->id); $this->summaryurl = ''; $this->icon = new icon($itemobject->id, false, 'fa-folder', get_string('category', 'core')); break; } } /** * Export the object data for use by a template * * @param renderer_base $output A renderer_base object * @return array $data Template-ready data */ public function export_for_template(\renderer_base $output) { $data = array( 'classes' => implode(' ', $this->classes), 'displaytext' => $this->displaytext, 'linkclasses' => implode(' ', $this->linkclasses), 'title' => $this->title, 'url' => $this->url, 'summaryurl' => $this->summaryurl, 'icon' => $this->icon, ); return $data; } /** * Return a completion class for a user in a courses * * @param stdClass $course object * @param string $userid * @return string $completionclass */ private function completion_class($course, $userid) { if (\completion_info::is_enabled_for_site()) { $completioninfo = new \completion_info($course); if ($completioninfo->is_enabled()) { if ($completioninfo->is_course_complete($userid)) { return 'block-fcl__list__item--complete'; } return '.block-fcl__list__item--incomplete'; } return; } return; } } /** * Helper class for rendering icons * * @package block_filtered_course_list * @copyright 2016 CLAMP * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class icon implements \renderable, \templatable { /** @var int course id */ public $id; /** @var bool is favourite */ public $isfavourite; /** @var str Font awesome class to use for item icon */ public $icon; /** @var str Title for screen reader */ public $title; /** * Constructor * * @param int $id course id * @param bool $isfavourite is favourite * @param str $icon Font-awesome class to use for icon * @param str $title The title attribute for the icon link */ public function __construct($id, $isfavourite, $icon, $title) { $this->id = $id; $this->isfavourite = $isfavourite; $this->icon = $icon; $this->title = $title; } /** * Export the object data for use by a template * * @param renderer_base $output A renderer_base object * @return array $data Template-ready data */ public function export_for_template(\renderer_base $output) { $data = array( 'id' => $this->id, 'isfavourite' => $this->isfavourite, 'icon' => $this->icon, 'title' => $this->title, ); return $data; } } /** * Helper class for rendering rubrics. * * @package block_filtered_course_list * @copyright 2016 CLAMP * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class renderable_rubric implements \renderable, \templatable { /** @var object Rubric */ public $rubric; /** @var string Block instance id */ public $instid; /** @var string Rubric key */ public $key; /** * Constructor * * @param array $rubric An original rubric object * @param string $instid The instance id of the calling block * @param string $key The array index of the rubric */ public function __construct($rubric, $instid, $key) { $this->rubric = $rubric; $this->instid = $instid; $this->key = $key; } /** * Export the object data for use by a template * * @param renderer_base $output A renderer_base object * @return array $data Template-ready data */ public function export_for_template(\renderer_base $output) { $itemdata = array_map(function($item) use ($output) { $renderable = new list_item($item, $this->rubric->config); $export = $renderable->export_for_template($output); return $export; }, $this->rubric->courses); $key = $this->key + 1; $hash = 'block-fcl_' . md5("{$this->instid}{$key}{$this->rubric->title}"); if (array_key_exists($hash, $_COOKIE) && property_exists($this->rubric->config, 'persistentexpansion') && $this->rubric->config->persistentexpansion) { $this->rubric->expanded = ($_COOKIE[$hash] == 'expanded') ? 'expanded' : 'collapsed'; } $exp = ($this->rubric->expanded == 'expanded') ? 'true' : 'false'; $hidden = ($this->rubric->expanded != 'expanded') ? 'true' : 'false'; $data = array( 'state' => $this->rubric->expanded, 'exp' => $exp, 'label' => $this->rubric->title, 'hidden' => $hidden, 'instid' => $this->instid, 'key' => $key, 'items' => array_values($itemdata), 'hash' => $hash, ); return $data; } } /** * Helper class for the main block content * * @package block_filtered_course_list * @copyright 2016 CLAMP * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class content implements \renderable, \templatable { /** @var array Rubrics to display */ public $rubrics = array(); /** @var string Block instance id */ public $instid; /** * Constructor * * @param string $instid The instance id of the calling block * @param array $rubrics The list of rubrics to display */ public function __construct($instid, $rubrics = array()) { $this->rubrics = $rubrics; $this->instid = $instid; } /** * Export the object data for use by a template * * @param renderer_base $output A renderer_base object * @return array $data Template-ready data */ public function export_for_template(\renderer_base $output) { $rubricdata = array_map(function($rubric, $key) use ($output) { $rubrichelper = new renderable_rubric($rubric, $this->instid, $key); $export = $rubrichelper->export_for_template($output); return $export; }, $this->rubrics, array_keys($this->rubrics)); $data = array( 'instid' => $this->instid, 'rubrics' => $rubricdata, 'persist' => $this->rubrics[0]->config->persistentexpansion, ); return $data; } } /** * Helper class for the "All courses" link. * * @package block_filtered_course_list * @copyright 2016 CLAMP * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class footer implements \renderable, \templatable { /** @var string Text for footer link */ public $linktext; /** @var string Link to the Course index page */ public $url; /** @var boolean Whether or not to display the link */ public $visible = false; /** * Constructor * * @param array $params A list of settings used to determine the link display */ public function __construct($params = array()) { if ($params['usertype'] == 'manager' || $params['hideallcourseslink'] == BLOCK_FILTERED_COURSE_LIST_FALSE) { $this->visible = true; } if ($params['liststyle'] == 'empty_block') { $this->visible = false; } $this->url = new \moodle_url('/course/index.php'); $this->linktext = get_string('fulllistofcourses'); if ($params['liststyle'] == 'generic_list') { $this->linktext = get_string('searchcourses'); } } /** * Export the object data for use by a template * * @param renderer_base $output A renderer_base object * @return array $data Template-ready data */ public function export_for_template(\renderer_base $output) { $data = array( 'linktext' => $this->linktext, 'url' => $this->url, 'visible' => $this->visible, ); return $data; } } /** * Renderer for the Filtered course list block. * * @package block_filtered_course_list * @copyright 2016 CLAMP * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class renderer extends \plugin_renderer_base { /** * Render HTML for the "All courses" link * * @param footer $footer A footer object * @return string The rendered html */ protected function render_footer (footer $footer) { $data = $footer->export_for_template($this); return $this->render_from_template('block_filtered_course_list/footer', $data); } /** * Render HTML for list item * * @param list_item $listitem * @return string The rendered html */ protected function render_list_item (list_item $listitem) { $data = $listitem->export_for_template($this); return $this->render_from_template('block_filtered_course_list/list_item', $data); } /** * Render HTML for icon * * @param icon $icon * @return string The rendered html */ protected function render_icon (icon $icon) { $data = $icon->export_for_template($this); return $this->render_from_template('block_filtered_course_list/icon', $data); } /** * Render HTML for rubric * * @param rubric $rubric * @return string The rendered html */ protected function render_rubric (rubric $rubric) { $data = $rubric->export_for_template($this); return $this->render_from_template('block_filtered_course_list/rubric', $data); } /** * Render HTML for content * * @param content $content * @return string The rendered html */ protected function render_content (content $content) { $data = $content->export_for_template($this); return $this->render_from_template('block_filtered_course_list/content', $data); } } <file_sep>/README.md # [Filtered course list v4.4.2] For Moodle 3.8, 3.9, 3.10, and 3.11 ![Moodle Plugin CI](https://github.com/CLAMP-IT/moodle-blocks_filtered_course_list/workflows/Moodle%20Plugin%20CI/badge.svg) The _Filtered course list_ block displays a configurable list of a user's courses. It is intended as a replacement for the _My courses_ block, although both may be used. It is maintained by the Collaborative Liberal Arts Moodle Project (CLAMP). ## Installation Unzip files into your Moodle blocks directory. This will create a folder called `filtered_course_list`. Alternatively, you may install it with git. In the top-level folder of your Moodle install, type the command: ``` git clone https://github.com/CLAMP-IT/moodle-blocks_filtered_course_list blocks/filtered_course_list ``` Then visit the admin screen to allow the install to complete. ## Upgrading ### From 2.8.3 or lower All of your configuration will automatically be converted to the new _textarea_ style. Filters that were set but not active will be listed as `DISABLED`. In addition, pipe characters ("|") within custom titles will be converted to hyphens ("-") in the new config. ### From v2.3 or lower During the upgrade you will be shown only the "new settings" but it is important to look at the new and the old settings together, so be sure to look at the block configuration once the upgrade is complete. ## Configuration ## To configure the block, go to _Site Administration > Plugins > Blocks > Filtered course list._ ### External filters ### If any external filters are available on your Moodle installation you can activate them by checking the appropriate boxes. If there are no external filters, this setting will not display. ### Filters ### Most of the configuration will be done in the _textarea_ near the top of the page. Add one filter per line; use pipes ("|") to separate the different settings for each filter. Whitespace at the beginning or end of a value is removed automatically, so you can pad your layout to make it more readable. Here is a sample of the possibilities: ``` category | expanded | 0 (category id) | 1 (depth) shortname | exp | Current courses | S17 regex | collapsed | Upcoming | (Su|F)17$ idnumber | col | History courses | HIST_ starred | exp | My starred courses completion | exp | Incomplete | incomplete completion | col | Completed | complete generic | exp | Categories | Courses enrolment | col | guest, self | Open courses #category | col | 1 (Misc) | 0 (show all children) The line above will be ignored, as will this comment. ``` Please see the usage guide for fuller details: https://github.com/CLAMP-IT/moodle-blocks_filtered_course_list/wiki ### Other settings | Setting | Description | |---------|-------------| | Hide "All courses" link | Check the box to suppress the "All courses" link that otherwise appears at the bottom of the block. This link takes the user to the main course index page. Note that this setting does not remove the link from an administrator's view. | | Hide from guests | Check this box to hide the block from guests and anonymous visitors. | | Hide other courses | By default an "Other courses" rubric appears at the end of the list and displays any of the user's courses that have not already been mentioned under some other heading. Check the box here to suppress that rubric. | | Persistent expansion | If activated, we will use cookies to persist expansion states for the duration of a session. | | Max for single category | On a site with only one category, admins and guests will see all courses, but above the number specified here they will see a category link instead. [Choose an integer between 0 and 999.] Unless you have a single-category installation there is no need to adjust this setting. | | Course name template | Use replacement tokens (FULLNAME, SHORTNAME, IDNUMBER or CATEGORY) to control the way links to courses are displayed. Add a character limit to any token by suffixing it in curly braces to the token. For instance: FULLNAME{20} | | Category rubric template | Use replacement tokens (NAME, IDNUMBER, PARENT or ANCESTRY) to control the way rubrics display when using a category filter. Add a character limit to any token by suffixing it in curly braces to the token. For instance: NAME{20} | | Category separator | Customize the separator between ancestor categories when using the ANCESTRY token above. | | Manager view | By default administrators and managers will see a list of categories rather than a list of their own courses. This setting allows you to change that, and it can be helpful to do so while configuring the block. Be advised, however, that admins and managers who are not enrolled in any courses will still see the generic list. | | Sorting | The next four settings control the way courses are sorted within a rubric. | ## Changing the display name To change the name of a block instance, turn editing on on a screen that displays the block and click on the (gear) icon to edit the settings. ## Issue reporting Please report any bugs or feature requests to the public repository page: <https://github.com/CLAMP-IT/moodle-blocks_filtered_course_list>. ## Developers Use Grunt to manage LESS/CSS and Javascript as described in the Moodle dev documentation: https://docs.moodle.org/dev/Grunt ## Changelog ### [v4.4.4] * Code cleanup: compatibility changes for PHP 8.0 ### [v4.4.3] * Add support for Moodle 4.0+ * Drop support for Moodles 3.11-3.9 * Bugfix: prevent external filter functional from traversing hidden directories ### [v4.4.2] * Add support for Moodle 3.11 * Ensure PHPUnit test can access renderer ### [v4.4.1] * Migrates CI to Github Actions * Adds method to facilitate mobile rendering ### [v4.4.0] * Drops support for Moodle 3.7 * Adds support for Moodle 3.10 * Converts to plugin CI from Moodle HQ ### [v4.3.0] * Drops support for Moodle 3.6 * Adds support for Moodle 3.9 ### [v4.2.2] * Adds test coverage for Moodle 3.8 ### [v4.2.1] * Bug: Instance config defaults to empty, multilang fix * Dev: npm update ### [v4.2.0] * Feature: Adds filtering by idnumber ### [v4.1.5] * Testing: Isolates/namespaces our custom behat step ### [v4.1.4] * Bug: Hops over hidden categories when drilling down category trees ### [v4.1.3] * Testing: gitignores a file created during testing * Testing: expands coverage to Moodle 3.7 ### [v4.1.2] * Bug: Handles visible categories nested within hidden categories ### [v4.1.1] * Bug: Fixes some inconsistent persistence behaviours * Bug: Applies content filters when appropriate to rubric and course titles * Backend: adds thirdpartylibs.xml ### [v4.1.0] * Feature: Enables persistent expansion states * Feature: Displays stars for starred courses * Backend: Removes GDPR polyfill ### [v4.0.0] * Requirements: Requires Moodle 3.6 * Feature: Filters are now pluggable. Details in the wiki. * Feature: Adds a starred courses filter * Feature: Adds enrolment filter * Testing: Fixes some superficial testing errors * Backend: updates deprecated coursecat calls to core_course_category * Backend: Updates node modules ### [v3.3.7] * Requirements: Requires Moodle 3.3 or higher * Feature: Option to truncate template values after a certain length * Feature: CSS classes corresponding to course completion status * Backend: Reorganizes filter classes ### [v3.3.6] * Bug: Fixes fatal error with Privacy API ### [v3.3.5] * Backend: Better compliance with GDPR for multiple PHP versions * Testing: Covers Moodle 3.5 ### [v3.3.4] * Policy: complies with GDPR * Bug: Better performance when fetching category ancestry * Backend: minor refactor ### [v3.3.3] * Bug: Provides additional language strings ### [v3.3.2] * Bug: Missed an AMOS string ### [v3.3.1] * Bug: Simplifies strings for AMOS Compatibility * Bug: Complies with Moodle's CSS styles ### [v3.3.0] * New: adds a generic filters * New: accepts display templates for category rubrics * Bug fix: now handles HTML entities correctly in display text * Back end: generates HTML solely via mustache templates * Back end: uses LESS to manage CSS ### [v3.2.2] * Makes course summary URLs available to the list_item template ### [v3.2.1] * Requirement bump: 3.2 and higher * Front end: Minor style and HTML tweaks * Back end: New mustache template to manage rubrics * Automated Testing: * Now using moodlerooms-plugin-ci v2 * Covers 3.2 to 3.4 ### [v3.2.0] * Feature: Display templates for course names * Bug: Style fixes for docked blocks in Clean themes * Bug: Allow permission overrides * Back end: streamlining the item link template ### [v3.1.0] * Supports multiple instances, each with their own configuration * Now uses folder icons for category links * Renders list items and block footer from template ### [v3.0.0] * Settings: * Provides clearer overview of multiple filters * Makes it easier to modify and reorder filters * Allows admin to set expansion preference for category filters * Allows multiple category filters * Introduces course completion filters * Allows recursion depth on category filters * Allows admin to intersperse filter types freely * Allows unlimited number of filters * Allows course sorting within rubrics * Replaces 'admin' with 'manager' where the latter is more accurate * Appearance: * Better support for core themes. * Back end: * Makes it easier to add new filter types * Refactors YUI module as AMD/jQuery * Requires `MOODLE_30_STABLE` * Testing: * Drops automated testing for `MOODLE_29_STABLE` * Correctly disables xdebug for Travis CI ### [v2.8.3] * Testing: Drops automated testing for `MOODLE_28_STABLE` ### [v2.8.2] * Back end: Uses core coursecat functions instead of external lib * Testing: Automated testing now covers `MOODLE_31_STABLE` ### [v2.8.1] * Back end: Confirms functionality for PHP7 * Bug: Adds support for matching non ascii characters * Back end: PHPDoc compliance ### [v2.8.0] * Back end: The FCL block now stores preferences in Moodle's plugin config table. Settings from older versions should migrate seamlessly. * Back end: Automated testing has been considerably expanded. ### [v2.7.0] * Feature: An admin can set arbitrary rubrics to be expanded by default * Feature: Aria accessibility improvements * Bug fix: Admins should see a block under all circumstances * Back end: Continuous integration with Travis CI ### [v2.6.0] * Dependency: Requires Moodle 2.8 * Behind the scenes: Updates automated testing for newer Moodles ### [v2.5.1] * Feature: Admin can designate "Top" when organizing by categories * Behind the scenes: automated testing and healthier code ### [v2.5] * Feature: Course rubrics can now be set to be collapsible * Feature: Shortname matches can be powered by regex * Bug fix: One course can now satisfy multiple shortname matches * Testing: Adds comprehensive PHPunit testing * Testing: Adds Behat acceptance tests for selected features ### [v2.4] * Fixes style issues for the Clean family of themes * Introduces better handling for sites with one category but many courses * Allows admin to edit the display title * Allows category based display, including subcategory logic * Allows admin to see 'own courses' instead of all courses * Allows optional 'other courses' catch-all category * Allows admins to define up to ten custom rubrics to match shortcodes against * Allows admins to hide the block from guests ### [v2.3] * Separate release for Moodle versions earlier than v2.5.0 * Minor code cleanup ### [v2.2] * Rewrote the block to use block_base instead of block_list * Added an option to suppress Other Courses ### [v2.1.1] * Added a missing language string ### [v2.1] * Compatibility with Moodle v2.5.0 ### [v2.0] * Resolved various code-checker issues * Compatibility with Moodle v2.4.0
f2356713fe80827c393c4cf6949eb6b6d8e71887
[ "Markdown", "PHP" ]
7
PHP
CLAMP-IT/moodle-blocks_filtered_course_list
d5a97b9066855cf69135fe85d55d10c455a2abb7
645bf4fa1b4c38ba63ebdfc7b484c0f6122294fd
refs/heads/master
<file_sep>#pragma once float ex_fmod(float a, float b);<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HeadSpin.CommonLib.Logging { public interface ILoggers { void LogError(String s, String s2, String s3); } public class Loggers : ILoggers { public void LogError(String s, String s2, String s3) { return; } } } <file_sep>#pragma once #include "mbed.h" #define M_PI 3.14159265358979323846 //Constants for direction relating directly to location of motors/proxi sensors int const FrontRight = 0; int const MidRight = 1; int const BackRight = 2; int const BackLeft = 3; int const MidLeft = 4; int const FrontLeft = 5; int const Top = 6; int const Bottom = 7; //Constants for direction relating to spaces between motors/proxi sensors int const Front = 8; int const FrontMidRight = 9; int const MidBackRight = 10; int const Back = 11; int const MidBackLeft = 12; int const FrontMidLeft = 13; //the angle divisor for radions betwen each rotor/proxi sensor (60 degrees = pi/3 radians) int const ANGLE_DIVISOR = 3; //number of proxi sensors int const NUM_SENSORS = 8; <file_sep>#pragma once #include "mbed.h" #include "Buzzer.h" //Vbat->R1->|->R2->||Gnd // V // AnalogIn //R1 ~= 1.5 kOhms //R2 ~= 500 Ohms //Vbat * R2/(R1+R2) = Vout //267ohms //216ohms // 12.6 * 500/(1500+500) = 3.15V // 3.23/3.3 = 0.98 // 10.5 * 500/(1500+500) = 2.63V //https://developer.mbed.org/users/tylerjw/notebook/battery-voltage-monitor/ #define BUFFER_SIZE 20 class BatteryLevel { private: AnalogIn VoltIn; float buffer[BUFFER_SIZE]; int buffer_ptr; Ticker trig; short trim; short * _err_state; void incr_buff_ptr() { buffer_ptr++; if (buffer_ptr == BUFFER_SIZE) { buffer_ptr = 0; } } void poll_voltage() { buffer[buffer_ptr] = VoltIn.read(); incr_buff_ptr(); float average = 0.0; for (int i = 0; i < BUFFER_SIZE; i++) { average += buffer[i]; } average = average / BUFFER_SIZE; trim = (short) (average * 100); } public: BatteryLevel (PinName VoltPin, short * err_state): VoltIn(VoltPin) { buffer_ptr = 0; _err_state = err_state; trig.attach(this, &BatteryLevel::poll_voltage, 0.2); } int init(Buzzer * buzz) { if (buzz == NULL) return -1; buzz->beep_thrice(); wait(1.0); buzz->long_beep(); wait(1.0); if (VoltIn.read() > 0) return 0; else return -1; } float GetRaw() { return VoltIn.read() * 3.3; } short GetLevel() { if (trim < 81) { return 0; } else if (trim > 95) { return 100; } else { return ((short)((trim - 80) * 6.66)); } } };<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HeadSpin.DroneMon.LibDroneMon { public class NucleoStatus { private short[] motor_speeds; private short[] proxies; private short batt; private short[] control; private int[] gyro; private int[] accel; private int[] magn; private int[] bar; private int[] atti; private bool rc_in_control; int loop_time; short err_state; short header; public NucleoStatus(short header, short[] motor_speeds, short[] proxies, short batt, short[] control, int[] gyro, int[] accel, int[] magn, int[] bar, int[] atti, short rc_in_control, int loop_time, short err_state) { this.header = header; this.motor_speeds = motor_speeds; this.proxies = proxies; this.batt = batt; this.control = control; this.gyro = gyro; this.accel = accel; this.magn = magn; this.bar = bar; this.atti = atti; this.rc_in_control = (rc_in_control != 0); this.loop_time = loop_time; this.err_state = err_state; } public short[] MotorSpeeds { get { return motor_speeds; } } public short[] ProximitySensors { get { return proxies; } } public short BatteryValue { get { return batt; } } public short[] RemoteControllerValues { get { return control; } } public int[] GyroscopeRawValues { get { return gyro; } } public int[] AccellerometerRawValues { get { return accel; } } public int[] MagnometerRawValues { get { return magn; } } public int[] BarometerValues { get { return bar; } } public int[] AttitudeValues { get { return atti; } } public bool IsRCInControl { get { return rc_in_control; } } public int LoopTime { get { return LoopTime; } } public short ErrorState { get { return err_state; } } public short Header { get { return header; } } public override string ToString() { return "1: " + MotorSpeeds[0] + " 2:" + MotorSpeeds[1] + " 3:" + MotorSpeeds[2] + " 4:" + MotorSpeeds[3] + " 5:" + MotorSpeeds[4] + " 6:" + MotorSpeeds[5]; } } } <file_sep>#include "mbed.h" #include "flightModule.h" #include "rx_mbed.h" #include "AcrobaticMode.h" #include "MotorControl.h" #include "RemoteController.h" //Serial MBED(PA_9, PA_10); Serial pc(USBTX, USBRX); AnalogIn test(PC_2); DigitalOut led1(LED1); short counter = 0; Rec * rec = new Rec; Msg * msg = new Msg; PC_Msg * pc_msg = new PC_Msg; PinName I2C_pins[2] = {PB_9, PB_8};// SDA SCL PinName inter_pins[2] = {PC_6, PC_8}; double attitude[3]; double velocity[3]; double altitude[1]; flightModule flightmodule(I2C_pins, inter_pins, attitude, velocity, altitude); PinName motor_pins[6] = {PA_10, PB_3, PB_5, PB_4, PB_10, PA_8}; short err_state = 0; MotorControl motors(motor_pins, &err_state); RemoteController rc(rec->control,PC_2, PC_3,PC_1, PC_0, &err_state); //pins: Aile, Elev, Thro, Rudd using namespace std; char state = ' '; // 'd' for debug int init() { msg->motor_speeds[0] = 0; msg->motor_speeds[1] = 0; msg->motor_speeds[2] = 0; msg->motor_speeds[3] = 0; msg->motor_speeds[4] = 0; msg->motor_speeds[5] = 0; msg->buzz_val = 0; rc.init(&led1); motors.init(); return 0; } int main () { pc.baud(921600); //MBED.baud(921600); //printf("HEXACOPTER NUCLEO SOFTWARE\n"); int err_no; if ((err_no = init()) != 0) { //printf("error during Nucleo init. error #: %i \n", err_no); } if ((err_no = flightmodule.init()) != 0) { //printf("error during flightmodule init, error #: %i \n", err_no); return 1; } if ((err_no = AcrobaticInit()) != 0) { //printf("error during Acrobatic mode init, error #: %i \n", err_no); return 1; } //char startChar = MBED.getc(); led1 = 1; while (true) { //char * buff = (char *) rec; //for (int i = 0; i < rec_size; i++) //{ // MBED.putc('A'); // buff[i] = MBED.getc(); //} if (counter == 100) { counter = 0; led1 = !led1; } counter++; // if (!stability_on || ProcessStabilityMode(Blah Blah Blah) == 0) // { /*for (int i = 0; i < 4; i++) { printf("channel 1: %i", rec->control[i]); }*/ if (ProcessAcrobaticMode(rec->control, &flightmodule, msg->motor_speeds) == 0) { for (int i = 0; i < 6; i++) { //printf("motor 1: %1", msg->motor_speeds[i]); motors.pulsewidth(i,msg->motor_speeds[i]); } /* WRITE to MBED */ //char * temp_msg = (char *)msg; //for (int i = 0; i < msg_size; i++) { // MBED.putc(temp_msg[i]); // } //WRITE TO R_PI (Info... Don't do this everytime?) } else { //Failure count? } // } // else // { // //Failure count? // } pc_msg->RCinControl = true; for (int i = 0; i < 4; i++) { pc_msg->control[i] = rec->control[i]; } for (int i = 0; i < 6; i++) { pc_msg->motor_speeds[i] = i;//msg->motor_speeds[i]; } pc_msg->err_state = 215;//rec->err_state; pc_msg->batt = 136;//rec->batt; for (int i = 0; i < 3; i++) { pc_msg->accel[i] = i;//0; pc_msg->gyro[i] = i;//0; pc_msg->atti[i] = i;//0; pc_msg->magn[i] = i;//0; } for (int i = 0; i < 2; i++) { pc_msg->bar[i] = i;//0; } pc_msg->header = PC_MSG_HEADER; pc_msg->loopTime = 20; pc_msg->carriage_return = '\n'; for (int i = 0; i < 8; i++) { pc_msg->proxies[i] = i; } char * temp_pc_msg = (char *)pc_msg; for (int i = 0; i < pc_msg_size; i++) { pc.putc(temp_pc_msg[i]); } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using HeadSpin.DroneMon.LibDroneMon; namespace HeadSpin.DroneMon.RPiDroneMon { public delegate void ChangedEventHandler(Queue<NucleoStatus> statusQueue); public delegate void BytesUpdatedEventHandler(Queue<Byte> bytesAdded); public unsafe class NucleoDeserialiser { private short PC_MSG_HEADER = 97; private int pc_msg_size = Marshal.SizeOf<PC_Msg>(); Queue<NucleoStatus> statusQueue = new Queue<NucleoStatus>(); Queue<Byte> InputBuffer = new Queue<Byte>(); private Byte[] buffer; int counter = 0; public event ChangedEventHandler QueueUpdated; private event BytesUpdatedEventHandler BytesUpdated; public NucleoDeserialiser() { BytesUpdated += NucleoDeserialiser_BytesUpdated; buffer = new Byte[pc_msg_size]; } private void NucleoDeserialiser_BytesUpdated(Queue<Byte> bytesAdded) { while (bytesAdded.Count != 0) { Byte b = bytesAdded.Dequeue(); if ((counter == 0 && b == PC_MSG_HEADER) || (counter > 0 && counter < pc_msg_size) || (counter == pc_msg_size && b == '\n')) { buffer[counter++] = b; if (counter == pc_msg_size) { statusQueue.Enqueue(ConvertToNucleoStatusObj(buffer)); QueueUpdated(statusQueue); counter = 0; } } else { counter = 0; } } } private NucleoStatus ConvertToNucleoStatusObj(Byte[] buffer) { PC_Msg msg = ReadStruct(buffer); short[] motor_speeds = new short[6]; short[] proxies = new short[8]; short[] control = new short[4]; int[] gyro = new int[3]; int[] accel = new int[3]; int[] magn = new int[3]; int[] bar = new int[2]; int[] atti = new int[3]; for (int i = 0; i < 6; i++) { motor_speeds[i] = msg.motor_speeds[i]; } for (int i = 0; i < 8; i++) { proxies[i] = msg.proxies[i]; } for (int i = 0; i < 4; i++) { control[i] = msg.control[i]; } for (int i = 0; i < 3; i++) { gyro[i] = msg.gyro[i]; accel[i] = msg.accel[i]; magn[i] = msg.magn[i]; atti[i] = msg.atti[i]; } for (int i = 0; i < 2; i++) { bar[i] = msg.bar[i]; } return new NucleoStatus(msg.header, motor_speeds, proxies, msg.batt, control, gyro, accel, magn, bar, atti, msg.RCinControl, msg.loopTime, msg.err_state); } public void deserialise(Byte[] bytes) { for (int i = 0; i < bytes.Length; i++) { InputBuffer.Enqueue(bytes[i]); BytesUpdated(InputBuffer); } } private PC_Msg ReadStruct(Byte[] bytes) { Byte[] buffer = new Byte[pc_msg_size]; System.Array.Copy(bytes, buffer, buffer.Length); GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); PC_Msg result = Marshal.PtrToStructure<PC_Msg>(handle.AddrOfPinnedObject()); handle.Free(); return result; } } [StructLayout(LayoutKind.Sequential,Pack = 1)] internal unsafe struct PC_Msg { public byte header; public fixed short motor_speeds[6]; public fixed short proxies[8]; public short batt; public fixed short control[4]; public fixed int gyro[3]; public fixed int accel[3]; public fixed int magn[3]; public fixed int bar[2]; public fixed int atti[3]; public byte RCinControl; public int loopTime; public byte err_state; public byte carriage_return; }; } <file_sep>#include "mbed.h" #include "flightModule.h" int ProcessStabilityMode(int * control, flightModule * fm);<file_sep>#Mon Sep 28 15:23:06 CEST 2015 org.eclipse.core.runtime=2 org.eclipse.platform=4.5.0.v20150320-0800 <file_sep>/* mbed PwmIn Library * Copyright (c) 2008-2010, sford * * 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. */ #include "PwmIn.h" #include "mbed.h" PwmIn::PwmIn(PinName p, short * buff) : _p(p) { failure = false; stat = 4; low = -1; high = -1; mid = -1; lowmulti = 0.0; highmulti = 0.0; buffer = buff; thro = false; _p.rise(this, &PwmIn::rise); _p.fall(this, &PwmIn::fall); _t.start(); } void PwmIn::safetyCall() { failure = true; *buffer = 0; } void PwmIn::rise() { safety.detach(); _t.reset(); safety.attach(this, &PwmIn::safetyCall, 0.2); } void PwmIn::fall() { safety.detach(); short temp = _t.read_us(); if (temp < 2100) //check to make sure it's not a massively wrong reading. { switch (stat) { case 0: if (thro) { if (temp >= high) { *buffer = 100; return; } else if (temp <= low) { *buffer = 0; return; } else { temp = temp - low; *buffer = (temp * lowmulti) + 0.5; return; } } else if (temp > mid) { if (temp >= high) { *buffer = 50; // 100 - 50 return; } temp = temp - mid; *buffer = (temp * highmulti) + 0.5; // 50.5 - 50 } else { if (temp <= low) { *buffer = -50; // 0 - 50 return; } temp = temp - low; *buffer = (temp * lowmulti) -49.5; // 0.5 - 50 } break; case 1: *buffer = temp; if (high != -1) { if (temp < 1900) { stat = 0; if (thro) { lowmulti = (float)(high - low); lowmulti = (1000.0/lowmulti)/10.0; } else { highmulti = (float)(high - mid); highmulti = (500.0/highmulti)/10.0; } } else if (high < temp) { high = temp; } } else if (temp > 1900) { high = temp; } break; case 2: *buffer = temp; if (low != -1) { if (temp > 1100) { stat = 1; lowmulti = (float)(mid-low); lowmulti = (500.0/lowmulti)/10.0; } else if (low > temp) { low = temp; } } else if (temp < 1100) { low = temp; } break; default: *buffer = temp; break; } } safety.attach(this, &PwmIn::safetyCall, 0.2); } <file_sep>#pragma once #include "mbed.h" struct Rec { short header; short proxies[8]; short control[4]; short batt; short err_state; }; short const REC_HEADER = 39; int const rec_size = sizeof(Rec); struct Msg { short header; short motor_speeds[6]; short buzz_val; }; short const MSG_HEADER = 26; int const msg_size = sizeof(Msg); #pragma pack(push, 1) struct PC_Msg { uint8_t header; uint16_t motor_speeds[6]; uint16_t proxies[8]; uint16_t batt; uint16_t control[4]; uint32_t gyro[3]; uint32_t accel[3]; uint32_t magn[3]; uint32_t bar[2]; uint32_t atti[3]; uint8_t RCinControl; uint32_t loopTime; uint8_t err_state; uint8_t carriage_return; }; #pragma pack(pop) short const PC_MSG_HEADER = 97; int const pc_msg_size = sizeof(PC_Msg); <file_sep>#region usings using System; using System.Collections.Generic; using System.Net.Sockets; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using HeadSpin.CommonLib.Comms.TcpSocket; #endregion namespace HeadSpin.CommonLib.Comms { /// <summary> /// An Asynchronous TCP Server that makes use of system managed threads /// and callbacks to stop the server ever locking up. /// </summary> public class TcpServer : IIoServer { #region Events //public delegate void ClientConnectionHandler(string sessionId, string remoteIpAddress); public event ClientConnectionHandler OnClientConnection; //public delegate void ClientDisconnectionHandler(string sessionId); public event ClientDisconnectionHandler OnClientDisconnection; //public delegate void MessageHandler(string sessionId, String message); public event ClientMessageHandler OnClientMessage; #endregion private TcpListener _tcpListener; private readonly SortedDictionary<string, Client> _clients = new SortedDictionary<string, Client>(); public TcpServer() { this._clients = new SortedDictionary<string, Client>(); } /// <summary> /// The encoding to use when sending / receiving strings. /// </summary> public Encoding Encoding { get; set; } = Encoding.ASCII; /// <summary> /// An enumerable collection of all the currently connected tcp clients /// </summary> public IEnumerable<TcpClientSocket> TcpClients { get { foreach (Client client in this._clients.Values) { yield return client.TcpClient; } } } /// <summary> /// Starts the TCP Server listening for new clients. /// </summary> public void Start(int port) { var localAddr = IPAddress.Parse("0.0.0.0"); _tcpListener = new TcpListener(localAddr, port); this._tcpListener.Start(); this._tcpListener.BeginAcceptTcpClient(AcceptTcpClientCallback, null); } /// <summary> /// Stops the TCP Server listening for new clients and disconnects /// any currently connected clients. /// </summary> public void Stop() { this._tcpListener.Stop(); lock (this._clients) { foreach (Client client in this._clients.Values) { client.TcpClient.Client.Dispose(); } this._clients.Clear(); } } public void CloseClient(string sessionId) { } /// <summary> /// Writes a string to a given TCP Client /// </summary> /// <param name="sessionId">The client to write to</param> /// <param name="data">The string to send.</param> public void SendMessage(string sessionId, string data) { byte[] bytes = this.Encoding.GetBytes(data); SendMessage(sessionId, bytes); } /// <summary> /// Writes a byte array to a given TCP Client /// </summary> /// <param name="sessionId">The client to write to</param> /// <param name="bytes">The bytes to send</param> public void SendMessage(string sessionId, byte[] bytes) { NetworkStream networkStream = _clients[sessionId].TcpClient.GetStream(); networkStream.BeginWrite(bytes, 0, bytes.Length, WriteCallback, _clients[sessionId].TcpClient); } /// <summary> /// Callback for the write opertaion. /// </summary> /// <param name="result">The async result object</param> private void WriteCallback(object sender, SocketAsyncEventArgs e) { //Write Complete. } /// <summary> /// Callback for the accept tcp client opertaion. /// </summary> /// <param name="result">The async result object</param> private void AcceptTcpClientCallback(TcpClientSocket result) { var tcpClient = result; byte[] buffer = new byte[tcpClient.ReceiveBufferSize]; var client = new Client(tcpClient, buffer); lock (this._clients) { this._clients.Add(client.SessionId, client); } NetworkStream networkStream = client.NetworkStream; string remoteIPAddress = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString(); if (OnClientConnection != null) OnClientConnection(client.SessionId, remoteIPAddress); networkStream.BeginRead(client.Buffer, 0, client.Buffer.Length, ReadCallback, client); _tcpListener.BeginAcceptTcpClient(AcceptTcpClientCallback, null); } /// <summary> /// Callback for the read opertaion. /// </summary> /// <param name="result">The async result object</param> private void ReadCallback(Object sender, SocketAsyncEventArgs e) { if (sender == null) return; if (e == null) return; Client client = (Client)sender; NetworkStream networkStream = client.TcpClient.GetStream(); int read = e.BytesTransferred; if (read == 0) { lock (this._clients) { this._clients.Remove(client.SessionId); if (OnClientDisconnection != null) OnClientDisconnection(client.SessionId); return; } } string message = this.Encoding.GetString(client.Buffer, 0, read); if (OnClientMessage != null) { OnClientMessage(client.SessionId, message); } try { networkStream.BeginRead(client.Buffer, 0, client.Buffer.Length, ReadCallback, client); } catch { } } } /// <summary> /// Internal class to join the TCP client and buffer together /// for easy management in the server /// </summary> internal class Client { /// <summary> /// Constructor for a new Client /// </summary> /// <param name="tcpClient">The TCP client</param> /// <param name="buffer">The byte array buffer</param> public Client(TcpClientSocket tcpClient, byte[] buffer) { tcpClient.ReceiveBufferSize = 65535; if (tcpClient == null) throw new ArgumentNullException("tcpClient"); if (buffer == null) throw new ArgumentNullException("buffer"); this.TcpClient = tcpClient; this.Buffer = buffer; this.SessionId = Guid.NewGuid().ToString(); } /// <summary> /// Gets the TCP Client /// </summary> public TcpClientSocket TcpClient { get; private set; } /// <summary> /// Gets the Buffer. /// </summary> public byte[] Buffer { get; private set; } /// <summary> /// Gets the network stream /// </summary> public NetworkStream NetworkStream { get { return TcpClient.GetStream(); } } public string SessionId { get; private set; } } } <file_sep>#include "mbed.h" #include "flightModule.h" int ProcessStabilityMode (int * control, flightModule * fm) { return 0; }<file_sep>#include "I3C.h" #include "mbed.h" I3C::I3C() { ; } I3C::I3C(I2C * i2c, int baseAddress) { _baseAddress = baseAddress; setI2c(i2c); } void I3C::setI2c(I2C * i2c) { _i2c = i2c; _i2c->frequency(400000); } void I3C::setBaseAddress (int baseAddress) { _baseAddress = baseAddress; } int I3C::read(int address) { char c = address; _i2c->write((_baseAddress << 1), &c, 1); // 0xFE ensure that the MSB bit is being set to zero (RW=0 -> Writing) _i2c->read((_baseAddress << 1), &c, 1); return c; } int I3C::write(int address, char value) { char c[2]; c[0] = address; c[1] = value; return _i2c->write((_baseAddress << 1), c, 2); }<file_sep>#pragma once //required to use mbed functions #include "mbed.h" #include "ProxiArray.h" #define CM_DIVISOR 58 #define BUFFER_SIZE 20 class Sensor { private: //friend class HCSR04; InterruptIn _echo_int; // pin to receive echo signal float buffer[BUFFER_SIZE]; int buff_pos; short * buff; bool err; Timer timer; float value; // to store the last pulse length bool isWaiting; void incr_buff_pos() { if (buff_pos == BUFFER_SIZE -1) { buff_pos = 0; } else { buff_pos++; } } void timer_start() { this->timer.start(); } void calc_measurement() { value = timer.read_us(); buffer[buff_pos] = value; int sum = 0; for (int i = 0; i < BUFFER_SIZE; i++) { sum += buffer[i]; } float aver = sum/BUFFER_SIZE; *buff = (short)((aver / CM_DIVISOR) * 10); incr_buff_pos(); this->timer.stop(); this->timer.reset(); } public: Sensor(PinName echo, short * b) : _echo_int(echo) { // _pass the names to the pin configuration err = false; buff = b; _echo_int.rise(this, &Sensor::timer_start); _echo_int.fall(this, &Sensor::calc_measurement); isWaiting = false; buff_pos = 0; for (int i = 0; i < BUFFER_SIZE; i++) { buffer[i] = 0; } } };<file_sep>using System; using System.Net.Sockets; using System.Text; using System.Threading; using HeadSpin.CommonLib.Comms.TcpSocket; namespace HeadSpin.CommonLib.Comms { /// <summary> /// Event driven TCP client wrapper /// </summary> public class TcpClient : IDisposable,ITcpClient { #region Delegates public event ConnectionHandler OnConnection; public event DisconnectionHandler OnDisconnection; public event MessageHandler OnMessage; public event StateChangeHandler OnStateChange; #endregion #region Constants private const int ReceiveTimeout = 5000; //Default to 5 seconds on all timeouts private const int SendTimeout = 5000; //Default to 5 seconds on all timeouts private const int ConnectTimeout = 5000; //Default to 5 seconds on all timeouts private const int ReconnectInterval = 2000; //Default to 2 seconds reconnect attempt rate #endregion #region Variables private readonly Timer _receiveTimeout = null; private readonly Timer _sendTimeout = null; private readonly Timer _connectTimeout = null; private string _sessionId; #endregion #region Constructor public TcpClient() { _receiveTimeout = new Timer(ReceiveTimeoutElapsed, null, ReceiveTimeout, Timeout.Infinite); _connectTimeout = new Timer(ConnectTimeoutElapsed, null, ConnectTimeout, Timeout.Infinite); _sendTimeout = new Timer(SendTimeoutElapsed, null, SendTimeout, Timeout.Infinite); ConnectionState = State.NeverConnected; } #endregion #region Private methods/Event Handlers private void SendTimeoutElapsed(object state) { ConnectionState = State.SendFailTimeout; DisconnectByHost(); } private void ReceiveTimeoutElapsed(object state) { ConnectionState = State.ReceiveFailTimeout; DisconnectByHost(); } private void ConnectTimeoutElapsed(object state) { ConnectionState = State.ConnectFailTimeout; DisconnectByHost(); } private void DisconnectByHost() { ConnectionState = State.DisconnectedByHost; _receiveTimeout.Change(Timeout.Infinite, Timeout.Infinite); if (_autoReconnect) Reconnect(); } private void Reconnect() { if (ConnectionState == State.Connected) return; ConnectionState = State.AutoReconnecting; try { _client.Disconnect(); } catch { } } #endregion #region Public Methods public string Start(string hostName, int portNum, bool autoReconnect = true) { _hostName = hostName; _port = portNum; _autoReconnect = autoReconnect; _client = new TcpClientSocket(AddressFamily.InterNetwork); _sessionId = Guid.NewGuid().ToString(); Connect(); return _sessionId; } /// <summary> /// Try connecting to the remote host /// </summary> public void Connect() { if (ConnectionState == State.Connected) return; ConnectionState = State.Connecting; _connectTimeout.Change(ConnectTimeout, Timeout.Infinite); _client.BeginConnect(_hostName, _port, Connect, _client.Client); } /// <summary> /// Try disconnecting from the remote host /// </summary> public void CloseConnection() { if (ConnectionState != State.Connected) return; _client.Disconnect(); _autoReconnect = false; } /// <summary> /// Try sending a string to the remote host /// </summary> /// <param name="data">The data to send</param> public void SendMessage(string data) { if (ConnectionState != State.Connected) { ConnectionState = State.SendFailNotConnected; return; } var bytes = _encode.GetBytes(data); lock (SyncLock) { // _sendTimeout.Start(); // Console.WriteLine("SendMessage: " + data); } var e = new SocketAsyncEventArgs(); e.SetBuffer(bytes, 0, bytes.Length); e.Completed += SendComplete; e.AcceptSocket = _client.Client; _client.Client.SendAsync(e); //_client.Client.SendAsync(bytes, 0, bytes.Length, SocketFlags.None, out err, SendComplete, _client.Client); if (e.SocketError != SocketError.Success) { var doDcHost = new Action(DisconnectByHost); doDcHost.Invoke(); } } /// <summary> /// Try sending byte data to the remote host /// </summary> /// <param name="data">The data to send</param> public void SendMessage(byte[] data) { if (ConnectionState != State.Connected) throw new InvalidOperationException("Cannot send data, socket is not connected"); var e = new SocketAsyncEventArgs(); e.SetBuffer(data, 0, data.Length); e.Completed += SendComplete; e.AcceptSocket = _client.Client; if (!_client.Client.SendAsync(e)) { SendComplete(_client.Client, e); } } public void Dispose() { _client.Client.Dispose(); } #endregion #region Callbacks private void ConnectComplete() { if (_client.Connected) { _connectTimeout.Change(Timeout.Infinite, Timeout.Infinite); ConnectionState = State.Connected; var e = new SocketAsyncEventArgs(); e.SetBuffer(_dataBuffer, 0, _dataBuffer.Length); e.Completed += DataReceived; e.AcceptSocket = _client.Client; if (!_client.Client.ReceiveAsync(e)) { DataReceived(_client.Client, e); } //_client.Client.BeginReceive(_dataBuffer, 0, _dataBuffer.Length, SocketFlags.None, DataReceived, _client.Client); } else { ConnectionState = State.Error; } } private void DisconnectByHostComplete(IAsyncResult result) { var r = result.AsyncState as Socket; if (r == null) throw new InvalidOperationException("Invalid IAsyncResult - Could not interpret as a socket object"); if (_autoReconnect) { var doConnect = new Action(Connect); doConnect.Invoke(); } } private void Connect(object sender, SocketAsyncEventArgs e) { if (sender == null) throw new InvalidOperationException("Invalid sender object - Could not interpret as a socket object"); var sock = sender as Socket; if (e == null) throw new InvalidOperationException("Invalid SocketAsyncEventArgs - Could not interpret as a socket object"); if (sock != null && !sock.Connected) { if (_autoReconnect) { System.Threading.Tasks.Task.Delay(ReconnectInterval).Wait(); var reconnect = new Action(Connect); reconnect.Invoke(); return; } return; } var callBack = new Action(ConnectComplete); callBack.Invoke(); } private void SendComplete(object sender, SocketAsyncEventArgs e) { if (e == null) throw new InvalidOperationException("Invalid IAsyncResult - Could not interpret as a socket object"); if (sender == null) throw new InvalidOperationException("Invalid IAsyncResult - Could not interpret as a socket object"); var r = sender; if (e.SocketError != SocketError.Success) { var doDcHost = new Action(DisconnectByHost); doDcHost.Invoke(); } else { lock (SyncLock) { _sendTimeout.Change(Timeout.Infinite, Timeout.Infinite); } } } private void Connection(IAsyncResult result) { var r = result.AsyncState as TcpClient; if (r == null) throw new InvalidOperationException("Invalid IAsyncResult - Could not interpret as a EDTC object"); r.OnConnection.EndInvoke(result); } private void Disconnection(IAsyncResult result) { var r = result.AsyncState as TcpClient; if (r == null) throw new InvalidOperationException("Invalid IAsyncResult - Could not interpret as a EDTC object"); r.OnDisconnection.EndInvoke(result); } private void ChangeConnectionStateComplete(IAsyncResult result) { var r = result.AsyncState as TcpClient; if (r == null) throw new InvalidOperationException("Invalid IAsyncResult - Could not interpret as a EDTC object"); r.OnStateChange.EndInvoke(result); } private void DataReceived(object sender, SocketAsyncEventArgs e) { if (sender == null) throw new InvalidOperationException("Invalid IASyncResult - Could not interpret as a socket"); var sock = sender as Socket; if (e == null) throw new InvalidOperationException("Invalid IASyncResult - Could not interpret as a socket"); int bytes = e.BytesTransferred; if (bytes == 0 || e.SocketError != SocketError.Success) { lock (SyncLock) { _receiveTimeout.Change(ReceiveTimeout, Timeout.Infinite); return; } } lock (SyncLock) { _receiveTimeout.Change(Timeout.Infinite, Timeout.Infinite); } if (OnMessage != null) OnMessage.BeginInvoke(_sessionId, _encode.GetString(_dataBuffer, 0, bytes), DataRecievedCallbackComplete, this); } private void DataRecievedCallbackComplete(IAsyncResult result) { var r = result.AsyncState as TcpClient; if (r == null) throw new InvalidOperationException("Invalid IAsyncResult - Could not interpret as EDTC object"); r.OnMessage.EndInvoke(result); var e = new SocketAsyncEventArgs(); e.SetBuffer(_dataBuffer, 0, _dataBuffer.Length); e.Completed += DataReceived; e.AcceptSocket = _client.Client; if (!_client.Client.ReceiveAsync(e)) { DataReceived(_client.Client, e); } } public String GetStateStr() { String stateStr; switch (_state) { case State.NeverConnected: stateStr = "Never Connected "; break; case State.Connecting: stateStr = "Connecting "; break; case State.Connected: stateStr = "Connected "; break; case State.AutoReconnecting: stateStr = "Reconnecting "; break; case State.DisconnectedByUser: stateStr = "Disconnected by user "; break; case State.DisconnectedByHost: stateStr = "Disconnected by host "; break; case State.ConnectFailTimeout: stateStr = "Connection timeout "; break; case State.ReceiveFailTimeout: stateStr = "Recieve timeout "; break; case State.SendFailTimeout: stateStr = "Send timeout "; break; case State.SendFailNotConnected: stateStr = "Send - not connected "; break; case State.Error: stateStr = "Error "; break; default: throw new ArgumentOutOfRangeException(); } return stateStr; } #endregion #region Properties and members private string _hostName; private State _state; private TcpClientSocket _client; private readonly byte[] _dataBuffer = new byte[5000]; private bool _autoReconnect; private int _port; private readonly Encoding _encode = Encoding.ASCII; private readonly object _syncLock = new object(); /// <summary> /// Syncronizing object for asyncronous operations /// </summary> public object SyncLock { get { return _syncLock; } } /// <summary> /// Current state that the connection is in /// </summary> private State ConnectionState { get { return _state; } set { State previousState = _state; if (value != _state) { _state = value; if (_state == State.Connected) if (OnConnection != null) OnConnection.BeginInvoke(_sessionId, Connection, this); if (previousState == State.Connected) if (OnDisconnection != null) OnDisconnection.BeginInvoke(_sessionId, Disconnection, this); if (OnStateChange != null) OnStateChange.BeginInvoke(_sessionId, GetStateStr(), _state, ChangeConnectionStateComplete, this); } } } #endregion } }<file_sep>#include "gyro.h" #include "mbed.h" #include <vector> #include <map> #include "ex_fmod.h" gyro::gyro(PinName inter_pin, double * buffer, double * accel_orie, bool * accel_orie_ready, I2C * i2c) : inter(inter_pin) { _i3c = new I3C(i2c, GYR_I2C_ADDR); setup = true; setup_counter = 0; for (int i = 0; i < GYR_SETUP_SAMPLE_SIZE; i++) { setup_buffer_x[i] = 0; setup_buffer_y[i] = 0; setup_buffer_z[i] = 0; } for (int i = 0; i < GYR_BUFFER_SIZE; i++) { buffer_x[i] = 0; buffer_y[i] = 0; buffer_z[i] = 0; } x_base_offset = 0.0; y_base_offset = 0.0; z_base_offset = 0.0; actual_fx = 0.0; actual_fy = 0.0; actual_fz = 0.0; _buffer = buffer; _accel_orie = accel_orie; _accel_orie_ready = accel_orie_ready; buffer_count = 0; } int gyro::init() { if (_i3c->read(GYR_ID_REG) != GYR_I2C_ADDR) return 2; //Check that the ID is correct for this chip if (_i3c->write(GYR_PWRM_REG, 0x80) < 0) return 3; //Write to Power Management to reset the chip if (_i3c->write(GYR_DLPFS_REG, 0x1B) < 0) return 4;//set the range and lowpass filter if ((_i3c->read(GYR_DLPFS_REG) & (~0xE0)) != 0x1b) return 5;//check that it was correctly if (_i3c->write(GYR_SMPLRT_REG, GYR_FREQUENCY - 1) < 0) return 6; //set the sample rate if (_i3c->read(GYR_SMPLRT_REG) != GYR_FREQUENCY - 1) return 7;//check that it set correctly. if (_i3c->write(GYR_INT_CFG_REG, 0x01) < 0) return 8; //set so we get interrupts for raw data if (_i3c->read(GYR_INT_CFG_REG) != 0x01) return 10; if (_i3c->write(GYR_PWRM_REG, 0x00) < 0) return 9; //set power management back to normal wait(0.5); inter.rise(this, &gyro::update); return 0; } void gyro::update() { if (setup && setup_counter < GYR_SETUP_SAMPLE_SIZE) { setup_buffer_x[setup_counter] = rawX(); setup_buffer_y[setup_counter] = rawY(); setup_buffer_z[setup_counter] = rawZ(); setup_counter++; if (setup_counter == GYR_SETUP_SAMPLE_SIZE) { vector<int> listx; map<int, int> tablex; vector<int> listy; map<int, int> tabley; vector<int> listz; map<int, int> tablez; //float x_temp = 0; //float y_temp = 0; //float z_temp = 0; for (int i = 0; i < GYR_SETUP_SAMPLE_SIZE; i++) { if (!tablex.count(setup_buffer_x[i])) { tablex[setup_buffer_x[i]] = 1; listx.push_back(setup_buffer_x[i]); } else { tablex[setup_buffer_x[i]] = tablex[setup_buffer_x[i]]++; } if (!tabley.count(setup_buffer_y[i])) { //printf("adding new val: %i\n", setup_buffer_y[i]); tabley[setup_buffer_y[i]] = 1; listy.push_back(setup_buffer_y[i]); } else { tabley[setup_buffer_y[i]] = tabley[setup_buffer_y[i]]++; //printf("incrementing val: %i, %i\n", setup_buffer_y[i], tabley[setup_buffer_y[i]]); } if (!tablez.count(setup_buffer_z[i])) { tablez[setup_buffer_z[i]] = 1; listz.push_back(setup_buffer_z[i]); } else { tablez[setup_buffer_z[i]] = tablez[setup_buffer_z[i]]++; } } int highestx = 0; int highesty = 0; int highestz = 0; for (int i = 0; i < listx.size(); i++) { if (tablex[listx[i]] > tablex[highestx]) { highestx = listx[i]; } } //printf("listy.size(): %i\n", listy.size()); for (int i = 0; i < listy.size(); i++) { //printf("tabley[%i[%i]] > tabley[%i]?: %i .. %i\n", listy[i], i, highesty, tabley[listy[i]], tabley[highesty]); if (tabley[listy[i]] > tabley[highesty]) { //printf("new highest: %i, %i, %i\n", listy[i], i, tabley[listy[i]]); highesty = listy[i]; } } for (int i = 0; i < listz.size(); i++) { if (tablez[listz[i]] > tablez[highestz]) { highestz = listz[i]; } } x_base_offset = highestx; y_base_offset = highesty; z_base_offset = highestz; setup = false; } } else { // buffer_x[buffer_count] = rawX() - x_base_offset; // buffer_y[buffer_count] = rawY() - y_base_offset; // buffer_z[buffer_count] = rawZ() - z_base_offset; velPitch = ((rawY() - y_base_offset)/32768.0) * 2000; velRoll = ((rawX() - x_base_offset)/32768.0) * 2000; velYaw = ((rawZ() - z_base_offset)/32768.0) * 2000; //printf("%i, %f, %i\n",rawY(), velPitch, y_base_offset); //printf("GP: %f, GR: %f, GY: %f\n", velPitch,velRoll, velYaw); // buffer_count++; // if (buffer_count >= GYR_BUFFER_SIZE) // { // double ave_x = 0; // double ave_y = 0; // double ave_z = 0; // for (int i = 0; i < GYR_BUFFER_SIZE; i++) // { // ave_x += buffer_x[i]; // ave_y += buffer_y[i]; // ave_z += buffer_z[i]; // } // double x_val = ave_x/GYR_BUFFER_SIZE; // double y_val = ave_y/GYR_BUFFER_SIZE; // double z_val = ave_z/GYR_BUFFER_SIZE; // velPitch = (y_val/32768.0) * 2000; // velRoll = (x_val/32768.0) * 2000; // velYaw = (z_val/32768.0) * 2000; // } // if(x_val < 0) // { // ave_x = ceil(x_val); // } // else // { // ave_x = floor(x_val); // } // if (y_val < 0) // { // ave_y = ceil(y_val); // } // else // { // ave_y = floor(y_val); // } // if (z_val < 0) // { // ave_z = ceil(z_val); // } // else // { // ave_z = floor(z_val); // } // actual_fx = (actual_fx+(ave_x * GYR_UPDATE_TIME/1000.0)/4); //divide by 1000 to convert from ms to seconds. // actual_fy = (actual_fy+(ave_y * GYR_UPDATE_TIME/1000.0)/4); // actual_fz = ex_fmod((actual_fz+(ave_z * GYR_UPDATE_TIME/1000.0)/4), 360); // if (_accel_orie_ready != 0 && * _accel_orie_ready) // { // if (actual_fx > 180.0) // { // actual_fx = -(ex_fmod(actual_fx,180)); // } // if (actual_fy > 180.0) // { // actual_fy = -(ex_fmod(actual_fy,180)); // } // actual_fx = 0.5*actual_fx + 0.5*(_accel_orie[0]); // actual_fy = 0.5*actual_fy + 0.5*(_accel_orie[1]); // } // if (actual_fx < -180.0) // { // actual_fx = 180 + (actual_fx + 180.0); // } // else if (actual_fx > 180.0) // { // actual_fx = (actual_fx - 180.0) - 180; // } // if (actual_fy < -180.0) // { // actual_fy = 180 + (actual_fy + 180.0); // } // else if (actual_fy > 180.0) // { // actual_fy = (actual_fy - 180.0) - 180; // } // _buffer[0] = actual_fx; // _buffer[1] = actual_fy; // _buffer[2] = actual_fz; // *_accel_orie_ready = false; // buffer_count = 0; // } //std::cout << "rawx: " << rawX() << "x_base_offset: " << x_base_offset << "\n"; //std::cout << "rawy: " << rawY() << "y_base_offset: " << y_base_offset << "\n"; //std::cout << "rawz: " << rawZ() << "z_base_offset: " << z_base_offset << "\n"; } } short gyro::rawX() { short value = _i3c->read(GYR_XLSB_REG); value |= _i3c->read(GYR_XMSB_REG) << 8; return value; } short gyro::rawY() { short value = _i3c->read(GYR_YLSB_REG); value |= _i3c->read(GYR_YMSB_REG) << 8; return value; } short gyro::rawZ() { short value = _i3c->read(GYR_YMSB_REG); value |= _i3c->read(GYR_ZMSB_REG) << 8; return value; } double gyro::gPitch() { return velPitch; } double gyro::gRoll() { return velRoll; } double gyro::gYaw() { return velYaw; } <file_sep>using System; namespace HeadSpin.CommonLib.Comms { public enum State { NeverConnected, Connecting, Connected, AutoReconnecting, DisconnectedByUser, DisconnectedByHost, ConnectFailTimeout, ReceiveFailTimeout, SendFailTimeout, SendFailNotConnected, Error } public delegate void ConnectionHandler(string sessionId); public delegate void DisconnectionHandler(string sessionId); public delegate void MessageHandler(string sessionId, String message); public delegate void StateChangeHandler(string sessionId, String stateMessage, State state); public interface ITcpClient { event ConnectionHandler OnConnection; event DisconnectionHandler OnDisconnection; event MessageHandler OnMessage; event StateChangeHandler OnStateChange; string Start(string hostName, int portNum, bool autoReconnect = true); void Connect(); void CloseConnection(); void SendMessage(string data); void SendMessage(byte[] data); void Dispose(); } } <file_sep>using System; using HeadSpin.CommonLib.Logging; using System.Threading; namespace HeadSpin.CommonLib.Comms { public class IoClientInterface { private const Char EndofMessageChar = (char)0x2; private const string HeartbeatMessage = "HB"; private const int HeartbeatPeriod = 30; // Seconds public delegate void ConnectionHandler(string sessionId); public event ConnectionHandler OnConnection; public delegate void DisconnectionHandler(string sessionId); public event DisconnectionHandler OnDisconnection; public delegate void MessageHandler(string sessionId, String message); public event MessageHandler OnMessage; public delegate void StateChangeHandler(string sessionId, String stateMessage, State state); public event StateChangeHandler OnStateChange; private readonly Char _endOfMessage; private readonly TimeSpan _heartbeatPeriod; private Timer _heartbeatTimer; private ILoggers _logger; private ITcpClient _tcpClient; private string _rxMessage = ""; public IoClientInterface(ILoggers logger, ITcpClient tcpClient, char endOfMessageChar = EndofMessageChar) { _logger = logger; _tcpClient = tcpClient; Initialise(); _endOfMessage = endOfMessageChar; _heartbeatPeriod = TimeSpan.FromSeconds(HeartbeatPeriod); _heartbeatTimer = new Timer(HeartbeatTimerElapsed,null, 0, (int)_heartbeatPeriod.TotalMilliseconds); //_heartbeatTimer.Elapsed += HeartbeatTimerElapsed; //_heartbeatTimer.Interval = _heartbeatPeriod.TotalMilliseconds; //_heartbeatTimer.Start(); } private void Initialise() { _tcpClient.OnConnection += _tcpClient_OnConnection; _tcpClient.OnDisconnection += _tcpClient_OnDisconnection; _tcpClient.OnMessage += _tcpClient_OnMessage; _tcpClient.OnStateChange +=_tcpClient_OnStateChange; } public string StartTcpClient(string hostName, int tcpPort) { return _tcpClient.Start(hostName, tcpPort, true); } public void CloseConnection() { _tcpClient.CloseConnection(); } public void SendMessage(String message) { _tcpClient.SendMessage(message + _endOfMessage); } void _tcpClient_OnMessage(string sessionId, string message) { HandleMessage(sessionId, message); } void _tcpClient_OnDisconnection(string sessionId) { if (OnDisconnection != null) OnDisconnection(sessionId); } void _tcpClient_OnConnection(string sessionId) { if (OnConnection != null) OnConnection(sessionId); } void _tcpClient_OnStateChange(string sessionId, String stateMessage, State state) { if (OnStateChange != null) OnStateChange(sessionId, stateMessage, state); } void HandleMessage(string sessionId, string message) { try { _rxMessage += message; string[] msgs = _rxMessage.Split(_endOfMessage); for (int i = 0; i < msgs.Length; i++) { if (i == msgs.Length - 1) { // If the last message == "" then the second to last message // was complete (with an _endOfMessage char on end) // else if the last message != "" then it is not a complete msg, // as there was no _endOfMessage on the end, so just set the RxMessage to the last message if (msgs[i] != "") _rxMessage = msgs[i]; else _rxMessage = ""; } else if (msgs[i] != "") if (OnMessage != null) { string msg = msgs[i]; OnMessage(sessionId, msg); } } } catch (Exception except) { _logger.LogError("IoClientInterface", "HandleMessage", "Exception: " + except); } } private void HeartbeatTimerElapsed(object args) { SendMessage(HeartbeatMessage); } } } <file_sep>#pragma once #include "mbed.h" #include "Buzzer.h" class MotorControl { public: MotorControl(PinName * pins, short * err_state) { _err_state = err_state; for (int i = 0; i < 6; i++) { motors[i] = new PwmOut(pins[i]); motors[i]->period(0.0021); pulsewidth(i, 10); wait(0.01); pulsewidth(i,0); } } int init(Buzzer * buzz) { if (buzz == NULL) return -1; for (int i = 0; i < 6; i++) { if (motors[i] == NULL) return -1; pulsewidth(i,0); wait(0.1); buzz->beep_once(); pulsewidth(i,35); wait(0.5); pulsewidth(i,0); wait(0.1); } if (_err_state == NULL) return -1; return 0; } void pulsewidth (int motor, int percent) { int useconds = (percent * 10) + 1000; if (motors[motor] == NULL) *_err_state = 5; //printf("%f, ",(float(useconds))/1000000.0); motors[motor]->pulsewidth((float(useconds))/1000000.0); } private: short * _err_state; PwmOut * motors[6]; }; <file_sep>#pragma once #include "mbed.h" #include "flightModule.h" #define THROTTLE_THRESH 5 #define YAW 0; #define THRO 1; #define ROLL 2; #define PITCH 3; #define FR 0; #define R_ 1; #define BR 2; #define BL 3; #define L_ 4; #define FL 5; #define PID_YAW 0; #define PID_ROLL 1; #define PID_PITCH 2; int AcrobaticInit(); int ProcessAcrobaticMode(short * remote,flightModule * fm, short * motors); <file_sep>#pragma once #include "mbed.h" #include "PwmIn.h" #include "AnalogIn.h" //#include "Buzzer.h" class RemoteController { private: PwmIn _Yaw; PwmIn _Thro; PwmIn _Pitch; PwmIn _Roll; short * _err_state; short * buffer; public: RemoteController(short * buff, PinName Yaw, PinName Thro, PinName Roll, PinName Pitch, short * err_state) : _Yaw(Yaw, buff), _Thro(Thro, buff + 1), _Pitch(Pitch, buff + 2), _Roll( Roll, buff + 3) { buffer = buff; _err_state = err_state; } int init(DigitalOut * Led) //Buzzer * buzz) { //if (buzz == NULL) return -1; wait_ms(50); *Led = 1; //buzz->long_beep(); wait(1.5); _Thro.isThro(); _Thro.init(); while (true) { wait_ms(100); if (_Thro.status() == 1) break; if (_Thro.status() == -1) return -1; } *Led = 0; //buzz->beep_once(); while (true) { wait_ms(100); if (_Thro.status() == 0) break; if (_Thro.status() == -1) return -1; } *Led = 1; //buzz->beep_twice(); _Yaw.init(); while (true) { wait_ms(100); if (_Yaw.status() == 1) break; if (_Yaw.status() == -1) return -1; } *Led = 0; //buzz->beep_once(); while (true) { wait_ms(100); if (_Yaw.status() == 0) break; if (_Yaw.status() == -1) return -1; } *Led = 1; //buzz->beep_twice(); _Roll.init(); while (true) { wait_ms(100); if (_Roll.status() == 1) break; if (_Roll.status() == -1) return -1; } *Led = 0; //buzz->beep_once(); while (true) { wait_ms(100); if (_Roll.status() == 0) break; if (_Roll.status() == -1) return -1; } *Led = 1; //buzz->beep_twice(); _Pitch.init(); while (true) { wait_ms(100); if (_Pitch.status() == 1) break; if (_Pitch.status() == -1) return -1; } *Led = 0; //buzz->beep_once(); while (true) { wait_ms(100); if (_Pitch.status() == 0) break; if (_Pitch.status() == -1) return -1; } *Led = 1; //buzz->beep_thrice(); if (!_Yaw.status() && !_Thro.status() && !_Pitch.status() && !_Roll.status()) return 0; return -1; } }; <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.Net; using System.Threading; using System.Threading.Tasks; namespace HeadSpin.CommonLib.Comms.TcpSocket { public class TcpListener { public delegate void AcceptTcpClientCallback(TcpClientSocket newClient); private event AcceptTcpClientCallback TcpClientCallback; private Socket _socket; private IPEndPoint _localEndPoint; private SocketAsyncEventArgs _socket_args; private readonly int MAX_PENDING_CONNECTIONS = 5; public TcpListener(IPAddress localIpAddress, int port) { _socket_args = new SocketAsyncEventArgs(); _localEndPoint = new IPEndPoint(localIpAddress, port); _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.Bind(_localEndPoint); _socket_args.Completed += _socket_args_Completed; } public void Start() { _socket.Listen(MAX_PENDING_CONNECTIONS); } public void Stop() { _socket.Dispose(); } public void BeginAcceptTcpClient(AcceptTcpClientCallback callback, Object state) { TcpClientCallback -= callback; TcpClientCallback += callback; if (!_socket.AcceptAsync(_socket_args)) { new Task(() => { _socket_args_Completed(_socket, _socket_args); }).Start(); } } private void _socket_args_Completed(object sender, SocketAsyncEventArgs e) { if (TcpClientCallback != null) { TcpClientCallback(new TcpClientSocket(e.AcceptSocket)); } } } public class TcpClientSocket { private bool _connected = false; public bool Connected { get { return _connected; } } private Socket _socket = null; private AddressFamily _type = AddressFamily.Unspecified; private NetworkStream _stream = null; public Socket Client { get { return _socket; } } public int ReceiveBufferSize { get; set; } = 8192; public TcpClientSocket(Socket socket) { _socket = socket; _stream = new NetworkStream(this); } public TcpClientSocket(AddressFamily type) { _type = type; } public NetworkStream GetStream() { return _stream; } public void BeginConnect(String hostname, int port, EventHandler<SocketAsyncEventArgs> callback, Socket sock) { SocketAsyncEventArgs e = new SocketAsyncEventArgs(); e.Completed += ConnectCompleted; e.Completed += callback; e.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(hostname), port); if (!_socket.ConnectAsync(e)) { ConnectCompleted(_socket, e); } } public void ConnectCompleted(object sender, SocketAsyncEventArgs e) { if (e.SocketError == SocketError.Success) { _connected = true; } } public void Disconnect() { _connected = false; _socket.Shutdown(SocketShutdown.Both); } } public class NetworkStream { public delegate void ReadStreamCallback(object client, SocketAsyncEventArgs events); private event ReadStreamCallback ReadCallback; public delegate void WriteStreamCallback(object client, SocketAsyncEventArgs events); private event WriteStreamCallback WriteCallback; private object temp_read_client = null; private object temp_write_client = null; private TcpClientSocket _tcpClientSocket; public NetworkStream(TcpClientSocket sock) { _tcpClientSocket = sock; } public void BeginRead(byte[] buffer, int offset, int size, ReadStreamCallback callback, object client) { temp_read_client = client; ReadCallback -= callback; ReadCallback += callback; SocketAsyncEventArgs e = new SocketAsyncEventArgs(); e.Completed += receive_Completed; e.SetBuffer(buffer, offset, size); e.AcceptSocket = _tcpClientSocket.Client; if (!_tcpClientSocket.Client.ReceiveAsync(e)) { receive_Completed(_tcpClientSocket.Client, e); } } private void receive_Completed(object client, SocketAsyncEventArgs e) { if (ReadCallback != null) { ReadCallback(temp_read_client, e); } } public void BeginWrite(byte[] buffer, int offset, int size, WriteStreamCallback callback, object client) { temp_write_client = client; WriteCallback -= callback; WriteCallback += callback; SocketAsyncEventArgs e = new SocketAsyncEventArgs(); e.Completed += send_Completed; e.SetBuffer(buffer, offset, size); e.AcceptSocket = _tcpClientSocket.Client; if (!_tcpClientSocket.Client.SendAsync(e)) { send_Completed(_tcpClientSocket.Client, e); } } private void send_Completed(object client, SocketAsyncEventArgs e) { if (WriteCallback != null) { WriteCallback(temp_write_client, e); } } } } <file_sep>#include "mbed.h" #include "ProxiArray.h" #include "RemoteController.h" #include "BatteryLevel.h" #include "MotorControl.h" #include "Buzzer.h" #define MAX_WAIT 10 DigitalOut led1(LED1); DigitalOut led2(LED2); DigitalOut led3(LED3); DigitalOut led4(LED4); Serial pc(USBTX, USBRX); Serial NUCLEO(p13, p14); Timeout safeGuard; extern "C" void mbed_reset(); short counter = 0; short res_err_cnt = 0; int send_message; #pragma pack(push, 1) struct { short header; short proxies[8]; //timer interrupt/interrupt in short control[4]; //interrupt in short batt; // interrupt of main thread check. short err_state; } Msg; #pragma pack(pop) short const MSG_HEADER = 39; int const msg_size = sizeof(Msg); bool rec_msg = false; #pragma pack(push, 1) struct { short header; short motor_speeds[6]; short buzz_val; } Rec; #pragma pack(pop) short const REC_HEADER = 26; int const rec_size = sizeof(Rec); char * buffer; int buff_pos; /** * Sensor declarations: * * Pins are set here refer to individual sensor packages for what pins do. * * **/ //PinName proxi_pins [9] = {p5,p6,p7,p8,p9,p10,p11,p12,p13}; //proxis TRIG, FR, R, BR, BL, L, FL, T, B //ProxiArray pa(Msg.proxies, proxi_pins, &Msg.err_state); PinName motor_pins[6] = {p26, p25, p24, p23, p22, p21}; MotorControl motors(motor_pins, &Msg.err_state); RemoteController rc(Msg.control, p15, p16, p17, p18, &Msg.err_state); //pins: Aile, Elev, Thro, Rudd BatteryLevel bl(p20, &Msg.err_state); Buzzer buzz(p19); void safeGuardOff() { for (int i = 0; i < 6; i++) { motors.pulsewidth(i, 0); } } void init() { char * msg_array = (char *)&Msg; for (int i = 0; i < msg_size; i++) { msg_array[i] = 0; } Msg.header = MSG_HEADER; if (rc.init(&buzz) != 0 && Msg.err_state == 0) Msg.err_state = 4; led1 = 1; if (motors.init(&buzz) != 0) Msg.err_state = 5; led2 = 2; //if (bl.init(&buzz) != 0 && Msg.err_state == 0) Msg.err_state = 3; led3 = 3; //if (pa.init(&buzz) != 0 && err_state == 0) Msg.err_state = 2; led4 = 4; buff_pos = 0; } int main() { pc.baud(115200); NUCLEO.baud(921600); printf("HEXACOPTER MBED SOFTWARE\n"); init(); wait(1); NUCLEO.putc('S'); wait(0.01); while(1) { safeGuard.attach(&safeGuardOff, 0.2); if (counter == 100) { counter = 0; led1 = !led1; if (Msg.err_state != 5 && !rec_msg) { led2 = !led1; } else if (Msg.err_state != 5) { led2 = 0; } rec_msg = false; switch (Msg.err_state) { case 2: led3 = !led1; if (led3 == 1) buzz.beep_once(); led2 = 0; led4 = 0; break; case 3: led2 = !led1; led3 = !led1; if (led3 == 1) buzz.beep_twice(); led4 = 0; break; case 4: led4 = !led1; if (led4 == 1) buzz.beep_thrice(); led2 = 0; led3 = 0; break; case 5: led4 = !led1; led3 = !led1; led2 = !led1; if (led4 == 1) buzz.long_beep(); if (res_err_cnt >= MAX_WAIT) { res_err_cnt = 0; mbed_reset(); } res_err_cnt++; break; default: led2 = 0; led3 = 0; led4 = 0; break; } } Msg.batt = bl.GetLevel(); char * msg_array = (char *)&Msg; for (int i = 0; i < msg_size; i++) { NUCLEO.getc(); NUCLEO.putc(msg_array[i]); } buffer = (char *) &Rec; while (!NUCLEO.readable()); for (int i = 0; i < rec_size; i++) { buffer[i] = NUCLEO.getc(); } for (int i = 0; i < 6; i++) { motors.pulsewidth(i,Rec.motor_speeds[i]); } switch (Rec.buzz_val) { case 0: //do nothing. break; case 1: buzz.beep_once(); break; case 2: buzz.beep_twice(); break; case 3: buzz.beep_thrice(); break; case 4: buzz.long_beep(); break; default: //do nothing. break; } counter++; safeGuard.detach(); } return 0; } <file_sep>#include "mbed.h" #include "AcrobaticMode.h" #include "rx_mbed.h" #include "PID.h" PID * pids[3]; int AcrobaticInit() { pids[2] = new PID(0.4,0.0,0.0,0.02);//Kp, kI, kD pids[1] = new PID(0.5,0.0,0.0,0.02); pids[0] = new PID(0.0,0.0,0.0,0.02); for (int i = 0; i < 3; i++) { pids[i]->setOutputLimits(0,50); pids[i]->setInputLimits(-50,50); } return 0; } int ProcessAcrobaticMode(short * remote, flightModule * fm, short * motors) { if (remote[1] > THROTTLE_THRESH) { pids[2]->setProcessValue((-fm->gyroPitch()) - remote[3]); pids[1]->setProcessValue((-fm->gyroRoll()) - remote[2]); long pitch_output = pids[2]->compute(); long roll_output = pids[1]->compute(); //long yaw_output = pids[0]->get_pid(fm->gyroYaw() - remote[0], 1); //printf("PIDS: %i, %i, %i\n", pitch_output, roll_output, yaw_output); //printf("P: %i, R: %i, Y: %i\n",remote[3], remote[2], remote[0]); //printf("GP: %f, GR: %f, GY: %f\n", fm->gyroPitch(), fm->gyroRoll(), fm->gyroYaw()); motors[5] = remote[1] - pitch_output - (roll_output/2); //+ yaw_output; motors[3] = remote[1] + pitch_output - (roll_output/2); //+ yaw_output; motors[0] = remote[1] - pitch_output + (roll_output/2); //- yaw_output; motors[2] = remote[1] + pitch_output + (roll_output/2); //- yaw_output; motors[1] = remote[1] + roll_output; // + yaw_output; motors[4] = remote[1] - roll_output; // - yaw_output; } else { for (int i = 0; i < 6; i++) { motors[i] = 0; } } return 0; } <file_sep>#pragma once #include "mbed.h" #include "I3C.h" int const GYR_I2C_ADDR = 0x68; int const GYR_ID_REG = 0x00; int const GYR_SMPLRT_REG = 0x15; int const GYR_DLPFS_REG = 0x16; int const GYR_INT_CFG_REG = 0x17; int const GYR_INT_STAT_REG = 0x1A; int const GYR_PWRM_REG = 0x3E; int const GYR_XMSB_REG = 0x1D; int const GYR_XLSB_REG = 0x1E; int const GYR_YMSB_REG = 0x1F; int const GYR_YLSB_REG = 0x20; int const GYR_ZMSB_REG = 0x21; int const GYR_ZLSB_REG = 0x22; int const GYR_SETUP_SAMPLE_SIZE = 100; int const GYR_BUFFER_SIZE = 5; int const GYR_FREQUENCY = 5; //in ms int const GYR_UPDATE_TIME = GYR_BUFFER_SIZE * GYR_FREQUENCY; class gyro { I3C * _i3c; double * _buffer; InterruptIn inter; double * _accel_orie; bool * _accel_orie_ready; bool setup; int setup_counter; double velPitch; double velRoll; double velYaw; double setup_buffer_x[GYR_SETUP_SAMPLE_SIZE]; double setup_buffer_y[GYR_SETUP_SAMPLE_SIZE]; double setup_buffer_z[GYR_SETUP_SAMPLE_SIZE]; double buffer_x[GYR_BUFFER_SIZE]; double buffer_y[GYR_BUFFER_SIZE]; double buffer_z[GYR_BUFFER_SIZE]; short buffer_count; short x_base_offset; short y_base_offset; short z_base_offset; double actual_fx; double actual_fy; double actual_fz; void update(); short rawX(); short rawY(); short rawZ(); public: double gPitch(); double gRoll(); double gYaw(); gyro(PinName inter_pin, double * buffer, double * accel_orie, bool * accel_orie_ready, I2C * i2c); ~gyro() { delete _i3c; } int init(); }; <file_sep>#include "mbed.h" #include "math.h" #include "accel.h" #include "I3C.h" accel::accel(PinName inter_pin, double * buffer, double * orie_buffer, bool * orie_ready, I2C * i2c) : inter(inter_pin) { _i3c = new I3C(i2c, ACCEL_I2C_ADDR); _buffer = buffer; _orie_buffer = orie_buffer; _orie_ready = orie_ready; } int accel::init() { if (_i3c->read(ACCEL_ID_REG) != ACCEL_ID_VAL) return 1; if (_i3c->write(ACCEL_CTRL_REG1, 0x02) < 0) return 2; // reset chip wait_ms(1000); if (_i3c->write(ACCEL_CTRL_REG1, 0x10) < 0) return 3; // set writable printf("%i",_i3c->read(ACCEL_CTRL_REG1)); if (_i3c->read(ACCEL_CTRL_REG1) != 0x10) return 4; //check if (_i3c->write(ACCEL_CTRL_REG3, 0x03) < 0) return 5; // range and bandwidth bits: xxx rr bbb //range: // 0x00 = +-2gs // 0x01 = +-4gs // 0x10 = +-8gs //bw: // 0x000 = 25Hz // 0x001 = 50Hz // 0x010 = 100Hz // 0x011 = 190Hz // 0x100 = 375Hz // 0x101 = 750Hz // 0x110 = 1500Hz if (_i3c->read(ACCEL_CTRL_REG3) != 0x03) return 6; // check if (_i3c->write(ACCEL_CTRL_REG2, 0x60) < 0) return 7; if (_i3c->read(ACCEL_CTRL_REG2) != 0x60) return 8; if (_i3c->write(ACCEL_ANY_MOT_THRES, 0x00) < 0) return 9; if (_i3c->read(ACCEL_ANY_MOT_THRES) != 0x00) return 10; if (_i3c->write(ACCEL_ANY_MOT_DUR, 0x00) < 0) return 11; if (_i3c->read(ACCEL_ANY_MOT_DUR) != 0x00) return 12; if (_i3c->write(ACCEL_CTRL_REG4, 0x20) < 0) return 19; // new_data_int = 1 (bit 5) if (_i3c->read(ACCEL_CTRL_REG4) != 0x20) return 20; // check inter.rise(this, &accel::update); return 0; } void accel::update() { double x = rawX(); double y = rawY(); double z = rawZ(); double rez = atan2(y,z) * 180/M_PI; if (rez < 0) rez = rez + 180; else if (rez > 0) rez = rez - 180; _orie_buffer[0] = rez; // roll _orie_buffer[1] = atan2(-x, sqrt(y*y + z*z)) * 180/M_PI; //pitch * _orie_ready = true; _buffer[0] = x; _buffer[1] = y; _buffer[2] = z; } float accel::rawX() { short value = (_i3c->read(ACCEL_XLSB_REG) >> 6) & 0x03; short temp = 0; temp = _i3c->read(ACCEL_XMSB_REG) << 8; temp = temp >> 6; value |= temp; value -= ACCEL_X_OFF_VAL; value *= ACCEL_X_GAIN_VAL; return (value/1024.0) * 4; } float accel::rawY() { short value = (_i3c->read(ACCEL_XMSB_REG >> 6) & 0x03); short temp = 0; temp = _i3c->read(ACCEL_YMSB_REG) << 8; temp = temp >> 6; value |= temp; value += ACCEL_Y_OFF_VAL; value *= ACCEL_Y_GAIN_VAL; return (value/1024.0) * 4; } float accel::rawZ() { short value = (_i3c->read(ACCEL_YMSB_REG >> 6) & 0x03); short temp = 0; temp = _i3c->read(ACCEL_ZMSB_REG) << 8; temp = temp >> 6; value |= temp; value -= ACCEL_Z_OFF_VAL; value *= ACCEL_Z_GAIN_VAL; return (value/1024.0) * 4; } <file_sep>#include "RemoteController.h" <file_sep>using System; using System.IO; using Polenter.Serialization; namespace HeadSpin.CommonLib.Serialisation { public static class BinarySerialisation { static readonly SharpSerializer _serializer = new SharpSerializer(true); public static string BinarySerialiseObject(object obj) { var stream = new MemoryStream(); _serializer.Serialize(obj, stream); return Convert.ToBase64String(stream.ToArray()); } public static object BinaryDeserialiseObject(string objString) { byte[] bytes = Convert.FromBase64String(objString); var memStream = new MemoryStream(bytes); return _serializer.Deserialize(memStream); } } } <file_sep>#pragma once #include "mbed.h" #include "PwmIn.h" #include "Buzzer.h" class RemoteController { private: PwmIn _Yaw; PwmIn _Thro; PwmIn _Pitch; PwmIn _Roll; short * _err_state; short * buffer; public: RemoteController(short * buff, PinName Yaw, PinName Thro, PinName Roll, PinName Pitch, short * err_state) : _Yaw(Yaw, buff), _Thro(Thro, buff + 1), _Pitch(Pitch, buff + 2), _Roll(Roll, buff + 3) { buffer = buff; _err_state = err_state; } int init(Buzzer * buzz) { if (buzz == NULL) return -1; wait_ms(50); buzz->long_beep(); wait(1.5); _Thro.isThro(); _Thro.init(); while (true) { wait_ms(100); if (_Thro.status() == 1) break; if (_Thro.status() == -1) return -1; } buzz->beep_once(); while (true) { wait_ms(100); if (_Thro.status() == 0) break; if (_Thro.status() == -1) return -1; } buzz->beep_twice(); _Yaw.init(); while (true) { wait_ms(100); if (_Yaw.status() == 1) break; if (_Yaw.status() == -1) return -1; } buzz->beep_once(); while (true) { wait_ms(100); if (_Yaw.status() == 0) break; if (_Yaw.status() == -1) return -1; } buzz->beep_twice(); _Roll.init(); while (true) { wait_ms(100); if (_Roll.status() == 1) break; if (_Roll.status() == -1) return -1; } buzz->beep_once(); while (true) { wait_ms(100); if (_Roll.status() == 0) break; if (_Roll.status() == -1) return -1; } buzz->beep_twice(); _Pitch.init(); while (true) { wait_ms(100); if (_Pitch.status() == 1) break; if (_Pitch.status() == -1) return -1; } buzz->beep_once(); while (true) { wait_ms(100); if (_Pitch.status() == 0) break; if (_Pitch.status() == -1) return -1; } buzz->beep_thrice(); if (!_Yaw.status() && !_Thro.status() && !_Pitch.status() && !_Roll.status()) return 0; return -1; } };<file_sep>#pragma once #include "mbed.h" #include <vector> class I3C { public: I2C * _i2c; int _baseAddress; I3C(); I3C(I2C * i2c, int baseAddress); void setI2c (I2C * i2c); void setBaseAddress (int baseAddress); int read(int address); int write(int address, char value); };<file_sep>// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- /// @file PID.h /// @brief Generic PID algorithm, with EEPROM-backed storage of constants. #ifndef __PID_H__ #define __PID_H__ #include <math.h> // for fabs() #include "mbed.h" #ifndef M_PI #define M_PI 3.14159265358979323846 #endif /// @class PID /// @brief Object managing one PID control class PID { public: PID(const float & initial_p = 0.0, const float & initial_i = 0.0, const float & initial_d = 0.0, const int & initial_imax = 0) { //AP_Param::setup_object_defaults(this, var_info); _kp = initial_p; _ki = initial_i; _kd = initial_d; _imax = initial_imax; t.start(); // set _last_derivative as invalid when we startup _last_derivative = NAN; } /// Iterate the PID, return the new control value /// /// Positive error produces positive output. /// /// @param error The measured error value /// @param scaler An arbitrary scale factor /// /// @returns The updated control output. /// float get_pid(float error, float scaler = 1.0); // get_pid() constrained to +/- 4500 int get_pid_4500(float error, float scaler = 1.0); /// Reset the PID integrator /// void reset_I(); /// Load gain properties /// //void load_gains(); /// Save gain properties /// //void save_gains(); /// @name parameter accessors //@{ /// Overload the function call operator to permit relatively easy initialisation void operator () (const float p, const float i, const float d, const int imaxval) { _kp = p; _ki = i; _kd = d; _imax = imaxval; } float kP() const { return _kp; } float kI() const { return _ki; } float kD() const { return _kd; } int imax() const { return _imax; } void kP(const float v) { _kp = v; } void kI(const float v) { _ki = v; } void kD(const float v) { _kd = v; } void imax(const int v) { _imax = abs(v); } float get_integrator() const { return _integrator; } private: float _kp; float _ki; float _kd; int _imax; Timer t; float _integrator;///< integrator value float _last_error;///< last error for derivative float _last_derivative;///< last derivative for low-pass filter int _last_t;///< last time get_pid() was called in millis float _get_pid(float error, int dt, float scaler); /// Low pass filter cut frequency for derivative calculation. /// /// 20 Hz becasue anything over that is probably noise, see /// http://en.wikipedia.org/wiki/Low-pass_filter. /// static const int _fCut = 20; inline float constrain_float(float x, float a, float b) { if (x<a) { return a; } else if (x>b) { return b; } else { return x; } } }; #endif<file_sep>#include "flightModule.h" flightModule::flightModule(PinName * I2C_pins, PinName * inter_pins, double * attitude, double * velocity, double * altitude) : _i2c(I2C_pins[0], I2C_pins[1]), g(inter_pins[1], attitude, _accel_attitude, _accel_ready, &_i2c), a(inter_pins[0], velocity, _accel_attitude, _accel_ready, &_i2c) { _inter_pins = inter_pins; _attitude = attitude; _velocity = velocity; _altitude = altitude; } int flightModule::init() { //printf("g: %i\n", );//, a: %i\n", g.init(), a.init()); g.init(); return 0;//g.init() + a.init(); } double flightModule::gyroPitch() { return g.gPitch(); } double flightModule::gyroRoll() { return g.gRoll(); } double flightModule::gyroYaw() { return g.gYaw(); } <file_sep>using System; using System.Collections.Generic; using System.Threading; using HeadSpin.CommonLib.Logging; namespace HeadSpin.CommonLib.Comms { public class IoServerInterface { private const Char EndofMessageChar = (char) 0x2; private const string HeartbeatMessage = "HB"; private const int HeartbeatPeriod = 30; // Seconds public delegate void ConnectionHandler(string sessionId, string remoteIpAddress, Boolean reconnection); public event ConnectionHandler OnConnection; public delegate void DisconnectionHandler(string sessionId); public event DisconnectionHandler OnDisconnection; public delegate void MessageHandler(string sessionId, String message); public event MessageHandler OnMessage; private Timer _timeoutTimer; private readonly Char _endOfMessage; private readonly TimeSpan _timeoutPeriod; private IIoServer _ioServer; private readonly SortedDictionary<string, Connection> _clients = new SortedDictionary<string, Connection>(); private ILoggers _logger; public IoServerInterface(ILoggers logger, IIoServer ioServer, char endOfMessageChar = EndofMessageChar) { _logger = logger; _ioServer = ioServer; Initialise(); _timeoutPeriod = TimeSpan.FromSeconds(HeartbeatPeriod*2); _endOfMessage = endOfMessageChar; _timeoutTimer = new Timer(TimeoutTimerElapsed,null,0, (int)TimeSpan.FromSeconds(10).TotalMilliseconds); } private void Initialise() { _ioServer.OnClientConnection += OnClientConnection; _ioServer.OnClientDisconnection += OnClientDisconnection; _ioServer.OnClientMessage += OnClientMessage; } public void StartServer(int tcpPort) { _ioServer.Start(tcpPort); } public void StopServer() { _ioServer.Stop(); } public void CloseClient(String sessionId) { if (_clients.ContainsKey(sessionId)) _ioServer.CloseClient(sessionId); } public void SendMessage(string sessionId, String message) { if (_clients.ContainsKey(sessionId)) _ioServer.SendMessage(sessionId, message + _endOfMessage); } void OnClientConnection(string sessionId, string remoteIpAddress) { HandleConnection(sessionId, remoteIpAddress, false); } void HandleConnection(string sessionId, string remoteIpAddress, Boolean reconnection) { if (_clients.ContainsKey(sessionId)) { Connection con = _clients[sessionId]; con.RxMessage = ""; con.LastActivityTime = DateTime.UtcNow; _clients[sessionId] = con; } else { Connection con = new Connection(); con.RxMessage = ""; con.LastActivityTime = DateTime.UtcNow; _clients.Add(sessionId, con); } if (OnConnection != null) OnConnection(sessionId, remoteIpAddress, reconnection); } void OnClientDisconnection(string sessionId) { HandleDisconnection(sessionId); } void HandleDisconnection(string sessionId) { if (_clients.ContainsKey(sessionId)) _clients.Remove(sessionId); if (OnDisconnection != null) OnDisconnection(sessionId); } void OnClientMessage(string sessionId, string message) { HandleMessage(sessionId, message); } void HandleMessage(string sessionId, string message) { try { String[] msgs; Connection con = _clients[sessionId]; con.RxMessage += message; con.LastActivityTime = DateTime.UtcNow; _clients[sessionId] = con; msgs = con.RxMessage.Split(_endOfMessage); for (int i = 0; i < msgs.Length; i++) { if (i == msgs.Length - 1) { con = _clients[sessionId]; // If the last message == "" then the second to last message // was complete (with an _endOfMessage char on end) // else if the last message != "" then it is not a complete msg, // as there was no _endOfMessage on the end, so just set the RxMessage to the last message if (msgs[i] != "") con.RxMessage = msgs[i]; else con.RxMessage = ""; _clients[sessionId] = con; } else if (msgs[i] != "") if (OnMessage != null) { string msg = msgs[i]; if (msg == HeartbeatMessage) SendMessage(sessionId, HeartbeatMessage); OnMessage(sessionId, msg); } } } catch (Exception ex) { _logger.LogError("IoServerInterface", "HandleMessage", "Exception: " + ex); } } void TimeoutTimerElapsed(object sender) { foreach (var client in _clients) { if (DateTime.UtcNow - client.Value.LastActivityTime > _timeoutPeriod) { CloseClient(client.Key); } } } private struct Connection { public string RxMessage; public DateTime LastActivityTime { get; set; } } } } <file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading; using System.Threading.Tasks; using Windows.Devices.Enumeration; using Windows.Devices.SerialCommunication; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Storage.Streams; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using HeadSpin.DroneMon.LibDroneMon; using HeadSpin.CommonLib.Comms; using HeadSpin.CommonLib.Serialisation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace HeadSpin.DroneMon.RPiDroneMon { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { /// <summary> /// Private variables /// </summary> private SerialDevice serialPort = null; DataWriter dataWriteObject = null; DataReader dataReaderObject = null; NucleoDeserialiser deserialiser = null; //IoServerInterface serverInt = new IoServerInterface(logger, new TcpServer(9374)); private Boolean Connected = false; private Boolean Reading = false; private ObservableCollection<DeviceInformation> listOfDevices; private CancellationTokenSource ReadCancellationTokenSource; public MainPage() { this.InitializeComponent(); serialDeviceConnectBtn.IsEnabled = false; listOfDevices = new ObservableCollection<DeviceInformation>(); deserialiser = new NucleoDeserialiser(); deserialiser.QueueUpdated += Deserialiser_QueueUpdated; ListAvailablePorts(); } private void Deserialiser_QueueUpdated(Queue<NucleoStatus> statusQueue) { while (statusQueue.Count > 0) { NucleoStatus status = statusQueue.Dequeue(); //Debug.WriteLine(status.ToString() + " Added to Queue!"); Control1.Text = status.RemoteControllerValues[0].ToString(); Control2.Text = status.RemoteControllerValues[1].ToString(); Control3.Text = status.RemoteControllerValues[2].ToString(); Control4.Text = status.RemoteControllerValues[3].ToString(); header.Text = status.Header.ToString(); } } /// <summary> /// ListAvailablePorts /// - Use SerialDevice.GetDeviceSelector to enumerate all serial devices /// - Attaches the DeviceInformation to the ListBox source so that DeviceIds are displayed /// </summary> private async void ListAvailablePorts() { try { listOfDevices.Clear(); string aqs = SerialDevice.GetDeviceSelector(); var dis = await DeviceInformation.FindAllAsync(aqs); Debug.WriteLine("Listing Devices..."); for (int i = 0; i < dis.Count; i++) { Debug.WriteLine(dis[i].Id); listOfDevices.Add(dis[i]); } DeviceListSource.Source = listOfDevices; if (dis.Count >= 0) { serialDeviceList.SelectedIndex = 0; serialDeviceConnectBtn.IsEnabled = true; } else { serialDeviceList.SelectedIndex = -1; serialDeviceConnectBtn.IsEnabled = false; } } catch (Exception ex) { Debug.WriteLine("ex.Message"); } } private async void serialDeviceConnectBtn_Click(object sender, RoutedEventArgs e) { if (!Connected) {//Connect!! DeviceInformation selection = (DeviceInformation)serialDeviceList.SelectedItem; if (selection == null) { serialDeviceConnectBtn.IsEnabled = false; return; } try { serialPort = await SerialDevice.FromIdAsync(selection.Id); serialDeviceConnectBtn.Content = "Disconnect"; // Configure serial settings serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000); serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000); serialPort.BaudRate = 921600; serialPort.Parity = SerialParity.None; serialPort.StopBits = SerialStopBitCount.One; serialPort.DataBits = 8; // Display configured settings Debug.WriteLine("Serial port configured successfully!\n ----- Properties ----- "); Debug.WriteLine("BaudRate: " + serialPort.BaudRate.ToString()); Debug.WriteLine("DataBits: " + serialPort.DataBits.ToString()); Debug.WriteLine("Handshake: " + serialPort.Handshake.ToString()); Debug.WriteLine("Parity: " + serialPort.Parity.ToString()); Debug.WriteLine("StopBits: " + serialPort.StopBits.ToString()); ReadCancellationTokenSource = new CancellationTokenSource(); Reading = true; dataReaderObject = new DataReader(serialPort.InputStream); ReadAsync(ReadCancellationTokenSource.Token); nucleoConnectionStatus.Text = "Connected"; Connected = true; } catch (Exception ex) { //Disconnect. Reading = false; Debug.WriteLine(ex.Message); CancelReadTask(); serialDeviceConnectBtn.Content = "Connect"; nucleoConnectionStatus.Text = "Disconnected"; Connected = false; if (serialPort != null) { serialPort.Dispose(); serialPort = null; } } } else { try { Reading = false; CancelReadTask(); if (serialPort != null) { serialPort.Dispose(); serialPort = null; } serialDeviceConnectBtn.Content = "Connect"; nucleoConnectionStatus.Text = "Disconnected"; Connected = false; ListAvailablePorts(); } catch (Exception ex) { Debug.WriteLine(ex.Message); } } } /// <summary> /// ReadAsync: Task that waits on data and reads asynchronously from the serial device InputStream /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> private async Task ReadAsync(CancellationToken cancellationToken) { Task<UInt32> loadAsyncTask; uint ReadBufferLength = 1024; // If task cancellation was requested, comply cancellationToken.ThrowIfCancellationRequested(); // Set InputStreamOptions to complete the asynchronous read operation when one or more bytes is available dataReaderObject.InputStreamOptions = InputStreamOptions.Partial; while (Reading) { // Create a task object to wait for data on the serialPort.InputStream loadAsyncTask = dataReaderObject.LoadAsync(ReadBufferLength).AsTask(cancellationToken); // Launch the task and wait UInt32 bytesRead = await loadAsyncTask; if (bytesRead > 0) { Byte[] bytes = new Byte[bytesRead]; dataReaderObject.ReadBytes(bytes); deserialiser.deserialise(bytes); //rcvdText.Text = System.Text.Encoding.Unicode.GetString(bytes);//dataReaderObject.ReadString(bytesRead); Debug.WriteLine("Bytes read successfully!"); } } } /// <summary> /// CancelReadTask: /// - Uses the ReadCancellationTokenSource to cancel read operations /// </summary> private void CancelReadTask() { if (ReadCancellationTokenSource != null) { if (!ReadCancellationTokenSource.IsCancellationRequested) { ReadCancellationTokenSource.Cancel(); } } } } } <file_sep>#include "ex_fmod.h" #include <math.h> float ex_fmod(float a, float b) { double ret = fmod(a, b); if (ret < 0.0) ret += b; return ret; } <file_sep>#pragma once //required to use mbed functions #include "mbed.h" #include "global_defs.h" #include "Sensor.h" #include "Buzzer.h" #define TRIGGER_DELAY 12 // length of trigger signal expected by HCSR04 sensor class ProxiArray { private: short * _err_state; friend class Sensor; Sensor * sensors[NUM_SENSORS]; friend class IO; int numSensors; Ticker trig; DigitalOut trigger_out; // pin to send the trigger signal void trigger(); bool running; public: ProxiArray (short * buffer, PinName * Echo, short * err_state); ~ProxiArray (); int init(Buzzer * buzz); };<file_sep>#include "ProxiArray.h" ProxiArray::ProxiArray (short * buffer, PinName * pins, short * err_state): trigger_out(pins[0]) { _err_state = err_state; for (int i = 1; i < 9; i++) { sensors[i] = new Sensor(pins[i], buffer + i - 1); } running = false; trig.attach(this,&ProxiArray::trigger,0.1); } ProxiArray::~ProxiArray () { for (int i = 1; i < NUM_SENSORS; i++) { delete sensors[i]; } } int ProxiArray::init(Buzzer * buzz) { if (buzz == NULL) return -1; if (running) return 0; return -1; } void ProxiArray::trigger() { running = true; trigger_out.write(1); wait_us(TRIGGER_DELAY); trigger_out.write(0); } <file_sep>#pragma once #include "gyro.h" #include "accel.h" //#include "bar.h" //#include "comp.h" class flightModule { I2C _i2c; PinName * _inter_pins; double * _attitude; double * _velocity; double * _altitude; gyro g; accel a; double _accel_attitude[2]; bool _accel_ready[1]; //bar b; //comp c; public: flightModule(PinName * I2C_pins, PinName * inter_pins, double * attitude, double * velocity, double * altitude); int init(); double gyroPitch(); double gyroRoll(); double gyroYaw(); }; <file_sep>#pragma once #include "mbed.h" #include "I3C.h" #ifndef M_PI #define M_PI 3.14159265358979323846 #endif int const ACCEL_I2C_ADDR = 0x38; int const ACCEL_ID_VAL = 0x02; int const ACCEL_ID_REG = 0x00; int const ACCEL_VERSION = 0x01; int const ACCEL_XLSB_REG = 0x02; int const ACCEL_XMSB_REG = 0x03; int const ACCEL_YLSB_REG = 0x04; int const ACCEL_YMSB_REG = 0x05; int const ACCEL_ZLSB_REG = 0x06; int const ACCEL_ZMSB_REG = 0x07; int const ACCEL_TEMP_REG = 0x08; int const ACCEL_STS_REG = 0x09; int const ACCEL_CTRL_REG1 = 0x0A; int const ACCEL_CTRL_REG2 = 0x0B; int const ACCEL_LG_THRES = 0x0C; int const ACCEL_LG_DUR = 0x0D; int const ACCEL_HG_THRES = 0x0E; int const ACCEL_HG_DUR = 0x0F; int const ACCEL_ANY_MOT_THRES = 0x10; int const ACCEL_ANY_MOT_DUR = 0x11; int const ACCEL_CR1 = 0x12; int const ACCEL_CR2 = 0x13; int const ACCEL_CTRL_REG3 = 0x14; int const ACCEL_CTRL_REG4 = 0x15; int const ACCEL_GAIN_X = 0x16; int const ACCEL_GAIN_Y = 0x17; int const ACCEL_GAIN_Z = 0x18; int const ACCEL_GAIN_T = 0x19; int const ACCEL_OFFSET_X = 0x1A; int const ACCEL_OFFSET_Y = 0x1B; int const ACCEL_OFFSET_Z = 0x1C; int const ACCEL_OFFSET_T = 0x1D; int const ACCEL_X_OFF_VAL = 0x12; int const ACCEL_Y_OFF_VAL = 0x18; int const ACCEL_Z_OFF_VAL = 0x40; float const ACCEL_X_GAIN_VAL = 1.06; float const ACCEL_Y_GAIN_VAL = 1.04; float const ACCEL_Z_GAIN_VAL = 1.02; class accel { I3C * _i3c; double * _buffer; double * _orie_buffer; bool * _orie_ready; InterruptIn inter; void update(); public: accel (PinName inter_pin, double * buffer, double * orie_buffer, bool * orie_ready, I2C * i2c); ~accel () { delete _i3c; } int init(); float rawX(); float rawY(); float rawZ(); }; <file_sep>using System; namespace HeadSpin.CommonLib.Comms { public delegate void ClientConnectionHandler(string sessionId, string remoteIpAddress); public delegate void ClientDisconnectionHandler(string sessionId); public delegate void ClientMessageHandler(string sessionId, String message); public interface IIoServer { event ClientConnectionHandler OnClientConnection; event ClientDisconnectionHandler OnClientDisconnection; event ClientMessageHandler OnClientMessage; void Start(int portNum); void Stop(); void CloseClient(string sessionId); void SendMessage(string sessionId, string data); void SendMessage(string sessionId, byte[] data); } }
fa332d98158c984a639e97525d831dad4984baec
[ "C#", "C", "C++", "INI" ]
41
C
scottyjoe9/SJDrone
c8f977f4c7d6d866f2ba68015270902268e6a876
21a5f64a2095edc2fb3e016b032f23bfbb537b7c
refs/heads/master
<file_sep>import React from 'react'; import Header from './components/Header'; import {BrowserRouter, Route} from 'react-router-dom'; import HomePage from './pages/Home'; import TodoPage from './pages/Todo'; import UsersPage from './pages/Users'; import UserDetailPage from './pages/UserDetail'; class App extends React.Component { render() { return ( <div> <BrowserRouter> <Header/> <Route component={HomePage} path={"/home"} /> <Route component={TodoPage} path={"/todo"} /> <Route component={UsersPage} path={"/users"} /> <Route component={UserDetailPage} path={"/user/:id"} /> </BrowserRouter> </div> ); } } export default App;
dfcf17f4af9e389a4d6aead0aeadc6d04c933ab0
[ "JavaScript" ]
1
JavaScript
recepgums/todo-ders
7993385f869c95076b06f884087fab3f0c4db527
57b5087670b0bdbb3f9da979f8694c4f8a231fbf
refs/heads/main
<file_sep>####### Simple Flask ###### #!/user/bin/python __author__ = "Midhunkumar" __version__ = "1.0.1" __status__ = "Prod" ############################# from flask import Flask, request app = Flask(__name__) @app.route("/", methods =["GET","POST","COPY","PUT"]) def home(): if request.method == "GET": return "This is GET Request" elif request.method == "POST": return "This is POST Method" else : return "this is " + request.method + " Method" if __name__ == "__main__": app.run(debug=True)
ff68a395d69165774ce8f4e83c76f4b7fbf73b7c
[ "Python" ]
1
Python
midhunkumar22/test
0594d0410c650b4c68ef6d983555e88ec7ea8f20
9f7bf3ed95c22a6dec3f7aa33eeb6d2cc11b0340
refs/heads/master
<file_sep>import React, { Component } from 'react' class SideMenuLayout extends Component { constructor(props) { super(props) this.state = { contentOpen: true } } toggleSideMenu = () => { this.setState({ contentOpen: !this.state.contentOpen }) } render() { const { contentOpen } = this.state return ( <div className="side-menu-layout"> <div className="main-side"> <div className="title">Flexbox</div> <ul> <li> <a href=""> <i className="material-icons">dashboard</i> Dashboard </a> </li> <li> <a href=""> <i className="material-icons">insert_chart</i> Statistics </a> </li> <li className="active"> <a href=""> <i className="material-icons">donut_small</i> Milestones </a> </li> <li> <a href=""> <i className="material-icons">bug_report</i> Experiments </a> </li> <li> <a href=""> <i className="material-icons">desktop_windows</i> Previews </a> </li> <li> <a href=""> <i className="material-icons">insert_drive_file</i> Assets </a> </li> <li> <a href=""> <i className="material-icons">settings</i> Settings </a> </li> <li> <a href=""> <i className="material-icons">call_made</i> Logout </a> </li> </ul> </div> <div className={`main-content ${contentOpen ? 'open' : ''}`}> <div className="header"> <button onClick={this.toggleSideMenu}><i className="material-icons">menu</i></button> </div> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quam nesciunt accusamus, sequi! Nam sapiente ullam alias, quam iste neque adipisci dolorem, nisi nobis accusantium sit cupiditate natus quis eaque pariatur! </div> </div> ) } } export default SideMenuLayout<file_sep>import React, { Component } from 'react' import DiceLayout from './components/DiceLayout' import ImageGalleryLayout from './components/ImageGalleryLayout' import CardLayout from './components/CardLayout' import MadnessLayout from './components/MadnessLayout' import ColorPaletteLayout from './components/ColorPaletteLayout' import SideMenuLayout from './components/SideMenuLayout' import Playground from './components/Playground' class App extends Component { render() { return ( <div className="App"> {/* header */} <div className="pg-header"> Flexbox Playground </div> <Playground /> {/* footer */} <div className="pg-footer"> CTF Studio </div> </div> ) } } export default App <file_sep>import React, { Component } from 'react' class ImageGalleryLayout extends Component { render() { return ( <div className="image-gallery-layout"> <div> <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/jeremiah-wilson-1.jpg" alt="" /> </div> <div> <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/jeremiah-wilson-2.jpg" alt="" /> </div> <div> <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/jeremiah-wilson-3.jpg" alt="" /> </div> <div> <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/jeremiah-wilson-4.jpg" alt="" /> </div> <div> <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/jeremiah-wilson-5.jpg" alt="" /> </div> </div> ) } } export default ImageGalleryLayout<file_sep># flex-playground 學習 Flexbox 做的的專案 <file_sep>import React, { Component } from 'react'; class DiceLayout extends Component { render() { return ( <div className="dice-layout"> <div className="first-face"> <span className="pip"></span> </div> <div className="second-face"> <span className="pip"></span> <span className="pip"></span> </div> <div className="third-face"> <span className="pip"></span> <span className="pip"></span> <span className="pip"></span> </div> <div className="fourth-face"> <div className="column"> <span className="pip"></span> <span className="pip"></span> </div> <div className="column"> <span className="pip"></span> <span className="pip"></span> </div> </div> <div className="fifth-face"> <div className="column"> <span className="pip"></span> <span className="pip"></span> </div> <div className="column"> <span className="pip"></span> </div> <div className="column"> <span className="pip"></span> <span className="pip"></span> </div> </div> <div className="sixth-face"> <div className="column"> <span className="pip"></span> <span className="pip"></span> <span className="pip"></span> </div> <div className="column"> <span className="pip"></span> <span className="pip"></span> <span className="pip"></span> </div> </div> </div> ); } } export default DiceLayout;<file_sep>import React, { Component } from 'react' class CardLayout extends Component { render() { return ( <div className="card-layout"> <div className="card card-news wide"> <div className="desc">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium iste delectus unde sint voluptatum, corporis harum et nihil praesentium fugit voluptate molestiae, soluta placeat possimus facilis qui nemo dolores eos.</div> <div> <button>123</button> </div> </div> <div className="card"></div> <div className="card"></div> <div className="card"></div> <div className="card card-news wide"> <div className="desc">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium iste delectus unde sint voluptatum, corporis harum et nihil praesentium fugit voluptate molestiae, soluta placeat possimus facilis qui nemo dolores eos.</div> <div> <button>123</button> </div> </div> <div className="card card-news"> <div className="desc">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium iste delectus unde sint voluptatum, corporis harum et nihil praesentium fugit voluptate molestiae, soluta placeat possimus facilis qui nemo dolores eos.</div> <div> <button>123</button> </div> </div> <div className="card"></div> <div className="card"></div> <div className="card"></div> <div className="card"></div> <div className="card card-news"> <div className="desc">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium iste delectus unde sint voluptatum, corporis harum et nihil praesentium fugit voluptate molestiae, soluta placeat possimus facilis qui nemo dolores eos.</div> <div> <button>123</button> </div> </div> </div> ) } } export default CardLayout<file_sep>import React, { Component } from 'react' class MadnessLayout extends Component { render() { return ( <div className="madness-layout"> <div className="column"> <div className="slabel"> <div>ROUND 1</div> <div>MARCH 6</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> </div> <div className="column"> <div className="slabel"> <div>ROUND 2</div> <div>MARCH 18</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> </div> <div className="column"> <div className="slabel"> <div>ROUND 3</div> <div>MARCH 22</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> </div> <div className="column"> <div className="slabel"> <div>WEST SEMIFINALS</div> <div>MARCH 26-28</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> <div className="champ"> <i className="material-icons">stars</i> <div className="slabel"> <div>CHAMPIONSHIP</div> <div>MARCH 30 - APR 1</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> </div> <div className="xxx"> <div className="slabel"> <div>EAST SEMIFINALS</div> <div>MARCH 26-28</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> </div> </div> <div className="column"> <div className="slabel"> <div>ROUND 3</div> <div>MARCH 22</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> </div> <div className="column"> <div className="slabel"> <div>ROUND 2</div> <div>MARCH 18</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> </div> <div className="column"> <div className="slabel"> <div>ROUND 1</div> <div>MARCH 6</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> <div className="madness"> <div>Duke</div> <div>Virginia</div> </div> </div> </div> ) } } export default MadnessLayout
519928411392f45b8210f59e438512e35860f86b
[ "JavaScript", "Markdown" ]
7
JavaScript
FlyMaple/flex-playground
3f2ff42b3cce460ceeb8b34398bee978d20d4924
b99f3484428c78faf4ae2fc5f3c125bf49c8ed72
refs/heads/master
<file_sep>var express = require('express'); var router = express.Router(); var db = require('../db'); var bodyParser = require('body-parser'); var fs = require('fs'); router.use(bodyParser.json()); // for parsing application/json //router.use(bodyParser.urlencoded({extended: true})); // for parsing application/x-www-form-urlencoded /* get method for fetch all items. */ router.get('/', function(req, res, next) { var sql = "select * from innodb.Items"; // query the data base db.query(sql, function(err, rows, fields) { if (err) { return res.status(500).send({ error: 'Something failed!' }) } console.log(rows) res.json(rows) }) console.log("Client asked for items") }); /*post method for create an item*/ router.post('/create', function(req, res, next) { const id = req.body.id; const title = req.body.title; const desc = req.body.desc; const price = req.body.price; const quantity = req.body.quantity; const url = req.body.url; console.log("Client asked to add an item", req.body) const query ="INSERT INTO `innodb`.`Items` (`id`, `title`, `desc`, `price`, `img`, `quantity`) VALUES"+`('${id}', '${title}', '${desc}', '${price}', '${url}' , '${quantity}' )` console.log("query to db is:"+ query) // query the data base db.query(query,function(err, result) { if(err) { return res.status(500).send({ error: 'Something failed!' }) } res.json({'status': 'success'}) }) }); /*rest api to delete record from mysql database*/ router.delete('/delete', function(req, res, next) { console.log("Client asked to delete" , req.query.id) var sql = `DELETE FROM Items WHERE id=${req.query.id}` console.log("query to db is:"+ sql) // query the data base db.query(sql, function(err, result) { if(err) { return res.status(500).send({ error: 'Something failed!' }) } res.json({ 'status': 'success' }) }) }); /*get method for fetch single product*/ router.get('/id', function(req, res, next) { var id = req.query.id; console.log(id) var sql = `SELECT * FROM Items WHERE id=${id}`; db.query(sql, function(err, row, fields) { if(err) { return res.status(500).send({ error: 'Something failed!' }) } res.json(row[0]) }) }); /*put method for update product*/ router.put('/update/id', function(req, res, next) { console.log(req) var id = req.body.id; var quantity = (req.body.quantity) ; var sql = `UPDATE Items SET quantity="${quantity}" WHERE id=${id}`; db.query(sql, function(err, result) { if(err) { return res.status(500).send({ error: 'Something failed!' }) } res.json({'status': 'success'}) }) }); module.exports = router;<file_sep>import React, { Component } from 'react'; import './App.css'; import "bootstrap/dist/css/bootstrap.min.css"; import "shards-ui/dist/css/shards.min.css"; import { Route, Switch, BrowserRouter as Router } from 'react-router-dom' import clientHome from './components/clientHome'; import adminHome from './components/adminHome'; import Cart from './components/cart'; import Landing from './components/landing' class App extends Component { render(){ return ( <Router> <Switch> <Route exact path="/" component={Landing} /> <Route path="/adminHome" component={adminHome} /> <Route path="/clientHome" component={clientHome} /> <Route path="/cart" component={Cart} /> </Switch> </Router> ); } } export default App; <file_sep>var mysql = require('mysql'); var connection = mysql.createConnection({ host: 'aws-simple.cbuos43uuptu.us-east-1.rds.amazonaws.com', user: 'admin', password: '<PASSWORD>', database: 'innodb' }); connection.connect(function(err) { if (err) throw err; console.log('connected!'); }); // add port to listen to module.exports = connection;<file_sep>import { GET_ITEMS, ADD_ITEM, DELETE_ITEM, SEARCH_ITEMS } from './action-types/items-actions' import axios from 'axios'; export function loadItems(){ return(dispatch)=>{ return axios.get('/items', null).then((response)=>{ dispatch(getItems(response.data)); }) } } //get all items export const getItems = (data)=>{ return{ type: GET_ITEMS, data } } // add one item to db export const addItem = (item)=>{ return{ type: ADD_ITEM, item } } // delete specific item from db by its id export const deleteItem = (id)=>{ return{ type: DELETE_ITEM, id } } // client search for items export const searchItems = (search)=>{ return{ type: SEARCH_ITEMS, search } }<file_sep> import {combineReducers} from 'redux'; import items from './itemsReducer'; import cart from './cartReducer'; import auth from './authReducer'; const rootReducer = combineReducers({ items, cart, auth }) export default rootReducer;<file_sep>import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import { Provider } from 'react-redux'; import { loadItems } from './components/actions/itemsActions'; import configureStore from './store/configureStore'; const store = configureStore(); store.dispatch(loadItems()); // when app starts, initiallizing store with all items from restapi. ReactDOM.render(<Provider store={store}><App/></Provider>, document.getElementById('root'));<file_sep>import React, { Component } from 'react'; import { Link, Redirect } from 'react-router-dom' import '../App.css'; import "bootstrap/dist/css/bootstrap.min.css"; import "shards-ui/dist/css/shards.min.css"; import first from '../images/first.png'; import mid from '../images/mid.png'; import last from '../images/last.png' import monitor from '../images/monitor.svg' import { Button, Modal, ModalBody, ModalHeader, Form, FormInput, FormGroup } from "shards-react"; import { logInUser, logIn } from './actions/authActions' import { connect } from 'react-redux'; class Landing extends Component { constructor(props) { super(props); this.state = { openMadal: false, username: '', password: 0, ok: false }; } modalUp() { this.setState({ openMadal: !this.state.openMadal }); } handleSubmit = (usr, psw) => { this.props.logInUser(usr,psw) } render(){ return ( <div className="body"> <div className="home-container"> <div id="inner" style={{marginBottom: '100px'}}> <h1>Shoppop</h1> <p class="subtitle">Welcome buyer!</p> <Button style={{margin: "10px"}} onClick={()=> this.modalUp()} size='lg'> Login </Button> <Button style={{margin: "10px"}} onClick={()=> this.modalUp()} size='lg'> Signup </Button> </div> <div id="illustration"> <img src={last} alt="dash img" id="dash" class="crypto-icons"/> <img src={first} alt="iota img" id="iota" class="crypto-icons"/> <img src={mid} alt="eth img" id="eth" class="crypto-icons"/> <img src={monitor} alt="monitor img" id="monitor"/> </div> </div> <Modal open={this.state.openMadal} toggle={this.modalUp}> <ModalBody > <div className="box" > <Form> <FormGroup> <label>Username</label> <FormInput placeholder="Username" onChange={(e) => this.setState({ username: e.target.value})}/> </FormGroup> <FormGroup> <label>Password</label> <FormInput type="password" placeholder="<PASSWORD>" onChange={(e) => this.setState({ password: e.target.value})}/> </FormGroup> <Link to="/clientHome"> <Button style={{margin: "10px"}} onClick={()=> this.handleSubmit(this.state.username, this.state.password)}> submit </Button> </Link> </Form> </div> </ModalBody> </Modal> </div> ); } } const mapStateToProps = (state)=>{ return { users: state.users, } } const mapDispatchToProps = (dispatch)=>{ return{ logInUser: (username,password)=>{dispatch(logInUser(username,password))}, } } export default connect(mapStateToProps,mapDispatchToProps)(Landing); <file_sep> import { GET_ITEMS, ADD_ITEM, DELETE_ITEM, SEARCH_ITEMS } from '../actions/action-types/items-actions' import axios from 'axios'; let initState = { items: [], } const itemsReducer = (state = initState, action)=>{ switch(action.type){ case GET_ITEMS: { // get all items return action.data } case ADD_ITEM: { // by admin axios.post('/items/create', action.item); return; } case DELETE_ITEM: { // by admin axios.delete('/items/delete', { params: { id: action.id }}) return; } case SEARCH_ITEMS: { // by client return state.filter(item=> item.title.includes(action.search)) } default: return state } } export default itemsReducer <file_sep>import { LOG_IN , LOG_OUT } from './action-types/auth-actions' import axios from 'axios'; export function logInUser(usr,psw){ return(dispatch)=>{ return axios.post('/auth/login', { username: usr, password: psw} ).then((response)=>{ console.log("res=",response) dispatch(logIn(response)); }) } } //user wants to login export const logIn= (response)=>{ return{ type: LOG_IN, response } } <file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux' import {Card,CardHeader,CardImg,CardBody,CardFooter,Button,Collapse} from "shards-react"; import NavBar from './navbar' import { Icon } from 'react-icons-kit' import {angleUp} from 'react-icons-kit/fa/angleUp' import {angleDown} from 'react-icons-kit/fa/angleDown' import { removeItem,addQuantity,subtractQuantity} from './actions/cartActions' import { Link } from 'react-router-dom' class Cart extends Component{ constructor(props) { super(props); this.toggle = this.toggle.bind(this); this.state = { collapse: false }; } // showing recipe or not.. toggle() { this.setState({ collapse: !this.state.collapse }); } //to remove the item completely handleRemove = (id)=>{ this.props.removeItem(id); } //to add the quantity handleAddQuantity = (id)=>{ this.props.addQuantity(id); } //to substruct from the quantity handleSubtractQuantity = (id)=>{ this.props.subtractQuantity(id); } render(){ let total = this.props.total; let addedItems = this.props.items.length ? ( this.props.items.map(item=>{ return( <div style={{margin:'10px'}} > <Card key={item.id} small style={{ maxWidth: "300px"}}> <CardHeader>{item.title}</CardHeader> <CardImg style={{ maxHeight: "100", maxWidth:"100px", marginLeft:"50px"}} src={item.img} /> <CardBody> Price: {item.price}$ | Quantity: {item.quantity} </CardBody> <CardFooter> <Link to="/cart"><Button outline pill theme='danger' onClick={()=>this.handleRemove(item.id)}>Remove</Button></Link> <Link to="/cart"><Icon size={32} icon={angleUp} onClick={()=>{this.handleAddQuantity(item.id)}} /></Link> <Link to="/cart"><Icon size={32} icon={angleDown} onClick={()=>{this.handleSubtractQuantity(item.id)}} /></Link> </CardFooter> </Card> </div> ) }) ) : ( <p> Nothing </p> ) return( <div style={{backgroundColor:'#0f0f11'}}> <div className="App-Background"> <NavBar/> <div className="centered"><h2 style={{textDecoration:"underline",color:"white"}}>What youve ordered</h2></div> <div className="cart-containter"> {addedItems} </div> <div className="recipe"> <Button onClick={this.toggle}>Recipe</Button> <Collapse open={this.state.collapse}> <div style={{margin:'10px'}}> <h4>Order Summary ({this.props.items.length} items)</h4> <h5 style={{color:'white'}}>Order number : #1</h5> <h5 style={{color:'white'}}>Date : {new Date().getDate()+'-'+(new Date().getMonth()+1)+'-'+new Date().getFullYear()}</h5> <h5 style={{color:'white'}}>Total : {this.props.total} US$</h5> </div> </Collapse> </div> </div> </div> ) } } const mapStateToProps = (state) =>{ return{ items: state.addedItems, total: state.total } } const mapDispatchToProps = (dispatch)=>{ return{ removeItem: (id)=>{dispatch(removeItem(id))}, addQuantity: (id)=>{dispatch(addQuantity(id))}, subtractQuantity: (id)=>{dispatch(subtractQuantity(id))} } } export default connect(mapStateToProps,mapDispatchToProps)(Cart)<file_sep># Shopping Cart Demo This project is based on 3 services: - ReactJS FrontEnd - RestApi using NodeJS - mySQL db using AWS RDS services ## Demo ![ShoppingCart - Animated gif demo](demo.gif) ## Project includes: * Authentication system with JWT * Redux for managing application state * AWS services such as RDS, EC2, S3 <file_sep>var express = require('express'); var router = express.Router(); const jwt = require('jsonwebtoken'); var db = require('../db'); /* GET users listing. */ router.get('/', function(req, res, next) { res.send('respond with a resource'); }); router.post('/login', function(req, res) { console.log("a user is trying to login..") const username = req.body.username; const password = req.body.password; console.log("usr:", username); console.log("pas:", password); const user = { username, password } if (username && password) { db.query('SELECT * FROM accounts WHERE username = ? AND password = ?', [username, password], function(error, results, fields) { if (results.length > 0) { jwt.sign({user}, 'secretkey', { expiresIn: '7d' }, (err, token) => { console.log(token) res.json({ token }); }); } else { console.log("error: Inccorect Username or Password") res.status(500).send({ error: 'Inccorect Username or Password!' }) } res.end(); }); } else { console.log("error: Please enter Username and Password!") res.send('Please enter Username and Password!'); res.end(); } }); // Verify Token function verifyToken(req, res, next) { // Get auth header value const bearerHeader = req.headers['authorization']; // Check if bearer is undefined if(typeof bearerHeader !== 'undefined') { // Split at the space const bearer = bearerHeader.split(' '); // Get token from array const bearerToken = bearer[1]; // Set the token req.token = bearerToken; // Next middleware next(); } else { // Forbidden res.sendStatus(403); } } module.exports = router; /// *************************** /// router.post('/api/posts', verifyToken, (req, res) => { jwt.verify(req.token, 'secretkey', (err, authData) => { if(err) { res.sendStatus(403); } else { res.json({ message: 'Post created...', authData }); } }); });<file_sep> import { LOG_IN , LOG_OUT } from '../actions/action-types/auth-actions' import axios from 'axios'; let user = JSON.parse(localStorage.getItem('user')); const initialState = { users: [] } const authReducer = (state = initialState, action)=>{ switch(action.type){ case LOG_IN: { if(action.response.status === 200){ return action.response; } else{ return "Failed" } } default: return state } } export default authReducer
c036bf11a5b65deaff26a495ef3ca07f26c048a4
[ "JavaScript", "Markdown" ]
13
JavaScript
MeidanNasi/ShoppingCart
f4d9a5bc4af919b74a624a49dea8024a148a22f7
8508e63dcc7fc90afcc57c736ee76502c9eed3f8
refs/heads/master
<repo_name>cricketue/hadoop-cdh-pseudo-docker<file_sep>/conf/run-hadoop.sh #!/bin/bash service hadoop-hdfs-namenode start service hadoop-hdfs-datanode start sudo -u hdfs hadoop fs -mkdir -p /tmp/hadoop-yarn/staging/history/done_intermediate sudo -u hdfs hadoop fs -chown -R mapred:mapred /tmp/hadoop-yarn/staging sudo -u hdfs hadoop fs -chmod -R 1777 /tmp sudo -u hdfs hadoop fs -mkdir -p /var/log/hadoop-yarn sudo -u hdfs hadoop fs -chown yarn:mapred /var/log/hadoop-yarn service hadoop-yarn-resourcemanager start service hadoop-yarn-nodemanager start service hadoop-mapreduce-historyserver start sudo -u hdfs hadoop fs -mkdir -p /user/hdfs sudo -u hdfs hadoop fs -chown hdfs /user/hdfs # init oozie sudo -u hdfs hadoop fs -mkdir /user/oozie sudo -u hdfs hadoop fs -chown oozie:oozie /user/oozie sudo oozie-setup sharelib create -fs hdfs://localhost:8020 -locallib /usr/lib/oozie/oozie-sharelib-yarn service oozie start # init spark history server sudo -u hdfs hadoop fs -mkdir /user/spark sudo -u hdfs hadoop fs -mkdir /user/spark/applicationHistory sudo -u hdfs hadoop fs -chown -R spark:spark /user/spark sudo -u hdfs hadoop fs -chmod 1777 /user/spark/applicationHistory # init spark shared libraries # client than can use SPARK_JAR=hdfs://<nn>:<port>/user/spark/share/lib/spark-assembly.jar sudo -u spark hadoop fs -mkdir -p /user/spark/share/lib sudo -u spark hadoop fs -put /usr/lib/spark/lib/spark-assembly.jar /user/spark/share/lib/spark-assembly.jar service spark-history-server start service hue start sleep 1 # tail log directory tail -n 1000 -f /var/log/hadoop-*/*.out
c30571ca8f844ced41091c82d582d7c1606c31f4
[ "Shell" ]
1
Shell
cricketue/hadoop-cdh-pseudo-docker
c0c1a573a80a9f1f1207a79e78cde1ad440f0bd9
198566ea76aed304ff5e69057e9ca161f031e2e4
refs/heads/master
<repo_name>drbess/Python-genhash<file_sep>/README.md # Python-genhash This is a simple python program that hashes a string entered by the user. <file_sep>/Psswd_hash.py import hashlib import uuid def new_password(password): salt = uuid.uuid4().hex # The uuid generates a random number return hashlib.sha1(salt.encode() + password.encode()).hexdigest() + ':' + salt def check_password(new_password, user_password): password, salt = new_password.split(':') return password == hashlib.sha1(salt.encode() + user_password.encode()).hexdigest() new_pass = raw_input('Enter a string to be hashed: ') new_password = new_password(<PASSWORD>) # Try new_pass if all else fails print('Your new password hashed: ' + new_password)
8c6bd7debdb193eea2fb3719ab2ad8d788dc5d5a
[ "Markdown", "Python" ]
2
Markdown
drbess/Python-genhash
4ff18392fe3133bcc6b66418828e4b2db44aec88
ff292b7abb472e8cb2c0d94e683325d3092f3d1b
refs/heads/master
<repo_name>MikeHartman/simple-thread-exercise<file_sep>/README.md # simple-thread-exercise Simple Thread Technical Exercise The simplest way I can think of to treat this is how I'd probably do it without a computer (assuming I couldn't just eyeball it): mark off the days for each project on a calendar and use that to see where the gaps are. The naive code equivalent is probably iterating through every day in every project range "marking" it in a hash map. I'll do that, saving the low/high value in the map and only updating existing days if that value needs to increase. At the end I can sort the keys and iterate through them, checking for travel/full day by whether the previous and next days exist in the map. Definitely not very efficient with all those lookups, but I suspect it won't make a noticeable difference until we start processing much more data. <a href="https://mikehartman.github.io/simple-thread-exercise/index.html">Run it</a> <file_sep>/exercise_tester.js var reimbursementCalculatorTester = (function () { var _public = {}; var testSuite = [ { 'label': "Example Project Set 1", 'expected': 165, 'projects': [ { 'cost': reimbursementCalculator.getLowCost(), 'startDate': new Date(2015,08,01), 'endDate': new Date(2015,08,03) } ] },{ 'label': "Example Project Set 2", 'expected': 590, 'projects': [ { 'cost': reimbursementCalculator.getLowCost(), 'startDate': new Date(2015,08,01), 'endDate': new Date(2015,08,01) },{ 'cost': reimbursementCalculator.getHighCost(), 'startDate': new Date(2015,08,02), 'endDate': new Date(2015,08,06) },{ 'cost': reimbursementCalculator.getLowCost(), 'startDate': new Date(2015,08,06), 'endDate': new Date(2015,08,08) } ] },{ 'label': "Example Project Set 3", 'expected': 445, 'projects': [ { 'cost': reimbursementCalculator.getLowCost(), 'startDate': new Date(2015,08,01), 'endDate': new Date(2015,08,03) },{ 'cost': reimbursementCalculator.getHighCost(), 'startDate': new Date(2015,08,05), 'endDate': new Date(2015,08,07) },{ 'cost': reimbursementCalculator.getHighCost(), 'startDate': new Date(2015,08,08), 'endDate': new Date(2015,08,08) } ] },{ 'label': "Example Project Set 4", 'expected': 185, 'projects': [ { 'cost': reimbursementCalculator.getLowCost(), 'startDate': new Date(2015,08,01), 'endDate': new Date(2015,08,01) },{ 'cost': reimbursementCalculator.getLowCost(), 'startDate': new Date(2015,08,01), 'endDate': new Date(2015,08,01) },{ 'cost': reimbursementCalculator.getHighCost(), 'startDate': new Date(2015,08,02), 'endDate': new Date(2015,08,02) },{ 'cost': reimbursementCalculator.getHighCost(), 'startDate': new Date(2015,08,02), 'endDate': new Date(2015,08,03) } ] },{ 'label': "Bad Cost Test 1", 'expected': -1, 'projects': [ { 'cost': 20, 'startDate': new Date(2015,08,01), 'endDate': new Date(2015,08,03) } ] },{ 'label': "Bad Cost Test 2", 'expected': -1, 'projects': [ { 'cost': "LOW", 'startDate': new Date(2015,08,01), 'endDate': new Date(2015,08,03) } ] },{ 'label': "Bad Start Date Test", 'expected': -1, 'projects': [ { 'cost': reimbursementCalculator.getLowCost(), 'startDate': "monkey", 'endDate': new Date(2015,08,03) } ] },{ 'label': "Bad End Date Test", 'expected': -1, 'projects': [ { 'cost': reimbursementCalculator.getLowCost(), 'startDate': new Date(2015,08,01), 'endDate': -34324233432432432432 } ] },{ 'label': "Bad Date Range Test", 'expected': -1, 'projects': [ { 'cost': reimbursementCalculator.getLowCost(), 'startDate': new Date(2015,08,03), 'endDate': new Date(2015,08,01) } ] },{ 'label': "No Cost Test", 'expected': -1, 'projects': [ { 'startDate': new Date(2015,08,01), 'endDate': new Date(2015,08,03) } ] },{ 'label': "No Start Date Test", 'expected': -1, 'projects': [ { 'cost': reimbursementCalculator.getLowCost(), 'endDate': new Date(2015,08,03) } ] },{ 'label': "No End Date Test", 'expected': -1, 'projects': [ { 'cost': reimbursementCalculator.getLowCost(), 'startDate': new Date(2015,08,01) } ] },{ 'label': "Empty Start Date Test", 'expected': -1, 'projects': [ { 'cost': reimbursementCalculator.getLowCost(), 'startDate': null, 'endDate': new Date(2015,08,03) } ] },{ 'label': "Empty End Date Test", 'expected': -1, 'projects': [ { 'cost': reimbursementCalculator.getLowCost(), 'startDate': new Date(2015,08,01), 'endDate': "" } ] } ]; _public.runTests = function () { var output = ""; testSuite.forEach(function(test) { var result = reimbursementCalculator.calculateProjects(test.projects); output += test.label + ": Expected " + test.expected + ", Calculated " + result + "."; test.expected != result ? output += " FAILED<br>" : output += " PASSED<br>"; }); return output; } return _public; }());
617c7c12859046cca9f97ec9f41f49fb45467db8
[ "Markdown", "JavaScript" ]
2
Markdown
MikeHartman/simple-thread-exercise
7eed5790e297c28d1514f90e0a0a9f39c8c43a17
72e029dc534bcde87c9219a8b98d256f3c94f509
refs/heads/master
<file_sep>class RefreshTweets { constructor () { console.log('test') window.setInterval(this.update, 1000); } update () { this.tweetsBar = document.querySelector('.js-new-tweets-bar'); if (document.body.scrollTop === 0) { this.tweetsBar.click(); } } } new RefreshTweets();
aacdcf8ad3f67cd02c876c6e29a3d8d16c22582e
[ "JavaScript" ]
1
JavaScript
dwrdev/twitter-refresh
40bbaa755574061bba9eb6945c25d141c603de98
e29aa24154d847487a796a882c1ac9fc763a260d
refs/heads/master
<file_sep>package edu.ktu.myfirstapplication; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import java.util.ArrayList; import java.util.List; public class ThirdActivity extends AppCompatActivity{ @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.thirdactivitydesign); ImageView Image1 = (ImageView) findViewById(R.id.image1); ImageView Image2 = (ImageView) findViewById(R.id.image2); ImageView Image3 = (ImageView) findViewById(R.id.image3); ImageView Image4 = (ImageView) findViewById(R.id.image4); ImageView Image5 = (ImageView) findViewById(R.id.image5); int imageResource1 = getResources().getIdentifier("@drawable/a11",null,this.getPackageName()); int imageResource2 = getResources().getIdentifier("@drawable/b22",null,this.getPackageName()); int imageResource3 = getResources().getIdentifier("@drawable/c33",null,this.getPackageName()); int imageResource4 = getResources().getIdentifier("@drawable/sc1",null,this.getPackageName()); int imageResource5 = getResources().getIdentifier("@drawable/sc2",null,this.getPackageName()); Image1.setImageResource(imageResource1); Image2.setImageResource(imageResource2); Image3.setImageResource(imageResource3); Image4.setImageResource(imageResource4); Image5.setImageResource(imageResource5); } }
feb2453f6192962f52a145498329da16dbe993f6
[ "Java" ]
1
Java
JackyMyBoy/Apps
abd49f6ecd1bebb407f42c3d7f00dbd652ca1448
f58f882723b2493b44452471616bb5f59cebde2f
refs/heads/master
<repo_name>SecuritySquad/webifier<file_sep>/src/main/java/de/securitysquad/webifier/config/websocket/MessageValidateInterceptor.java package de.securitysquad.webifier.config.websocket; import de.securitysquad.webifier.config.WebifierConstants; import org.springframework.context.ApplicationEventPublisher; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.simp.stomp.StompHeaderAccessor; import org.springframework.messaging.support.ChannelInterceptorAdapter; import org.springframework.session.events.SessionDestroyedEvent; import javax.servlet.http.HttpSession; import static java.util.Arrays.asList; import static org.springframework.messaging.simp.SimpMessageType.*; /** * Created by samuel on 05.11.16. */ public class MessageValidateInterceptor extends ChannelInterceptorAdapter { private ApplicationEventPublisher eventPublisher; public MessageValidateInterceptor(ApplicationEventPublisher eventPublisher) { this.eventPublisher = eventPublisher; } @Override public Message<?> preSend(Message<?> message, MessageChannel channel) { StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message); HttpSession session = (HttpSession) accessor.getSessionAttributes().get(WebifierConstants.Session.HTTP_SESSION); if (asList(CONNECT_ACK, SUBSCRIBE, MESSAGE).contains(accessor.getMessageType())) { if (!validateMessageHeader(session, accessor)) { eventPublisher.publishEvent(new SessionDestroyedEvent(this, session.getId())); } } accessor.setLeaveMutable(true); return message; } private boolean validateMessageHeader(HttpSession session, StompHeaderAccessor accessor) { String url = accessor.getFirstNativeHeader(WebifierConstants.Parameter.URL); String id = accessor.getFirstNativeHeader(WebifierConstants.Parameter.ID); return (url != null && id != null) && url.equals(session.getAttribute(WebifierConstants.Session.CHECK_URL)) && id.equals(session.getAttribute(WebifierConstants.Session.CHECK_ID)); } }<file_sep>/src/main/webapp/resources/js/index.js var updateQueue = function () { $('#queue-size-item').removeClass('hidden'); $.getJSON("/queue", {}, function (queue) { $('#queue-size').html(queue.size); }); }; updateQueue(); setInterval(updateQueue, 10000);<file_sep>/src/main/webapp/resources/js/check.js /** * Created by samuel on 02.11.16. */ var client = Stomp.over(new SockJS('/connect')); client.debug = function (message) { // no debug }; client.connect(getHeader(), function (frame) { console.log(frame); client.subscribe('/user/started', function (payload) { $('#test-state').attr('src', 'img/webifier-loading.gif'); $('#waiting-position').hide(); $('#test-info').hide(); }, getHeader()); client.subscribe('/user/waiting', function (payload) { $('#waiting-position').html(payload.body); }, getHeader()); client.subscribe('/user/check', function (payload) { var event = JSON.parse(payload.body); if (event.message) { $('#log').append('</br>' + event.message); } executeEvent(event); }, getHeader()); client.send('/connect', header, 'connect'); }, function (err) { console.error('connection error:' + err); }); function getHeader() { return JSON.parse(JSON.stringify(header)); } function executeEvent(event) { switch (event.typ) { case 'ResolverFinished': setResolvedResult(event.result); break; case 'TestStarted': setTestLoading(event); break; case 'TestFinished': setTestResult(event); break; case 'TesterFinished': setResultImage(event.result); setAllRunningTestsUndefined(); break; default: break; } } function setTestLoading(event) { switch (event.test_name) { case 'VirusScan': $('#virusscan-state').attr('src', 'img/loading.gif'); break; case 'PortScan': $('#portscan-state').attr('src', 'img/loading.gif'); break; case 'IpScan': $('#ipscan-state').attr('src', 'img/loading.gif'); break; case 'HeaderInspection': $('#header-inspection-state').attr('src', 'img/loading.gif'); break; case 'LinkChecker': $('#linkchecker-state').attr('src', 'img/loading.gif'); break; case 'CertificateChecker': $('#certificatechecker-state').attr('src', 'img/loading.gif'); break; case 'PhishingDetector': $('#phishingdetector-state').attr('src', 'img/loading.gif'); break; case 'Screenshot': $('#screenshot-state').attr('src', 'img/loading.gif'); break; case 'GoogleSafeBrowsing': $('#google-safe-browsing-state').attr('src', 'img/loading.gif'); break; } } function setTestResult(event) { switch (event.test_name) { case 'VirusScan': setVirusScanResult(event.result); break; case 'PortScan': setPortScanResult(event.result); break; case 'IpScan': setIpScanResult(event.result); break; case 'HeaderInspection': setHeaderInspectionResult(event.result); break; case 'LinkChecker': setLinkCheckerResult(event.result); break; case 'CertificateChecker': setCertificateCheckerResult(event.result); break; case 'PhishingDetector': setPhishingDetectorResult(event.result); break; case 'Screenshot': setScreenshotResult(event.result); break; case 'GoogleSafeBrowsing': setGoogleSafeBrowsingResult(event.result); break; } } function setScreenshotResult(result) { setSingleTestResultImage($('#screenshot-state'), result.result); $('#screenshot-placeholder').addClass('invisible'); var base64img = result.info.base64img; $('#screenshot-block').append($('<img>').css({ 'display': 'block', 'margin': '0 auto', 'border': '1px solid rgba(0, 0, 0, 0.125)', 'max-width': '100%' }).attr('src', base64img)); } function setVirusScanResult(result) { setSingleTestResultImage($('#virusscan-state'), result.result); $('#virusscan-placeholder').addClass('invisible'); $('#virusscan-info').html('Geprüfte Dateien: ' + result.info.scanned_files + '</br>Verdächtige Dateien: ' + result.info.suspicious_files + '</br>Maliziöse Dateien: ' + result.info.malicious_files).removeClass('invisible'); var files = result.info.files; for (var i = 0; i < files.length; i++) { var table = ''; if (files[i].result == "SUSPICIOUS") table = 'table-warning'; if (files[i].result == "MALICIOUS") table = 'table-danger'; $('#virusscan-result').append('<tr class="' + table + '"><td><small>' + files[i].name + '</small></td><td>' + getFontAwesomeResultSymbol(files[i].result) + '</td></tr>'); } $('#virusscan-result').removeClass('invisible'); } function setPortScanResult(result) { setSingleTestResultImage($('#portscan-state'), result.result); $('#portscan-placeholder').addClass('invisible'); var $portscan_info = $('#portscan-info'); $portscan_info.html('Keine verdächtigen Portabfragen gefunden.').removeClass('invisible'); var unknown_ports = result.info.unknown_ports; if (unknown_ports.length > 0) { $portscan_info.html('Folgende verdächtige Ports wurden abgefragt:'); var $portscan_result = $('#portscan-result'); for (var i = 0; i < unknown_ports.length; i++) { $portscan_result.append('<tr><td>' + unknown_ports[i] + '</td></tr>'); } $portscan_result.removeClass('invisible'); } } function setIpScanResult(result) { setSingleTestResultImage($('#ipscan-state'), result.result); $('#ipscan-placeholder').addClass('invisible'); var $ipscan_info = $('#ipscan-info'); $ipscan_info.html('Keine verdächtigen IP-Abfragen gefunden.').removeClass('invisible'); var risky_hosts = result.info.risky_hosts; if (risky_hosts.length > 0) { $ipscan_info.html('Folgende verdächtige IPs wurden abgefragt:'); var $ipscan_result = $('#ipscan-result'); for (var i = 0; i < risky_hosts.length; i++) { $ipscan_result.append('<tr><td>' + risky_hosts[i] + '</td></tr>'); } $ipscan_result.removeClass('invisible'); } } function setHeaderInspectionResult(result) { setSingleTestResultImage($('#header-inspection-state'), result.result); $('#header-inspection-placeholder').addClass('invisible'); var info = $('<table>').addClass('table table-sm table-striped small'); info.append($('<tr>').append($('<th>').html('Durchschnittliche Abweichung:')) .append($('<td>').html(result.info.medianDiff + ' Zeichen')) .append($('<td>').html(((1 - result.info.medianRatio) * 100).toFixed(2) + ' %'))); info.append($('<tr>').append($('<th>').html('Maximale Abweichung:')) .append($('<td>').html(result.info.worstDiff + ' Zeichen')) .append($('<td>').html(((1 - result.info.worstRatio) * 100).toFixed(2) + ' %'))); var list = $('<ul>').addClass('list-group small'); var browsers = result.info.browsers; for (var i = 0; i < browsers.length; i++) { list.append($('<li>').addClass('list-group-item').html(browsers[i])); } $('#header-inspection-info').append(info).append($('<p>').html("Geprüfte Systeme:")).append(list).removeClass('invisible'); } function setLinkCheckerResult(result) { setSingleTestResultImage($('#linkchecker-state'), result.result); $('#linkchecker-placeholder').addClass('invisible'); var hosts = result.info.hosts; $('#linkchecker-info').html((hosts.length > 0) ? 'Geprüfte Webseiten:' : 'Keine Links gefunden.').removeClass('invisible'); for (var i = 0; i < hosts.length; i++) { var table = ''; if (hosts[i].result == "SUSPICIOUS") table = 'table-warning'; if (hosts[i].result == "MALICIOUS") table = 'table-danger'; $('#linkchecker-result').append('<tr class="' + table + '"><td><small>' + hosts[i].host + '</small></td><td>' + getFontAwesomeResultSymbol(hosts[i].result) + '</td></tr>'); } $('#linkchecker-result').removeClass('invisible'); } function setCertificateCheckerResult(result) { setSingleTestResultImage($('#certificatechecker-state'), result.result); $('#certificatechecker-placeholder').addClass('invisible'); $('#certificatechecker-info').html((result.info && result.info.certificate) ? 'Zertifikat:' : 'Kein Zertifikat gefunden!').removeClass('invisible'); if (result.info && result.info.certificate) { var certificate = result.info.certificate; if (result.result == 'MALICIOUS') { $('#certificatechecker-result').append($('<p>').css('font-weight', 'bold').html('Fehler: ' + certificate.return_code)); } var subject = $('<table>').addClass('table table-sm table-striped small'); subject.append($('<tr>').append($('<th>').html('Name')).append($('<td>').html(certificate.subject.name))); subject.append($('<tr>').append($('<th>').html('Organisation')).append($('<td>').html(certificate.subject.organisation))); subject.append($('<tr>').append($('<th>').html('Organisationseinheit')).append($('<td>').html(certificate.subject.organisation_unit))); $('#certificatechecker-result').append($('<p>').addClass('small').html('Ausgestellt für:')).append(subject); var issuer = $('<table>').addClass('table table-sm table-striped small'); issuer.append($('<tr>').append($('<th>').html('Name')).append($('<td>').html(certificate.issuer.name))); issuer.append($('<tr>').append($('<th>').html('Organisation')).append($('<td>').html(certificate.issuer.organisation))); issuer.append($('<tr>').append($('<th>').html('Organisationseinheit')).append($('<td>').html(certificate.issuer.organisation_unit))); $('#certificatechecker-result').append($('<p>').addClass('small').html('Ausgestellt von:')).append(issuer); var validity = $('<table>').addClass('table table-sm table-striped small'); var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit' }; var from = new Date(certificate.validity.from); validity.append($('<tr>').append($('<th>').html('Gültig ab')).append($('<td>').html(from.toLocaleString('de-DE', options)))); var to = new Date(certificate.validity.to); validity.append($('<tr>').append($('<th>').html('Gültig bis')).append($('<td>').html(to.toLocaleString('de-DE', options)))); $('#certificatechecker-result').append($('<p>').addClass('small').html('Gültigkeitszeitraum:')).append(validity); $('#certificatechecker-result').removeClass('invisible'); } } function setPhishingDetectorResult(result) { setSingleTestResultImage($('#phishingdetector-state'), result.result); $('#phishingdetector-placeholder').addClass('invisible'); $('#phishingdetector-info').html('<b>Schlagwörter:</b> ' + result.info.keywords.join(', ')).removeClass('invisible'); if (result.info.matches.length > 0) { $('#phishingdetector-result').append($('<p>').html('Übereinstimmungen:')); var matches = result.info.matches; for (var i = 0; i < matches.length; i++) { var match = matches[i]; $('#phishingdetector-result').append($('<p>').addClass('small').html($('<a>').attr({ 'href': match.url, 'target': '_blank' }).html(match.url))); var match_result = $('<table>').addClass('table table-sm table-striped small no-margin'); match_result.append($('<tr>').append($('<th>').html('Resultat')).append($('<th>').html(getFontAwesomeResultSymbol(match.result)))); match_result.append($('<tr>').append($('<th>').html('Übereinstimmung')).append($('<th>').html((match.ratio * 100).toFixed(2) + ' %'))); match_result.append($('<tr>').append($('<td>').html('-> Inhalt')).append($('<td>').html((match.content_ratio * 100).toFixed(2) + ' %'))); match_result.append($('<tr>').append($('<td>').html('-> Quelltext')).append($('<td>').html((match.html_ratio * 100).toFixed(2) + ' %'))); match_result.append($('<tr>').append($('<td>').html('-> Aussehen')).append($('<td>').html((match.screenshot_ratio * 100).toFixed(2) + ' %'))); $('#phishingdetector-result').append(match_result); var match_comparison = $('<div>').css({ 'width': '100%', 'max-height': '400px', 'overflow': 'auto', 'border': '1px solid #eceeef', 'margin-bottom': '1rem' }).html($('<img>').attr({ 'src': match.comparison }).css({ 'display': 'block', 'margin': '0 auto', 'width': '100%' })); $('#phishingdetector-result').append(match_comparison); } $('#phishingdetector-result').removeClass('invisible'); } } function setGoogleSafeBrowsingResult(result) { setSingleTestResultImage($('#google-safe-browsing-state'), result.result); $('#google-safe-browsing-placeholder').addClass('invisible'); var list = $('<ul>').addClass('list-group small'); var matches = result.info.matches; if (matches.length > 0) { for (var i = 0; i < matches.length; i++) { list.append($('<li>').addClass('list-group-item').html(matches[i])); } $('#google-safe-browsing-info').append($('<p>').html("Gefundene Bedrohungen:")).append(list).removeClass('invisible'); } else { $('#google-safe-browsing-info').append($('<p>').html("Keine Bedrohungen gefunden.")).removeClass('invisible'); } } function getFontAwesomeResultSymbol(result) { var icon = 'fa-check-circle'; var color = 'text-success'; if (result == "SUSPICIOUS") { icon = 'fa-exclamation-triangle'; color = 'text-warning'; } if (result == "MALICIOUS") { icon = 'fa-times-circle'; color = 'text-danger'; } if (result == "UNDEFINED") { icon = 'fa-question-circle'; color = 'text-muted'; } return '<span class="fa ' + icon + ' ' + color + '"></span>'; } function setResolvedResult(result) { if (result.reachable) { $('#resolved-url').html(result.resolved); } else { $('#resolved-url').html("Nicht erreichbar!"); $('#test-state').attr('src', '/img/webifier.png'); } } function setSingleTestResultImage(element, result) { element.attr('src', 'img/' + getResultImage(result)); } function setResultImage(result) { $('#heading-log').css('background-color', '#f5f5f5'); $("#favicon").attr('href', '/img/webifier-' + getResultImage(result)); $('#test-state').attr('src', '/img/webifier-' + getResultImage(result)); } function setAllRunningTestsUndefined() { $('img[src="/img/loading.gif"]').attr('src', '/img/undefined.png'); } function getResultImage(result) { switch (result) { case "CLEAN": return 'clean.png'; case "SUSPICIOUS": return 'warning.png'; case "MALICIOUS": return 'malicious.png'; default: return 'undefined.png'; } }<file_sep>/src/main/java/de/securitysquad/webifier/web/controller/BatchController.java package de.securitysquad.webifier.web.controller; import de.securitysquad.webifier.config.WebifierConstants; import de.securitysquad.webifier.core.WebifierTesterLauncher; import org.apache.commons.validator.routines.UrlValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.Assert; 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.servlet.ModelAndView; import javax.servlet.http.HttpSession; import java.util.HashMap; import java.util.Map; /** * Created by samuel on 02.03.17. */ @Controller public class BatchController { private final WebifierTesterLauncher webifierTesterLauncher; @Autowired public BatchController(WebifierTesterLauncher webifierTesterLauncher) { Assert.notNull(webifierTesterLauncher, "webifierTesterLauncher must not be null!"); this.webifierTesterLauncher = webifierTesterLauncher; } @RequestMapping("/batch") public ModelAndView returnBatchView(HttpSession session) { ModelAndView result = new ModelAndView("batch"); Object error = session.getAttribute(WebifierConstants.Session.ERROR); if (error != null) { result.addObject("error", error); session.removeAttribute(WebifierConstants.Session.ERROR); } return result; } @RequestMapping(value = "/batch/check", method = RequestMethod.POST) public String redirectResultView(@RequestParam("urls") String urls, HttpSession session) { Map<String, Boolean> startedUrls = new HashMap<>(); UrlValidator validator = new UrlValidator(new String[]{"http", "https"}); for (String url : urls.split("\n")) { String trimmedUrl = withProtocol(url.trim()); if (validator.isValid(trimmedUrl)) { String id = webifierTesterLauncher.launch(url); startedUrls.put(trimmedUrl, id != null); } } session.setAttribute(WebifierConstants.Session.STARTED, startedUrls); return "redirect:/batch/checked"; } private String withProtocol(String url) { if (url.matches("^https?://.*")) { return url; } return "http://" + url; } @RequestMapping(value = "/batch/checked") public ModelAndView returnResultView(HttpSession session) { Object started = session.getAttribute(WebifierConstants.Session.STARTED); if (started == null) { return new ModelAndView("redirect:/batch"); } ModelAndView result = new ModelAndView("batchresult"); result.addObject("started", started); return result; } }<file_sep>/settings.gradle rootProject.name = 'webifier-platform'<file_sep>/src/main/java/de/securitysquad/webifier/core/WebifierTesterResult.java package de.securitysquad.webifier.core; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; /** * Created by samuel on 16.11.16. */ @JsonIgnoreProperties(ignoreUnknown = true) public class WebifierTesterResult { @JsonProperty private String typ; @JsonProperty private String message; @JsonProperty("tester_id") private String launchId; private String content; public String getTyp() { return typ; } public void setTyp(String typ) { this.typ = typ; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getLaunchId() { return launchId; } public void setLaunchId(String launchId) { this.launchId = launchId; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } } <file_sep>/src/main/resources/application.properties app.name=webifier app.version=0.0.1-SNAPSHOT app.description=${app.name} is a security application which tests certain websites for malicious code.<file_sep>/src/main/java/de/securitysquad/webifier/config/websocket/AnonymousHandshakeHandler.java package de.securitysquad.webifier.config.websocket; import de.securitysquad.webifier.config.WebifierConstants; import org.springframework.http.server.ServerHttpRequest; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.server.support.DefaultHandshakeHandler; import javax.servlet.http.HttpSession; import java.security.Principal; import java.util.Map; /** * Created by samuel on 05.11.16. */ public class AnonymousHandshakeHandler extends DefaultHandshakeHandler { @Override protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) { return () -> { HttpSession session = (HttpSession) attributes.get(WebifierConstants.Session.HTTP_SESSION); return (String) session.getAttribute(WebifierConstants.Session.CHECK_ID); }; } }<file_sep>/src/main/webapp/resources/js/batch.js $('#open-batch-file').click(function (event) { event.preventDefault(); $('#open-batch-file-input').click(); }); $('#open-batch-file-input').change(function (event) { var file = event.target.files[0]; if (!file) { return; } var reader = new FileReader(); reader.onload = function(e) { var contents = e.target.result; $('.input-webifier-batch').text(contents); }; reader.readAsText(file); });<file_sep>/src/main/java/de/securitysquad/webifier/config/WebifierConstants.java package de.securitysquad.webifier.config; /** * Created by samuel on 05.11.16. */ public class WebifierConstants { public class Session { public static final String HTTP_SESSION = "http_session"; public static final String CHECK_URL = "check_url"; public static final String CHECK_ID = "check_id"; public static final String ERROR = "error"; public static final String STARTED = "error"; } public class Parameter { public static final String URL = "checkUrl"; public static final String ID = "checkId"; } public class Configuration { public static final String NAME = "config.json"; } } <file_sep>/src/main/java/de/securitysquad/webifier/config/WebMvcConfig.java package de.securitysquad.webifier.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration @EnableWebMvc public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**").addResourceLocations("classpath:resources/"); registry.addResourceHandler("/lib/**").addResourceLocations("classpath:static/"); } }<file_sep>/src/main/java/de/securitysquad/webifier/web/controller/WebifierController.java package de.securitysquad.webifier.web.controller; import de.securitysquad.webifier.config.WebifierConstants; import de.securitysquad.webifier.core.WebifierTesterLauncher; import de.securitysquad.webifier.core.WebifierTesterResultListener; import org.apache.commons.validator.routines.UrlValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.Assert; 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.servlet.ModelAndView; import javax.servlet.http.HttpSession; /** * Created by samuel on 25.10.16. */ @Controller public class WebifierController { private final WebifierTesterLauncher webifierTesterLauncher; private final WebifierTesterResultListener checkController; @Autowired public WebifierController(WebifierTesterLauncher webifierTesterLauncher, WebifierTesterResultListener checkController) { Assert.notNull(webifierTesterLauncher, "webifierTesterLauncher must not be null!"); Assert.notNull(checkController, "checkController must not be null!"); this.webifierTesterLauncher = webifierTesterLauncher; this.checkController = checkController; } @RequestMapping("/") public ModelAndView returnIndexView(HttpSession session) { ModelAndView result = new ModelAndView("index"); Object error = session.getAttribute(WebifierConstants.Session.ERROR); if (error != null) { result.addObject("error", error); session.removeAttribute(WebifierConstants.Session.ERROR); } return result; } @RequestMapping(value = "/check", method = RequestMethod.POST) public String redirectResultView(@RequestParam("url") String url, HttpSession session) { String trimmedUrl = url.trim(); UrlValidator validator = new UrlValidator(new String[]{"http", "https"}); if (validator.isValid(withProtocol(trimmedUrl))) { if (!launchTester(trimmedUrl, session)) { session.setAttribute(WebifierConstants.Session.ERROR, "queue_full"); return "redirect:/"; } return "redirect:/checked"; } session.setAttribute(WebifierConstants.Session.ERROR, "url_invalid"); return "redirect:/"; } private boolean launchTester(String url, HttpSession session) { String id = webifierTesterLauncher.launch(url, session, checkController); if (id == null) return false; session.setAttribute(WebifierConstants.Session.CHECK_URL, url); session.setAttribute(WebifierConstants.Session.CHECK_ID, id); return true; } private String withProtocol(String url) { if (url.matches("^https?://.*")) { return url; } return "http://" + url; } @RequestMapping(value = "/checked") public ModelAndView returnResultView(HttpSession session) { Object id = session.getAttribute(WebifierConstants.Session.CHECK_ID); Object url = session.getAttribute(WebifierConstants.Session.CHECK_URL); if (id == null || url == null) { return new ModelAndView("redirect:/"); } ModelAndView result = new ModelAndView("result"); result.addObject("check_url", url); result.addObject("check_id", id); return result; } }<file_sep>/src/main/java/de/securitysquad/webifier/web/controller/CheckController.java package de.securitysquad.webifier.web.controller; import de.securitysquad.webifier.core.WebifierTesterResult; import de.securitysquad.webifier.core.WebifierTesterResultListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpSession; import java.security.Principal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by samuel on 02.11.16. */ @RestController public class CheckController implements WebifierTesterResultListener { private final SimpMessagingTemplate messagingTemplate; private final Map<WebifierEndpoint, List<String>> subscribed; private final Map<WebifierEndpoint, Map<String, List<String>>> cache; @Autowired public CheckController(SimpMessagingTemplate messagingTemplate) { Assert.notNull(messagingTemplate, "messagingTemplate must not be null!"); this.messagingTemplate = messagingTemplate; this.subscribed = new HashMap<>(); this.subscribed.put(WebifierEndpoint.WAITING, new ArrayList<>()); this.subscribed.put(WebifierEndpoint.STARTED, new ArrayList<>()); this.subscribed.put(WebifierEndpoint.CHECK, new ArrayList<>()); this.cache = new HashMap<>(); this.cache.put(WebifierEndpoint.WAITING, new HashMap<>()); this.cache.put(WebifierEndpoint.STARTED, new HashMap<>()); this.cache.put(WebifierEndpoint.CHECK, new HashMap<>()); } @MessageMapping("/connect") public void connect(Principal p) { subscribed.get(WebifierEndpoint.WAITING).add(p.getName()); cache.get(WebifierEndpoint.WAITING).getOrDefault(p.getName(), new ArrayList<>()).forEach(message -> sendWaitingEvent(p.getName(), message)); subscribed.get(WebifierEndpoint.STARTED).add(p.getName()); cache.get(WebifierEndpoint.STARTED).getOrDefault(p.getName(), new ArrayList<>()).forEach(message -> sendStartedEvent(p.getName())); subscribed.get(WebifierEndpoint.CHECK).add(p.getName()); messagingTemplate.convertAndSendToUser(p.getName(), "/check", Boolean.toString(true)); cache.get(WebifierEndpoint.CHECK).getOrDefault(p.getName(), new ArrayList<>()).forEach(message -> sendCheckEvent(p.getName(), message)); } @Override public void onWaitingPositionChanged(HttpSession session, String id, int position) { sendWaitingEvent(id, Integer.toString(position)); } @Override public void onStarted(HttpSession session, String id) { sendStartedEvent(id); } @Override public void onTestResult(HttpSession session, String launchId, WebifierTesterResult result) { sendCheckEvent(launchId, result.getContent()); } @Override public void onError(HttpSession session, String line) { System.err.println(line); } @Override public void onFinished(HttpSession session, String id) { subscribed.forEach((endpoint, ids) -> ids.remove(id)); cache.forEach((endpoint, cache) -> cache.remove(id)); try { session.invalidate(); } catch (IllegalStateException e) { // session is already expired } } private void sendStartedEvent(String id) { List<String> cache = getOrCreateCache(WebifierEndpoint.STARTED, id); String message = "started"; if (!cache.contains(message)) { cache.add(message); } if (subscribed.get(WebifierEndpoint.STARTED).contains(id)) { messagingTemplate.convertAndSendToUser(id, "/started", message); } } private void sendWaitingEvent(String id, String message) { List<String> cache = getOrCreateCache(WebifierEndpoint.WAITING, id); if (!cache.contains(message)) { cache.add(message); } if (subscribed.get(WebifierEndpoint.WAITING).contains(id)) { messagingTemplate.convertAndSendToUser(id, "/waiting", message); } } private void sendCheckEvent(String id, String message) { List<String> cache = getOrCreateCache(WebifierEndpoint.CHECK, id); if (!cache.contains(message)) { cache.add(message); } if (subscribed.get(WebifierEndpoint.CHECK).contains(id)) { messagingTemplate.convertAndSendToUser(id, "/check", message); } } private List<String> getOrCreateCache(WebifierEndpoint endpoint, String id) { if (!cache.get(endpoint).containsKey(id)) { cache.get(endpoint).put(id, new ArrayList<>()); } return cache.get(endpoint).get(id); } private enum WebifierEndpoint { WAITING, STARTED, CHECK } }<file_sep>/README.md [![Build Status](https://travis-ci.org/SecuritySquad/webifier-platform.svg?branch=master)](https://travis-ci.org/SecuritySquad/webifier-platform) # webifier-platform webifier-platform is a webapp for webifier-tester, which tests certain websites for malicious code. ## Installation To install and run webifier-platform your system needs the following requirements: ### Requirements - Java 8 - Docker - Bower - git - libprocname.so If you have all the requirements installed you need to create the folder persistent/ and run/ in the parent directory of webifier-platform. Move the libprocname.so in the persistent/ folder. The executable .jar files, start scripts and log files are moved in the run/ folder. Now you can simply execute the [install.sh](install.sh) script, which installs all the other needed webifier-components. ### Execution To run webifier-platform you have run the script start-platform.sh, which will be created in the run/ folder. ### Configuration ... <file_sep>/src/main/java/de/securitysquad/webifier/core/WebifierTesterState.java package de.securitysquad.webifier.core; /** * Created by samuel on 12.02.17. */ public enum WebifierTesterState { WAITING, RUNNING, FINISHED, ERROR }<file_sep>/src/main/java/de/securitysquad/webifier/config/websocket/SessionResolver.java package de.securitysquad.webifier.config.websocket; import de.securitysquad.webifier.config.WebifierConstants; import org.springframework.core.MethodParameter; import org.springframework.messaging.Message; import org.springframework.messaging.handler.invocation.HandlerMethodArgumentResolver; import javax.servlet.http.HttpSession; import java.util.Map; import static org.springframework.messaging.simp.SimpMessageHeaderAccessor.getSessionAttributes; /** * Created by samuel on 05.11.16. */ public class SessionResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter parameter) { return parameter.getParameterType().equals(HttpSession.class); } @Override public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception { Map<String, Object> session = getSessionAttributes(message.getHeaders()); return session.get(WebifierConstants.Session.HTTP_SESSION); } } <file_sep>/src/main/java/de/securitysquad/webifier/core/WebifierTesterLauncher.java package de.securitysquad.webifier.core; import de.securitysquad.webifier.config.WebifierConfig; import de.securitysquad.webifier.config.WebifierTesterConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PreDestroy; import javax.servlet.http.HttpSession; import java.util.*; import java.util.function.Predicate; import static de.securitysquad.webifier.core.WebifierTesterState.*; import static java.util.Arrays.asList; import static java.util.Comparator.comparingLong; import static java.util.stream.Collectors.toList; /** * Created by samuel on 08.11.16. */ @Component public class WebifierTesterLauncher implements Runnable { private static final int MAX_QUEUE_SIZE = 150000; private final WebifierTesterConfig config; private final List<WebifierTester> queue; private final Thread testerProcessor; @Autowired public WebifierTesterLauncher(WebifierConfig config) { this.config = config.getTester(); this.queue = Collections.synchronizedList(new ArrayList<>()); this.testerProcessor = new Thread(this, "WebifierTesterLauncher"); this.testerProcessor.start(); } @PreDestroy public void destroy() { queue.forEach(WebifierTester::exit); testerProcessor.interrupt(); } public synchronized String launch(String url) { return launch(url, null, null); } public synchronized String launch(String url, HttpSession session, WebifierTesterResultListener listener) { if (queue.size() >= MAX_QUEUE_SIZE) { return null; } if (queue.stream().anyMatch(test -> test.getUrl().equals(url))) { return null; } String id = UUID.randomUUID().toString(); String command = config.getCommand().replace("#URL", url).replace("#ID", id); queue.add(new WebifierTester(id, url, command, session, listener, config.getTimeout())); return id; } public synchronized int getQueueSize() { return (int) queue.stream().filter(t -> t.getState() == WAITING).count(); } @Override public void run() { Predicate<? super WebifierTester> waiting = t -> t.getState() == WAITING; Predicate<? super WebifierTester> exited = t -> asList(FINISHED, ERROR).contains(t.getState()); while (!testerProcessor.isInterrupted()) { synchronized (queue) { queue.stream().filter(exited).collect(toList()).forEach(t -> { t.exit(); queue.remove(t); }); List<WebifierTester> waitingTesters = queue.stream().filter(waiting).sorted(comparingLong(WebifierTester::getCreationIndex)).collect(toList()); for (int index = 0; index < waitingTesters.size(); index++) { waitingTesters.get(index).setWaitingPosition(index + 1); } if (queue.stream().mapToInt(t -> t.getState() == RUNNING ? 1 : 0).sum() < config.getParallel()) { queue.stream().filter(waiting).min(comparingLong(WebifierTester::getCreationIndex)).ifPresent(WebifierTester::launch); } } Runtime.getRuntime().gc(); try { Thread.sleep(500); } catch (InterruptedException e) { testerProcessor.interrupt(); } } } }<file_sep>/install.sh #!/usr/bin/env bash if [[ "$1" == "--help" ]]; then echo "Usage: bash install.sh [--only \"test1 test2\"]" exit fi cd .. rm -rf webifier-tester git clone https://github.com/SecuritySquad/webifier-tester.git cd webifier-tester bash install.sh $1 $2 cd .. if [ -e persistent/application-platform.extension ] then cat persistent/application-platform.extension >> webifier-platform/src/main/resources/application.properties fi cd webifier-platform bower install ./gradlew :build cd .. cd run rm -f webifier-platform-*.jar rm -f start-platform.sh cp ../webifier-platform/build/libs/webifier-platform-*.jar . JAR=$(ls| grep 'webifier\-platform\-.*\.jar') cat > start-platform.sh << EOF killall webifier-plat docker stop \$(docker ps -a -q) docker rm \$(docker ps -a -q) LD_PRELOAD=../persistent/libprocname.so PROCNAME=webifier-plat java -jar ${JAR} > output-platform.log 2>&1 & EOF chmod +x start-platform.sh
f98649e5a7d861a042c37afeba8a148f2f67a9d9
[ "JavaScript", "Markdown", "INI", "Gradle", "Java", "Shell" ]
18
Java
SecuritySquad/webifier
af7e780f626c16680e588bbd7e3e86cc232ffe34
f53bb376c522a94e1efba0964170d6012e118a8c
refs/heads/7.0
<repo_name>dvitme/openerp-dav<file_sep>/so_tax/__openerp__.py # -*- coding: utf-8 -*- { 'name': 'Sale Order Tax', 'summary': 'Sale Order Tax', 'description': """ This module adds a tax field whose value put in every product record. This is also being made in customer invoice. """, 'version': '8.0.1.0', 'category': 'Accounting', 'author': 'DVIT.me', 'website': 'http://dvit.me', 'license': 'AGPL-3', 'depends': [ 'account','sale' ], 'data': ['templates.xml'], 'installable': True, 'auto_install': False, 'application': False, }<file_sep>/so_tax/models.py # -*- coding: utf-8 -*- from openerp import models, fields, api class SaleOrder(models.Model): _inherit = 'sale.order' tax_ids = fields.Many2many( 'account.tax', string='Taxes', help='Note: this will be put on all Order Lines below.', states={'draft': [('readonly', False)]}, domain=['|', ('active', '=', False), ('active', '=', True)] ) @api.onchange("tax_ids") def onchange_tax_ids(self): for o in self.order_line: o.tax_id = self.tax_ids class AccountInvoice(models.Model): _inherit = 'account.invoice' tax_ids = fields.Many2many( 'account.tax', string='Taxes', help='Note: this will be put on all Invoice Lines below.', states={'draft': [('readonly', False)]}, domain=[('parent_id', '=', False), '|', ('active', '=', False), ('active', '=', True)] ) @api.onchange("tax_ids") def onchange_tax_ids(self): for o in self.invoice_line: o.invoice_line_tax_id = self.tax_ids
75c7bacae1c681ea074365a7ef2df3fc0fa18ba0
[ "Python" ]
2
Python
dvitme/openerp-dav
06fc0310bd636818b8c52980231158ec99211408
ada6fe5a4b15c49639d9ab187dec0af3a30997a1
refs/heads/master
<repo_name>Cayshin/hobby-os<file_sep>/start.sh qemu-system-i386 -cdrom build/hobby-os.iso <file_sep>/Makefile iso := build/hobby-os.iso kernel := build/kernel.bin grub_cfg := kernel/grub.cfg all: kernel.bin boot.o: kernel/boot.asm nasm -felf32 kernel/boot.asm -o boot.o kernel.bin: boot.o kernel/linker.ld i686-elf-gcc -T kernel/linker.ld -o $(kernel) -ffreestanding -O2 -nostdlib boot.o -lgcc iso: $(iso) $(iso): $(kernel) $(grub_cfg) @mkdir -p build/isofiles/boot/grub @cp $(kernel) build/isofiles/boot/kernel.bin @cp $(grub_cfg) build/isofiles/boot/grub @grub-mkrescue -o $(iso) build/isofiles 2> /dev/null @rm -r build/isofiles
dc8d23a4e9251a614ec465ee2b377006fd84ece7
[ "Makefile", "Shell" ]
2
Shell
Cayshin/hobby-os
8b3383cdc8e5ff78e70a050a93b4fca494cd04d8
c25fd6d0aa5e5bd5a45dae283a19fa562e4943f9
refs/heads/master
<repo_name>ThePatrickLynch/canvas<file_sep>/mysql/import.sh <!DOCTYPE html> <html lang="en" class=" is-u2f-enabled"> <head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# object: http://ogp.me/ns/object# article: http://ogp.me/ns/article# profile: http://ogp.me/ns/profile#"> <meta charset='utf-8'> <link crossorigin="anonymous" href="https://assets-cdn.github.com/assets/frameworks-298818692f75de57d67115ca5a0c1f983d1d5ad302774216c297495f46f0a3da.css" integrity="<KEY> media="all" rel="stylesheet" /> <link crossorigin="anonymous" href="https://assets-cdn.github.com/assets/github-5cdfa79e1c4beb2f5bf44e460eab049867751ad7d5bc0c37f2faab8233768bf0.css" integrity="<KEY> media="all" rel="stylesheet" /> <link crossorigin="anonymous" href="https://assets-cdn.github.com/assets/site-73b3dae8eb441c98982c7306f0e59decca409e87188e07bc1a961b8cea511aab.css" integrity="<KEY> media="all" rel="stylesheet" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="Content-Language" content="en"> <meta name="viewport" content="width=device-width"> <title>canvancement/import.sh at master · jamesjonesmath/canvancement · GitHub</title> <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub"> <link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub"> <link rel="apple-touch-icon" href="/apple-touch-icon.png"> <link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/apple-touch-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/apple-touch-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/apple-touch-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/apple-touch-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-180x180.png"> <meta property="fb:app_id" content="1401488693436528"> <meta content="https://avatars1.githubusercontent.com/u/14840711?v=3&amp;s=400" name="twitter:image:src" /><meta content="@github" name="twitter:site" /><meta content="summary" name="twitter:card" /><meta content="jamesjonesmath/canvancement" name="twitter:title" /><meta content="canvancement - Enhancements to the Canvas LMS" name="twitter:description" /> <meta content="https://avatars1.githubusercontent.com/u/14840711?v=3&amp;s=400" property="og:image" /><meta content="GitHub" property="og:site_name" /><meta content="object" property="og:type" /><meta content="jamesjonesmath/canvancement" property="og:title" /><meta content="https://github.com/jamesjonesmath/canvancement" property="og:url" /><meta content="canvancement - Enhancements to the Canvas LMS" property="og:description" /> <meta name="browser-stats-url" content="https://api.github.com/_private/browser/stats"> <meta name="browser-errors-url" content="https://api.github.com/_private/browser/errors"> <link rel="assets" href="https://assets-cdn.github.com/"> <meta name="pjax-timeout" content="1000"> <meta name="request-id" content="EBF5:574C:43E5D84:6ADC685:5890C44D" data-pjax-transient> <meta name="msapplication-TileImage" content="/windows-tile.png"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="selected-link" value="repo_source" data-pjax-transient> <meta name="google-site-verification" content="<KEY>"> <meta name="google-site-verification" content="<KEY>w2fsA"> <meta name="google-analytics" content="UA-3769691-2"> <meta content="collector.githubapp.com" name="octolytics-host" /><meta content="github" name="octolytics-app-id" /><meta content="EBF5:574C:43E5D84:6ADC685:5890C44D" name="octolytics-dimension-request_id" /> <meta content="/&lt;user-name&gt;/&lt;repo-name&gt;/blob/show" data-pjax-transient="true" name="analytics-location" /> <meta class="js-ga-set" name="dimension1" content="Logged Out"> <meta name="hostname" content="github.com"> <meta name="user-login" content=""> <meta name="expected-hostname" content="github.com"> <meta name="js-proxy-site-detection-payload" content="<KEY>> <link rel="mask-icon" href="https://assets-cdn.github.com/pinned-octocat.svg" color="#000000"> <link rel="icon" type="image/x-icon" href="https://assets-cdn.github.com/favicon.ico"> <meta name="html-safe-nonce" content="16e4e7131b1a34401d011556dfd8384c6a3f33ad"> <meta http-equiv="x-pjax-version" content="1d80b0dec465135d3cc8117d8f2fc2f3"> <meta name="description" content="canvancement - Enhancements to the Canvas LMS"> <meta name="go-import" content="github.com/jamesjonesmath/canvancement git https://github.com/jamesjonesmath/canvancement.git"> <meta content="14840711" name="octolytics-dimension-user_id" /><meta content="jamesjonesmath" name="octolytics-dimension-user_login" /><meta content="43180026" name="octolytics-dimension-repository_id" /><meta content="jamesjonesmath/canvancement" name="octolytics-dimension-repository_nwo" /><meta content="true" name="octolytics-dimension-repository_public" /><meta content="false" name="octolytics-dimension-repository_is_fork" /><meta content="43180026" name="octolytics-dimension-repository_network_root_id" /><meta content="jamesjonesmath/canvancement" name="octolytics-dimension-repository_network_root_nwo" /> <link href="https://github.com/jamesjonesmath/canvancement/commits/master.atom" rel="alternate" title="Recent Commits to canvancement:master" type="application/atom+xml"> <link rel="canonical" href="https://github.com/jamesjonesmath/canvancement/blob/master/canvas-data/mysql/import.sh" data-pjax-transient> </head> <body class="logged-out env-production windows vis-public page-blob"> <div id="js-pjax-loader-bar" class="pjax-loader-bar"><div class="progress"></div></div> <a href="#start-of-content" tabindex="1" class="accessibility-aid js-skip-to-content">Skip to content</a> <header class="site-header js-details-container Details alt-body-font" role="banner"> <div class="container-responsive"> <a class="header-logo-invertocat" href="https://github.com/" aria-label="Homepage" data-ga-click="(Logged out) Header, go to homepage, icon:logo-wordmark"> <svg aria-hidden="true" class="octicon octicon-mark-github" height="32" version="1.1" viewBox="0 0 16 16" width="32"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"/></svg> </a> <button class="btn-link float-right site-header-toggle js-details-target" type="button" aria-label="Toggle navigation"> <svg aria-hidden="true" class="octicon octicon-three-bars" height="24" version="1.1" viewBox="0 0 12 16" width="18"><path fill-rule="evenodd" d="M11.41 9H.59C0 9 0 8.59 0 8c0-.59 0-1 .59-1H11.4c.59 0 .59.41.59 1 0 .59 0 1-.59 1h.01zm0-4H.59C0 5 0 4.59 0 4c0-.59 0-1 .59-1H11.4c.59 0 .59.41.59 1 0 .59 0 1-.59 1h.01zM.59 11H11.4c.59 0 .59.41.59 1 0 .59 0 1-.59 1H.59C0 13 0 12.59 0 12c0-.59 0-1 .59-1z"/></svg> </button> <div class="site-header-menu"> <nav class="site-header-nav site-header-nav-main"> <a href="/personal" class="js-selected-navigation-item nav-item nav-item-personal" data-ga-click="Header, click, Nav menu - item:personal" data-selected-links="/personal /personal"> Personal </a> <a href="/open-source" class="js-selected-navigation-item nav-item nav-item-opensource" data-ga-click="Header, click, Nav menu - item:opensource" data-selected-links="/open-source /open-source"> Open source </a> <a href="/business" class="js-selected-navigation-item nav-item nav-item-business" data-ga-click="Header, click, Nav menu - item:business" data-selected-links="/business /business/partners /business/features /business/customers /business"> Business </a> <a href="/explore" class="js-selected-navigation-item nav-item nav-item-explore" data-ga-click="Header, click, Nav menu - item:explore" data-selected-links="/explore /trending /trending/developers /integrations /integrations/feature/code /integrations/feature/collaborate /integrations/feature/ship /showcases /explore"> Explore </a> </nav> <div class="site-header-actions"> <a class="btn btn-primary site-header-actions-btn" href="/join?source=header-repo" data-ga-click="(Logged out) Header, clicked Sign up, text:sign-up">Sign up</a> <a class="btn site-header-actions-btn mr-1" href="/login?return_to=%2Fjamesjonesmath%2Fcanvancement%2Fblob%2Fmaster%2Fcanvas-data%2Fmysql%2Fimport.sh" data-ga-click="(Logged out) Header, clicked Sign in, text:sign-in">Sign in</a> </div> <nav class="site-header-nav site-header-nav-secondary mr-md-3"> <a class="nav-item" href="/pricing">Pricing</a> <a class="nav-item" href="/blog">Blog</a> <a class="nav-item" href="https://help.github.com">Support</a> <a class="nav-item header-search-link" href="https://github.com/search">Search GitHub</a> <div class="header-search scoped-search site-scoped-search js-site-search" role="search"> <!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/jamesjonesmath/canvancement/search" class="js-site-search-form" data-scoped-search-url="/jamesjonesmath/canvancement/search" data-unscoped-search-url="/search" method="get"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /></div> <label class="form-control header-search-wrapper js-chromeless-input-container"> <div class="header-search-scope">This repository</div> <input type="text" class="form-control header-search-input js-site-search-focus js-site-search-field is-clearable" data-hotkey="s" name="q" placeholder="Search" aria-label="Search this repository" data-unscoped-placeholder="Search GitHub" data-scoped-placeholder="Search" autocapitalize="off"> </label> </form></div> </nav> </div> </div> </header> <div id="start-of-content" class="accessibility-aid"></div> <div id="js-flash-container"> </div> <div role="main"> <div itemscope itemtype="http://schema.org/SoftwareSourceCode"> <div id="js-repo-pjax-container" data-pjax-container> <div class="pagehead repohead instapaper_ignore readability-menu experiment-repo-nav"> <div class="container repohead-details-container"> <ul class="pagehead-actions"> <li> <a href="/login?return_to=%2Fjamesjonesmath%2Fcanvancement" class="btn btn-sm btn-with-count tooltipped tooltipped-n" aria-label="You must be signed in to watch a repository" rel="nofollow"> <svg aria-hidden="true" class="octicon octicon-eye" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6C13 14 16 8 16 8s-3-6-7.94-6zM8 12c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4zm2-4c0 1.11-.89 2-2 2-1.11 0-2-.89-2-2 0-1.11.89-2 2-2 1.11 0 2 .89 2 2z"/></svg> Watch </a> <a class="social-count" href="/jamesjonesmath/canvancement/watchers" aria-label="13 users are watching this repository"> 13 </a> </li> <li> <a href="/login?return_to=%2Fjamesjonesmath%2Fcanvancement" class="btn btn-sm btn-with-count tooltipped tooltipped-n" aria-label="You must be signed in to star a repository" rel="nofollow"> <svg aria-hidden="true" class="octicon octicon-star" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M14 6l-4.9-.64L7 1 4.9 5.36 0 6l3.6 3.26L2.67 14 7 11.67 11.33 14l-.93-4.74z"/></svg> Star </a> <a class="social-count js-social-count" href="/jamesjonesmath/canvancement/stargazers" aria-label="27 users starred this repository"> 27 </a> </li> <li> <a href="/login?return_to=%2Fjamesjonesmath%2Fcanvancement" class="btn btn-sm btn-with-count tooltipped tooltipped-n" aria-label="You must be signed in to fork a repository" rel="nofollow"> <svg aria-hidden="true" class="octicon octicon-repo-forked" height="16" version="1.1" viewBox="0 0 10 16" width="10"><path fill-rule="evenodd" d="M8 1a1.993 1.993 0 0 0-1 3.72V6L5 8 3 6V4.72A1.993 1.993 0 0 0 2 1a1.993 1.993 0 0 0-1 3.72V6.5l3 3v1.78A1.993 1.993 0 0 0 5 15a1.993 1.993 0 0 0 1-3.72V9.5l3-3V4.72A1.993 1.993 0 0 0 8 1zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3 10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3-10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"/></svg> Fork </a> <a href="/jamesjonesmath/canvancement/network" class="social-count" aria-label="15 users forked this repository"> 15 </a> </li> </ul> <h1 class="public "> <svg aria-hidden="true" class="octicon octicon-repo" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M4 9H3V8h1v1zm0-3H3v1h1V6zm0-2H3v1h1V4zm0-2H3v1h1V2zm8-1v12c0 .55-.45 1-1 1H6v2l-1.5-1.5L3 16v-2H1c-.55 0-1-.45-1-1V1c0-.55.45-1 1-1h10c.55 0 1 .45 1 1zm-1 10H1v2h2v-1h3v1h5v-2zm0-10H2v9h9V1z"/></svg> <span class="author" itemprop="author"><a href="/jamesjonesmath" class="url fn" rel="author">jamesjonesmath</a></span><!-- --><span class="path-divider">/</span><!-- --><strong itemprop="name"><a href="/jamesjonesmath/canvancement" data-pjax="#js-repo-pjax-container">canvancement</a></strong> </h1> </div> <div class="container"> <nav class="reponav js-repo-nav js-sidenav-container-pjax" itemscope itemtype="http://schema.org/BreadcrumbList" role="navigation" data-pjax="#js-repo-pjax-container"> <span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement"> <a href="/jamesjonesmath/canvancement" class="js-selected-navigation-item selected reponav-item" data-hotkey="g c" data-selected-links="repo_source repo_downloads repo_commits repo_releases repo_tags repo_branches /jamesjonesmath/canvancement" itemprop="url"> <svg aria-hidden="true" class="octicon octicon-code" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M9.5 3L8 4.5 11.5 8 8 11.5 9.5 13 14 8 9.5 3zm-5 0L0 8l4.5 5L6 11.5 2.5 8 6 4.5 4.5 3z"/></svg> <span itemprop="name">Code</span> <meta itemprop="position" content="1"> </a> </span> <span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement"> <a href="/jamesjonesmath/canvancement/issues" class="js-selected-navigation-item reponav-item" data-hotkey="g i" data-selected-links="repo_issues repo_labels repo_milestones /jamesjonesmath/canvancement/issues" itemprop="url"> <svg aria-hidden="true" class="octicon octicon-issue-opened" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7s-2.56 5.7-5.7 5.7A5.71 5.71 0 0 1 1.3 8c0-3.14 2.56-5.7 5.7-5.7zM7 1C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7-3.14-7-7-7zm1 3H6v5h2V4zm0 6H6v2h2v-2z"/></svg> <span itemprop="name">Issues</span> <span class="counter">0</span> <meta itemprop="position" content="2"> </a> </span> <span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement"> <a href="/jamesjonesmath/canvancement/pulls" class="js-selected-navigation-item reponav-item" data-hotkey="g p" data-selected-links="repo_pulls /jamesjonesmath/canvancement/pulls" itemprop="url"> <svg aria-hidden="true" class="octicon octicon-git-pull-request" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M11 11.28V5c-.03-.78-.34-1.47-.94-2.06C9.46 2.35 8.78 2.03 8 2H7V0L4 3l3 3V4h1c.27.02.48.11.69.31.21.2.3.42.31.69v6.28A1.993 1.993 0 0 0 10 15a1.993 1.993 0 0 0 1-3.72zm-1 2.92c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zM4 3c0-1.11-.89-2-2-2a1.993 1.993 0 0 0-1 3.72v6.56A1.993 1.993 0 0 0 2 15a1.993 1.993 0 0 0 1-3.72V4.72c.59-.34 1-.98 1-1.72zm-.8 10c0 .66-.55 1.2-1.2 1.2-.65 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"/></svg> <span itemprop="name">Pull requests</span> <span class="counter">0</span> <meta itemprop="position" content="3"> </a> </span> <a href="/jamesjonesmath/canvancement/projects" class="js-selected-navigation-item reponav-item" data-selected-links="repo_projects new_repo_project repo_project /jamesjonesmath/canvancement/projects"> <svg aria-hidden="true" class="octicon octicon-project" height="16" version="1.1" viewBox="0 0 15 16" width="15"><path fill-rule="evenodd" d="M10 12h3V2h-3v10zm-4-2h3V2H6v8zm-4 4h3V2H2v12zm-1 1h13V1H1v14zM14 0H1a1 1 0 0 0-1 1v14a1 1 0 0 0 1 1h13a1 1 0 0 0 1-1V1a1 1 0 0 0-1-1z"/></svg> Projects <span class="counter">0</span> </a> <a href="/jamesjonesmath/canvancement/pulse" class="js-selected-navigation-item reponav-item" data-selected-links="pulse /jamesjonesmath/canvancement/pulse"> <svg aria-hidden="true" class="octicon octicon-pulse" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M11.5 8L8.8 5.4 6.6 8.5 5.5 1.6 2.38 8H0v2h3.6l.9-1.8.9 5.4L9 8.5l1.6 1.5H14V8z"/></svg> Pulse </a> <a href="/jamesjonesmath/canvancement/graphs" class="js-selected-navigation-item reponav-item" data-selected-links="repo_graphs repo_contributors /jamesjonesmath/canvancement/graphs"> <svg aria-hidden="true" class="octicon octicon-graph" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M16 14v1H0V0h1v14h15zM5 13H3V8h2v5zm4 0H7V3h2v10zm4 0h-2V6h2v7z"/></svg> Graphs </a> </nav> </div> </div> <div class="container new-discussion-timeline experiment-repo-nav"> <div class="repository-content"> <a href="/jamesjonesmath/canvancement/blob/834407a65be2ee91ec97b2bdfe4ce58682c2b4e5/canvas-data/mysql/import.sh" class="d-none js-permalink-shortcut" data-hotkey="y">Permalink</a> <!-- blob contrib key: blob_contributors:v21:65f37f1e9fa87caeb88e1dc878c9d0bc --> <div class="file-navigation js-zeroclipboard-container"> <div class="select-menu branch-select-menu js-menu-container js-select-menu float-left"> <button class="btn btn-sm select-menu-button js-menu-target css-truncate" data-hotkey="w" type="button" aria-label="Switch branches or tags" tabindex="0" aria-haspopup="true"> <i>Branch:</i> <span class="js-select-button css-truncate-target">master</span> </button> <div class="select-menu-modal-holder js-menu-content js-navigation-container" data-pjax aria-hidden="true"> <div class="select-menu-modal"> <div class="select-menu-header"> <svg aria-label="Close" class="octicon octicon-x js-menu-close" height="16" role="img" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48z"/></svg> <span class="select-menu-title">Switch branches/tags</span> </div> <div class="select-menu-filters"> <div class="select-menu-text-filter"> <input type="text" aria-label="Filter branches/tags" id="context-commitish-filter-field" class="form-control js-filterable-field js-navigation-enable" placeholder="Filter branches/tags"> </div> <div class="select-menu-tabs"> <ul> <li class="select-menu-tab"> <a href="#" data-tab-filter="branches" data-filter-placeholder="Filter branches/tags" class="js-select-menu-tab" role="tab">Branches</a> </li> <li class="select-menu-tab"> <a href="#" data-tab-filter="tags" data-filter-placeholder="Find a tag…" class="js-select-menu-tab" role="tab">Tags</a> </li> </ul> </div> </div> <div class="select-menu-list select-menu-tab-bucket js-select-menu-tab-bucket" data-tab-filter="branches" role="menu"> <div data-filterable-for="context-commitish-filter-field" data-filterable-type="substring"> <a class="select-menu-item js-navigation-item js-navigation-open selected" href="/jamesjonesmath/canvancement/blob/master/canvas-data/mysql/import.sh" data-name="master" data-skip-pjax="true" rel="nofollow"> <svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"/></svg> <span class="select-menu-item-text css-truncate-target js-select-menu-filter-text"> master </span> </a> </div> <div class="select-menu-no-results">Nothing to show</div> </div> <div class="select-menu-list select-menu-tab-bucket js-select-menu-tab-bucket" data-tab-filter="tags"> <div data-filterable-for="context-commitish-filter-field" data-filterable-type="substring"> </div> <div class="select-menu-no-results">Nothing to show</div> </div> </div> </div> </div> <div class="BtnGroup float-right"> <a href="/jamesjonesmath/canvancement/find/master" class="js-pjax-capture-input btn btn-sm BtnGroup-item" data-pjax data-hotkey="t"> Find file </a> <button aria-label="Copy file path to clipboard" class="js-zeroclipboard btn btn-sm BtnGroup-item tooltipped tooltipped-s" data-copied-hint="Copied!" type="button">Copy path</button> </div> <div class="breadcrumb js-zeroclipboard-target"> <span class="repo-root js-repo-root"><span class="js-path-segment"><a href="/jamesjonesmath/canvancement"><span>canvancement</span></a></span></span><span class="separator">/</span><span class="js-path-segment"><a href="/jamesjonesmath/canvancement/tree/master/canvas-data"><span>canvas-data</span></a></span><span class="separator">/</span><span class="js-path-segment"><a href="/jamesjonesmath/canvancement/tree/master/canvas-data/mysql"><span>mysql</span></a></span><span class="separator">/</span><strong class="final-path">import.sh</strong> </div> </div> <include-fragment class="commit-tease" src="/jamesjonesmath/canvancement/contributors/master/canvas-data/mysql/import.sh"> <div> Fetching contributors&hellip; </div> <div class="commit-tease-contributors"> <img alt="" class="loader-loading float-left" height="16" src="https://assets-cdn.github.com/images/spinners/octocat-spinner-32-EAF2F5.gif" width="16" /> <span class="loader-error">Cannot retrieve contributors at this time</span> </div> </include-fragment> <div class="file"> <div class="file-header"> <div class="file-actions"> <div class="BtnGroup"> <a href="/jamesjonesmath/canvancement/raw/master/canvas-data/mysql/import.sh" class="btn btn-sm BtnGroup-item" id="raw-url">Raw</a> <a href="/jamesjonesmath/canvancement/blame/master/canvas-data/mysql/import.sh" class="btn btn-sm js-update-url-with-hash BtnGroup-item" data-hotkey="b">Blame</a> <a href="/jamesjonesmath/canvancement/commits/master/canvas-data/mysql/import.sh" class="btn btn-sm BtnGroup-item" rel="nofollow">History</a> </div> <a class="btn-octicon tooltipped tooltipped-nw" href="https://windows.github.com" aria-label="Open this file in GitHub Desktop" data-ga-click="Repository, open with desktop, type:windows"> <svg aria-hidden="true" class="octicon octicon-device-desktop" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M15 2H1c-.55 0-1 .45-1 1v9c0 .55.45 1 1 1h5.34c-.25.61-.86 1.39-2.34 2h8c-1.48-.61-2.09-1.39-2.34-2H15c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zm0 9H1V3h14v8z"/></svg> </a> <button type="button" class="btn-octicon disabled tooltipped tooltipped-nw" aria-label="You must be signed in to make or propose changes"> <svg aria-hidden="true" class="octicon octicon-pencil" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M0 12v3h3l8-8-3-3-8 8zm3 2H1v-2h1v1h1v1zm10.3-9.3L12 6 9 3l1.3-1.3a.996.996 0 0 1 1.41 0l1.59 1.59c.39.39.39 1.02 0 1.41z"/></svg> </button> <button type="button" class="btn-octicon btn-octicon-danger disabled tooltipped tooltipped-nw" aria-label="You must be signed in to make or propose changes"> <svg aria-hidden="true" class="octicon octicon-trashcan" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M11 2H9c0-.55-.45-1-1-1H5c-.55 0-1 .45-1 1H2c-.55 0-1 .45-1 1v1c0 .55.45 1 1 1v9c0 .55.45 1 1 1h7c.55 0 1-.45 1-1V5c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zm-1 12H3V5h1v8h1V5h1v8h1V5h1v8h1V5h1v9zm1-10H2V3h9v1z"/></svg> </button> </div> <div class="file-info"> 230 lines (184 sloc) <span class="file-info-divider"></span> 6.57 KB </div> </div> <div itemprop="text" class="blob-wrapper data type-shell"> <table class="highlight tab-size js-file-line-container" data-tab-size="8"> <tr> <td id="L1" class="blob-num js-line-number" data-line-number="1"></td> <td id="LC1" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#!</span>/bin/bash</span></td> </tr> <tr> <td id="L2" class="blob-num js-line-number" data-line-number="2"></td> <td id="LC2" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L3" class="blob-num js-line-number" data-line-number="3"></td> <td id="LC3" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> START OF CONFIGURATION</span></td> </tr> <tr> <td id="L4" class="blob-num js-line-number" data-line-number="4"></td> <td id="LC4" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L5" class="blob-num js-line-number" data-line-number="5"></td> <td id="LC5" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> dbname is the name of the Canvas Data database</span></td> </tr> <tr> <td id="L6" class="blob-num js-line-number" data-line-number="6"></td> <td id="LC6" class="blob-code blob-code-inner js-file-line">dbname=canvas_data</td> </tr> <tr> <td id="L7" class="blob-num js-line-number" data-line-number="7"></td> <td id="LC7" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L8" class="blob-num js-line-number" data-line-number="8"></td> <td id="LC8" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> basedir is the directory containing the data files.</span></td> </tr> <tr> <td id="L9" class="blob-num js-line-number" data-line-number="9"></td> <td id="LC9" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> These may be from the CLI tool or files you&#39;ve manually downloaded</span></td> </tr> <tr> <td id="L10" class="blob-num js-line-number" data-line-number="10"></td> <td id="LC10" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> The names of the files do not depend on the structure of the CLI tool</span></td> </tr> <tr> <td id="L11" class="blob-num js-line-number" data-line-number="11"></td> <td id="LC11" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> It may be a relative path to the current directory or an absolute path</span></td> </tr> <tr> <td id="L12" class="blob-num js-line-number" data-line-number="12"></td> <td id="LC12" class="blob-code blob-code-inner js-file-line">basedir=dataFiles</td> </tr> <tr> <td id="L13" class="blob-num js-line-number" data-line-number="13"></td> <td id="LC13" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L14" class="blob-num js-line-number" data-line-number="14"></td> <td id="LC14" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> checksequence queries the database before importing data to see if</span></td> </tr> <tr> <td id="L15" class="blob-num js-line-number" data-line-number="15"></td> <td id="LC15" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> this sequence has already been imported. It mostly applies to</span></td> </tr> <tr> <td id="L16" class="blob-num js-line-number" data-line-number="16"></td> <td id="LC16" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> incremental files like the requests table. It allows you to leave your</span></td> </tr> <tr> <td id="L17" class="blob-num js-line-number" data-line-number="17"></td> <td id="LC17" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> files on the disk without having to extract them or truncate your tables</span></td> </tr> <tr> <td id="L18" class="blob-num js-line-number" data-line-number="18"></td> <td id="LC18" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> It can also be used to pick back up where you left off, although if the</span></td> </tr> <tr> <td id="L19" class="blob-num js-line-number" data-line-number="19"></td> <td id="LC19" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> sequence bombs in the middle, you may need to truncate the offended table</span></td> </tr> <tr> <td id="L20" class="blob-num js-line-number" data-line-number="20"></td> <td id="LC20" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> Note that this relies on a versions table that was created using the</span></td> </tr> <tr> <td id="L21" class="blob-num js-line-number" data-line-number="21"></td> <td id="LC21" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> accompanying SQL script</span></td> </tr> <tr> <td id="L22" class="blob-num js-line-number" data-line-number="22"></td> <td id="LC22" class="blob-code blob-code-inner js-file-line">checksequence=1</td> </tr> <tr> <td id="L23" class="blob-num js-line-number" data-line-number="23"></td> <td id="LC23" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L24" class="blob-num js-line-number" data-line-number="24"></td> <td id="LC24" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> incrementaltables is a comma separated list of the tables that are partial</span></td> </tr> <tr> <td id="L25" class="blob-num js-line-number" data-line-number="25"></td> <td id="LC25" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> and should not have their tables truncated before importing</span></td> </tr> <tr> <td id="L26" class="blob-num js-line-number" data-line-number="26"></td> <td id="LC26" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> If you are using checksequence=1, then it will try to figure this out from</span></td> </tr> <tr> <td id="L27" class="blob-num js-line-number" data-line-number="27"></td> <td id="LC27" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> the database</span></td> </tr> <tr> <td id="L28" class="blob-num js-line-number" data-line-number="28"></td> <td id="LC28" class="blob-code blob-code-inner js-file-line">incrementaltables=requests</td> </tr> <tr> <td id="L29" class="blob-num js-line-number" data-line-number="29"></td> <td id="LC29" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L30" class="blob-num js-line-number" data-line-number="30"></td> <td id="LC30" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> leaveasgzip temporarily extracts the compressed gzip file for importing</span></td> </tr> <tr> <td id="L31" class="blob-num js-line-number" data-line-number="31"></td> <td id="LC31" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> but then removes the uncompressed version after the import</span></td> </tr> <tr> <td id="L32" class="blob-num js-line-number" data-line-number="32"></td> <td id="LC32" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> This is an attempt to save file space</span></td> </tr> <tr> <td id="L33" class="blob-num js-line-number" data-line-number="33"></td> <td id="LC33" class="blob-code blob-code-inner js-file-line">leaveasgzip=1</td> </tr> <tr> <td id="L34" class="blob-num js-line-number" data-line-number="34"></td> <td id="LC34" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L35" class="blob-num js-line-number" data-line-number="35"></td> <td id="LC35" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> sortdata will pipe the data through the sort -u command</span></td> </tr> <tr> <td id="L36" class="blob-num js-line-number" data-line-number="36"></td> <td id="LC36" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> This can have a huge impact on the import process</span></td> </tr> <tr> <td id="L37" class="blob-num js-line-number" data-line-number="37"></td> <td id="LC37" class="blob-code blob-code-inner js-file-line">sortdata=1</td> </tr> <tr> <td id="L38" class="blob-num js-line-number" data-line-number="38"></td> <td id="LC38" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L39" class="blob-num js-line-number" data-line-number="39"></td> <td id="LC39" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> MYSQL is the mysql command that is needed to execute mysql</span></td> </tr> <tr> <td id="L40" class="blob-num js-line-number" data-line-number="40"></td> <td id="LC40" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> You can put items like username and password here, but it is recommended</span></td> </tr> <tr> <td id="L41" class="blob-num js-line-number" data-line-number="41"></td> <td id="LC41" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> that you configure the ~/.my.cnf file instead</span></td> </tr> <tr> <td id="L42" class="blob-num js-line-number" data-line-number="42"></td> <td id="LC42" class="blob-code blob-code-inner js-file-line">MYSQL=mysql</td> </tr> <tr> <td id="L43" class="blob-num js-line-number" data-line-number="43"></td> <td id="LC43" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L44" class="blob-num js-line-number" data-line-number="44"></td> <td id="LC44" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> verbosity controls the logging of messages</span></td> </tr> <tr> <td id="L45" class="blob-num js-line-number" data-line-number="45"></td> <td id="LC45" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> 0 = no logging of messages</span></td> </tr> <tr> <td id="L46" class="blob-num js-line-number" data-line-number="46"></td> <td id="LC46" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> 1 = minimal logging of 1 per file</span></td> </tr> <tr> <td id="L47" class="blob-num js-line-number" data-line-number="47"></td> <td id="LC47" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> 2 = log importing of data into database</span></td> </tr> <tr> <td id="L48" class="blob-num js-line-number" data-line-number="48"></td> <td id="LC48" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> 3 = more verbose logging including decompressing file and truncating tables</span></td> </tr> <tr> <td id="L49" class="blob-num js-line-number" data-line-number="49"></td> <td id="LC49" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> 4 = log little things that probably don&#39;t need logged</span></td> </tr> <tr> <td id="L50" class="blob-num js-line-number" data-line-number="50"></td> <td id="LC50" class="blob-code blob-code-inner js-file-line">verbosity=1</td> </tr> <tr> <td id="L51" class="blob-num js-line-number" data-line-number="51"></td> <td id="LC51" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L52" class="blob-num js-line-number" data-line-number="52"></td> <td id="LC52" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> END OF CONFIGURATION</span></td> </tr> <tr> <td id="L53" class="blob-num js-line-number" data-line-number="53"></td> <td id="LC53" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L54" class="blob-num js-line-number" data-line-number="54"></td> <td id="LC54" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L55" class="blob-num js-line-number" data-line-number="55"></td> <td id="LC55" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> Create a temporary file to hold all of the files to be considered</span></td> </tr> <tr> <td id="L56" class="blob-num js-line-number" data-line-number="56"></td> <td id="LC56" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> Store only the directory and basenames to allow for both the compressed</span></td> </tr> <tr> <td id="L57" class="blob-num js-line-number" data-line-number="57"></td> <td id="LC57" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> and uncompressed versions to exist</span></td> </tr> <tr> <td id="L58" class="blob-num js-line-number" data-line-number="58"></td> <td id="LC58" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> This file will be created in your systems $TMPDIR folder,</span></td> </tr> <tr> <td id="L59" class="blob-num js-line-number" data-line-number="59"></td> <td id="LC59" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> which is often /tmp or /var/tmp</span></td> </tr> <tr> <td id="L60" class="blob-num js-line-number" data-line-number="60"></td> <td id="LC60" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> The file will be removed if the process successfully completes, but will</span></td> </tr> <tr> <td id="L61" class="blob-num js-line-number" data-line-number="61"></td> <td id="LC61" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> be orphaned if it aborts</span></td> </tr> <tr> <td id="L62" class="blob-num js-line-number" data-line-number="62"></td> <td id="LC62" class="blob-code blob-code-inner js-file-line">tmpfile=<span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-s"><span class="pl-pds">$(</span>mktemp<span class="pl-pds">)</span></span><span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L63" class="blob-num js-line-number" data-line-number="63"></td> <td id="LC63" class="blob-code blob-code-inner js-file-line">find <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${basedir}</span><span class="pl-pds">&quot;</span></span> -type f -regextype posix-egrep -regex <span class="pl-s"><span class="pl-pds">&#39;</span>.*/([0-9]+_)?[a-z_]+-[0-9]{5}-[0-9a-f]{8}(\.gz)?$<span class="pl-pds">&#39;</span></span> -printf <span class="pl-s"><span class="pl-pds">&#39;</span>%h/<span class="pl-pds">&#39;</span></span> -exec basename {} .gz <span class="pl-cce">\;</span> <span class="pl-k">|</span> sort -u <span class="pl-k">&gt;</span> <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${tmpfile}</span><span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L64" class="blob-num js-line-number" data-line-number="64"></td> <td id="LC64" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L65" class="blob-num js-line-number" data-line-number="65"></td> <td id="LC65" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L66" class="blob-num js-line-number" data-line-number="66"></td> <td id="LC66" class="blob-code blob-code-inner js-file-line"><span class="pl-k">if</span> [ <span class="pl-smi">${checksequence}</span> <span class="pl-k">-eq</span> 1 ]</td> </tr> <tr> <td id="L67" class="blob-num js-line-number" data-line-number="67"></td> <td id="LC67" class="blob-code blob-code-inner js-file-line"><span class="pl-k">then</span></td> </tr> <tr> <td id="L68" class="blob-num js-line-number" data-line-number="68"></td> <td id="LC68" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">#</span> Try to fetch the list of incremental tables from the database</span></td> </tr> <tr> <td id="L69" class="blob-num js-line-number" data-line-number="69"></td> <td id="LC69" class="blob-code blob-code-inner js-file-line"> tables=<span class="pl-s"><span class="pl-pds">$(</span> <span class="pl-smi">${MYSQL}</span> <span class="pl-smi">${dbname}</span> -sse <span class="pl-s"><span class="pl-pds">&quot;</span>SELECT CONCAT_WS(&#39;,&#39;, table_name) FROM versions WHERE incremental=1<span class="pl-pds">&quot;</span></span> <span class="pl-pds">)</span></span></td> </tr> <tr> <td id="L70" class="blob-num js-line-number" data-line-number="70"></td> <td id="LC70" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> [ <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${tables}</span><span class="pl-pds">&quot;</span></span> <span class="pl-k">!=</span> <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-pds">&quot;</span></span> ]</td> </tr> <tr> <td id="L71" class="blob-num js-line-number" data-line-number="71"></td> <td id="LC71" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">then</span></td> </tr> <tr> <td id="L72" class="blob-num js-line-number" data-line-number="72"></td> <td id="LC72" class="blob-code blob-code-inner js-file-line"> incrementaltables=<span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${tables}</span><span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L73" class="blob-num js-line-number" data-line-number="73"></td> <td id="LC73" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">fi</span></td> </tr> <tr> <td id="L74" class="blob-num js-line-number" data-line-number="74"></td> <td id="LC74" class="blob-code blob-code-inner js-file-line"><span class="pl-k">fi</span></td> </tr> <tr> <td id="L75" class="blob-num js-line-number" data-line-number="75"></td> <td id="LC75" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L76" class="blob-num js-line-number" data-line-number="76"></td> <td id="LC76" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> Initialize some variables</span></td> </tr> <tr> <td id="L77" class="blob-num js-line-number" data-line-number="77"></td> <td id="LC77" class="blob-code blob-code-inner js-file-line">oldtable=<span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L78" class="blob-num js-line-number" data-line-number="78"></td> <td id="LC78" class="blob-code blob-code-inner js-file-line">oldseq=<span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L79" class="blob-num js-line-number" data-line-number="79"></td> <td id="LC79" class="blob-code blob-code-inner js-file-line">hasprocessed=0</td> </tr> <tr> <td id="L80" class="blob-num js-line-number" data-line-number="80"></td> <td id="LC80" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L81" class="blob-num js-line-number" data-line-number="81"></td> <td id="LC81" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> Iterate through the files</span></td> </tr> <tr> <td id="L82" class="blob-num js-line-number" data-line-number="82"></td> <td id="LC82" class="blob-code blob-code-inner js-file-line"><span class="pl-k">for</span> <span class="pl-smi">pathname</span> <span class="pl-k">in</span> <span class="pl-s"><span class="pl-pds">$(</span>cat <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${tmpfile}</span><span class="pl-pds">&quot;</span></span><span class="pl-pds">)</span></span></td> </tr> <tr> <td id="L83" class="blob-num js-line-number" data-line-number="83"></td> <td id="LC83" class="blob-code blob-code-inner js-file-line"><span class="pl-k">do</span></td> </tr> <tr> <td id="L84" class="blob-num js-line-number" data-line-number="84"></td> <td id="LC84" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L85" class="blob-num js-line-number" data-line-number="85"></td> <td id="LC85" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> [ <span class="pl-smi">${verbosity}</span> <span class="pl-k">-gt</span> 0 ]</td> </tr> <tr> <td id="L86" class="blob-num js-line-number" data-line-number="86"></td> <td id="LC86" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">then</span></td> </tr> <tr> <td id="L87" class="blob-num js-line-number" data-line-number="87"></td> <td id="LC87" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">echo</span> <span class="pl-s"><span class="pl-pds">&quot;</span>Processing <span class="pl-smi">${pathname}</span><span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L88" class="blob-num js-line-number" data-line-number="88"></td> <td id="LC88" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">fi</span></td> </tr> <tr> <td id="L89" class="blob-num js-line-number" data-line-number="89"></td> <td id="LC89" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L90" class="blob-num js-line-number" data-line-number="90"></td> <td id="LC90" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">#</span> Split the filename into parts</span></td> </tr> <tr> <td id="L91" class="blob-num js-line-number" data-line-number="91"></td> <td id="LC91" class="blob-code blob-code-inner js-file-line"> dirname=<span class="pl-s"><span class="pl-pds">$(</span>dirname <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${pathname}</span><span class="pl-pds">&quot;</span></span><span class="pl-pds">)</span></span></td> </tr> <tr> <td id="L92" class="blob-num js-line-number" data-line-number="92"></td> <td id="LC92" class="blob-code blob-code-inner js-file-line"> filename=<span class="pl-s"><span class="pl-pds">$(</span>basename <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${pathname}</span><span class="pl-pds">&quot;</span></span><span class="pl-pds">)</span></span></td> </tr> <tr> <td id="L93" class="blob-num js-line-number" data-line-number="93"></td> <td id="LC93" class="blob-code blob-code-inner js-file-line"> firstpart=<span class="pl-s"><span class="pl-pds">$(</span>echo <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${filename}</span><span class="pl-pds">&quot;</span></span> <span class="pl-k">|</span> cut -f1 -d-<span class="pl-pds">)</span></span></td> </tr> <tr> <td id="L94" class="blob-num js-line-number" data-line-number="94"></td> <td id="LC94" class="blob-code blob-code-inner js-file-line"> tablepart=<span class="pl-s"><span class="pl-pds">$(</span>echo <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${firstpart}</span><span class="pl-pds">&quot;</span></span> <span class="pl-k">|</span> sed -r <span class="pl-s"><span class="pl-pds">&quot;</span>s/^[0-9]+_//<span class="pl-pds">&quot;</span></span><span class="pl-pds">)</span></span></td> </tr> <tr> <td id="L95" class="blob-num js-line-number" data-line-number="95"></td> <td id="LC95" class="blob-code blob-code-inner js-file-line"> seqpart=<span class="pl-s"><span class="pl-pds">$(</span>echo <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${firstpart}</span><span class="pl-pds">&quot;</span></span> <span class="pl-k">|</span> grep -Eo <span class="pl-s"><span class="pl-pds">&quot;</span>^[0-9]+<span class="pl-pds">&quot;</span></span><span class="pl-pds">)</span></span></td> </tr> <tr> <td id="L96" class="blob-num js-line-number" data-line-number="96"></td> <td id="LC96" class="blob-code blob-code-inner js-file-line"> numidpart=<span class="pl-s"><span class="pl-pds">$(</span>echo <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${filename}</span><span class="pl-pds">&quot;</span></span> <span class="pl-k">|</span> cut -f2- -d-<span class="pl-pds">)</span></span></td> </tr> <tr> <td id="L97" class="blob-num js-line-number" data-line-number="97"></td> <td id="LC97" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L98" class="blob-num js-line-number" data-line-number="98"></td> <td id="LC98" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">#</span> Check to see if the previous table has been processed, if so then update the database</span></td> </tr> <tr> <td id="L99" class="blob-num js-line-number" data-line-number="99"></td> <td id="LC99" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> [ <span class="pl-smi">${hasprocessed}</span> <span class="pl-k">-eq</span> 1 <span class="pl-k">-a</span> <span class="pl-smi">${checksequence}</span> <span class="pl-k">-eq</span> 1 <span class="pl-k">-a</span> <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${oldtable}</span><span class="pl-pds">&quot;</span></span> <span class="pl-k">!=</span> <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${tablepart}</span><span class="pl-pds">&quot;</span></span> <span class="pl-k">-a</span> <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">$oldseq</span><span class="pl-pds">&quot;</span></span> <span class="pl-k">!=</span> <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-pds">&quot;</span></span> ]</td> </tr> <tr> <td id="L100" class="blob-num js-line-number" data-line-number="100"></td> <td id="LC100" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">then</span></td> </tr> <tr> <td id="L101" class="blob-num js-line-number" data-line-number="101"></td> <td id="LC101" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L102" class="blob-num js-line-number" data-line-number="102"></td> <td id="LC102" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> [ <span class="pl-smi">${verbosity}</span> <span class="pl-k">-ge</span> 4 ]</td> </tr> <tr> <td id="L103" class="blob-num js-line-number" data-line-number="103"></td> <td id="LC103" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">then</span></td> </tr> <tr> <td id="L104" class="blob-num js-line-number" data-line-number="104"></td> <td id="LC104" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">echo</span> <span class="pl-s"><span class="pl-pds">&quot;</span>Updating sequence number for <span class="pl-smi">${oldtable}</span> to <span class="pl-smi">${oldseq}</span><span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L105" class="blob-num js-line-number" data-line-number="105"></td> <td id="LC105" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">fi</span></td> </tr> <tr> <td id="L106" class="blob-num js-line-number" data-line-number="106"></td> <td id="LC106" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L107" class="blob-num js-line-number" data-line-number="107"></td> <td id="LC107" class="blob-code blob-code-inner js-file-line"> <span class="pl-s"><span class="pl-pds">$(</span> <span class="pl-smi">${MYSQL}</span> <span class="pl-smi">${dbname}</span> -sqe <span class="pl-s"><span class="pl-pds">&quot;</span>UPDATE versions SET version = <span class="pl-smi">${oldseq}</span> WHERE table_name = &#39;<span class="pl-smi">${oldtable}</span>&#39;<span class="pl-pds">&quot;</span></span> <span class="pl-pds">)</span></span></td> </tr> <tr> <td id="L108" class="blob-num js-line-number" data-line-number="108"></td> <td id="LC108" class="blob-code blob-code-inner js-file-line"> hasprocessed=0</td> </tr> <tr> <td id="L109" class="blob-num js-line-number" data-line-number="109"></td> <td id="LC109" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">fi</span></td> </tr> <tr> <td id="L110" class="blob-num js-line-number" data-line-number="110"></td> <td id="LC110" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L111" class="blob-num js-line-number" data-line-number="111"></td> <td id="LC111" class="blob-code blob-code-inner js-file-line"> process=1</td> </tr> <tr> <td id="L112" class="blob-num js-line-number" data-line-number="112"></td> <td id="LC112" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L113" class="blob-num js-line-number" data-line-number="113"></td> <td id="LC113" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">#</span> Get the last version imported</span></td> </tr> <tr> <td id="L114" class="blob-num js-line-number" data-line-number="114"></td> <td id="LC114" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> [ <span class="pl-smi">${checksequence}</span> <span class="pl-k">-eq</span> 1 <span class="pl-k">-a</span> <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">$seqpart</span><span class="pl-pds">&quot;</span></span> <span class="pl-k">!=</span> <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-pds">&quot;</span></span> ]</td> </tr> <tr> <td id="L115" class="blob-num js-line-number" data-line-number="115"></td> <td id="LC115" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">then</span></td> </tr> <tr> <td id="L116" class="blob-num js-line-number" data-line-number="116"></td> <td id="LC116" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L117" class="blob-num js-line-number" data-line-number="117"></td> <td id="LC117" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> [ <span class="pl-smi">${verbosity}</span> <span class="pl-k">-ge</span> 4 ]</td> </tr> <tr> <td id="L118" class="blob-num js-line-number" data-line-number="118"></td> <td id="LC118" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">then</span></td> </tr> <tr> <td id="L119" class="blob-num js-line-number" data-line-number="119"></td> <td id="LC119" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">echo</span> <span class="pl-s"><span class="pl-pds">&quot;</span>Checking for previously saved version of <span class="pl-smi">${tablepart}</span><span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L120" class="blob-num js-line-number" data-line-number="120"></td> <td id="LC120" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">fi</span></td> </tr> <tr> <td id="L121" class="blob-num js-line-number" data-line-number="121"></td> <td id="LC121" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L122" class="blob-num js-line-number" data-line-number="122"></td> <td id="LC122" class="blob-code blob-code-inner js-file-line"> extseq=<span class="pl-s"><span class="pl-pds">$(</span> <span class="pl-smi">${MYSQL}</span> <span class="pl-smi">${dbname}</span> -sse <span class="pl-s"><span class="pl-pds">&quot;</span>SELECT IFNULL(version,0) FROM versions WHERE table_name=&#39;<span class="pl-smi">${tablepart}</span>&#39;<span class="pl-pds">&quot;</span></span> <span class="pl-pds">)</span></span></td> </tr> <tr> <td id="L123" class="blob-num js-line-number" data-line-number="123"></td> <td id="LC123" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> [ <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${extseq}</span><span class="pl-pds">&quot;</span></span> <span class="pl-k">==</span> <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-pds">&quot;</span></span> <span class="pl-k">-o</span> <span class="pl-smi">${extseq}</span> <span class="pl-k">-ge</span> <span class="pl-smi">$seqpart</span> ]</td> </tr> <tr> <td id="L124" class="blob-num js-line-number" data-line-number="124"></td> <td id="LC124" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">then</span></td> </tr> <tr> <td id="L125" class="blob-num js-line-number" data-line-number="125"></td> <td id="LC125" class="blob-code blob-code-inner js-file-line"> process=0</td> </tr> <tr> <td id="L126" class="blob-num js-line-number" data-line-number="126"></td> <td id="LC126" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">fi</span></td> </tr> <tr> <td id="L127" class="blob-num js-line-number" data-line-number="127"></td> <td id="LC127" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">fi</span></td> </tr> <tr> <td id="L128" class="blob-num js-line-number" data-line-number="128"></td> <td id="LC128" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L129" class="blob-num js-line-number" data-line-number="129"></td> <td id="LC129" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">#</span> Process this file</span></td> </tr> <tr> <td id="L130" class="blob-num js-line-number" data-line-number="130"></td> <td id="LC130" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> [ <span class="pl-smi">${process}</span> <span class="pl-k">-eq</span> 1 ]</td> </tr> <tr> <td id="L131" class="blob-num js-line-number" data-line-number="131"></td> <td id="LC131" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">then</span></td> </tr> <tr> <td id="L132" class="blob-num js-line-number" data-line-number="132"></td> <td id="LC132" class="blob-code blob-code-inner js-file-line"> removefile=0</td> </tr> <tr> <td id="L133" class="blob-num js-line-number" data-line-number="133"></td> <td id="LC133" class="blob-code blob-code-inner js-file-line"> datafile=<span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${dirname}</span>/<span class="pl-smi">${filename}</span><span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L134" class="blob-num js-line-number" data-line-number="134"></td> <td id="LC134" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> [ <span class="pl-k">!</span> <span class="pl-k">-f</span> <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${datafile}</span><span class="pl-pds">&quot;</span></span> ]</td> </tr> <tr> <td id="L135" class="blob-num js-line-number" data-line-number="135"></td> <td id="LC135" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">then</span></td> </tr> <tr> <td id="L136" class="blob-num js-line-number" data-line-number="136"></td> <td id="LC136" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">#</span> There is no already-extracted file</span></td> </tr> <tr> <td id="L137" class="blob-num js-line-number" data-line-number="137"></td> <td id="LC137" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> [ <span class="pl-k">-f</span> <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${datafile}</span>.gz<span class="pl-pds">&quot;</span></span> ]</td> </tr> <tr> <td id="L138" class="blob-num js-line-number" data-line-number="138"></td> <td id="LC138" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">then</span></td> </tr> <tr> <td id="L139" class="blob-num js-line-number" data-line-number="139"></td> <td id="LC139" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">#</span> There is a gzipped version</span></td> </tr> <tr> <td id="L140" class="blob-num js-line-number" data-line-number="140"></td> <td id="LC140" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L141" class="blob-num js-line-number" data-line-number="141"></td> <td id="LC141" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> [ <span class="pl-smi">${verbosity}</span> <span class="pl-k">-ge</span> 3 ]</td> </tr> <tr> <td id="L142" class="blob-num js-line-number" data-line-number="142"></td> <td id="LC142" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">then</span></td> </tr> <tr> <td id="L143" class="blob-num js-line-number" data-line-number="143"></td> <td id="LC143" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">echo</span> <span class="pl-s"><span class="pl-pds">&quot;</span>Uncompressing <span class="pl-smi">${filename}</span><span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L144" class="blob-num js-line-number" data-line-number="144"></td> <td id="LC144" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">fi</span></td> </tr> <tr> <td id="L145" class="blob-num js-line-number" data-line-number="145"></td> <td id="LC145" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L146" class="blob-num js-line-number" data-line-number="146"></td> <td id="LC146" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> [ <span class="pl-smi">${leaveasgzip}</span> <span class="pl-k">-eq</span> 1 ]</td> </tr> <tr> <td id="L147" class="blob-num js-line-number" data-line-number="147"></td> <td id="LC147" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">then</span></td> </tr> <tr> <td id="L148" class="blob-num js-line-number" data-line-number="148"></td> <td id="LC148" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">#</span> Extract it, but plan on removing it later</span></td> </tr> <tr> <td id="L149" class="blob-num js-line-number" data-line-number="149"></td> <td id="LC149" class="blob-code blob-code-inner js-file-line"> gzip -dc <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${datafile}</span>.gz<span class="pl-pds">&quot;</span></span> <span class="pl-k">&gt;</span> <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${datafile}</span><span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L150" class="blob-num js-line-number" data-line-number="150"></td> <td id="LC150" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> [ <span class="pl-smi">${sortdata}</span> <span class="pl-k">-eq</span> 1 ]</td> </tr> <tr> <td id="L151" class="blob-num js-line-number" data-line-number="151"></td> <td id="LC151" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">then</span></td> </tr> <tr> <td id="L152" class="blob-num js-line-number" data-line-number="152"></td> <td id="LC152" class="blob-code blob-code-inner js-file-line"> sort -u -o <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${datafile}</span><span class="pl-pds">&quot;</span></span> <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${datafile}</span><span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L153" class="blob-num js-line-number" data-line-number="153"></td> <td id="LC153" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">fi</span></td> </tr> <tr> <td id="L154" class="blob-num js-line-number" data-line-number="154"></td> <td id="LC154" class="blob-code blob-code-inner js-file-line"> removefile=1</td> </tr> <tr> <td id="L155" class="blob-num js-line-number" data-line-number="155"></td> <td id="LC155" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">else</span></td> </tr> <tr> <td id="L156" class="blob-num js-line-number" data-line-number="156"></td> <td id="LC156" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">#</span> Extract it and leave it extracted</span></td> </tr> <tr> <td id="L157" class="blob-num js-line-number" data-line-number="157"></td> <td id="LC157" class="blob-code blob-code-inner js-file-line"> gzip -d <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${datafile}</span>.gz<span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L158" class="blob-num js-line-number" data-line-number="158"></td> <td id="LC158" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> [ <span class="pl-smi">${sortdata}</span> <span class="pl-k">-eq</span> 1 ]</td> </tr> <tr> <td id="L159" class="blob-num js-line-number" data-line-number="159"></td> <td id="LC159" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">then</span></td> </tr> <tr> <td id="L160" class="blob-num js-line-number" data-line-number="160"></td> <td id="LC160" class="blob-code blob-code-inner js-file-line"> sort -u -o <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${datafile}</span><span class="pl-pds">&quot;</span></span> <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${datafile}</span><span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L161" class="blob-num js-line-number" data-line-number="161"></td> <td id="LC161" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">fi</span></td> </tr> <tr> <td id="L162" class="blob-num js-line-number" data-line-number="162"></td> <td id="LC162" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">fi</span></td> </tr> <tr> <td id="L163" class="blob-num js-line-number" data-line-number="163"></td> <td id="LC163" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">fi</span></td> </tr> <tr> <td id="L164" class="blob-num js-line-number" data-line-number="164"></td> <td id="LC164" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">fi</span></td> </tr> <tr> <td id="L165" class="blob-num js-line-number" data-line-number="165"></td> <td id="LC165" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L166" class="blob-num js-line-number" data-line-number="166"></td> <td id="LC166" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">#</span> Check to see if this is an incremental table</span></td> </tr> <tr> <td id="L167" class="blob-num js-line-number" data-line-number="167"></td> <td id="LC167" class="blob-code blob-code-inner js-file-line"> partial=0</td> </tr> <tr> <td id="L168" class="blob-num js-line-number" data-line-number="168"></td> <td id="LC168" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> [ <span class="pl-s"><span class="pl-pds">&quot;</span>x<span class="pl-smi">${incrementaltables<span class="pl-k">/</span><span class="pl-smi">$tablepart</span>}</span><span class="pl-pds">&quot;</span></span> <span class="pl-k">!=</span> <span class="pl-s"><span class="pl-pds">&quot;</span>x<span class="pl-smi">${incrementaltables}</span><span class="pl-pds">&quot;</span></span> ]</td> </tr> <tr> <td id="L169" class="blob-num js-line-number" data-line-number="169"></td> <td id="LC169" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">then</span></td> </tr> <tr> <td id="L170" class="blob-num js-line-number" data-line-number="170"></td> <td id="LC170" class="blob-code blob-code-inner js-file-line"> partial=1</td> </tr> <tr> <td id="L171" class="blob-num js-line-number" data-line-number="171"></td> <td id="LC171" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">fi</span></td> </tr> <tr> <td id="L172" class="blob-num js-line-number" data-line-number="172"></td> <td id="LC172" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L173" class="blob-num js-line-number" data-line-number="173"></td> <td id="LC173" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">#</span> If it is incremental or the previous file used the same table,</span></td> </tr> <tr> <td id="L174" class="blob-num js-line-number" data-line-number="174"></td> <td id="LC174" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">#</span> then don&#39;t truncate it first, but do an append instead</span></td> </tr> <tr> <td id="L175" class="blob-num js-line-number" data-line-number="175"></td> <td id="LC175" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> [ <span class="pl-smi">${partial}</span> <span class="pl-k">-eq</span> 0 <span class="pl-k">-a</span> <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${oldtable}</span><span class="pl-pds">&quot;</span></span> <span class="pl-k">!=</span> <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${tablepart}</span><span class="pl-pds">&quot;</span></span> ]</td> </tr> <tr> <td id="L176" class="blob-num js-line-number" data-line-number="176"></td> <td id="LC176" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">then</span></td> </tr> <tr> <td id="L177" class="blob-num js-line-number" data-line-number="177"></td> <td id="LC177" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L178" class="blob-num js-line-number" data-line-number="178"></td> <td id="LC178" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> [ <span class="pl-smi">${verbosity}</span> <span class="pl-k">-ge</span> 3 ]</td> </tr> <tr> <td id="L179" class="blob-num js-line-number" data-line-number="179"></td> <td id="LC179" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">then</span></td> </tr> <tr> <td id="L180" class="blob-num js-line-number" data-line-number="180"></td> <td id="LC180" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">echo</span> <span class="pl-s"><span class="pl-pds">&quot;</span>Truncating <span class="pl-smi">${tablepart}</span><span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L181" class="blob-num js-line-number" data-line-number="181"></td> <td id="LC181" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">fi</span></td> </tr> <tr> <td id="L182" class="blob-num js-line-number" data-line-number="182"></td> <td id="LC182" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L183" class="blob-num js-line-number" data-line-number="183"></td> <td id="LC183" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">${MYSQL}</span> <span class="pl-smi">${dbname}</span> -sqe <span class="pl-s"><span class="pl-pds">&quot;</span>TRUNCATE <span class="pl-smi">${tablepart}</span><span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L184" class="blob-num js-line-number" data-line-number="184"></td> <td id="LC184" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L185" class="blob-num js-line-number" data-line-number="185"></td> <td id="LC185" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">fi</span></td> </tr> <tr> <td id="L186" class="blob-num js-line-number" data-line-number="186"></td> <td id="LC186" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">#</span> Load the data into the table</span></td> </tr> <tr> <td id="L187" class="blob-num js-line-number" data-line-number="187"></td> <td id="LC187" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L188" class="blob-num js-line-number" data-line-number="188"></td> <td id="LC188" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> [ <span class="pl-smi">${verbosity}</span> <span class="pl-k">-ge</span> 2 ]</td> </tr> <tr> <td id="L189" class="blob-num js-line-number" data-line-number="189"></td> <td id="LC189" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">then</span></td> </tr> <tr> <td id="L190" class="blob-num js-line-number" data-line-number="190"></td> <td id="LC190" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">echo</span> <span class="pl-s"><span class="pl-pds">&quot;</span>Loading <span class="pl-smi">${filename}</span> into <span class="pl-smi">${tablepart}</span><span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L191" class="blob-num js-line-number" data-line-number="191"></td> <td id="LC191" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">fi</span></td> </tr> <tr> <td id="L192" class="blob-num js-line-number" data-line-number="192"></td> <td id="LC192" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L193" class="blob-num js-line-number" data-line-number="193"></td> <td id="LC193" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">${MYSQL}</span> <span class="pl-smi">${dbname}</span> -sqe <span class="pl-s"><span class="pl-pds">&quot;</span>LOAD DATA LOCAL INFILE &#39;<span class="pl-smi">${datafile}</span>&#39; INTO TABLE <span class="pl-smi">${tablepart}</span><span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L194" class="blob-num js-line-number" data-line-number="194"></td> <td id="LC194" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L195" class="blob-num js-line-number" data-line-number="195"></td> <td id="LC195" class="blob-code blob-code-inner js-file-line"> hasprocessed=1</td> </tr> <tr> <td id="L196" class="blob-num js-line-number" data-line-number="196"></td> <td id="LC196" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">#</span> Remove the uncompressed version if needed</span></td> </tr> <tr> <td id="L197" class="blob-num js-line-number" data-line-number="197"></td> <td id="LC197" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> [ <span class="pl-smi">${removefile}</span> <span class="pl-k">-eq</span> 1 ]</td> </tr> <tr> <td id="L198" class="blob-num js-line-number" data-line-number="198"></td> <td id="LC198" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">then</span></td> </tr> <tr> <td id="L199" class="blob-num js-line-number" data-line-number="199"></td> <td id="LC199" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L200" class="blob-num js-line-number" data-line-number="200"></td> <td id="LC200" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> [ <span class="pl-smi">${verbosity}</span> <span class="pl-k">-ge</span> 4 ]</td> </tr> <tr> <td id="L201" class="blob-num js-line-number" data-line-number="201"></td> <td id="LC201" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">then</span></td> </tr> <tr> <td id="L202" class="blob-num js-line-number" data-line-number="202"></td> <td id="LC202" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">echo</span> <span class="pl-s"><span class="pl-pds">&quot;</span>Removing uncompressed version of <span class="pl-smi">${datafile}</span><span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L203" class="blob-num js-line-number" data-line-number="203"></td> <td id="LC203" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">fi</span></td> </tr> <tr> <td id="L204" class="blob-num js-line-number" data-line-number="204"></td> <td id="LC204" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L205" class="blob-num js-line-number" data-line-number="205"></td> <td id="LC205" class="blob-code blob-code-inner js-file-line"> rm <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${datafile}</span><span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L206" class="blob-num js-line-number" data-line-number="206"></td> <td id="LC206" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">fi</span></td> </tr> <tr> <td id="L207" class="blob-num js-line-number" data-line-number="207"></td> <td id="LC207" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L208" class="blob-num js-line-number" data-line-number="208"></td> <td id="LC208" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">fi</span></td> </tr> <tr> <td id="L209" class="blob-num js-line-number" data-line-number="209"></td> <td id="LC209" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L210" class="blob-num js-line-number" data-line-number="210"></td> <td id="LC210" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">#</span> Update the previous table and sequence data</span></td> </tr> <tr> <td id="L211" class="blob-num js-line-number" data-line-number="211"></td> <td id="LC211" class="blob-code blob-code-inner js-file-line"> oldtable=<span class="pl-smi">${tablepart}</span></td> </tr> <tr> <td id="L212" class="blob-num js-line-number" data-line-number="212"></td> <td id="LC212" class="blob-code blob-code-inner js-file-line"> oldseq=<span class="pl-smi">${seqpart}</span></td> </tr> <tr> <td id="L213" class="blob-num js-line-number" data-line-number="213"></td> <td id="LC213" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L214" class="blob-num js-line-number" data-line-number="214"></td> <td id="LC214" class="blob-code blob-code-inner js-file-line"><span class="pl-k">done</span></td> </tr> <tr> <td id="L215" class="blob-num js-line-number" data-line-number="215"></td> <td id="LC215" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L216" class="blob-num js-line-number" data-line-number="216"></td> <td id="LC216" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> Update the sequence on the final file if necessary</span></td> </tr> <tr> <td id="L217" class="blob-num js-line-number" data-line-number="217"></td> <td id="LC217" class="blob-code blob-code-inner js-file-line"><span class="pl-k">if</span> [ <span class="pl-smi">${hasprocessed}</span> <span class="pl-k">-eq</span> 1 <span class="pl-k">-a</span> <span class="pl-smi">${checksequence}</span> <span class="pl-k">-eq</span> 1 <span class="pl-k">-a</span> <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${oldtable}</span><span class="pl-pds">&quot;</span></span> <span class="pl-k">!=</span> <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-pds">&quot;</span></span> <span class="pl-k">-a</span> <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">$oldseq</span><span class="pl-pds">&quot;</span></span> <span class="pl-k">!=</span> <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-pds">&quot;</span></span> ]</td> </tr> <tr> <td id="L218" class="blob-num js-line-number" data-line-number="218"></td> <td id="LC218" class="blob-code blob-code-inner js-file-line"><span class="pl-k">then</span></td> </tr> <tr> <td id="L219" class="blob-num js-line-number" data-line-number="219"></td> <td id="LC219" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L220" class="blob-num js-line-number" data-line-number="220"></td> <td id="LC220" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> [ <span class="pl-smi">${verbosity}</span> <span class="pl-k">-ge</span> 4 ]</td> </tr> <tr> <td id="L221" class="blob-num js-line-number" data-line-number="221"></td> <td id="LC221" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">then</span></td> </tr> <tr> <td id="L222" class="blob-num js-line-number" data-line-number="222"></td> <td id="LC222" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">echo</span> <span class="pl-s"><span class="pl-pds">&quot;</span>Updating sequence number for <span class="pl-smi">${oldtable}</span> to <span class="pl-smi">${oldseq}</span><span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L223" class="blob-num js-line-number" data-line-number="223"></td> <td id="LC223" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">fi</span></td> </tr> <tr> <td id="L224" class="blob-num js-line-number" data-line-number="224"></td> <td id="LC224" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L225" class="blob-num js-line-number" data-line-number="225"></td> <td id="LC225" class="blob-code blob-code-inner js-file-line"> <span class="pl-s"><span class="pl-pds">$(</span> <span class="pl-smi">${MYSQL}</span> <span class="pl-smi">${dbname}</span> -sqe <span class="pl-s"><span class="pl-pds">&quot;</span>UPDATE versions SET version = <span class="pl-smi">${oldseq}</span> WHERE table_name = &#39;<span class="pl-smi">${oldtable}</span>&#39;<span class="pl-pds">&quot;</span></span> <span class="pl-pds">)</span></span></td> </tr> <tr> <td id="L226" class="blob-num js-line-number" data-line-number="226"></td> <td id="LC226" class="blob-code blob-code-inner js-file-line"><span class="pl-k">fi</span></td> </tr> <tr> <td id="L227" class="blob-num js-line-number" data-line-number="227"></td> <td id="LC227" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L228" class="blob-num js-line-number" data-line-number="228"></td> <td id="LC228" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">#</span> Remove the list of files</span></td> </tr> <tr> <td id="L229" class="blob-num js-line-number" data-line-number="229"></td> <td id="LC229" class="blob-code blob-code-inner js-file-line">rm <span class="pl-s"><span class="pl-pds">&quot;</span><span class="pl-smi">${tmpfile}</span><span class="pl-pds">&quot;</span></span></td> </tr> </table> </div> </div> <button type="button" data-facebox="#jump-to-line" data-facebox-class="linejump" data-hotkey="l" class="d-none">Jump to Line</button> <div id="jump-to-line" style="display:none"> <!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="" class="js-jump-to-line-form" method="get"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /></div> <input class="form-control linejump-input js-jump-to-line-field" type="text" placeholder="Jump to line&hellip;" aria-label="Jump to line" autofocus> <button type="submit" class="btn">Go</button> </form></div> </div> <div class="modal-backdrop js-touch-events"></div> </div> </div> </div> </div> <div class="container site-footer-container"> <div class="site-footer" role="contentinfo"> <ul class="site-footer-links float-right"> <li><a href="https://github.com/contact" data-ga-click="Footer, go to contact, text:contact">Contact GitHub</a></li> <li><a href="https://developer.github.com" data-ga-click="Footer, go to api, text:api">API</a></li> <li><a href="https://training.github.com" data-ga-click="Footer, go to training, text:training">Training</a></li> <li><a href="https://shop.github.com" data-ga-click="Footer, go to shop, text:shop">Shop</a></li> <li><a href="https://github.com/blog" data-ga-click="Footer, go to blog, text:blog">Blog</a></li> <li><a href="https://github.com/about" data-ga-click="Footer, go to about, text:about">About</a></li> </ul> <a href="https://github.com" aria-label="Homepage" class="site-footer-mark" title="GitHub"> <svg aria-hidden="true" class="octicon octicon-mark-github" height="24" version="1.1" viewBox="0 0 16 16" width="24"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 172.16.17.32.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"/></svg> </a> <ul class="site-footer-links"> <li>&copy; 2017 <span title="0.12658s from github-fe145-cp1-prd.iad.github.net">GitHub</span>, Inc.</li> <li><a href="https://github.com/site/terms" data-ga-click="Footer, go to terms, text:terms">Terms</a></li> <li><a href="https://github.com/site/privacy" data-ga-click="Footer, go to privacy, text:privacy">Privacy</a></li> <li><a href="https://github.com/security" data-ga-click="Footer, go to security, text:security">Security</a></li> <li><a href="https://status.github.com/" data-ga-click="Footer, go to status, text:status">Status</a></li> <li><a href="https://help.github.com" data-ga-click="Footer, go to help, text:help">Help</a></li> </ul> </div> </div> <div id="ajax-error-message" class="ajax-error-message flash flash-error"> <svg aria-hidden="true" class="octicon octicon-alert" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M8.865 1.52c-.18-.31-.51-.5-.87-.5s-.69.19-.87.5L.275 13.5c-.18.31-.18.69 0 1 .19.31.52.5.87.5h13.7c.36 0 .69-.19.86-.5.17-.31.18-.69.01-1L8.865 1.52zM8.995 13h-2v-2h2v2zm0-3h-2V6h2v4z"/></svg> <button type="button" class="flash-close js-flash-close js-ajax-error-dismiss" aria-label="Dismiss error"> <svg aria-hidden="true" class="octicon octicon-x" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48z"/></svg> </button> You can't perform that action at this time. </div> <script crossorigin="anonymous" integrity="<KEY> src="https://assets-cdn.github.com/assets/frameworks-0e60113e819f4a848338c285bca43f146ee807b883c0ae843d849d7af5ab2c99.js"></script> <script async="async" crossorigin="anonymous" integrity="<KEY> src="https://assets-cdn.github.com/assets/github-0e004cb8e670680f43c688b6ef67d59e40aa8dab4801d8aa4dca0f2fa37ff802.js"></script> <div class="js-stale-session-flash stale-session-flash flash flash-warn flash-banner d-none"> <svg aria-hidden="true" class="octicon octicon-alert" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M8.865 1.52c-.18-.31-.51-.5-.87-.5s-.69.19-.87.5L.275 13.5c-.18.31-.18.69 0 1 .19.31.52.5.87.5h13.7c.36 0 .69-.19.86-.5.17-.31.18-.69.01-1L8.865 1.52zM8.995 13h-2v-2h2v2zm0-3h-2V6h2v4z"/></svg> <span class="signed-in-tab-flash">You signed in with another tab or window. <a href="">Reload</a> to refresh your session.</span> <span class="signed-out-tab-flash">You signed out in another tab or window. <a href="">Reload</a> to refresh your session.</span> </div> <div class="facebox" id="facebox" style="display:none;"> <div class="facebox-popup"> <div class="facebox-content" role="dialog" aria-labelledby="facebox-header" aria-describedby="facebox-description"> </div> <button type="button" class="facebox-close js-facebox-close" aria-label="Close modal"> <svg aria-hidden="true" class="octicon octicon-x" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48z"/></svg> </button> </div> </div> </body> </html> <file_sep>/canvas-data-cli/README.md # Canvas Data CLI A small CLI tool for syncing data from the Canvas Data API. NOTE: this is currently in beta, please report any bugs or issues you find! ## Installing ### Prerequisites This tool should work on Linux, OSX, and Windows. The tool uses node.js runtime, which you will need to install before being able to use it. 1. Install Node.js - Any version newer than 0.12.0 should work, best bet is to follow the instructions [here](https://nodejs.org/en/download/package-manager/) ### Install via npm `npm install -g canvas-data-cli` ### OR Install from github `git clone https://github.com/instructure/canvas-data-cli.git && cd canvas-data-cli && make installLocal` ### Configuring The Canvas Data CLI requires a configuration file with a fields set. Canvas Data CLI uses a small javascript file as configuration file. To generate a stub of this configuration run `canvasDataCli sampleConfig` which will create a `config.js.sample` file. Rename this to a file, like `config.js`. Edit the file to point to where you want to save the files as well as the file used to track the state of which data exports you have already downloaded. By default the sample config file tries to pull your API key and secret from environment variables, `CD_API_KEY` and `CD_API_SECRET`, which is more secure, however, you can also hard code the credentials in the config file. #### Configuring an HTTP Proxy canvas-data-cli has support for HTTP Proxies, both with and without basic authentication. To do this there are three extra options you can add to your config file. `httpsProxy`, `proxyUsername`, and `proxyPassword`. | Config Option | Value | |:--------------|:----------------------------------------------------------------------------------------| | httpsProxy | the `host:port` of the https proxy. Ideally it'd look like: `https_proxy_stuff.com:433` | | proxyUsername | the basic auth username for the https proxy. | | proxyPassword | the basic auth password for the https proxy. | ## Usage ### Syncing If you want to simply download all the data from Canva Data, the `sync` command can be used to keep an up-to-date copy locally. ```Shell canvasDataCli sync -c path/to/config.js ``` This will start the sync process. The sync process uses the `sync` api endpoint to get a list of all the files. If the file does not exist, it will download it. Otherwise, it will skip the file. After downloading all files, it will delete any unexpected files in the directory to remove old data. On subsequent executions, it will only download the files it doesn't have. This process is also resumeable, if for whatever reason you have issues, it should restart and download only the files that previously failed. One of the ways to make this more safe is that it downloads the file to a temporary name and renames it once the process is finished. This may leave around `gz.tmp` files, but they should get deleted automatically once you have a successful run. If you run this daily, you should keep all of your data from Canvas Data up to date. ### Fetch Fetches most up to date data for a single table from the API. This ignores any previously downloaded files and will redownload all the files associated with that table. ```Shell canvasDataCli fetch -c path/to/config.js -t user_dim ``` This will start the fetch process and download what is needed to get the most recent data for that table (in this case, the `user_dim`). On subsequent executions, this will redownload all the data for that table, ignoring any previous days data. ### Unpack *NOTE*: This only works after properly running a `sync` command This command will unpack the gzipped files, concat any partitioned files, and add a header to the output file ```Shell canvasDataCli unpack -c path/to/config.js -f user_dim,account_dim ``` This command will unpack the user_dim and account_dim tables to a directory. Currently, you explictly have to give the files you want to unpack as this has the potential for creating very large files. ## Developing Process: 1. Write some code 2. Write tests 3. Open a pull request ### Running tests #### In Docker If you use docker, you can run tests inside a docker container ```Shell ./build.sh ``` #### Native ```Shell npm install . npm test ``` <file_sep>/canvas-data-cli/Dockerfile FROM instructure/node:latest USER root RUN mkdir -p /usr/src/app/report && chown -R docker /usr/src/app USER docker ADD package.json package.json RUN npm install . --ignore-scripts && rm package.json ADD . /usr/src/app CMD npm test <file_sep>/canvas-data-cli/build.sh #!/bin/sh set -e mkdir -p report chmod -R 777 report || true docker build -t canvas-data-cli:ci . docker run -v $(pwd)/report:/usr/src/app/report --rm canvas-data-cli:ci <file_sep>/mycanvas/squish file.R ###### # # Read canvas requests file and strip uneeded fields to reduce size # processed in 3M chunks # ###### rm(list=ls()) # just clear everything setwd("D:/canvas/unpackedFiles") myFile <- "requests_001(725).txt" outFile <- "requests processed" thisoutFile <- "requests_001(725).csv" remove <- c(1,3:5,8:9,16,22,24:27) rec.skip <- 0 # starting point rec.chunksize <- 10 # number of records in each chunk canvasrequest <- read.table(myFile, sep='\t', na.strings="\\N", quote='"', fill=TRUE) canvasrequest <- canvasrequest[ -c(remove)] # strip unwanted columns colnames(canvasrequest) = c("timestamp", "user_id", "course_id", "quiz_id", "discussion_id", "conversation_id", "assignment_id", "url", "user_agent", "remote_ip","interaction_micros", "web_application_controller", "web_application_action", "web_application_context_type","real_user_id") # strip unwanted rows canvasrequest <- subset(canvasrequest, !is.na(canvasrequest$user_id)) # no user identified canvasrequest <- subset(canvasrequest, canvasrequest$web_application_controller!="accounts") # not account management canvasrequest <- subset(canvasrequest, canvasrequest$web_application_action!="masquerade") # not changing to masquerade canvasrequest$real_user_id <- NULL # not masquerades write.table(canvasrequest, thisoutFile, sep=",", row.names = FALSE, col.names = FALSE, append = FALSE) i <- 1 for (i in 1:1){ # Read next chunk rec.skip <- rec.skip + rec.chunksize + 1 thisoutFile <- capture.output(cat(outFile, i, ".csv")) # new file for each chunk canvasrequest <- read.table(myFile, sep='\t', na.strings="\\N", quote='"', fill=TRUE, skip=rec.skip, nrows=rec.chunksize) #colnames(canvasrequest) = c("timestamp", "user_id", "course_id", "quiz_id", "discussion_id", "conversation_id", # "assignment_id", "url", "user_agent", "remote_ip","interaction_micros", "web_application_controller", # "web_applicaiton_action", "web_application_context_type","real_user_id") # canvasrequest <- canvasrequest[ -c(remove)] # strip unwanted # write.table(canvasrequest, thisoutFile, sep=",", row_names = FALSE, col.names = FALSE, append = TRUE) } <file_sep>/canvas-data-cli/Makefile compile: npm install . ./node_modules/.bin/babel src --out-dir lib/ publish: compile npm publish installLocal: compile npm install -g --progress=false . <file_sep>/canvas-data-cli/sonar-project.properties sonar.projectKey=canvas-data-cli sonar.projectName=canvas-data-cli sonar.projectVersion=0.0.1 sonar.sources=src sonar.tests=test sonar.language=js sonar.dynamicAnalysis=reuseReports sonar.javascript.jstest.reportsPath=report sonar.javascript.lcov.reportPath=report/lcov.info <file_sep>/canvas-data-cli/bin/canvasDataCli #!/usr/bin/env node var cli = require('../').cli var argv = cli.cli.parse(process.argv.slice(2)) cli.run(argv)
de23e4571d9b5ffd00429530ccfda46539b5cc93
[ "Markdown", "JavaScript", "Makefile", "INI", "R", "Dockerfile", "Shell" ]
8
Shell
ThePatrickLynch/canvas
15bf009cf9d3facbe7be98290172d9208af99b34
839a37f497bea93d5842942a5e853b09898ced61
refs/heads/master
<file_sep>import AppDispatcher from '../dispatcher'; import ActionTypes from '../constants'; export default { receivedTweets( rawTweets ) { AppDispatcher.dispatch({ actionType: ActionTypes.RECEIVED_TWEETS, rawTweets }); }, receivedOneTweet( rawTweet ) { AppDispatcher.dispatch({ actionType: ActionTypes.RECEIVED_ONE_TWEET, rawTweet }); }, receivedUsers( rawUsers ) { AppDispatcher.dispatch({ actionType: ActionTypes.RECEIVED_USERS, rawUsers }); }, receivedOneFollower( rawFollower ) { AppDispatcher.dispatch({ actionType: ActionTypes.RECEIVED_ONE_FOLLOWER, rawFollower }); } }
69a0c33a243bfc5910c0b354671bcddd847c9f0a
[ "JavaScript" ]
1
JavaScript
gailsteiger/twitter-clone
0ecb07f9466fd921a7eff02ee5a646cb0af77d84
1a4e0e158c236bf5285efffc8c344c04e59e5941
refs/heads/master
<file_sep># nba-stat-tweeter This is a Python script to both fetch stats from the latest NBA games, and post them to Twitter. It uses the Twitter API and the nba-api for Python. The script expects the Twitter authentication items in the file at the following location: "~/keys/twitter/keys" The script requires numpy for Python, however it is not included in requirements.txt. This is because I could not get the script to run with pip3's version of numpy. I instead installed it with "sudo apt-get install python3-numpy" <file_sep>import schedule import os import time import pandas import twitter from nba_api.stats.endpoints import boxscoretraditionalv2 from nba_api.stats.static import teams from nba_api.stats.endpoints import leaguegamefinder # Variables last_game_date = ck = cs = atk = ats = "" FILENAME = os.path.expanduser("~/keys/twitter/keys") # Functions def check_and_post(player_name, city): """The following function gets the last nuggets game, checks if it's a new game, and posts <NAME>'s stats to twitter. Some code snippets were lifted and modified from the nba_api and Twitter API Python documentation""" global last_game_date # Get all teams nba_teams = teams.get_teams() # Select the dictionary for the selected player's team, which contains their team ID player_team = [team for team in nba_teams if team['abbreviation'] == city][0] team_id = player_team['id'] # Query for games where the Nuggets were playing gamefinder = leaguegamefinder.LeagueGameFinder(team_id_nullable=team_id) # The first DataFrame of those returned is what we want. games = gamefinder.get_data_frames()[0] last_team_game = games.sort_values('GAME_DATE').iloc[-1] current_game_date = last_team_game["GAME_DATE"] # Get the stats of the game game_stats = boxscoretraditionalv2.BoxScoreTraditionalV2(last_team_game["GAME_ID"]) # Search for player, and build a string of his stats for player in game_stats.player_stats.get_dict()["data"]: if player_name in player: stats = "{0}'s stats for {1} {2}: points: {3}, rebounds: {4}, assists: {5}".format(player_name, last_team_game["GAME_DATE"], last_team_game["MATCHUP"], player[-2], player[-8], player[-7]) # Make Twitter API api = twitter.Api(consumer_key=ck, consumer_secret=cs, access_token_key=atk, access_token_secret=ats) try: status = api.PostUpdate(stats) print("{0} just posted: {1}".format(status.user.name, status.text)) except UnicodeDecodeError: print("Failed to post to Twitter") sys.exit(2) def get_credentials(): """ The following function loads the keys to authenticate with Twitter""" global ck, cs, atk, ats lines = open(FILENAME).read().splitlines() ck = lines[0]; cs = lines[1]; atk = lines[2]; ats = lines[3] print("Enter the player's name:") player = input() print("Enter the team the player plays for") team = input() get_credentials() check_and_post(player, team) """schedule.every().day.at("10:00").do(check_and_post) while True: schedule.run_pending() time.sleep(1)""" <file_sep>attrs certifi chardet coverage future idna importlib-metadata nba-api numpy oauthlib packaging panda pandas pluggy py pyparsing pytest pytest-cov python-dateutil python-twitter pytz requests requests-oauthlib schedule six urllib3 wcwidth zipp
167202a67d198b8f060454b80ee3ec73720ce22e
[ "Markdown", "Python", "Text" ]
3
Markdown
jayzym/nba-stat-tweeter
062b4d1e82391ead58f18da297541d7425b60e3c
3a209c6cbbc282cd5eb4490580cda1ac752bbb02
refs/heads/master
<file_sep>import React, { useEffect, useState } from 'react'; import styled from 'styled-components'; import Button from './Button'; import Checkbox from './Checkbox'; import Dropdown from './Dropdown'; import TextField from './TextField'; const Container = styled.div` display: flex; min-height: 100vh; justify-content: center; align-items: center; padding: 40px 15px; background-color: palevioletred; `; const Heading = styled.h1` font-weight: bold; font-size: 34px; line-height: 44px; margin: 10px 0; color: #2c2738; `; const Form = styled.form` width: 100%; max-width: 460px; padding: 30px 30px; background: #ffffff; box-shadow: 0px 12px 24px rgba(44, 39, 56, 0.02), 0px 32px 64px rgba(44, 39, 56, 0.04); border-radius: 24px; color: #2c2738; `; export default function AppForm({ onSubmit }) { // form validators const validators = { name: (v) => v.match(/^[a-zA-ZА-Яа-я -]{3,}$/) !== null, email: (v) => v.match(/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/) !== null, phone: (v) => v.match(/^[+]?[0-9]\(?[0-9]{3}\)?[0-9]{3}-?[0-9]{2}-?[0-9]{2}$/) !== null, lang: (v) => v !== null, agreement: (v) => v, }; // form values const [values, setValues] = useState({ name: '', email: '', phone: '', agreement: false, lang: { text: 'Язык', value: null }, }); // form validity const [valid, setValid] = useState({ name: false, email: false, phone: false, agreement: false, lang: false, }); // helpers to include validation on change const onChange = (key) => (v) => { setValues((prev) => ({ ...prev, [key]: v })); setValid((prev) => ({ ...prev, [key]: validators[key](v) })); }; // form ready to submit const [ready, setReady] = useState(false); useEffect(() => setReady(Object.values(valid).every((v) => v)), [valid]); return ( <Container> <Form onSubmit={(e) => { e.preventDefault(); onSubmit(values); }} > <Heading>Регистрация</Heading> <p> Уже есть аккаунт? <a href="/">Войти</a> </p> <TextField id="name" placeholder="Введите ваше имя" label="Имя" value={values.name} onChange={onChange('name')} errorMessage={ !valid.name && 'Минимум 3 символа, только буквы пробелы и дефис' } /> <TextField id="email" placeholder="Введите ваш email" label="Email" value={values.email} onChange={onChange('email')} errorMessage={ !valid.email && 'Email должен быть дейтвительным' } /> <TextField id="phone" placeholder="Введите ваш номер телефона" label="Номер телефона" value={values.phone} onChange={onChange('phone')} errorMessage={ !valid.email && 'Телефон должен быть дейтвительным' } /> <Dropdown items={[ { text: 'Русский', value: 'ru' }, { text: 'Английский', value: 'en' }, { text: 'Китайский', value: 'cn' }, { text: 'Испанский', value: 'es' }, ]} selected={values.lang} setSelected={onChange('lang')} label="Язык" /> <Checkbox id="chkbx" value={values.agreement} onChange={onChange('agreement')} required > Принимаю <a href="/">условия</a> использования </Checkbox> <Button disabled={!ready} block type="submit"> Зарегестрироваться </Button> </Form> </Container> ); } <file_sep># Тестовое задание для Amigoweb ## Использованные технологии - Framework: React - Syles: styled-components: библиотека для component scoped styles // можно при желании переделать в обычный css и использовать className - Валидация полей: regex Visit [here](https://rtabulov.github.io/amigoweb-test/). <file_sep>import React from 'react'; import AppForm from './AppForm'; export default function App() { const onSubmit = (values) => { alert(JSON.stringify(values, null, 2)); }; return ( <div> <AppForm onSubmit={onSubmit} /> </div> ); } <file_sep>import React, { useState } from 'react'; import styled from 'styled-components'; import checkmark from './assets/checkbox.svg'; import Label from './Label'; const StyledCheckbox = styled.label` display: inline-block; width: 28px; height: 28px; background: #ffffff; border: 1px solid #dbe2ea; box-shadow: 0px 4px 8px rgba(44, 39, 56, 0.04); border-radius: 4px; margin-right: 10px; ${(props) => props.invalid && `border: 1px solid red;pP`} ${(props) => props.checked && `background: #ffffff; border: 2px solid #0880ae; box-sizing: border-box; box-shadow: 0px 4px 8px rgba(44, 39, 56, 0.04); border-radius: 4px; background-image: url(${checkmark}); background-size: cover; background-position: center;`} `; const Container = styled.div` margin: 30px 0; display: flex; align-items: center; `; export default function Checkbox({ children, onChange, id, required, value, ...other }) { const [touched, setTouched] = useState(false); return ( <Container> <input style={{ display: 'none' }} type="checkbox" onChange={(e) => { onChange(e.target.checked); setTouched(true); }} id={id} checked={value} {...other} /> <StyledCheckbox invalid={required && touched && !value} htmlFor={id} checked={value} /> <Label style={{ marginBottom: '0' }} block={false} htmlFor={id}> {children} </Label> </Container> ); } <file_sep>import React from 'react'; import styled from 'styled-components'; const StyledButton = styled.button` ${(props) => props.block ? 'display: block; width: 100%;' : 'display: inline-block;'} padding: 18px 65px 17px; margin: 15px 0; background-color: #0880ae; border: none; border-radius: 6px; box-shadow: 0px 4px 8px 0px rgba(44, 39, 56, 0.08), 0px 2px 4px 0px rgba(44, 39, 56, 0.08); font-family: inherit; font-weight: 500; color: #ebf4f8; font-style: normal; line-height: 21px; transition: 0.15s; border: 2px solid #0880ae; cursor: pointer; &:hover { box-shadow: 0px 12px 24px rgba(44, 39, 56, 0.08), 0px 24px 48px rgba(44, 39, 56, 0.16); } &:active { box-shadow: 0px 2px 4px rgba(44, 39, 56, 0.0001), 0px 4px 8px rgba(44, 39, 56, 0.08); border: 2px solid rgba(44, 39, 56, 0.86); } &:disabled { cursor: not-allowed; color: rgba(44, 39, 56, 0.5); background: #dbe2ea; border-color: #dbe2ea; box-shadow: 0px 4px 8px rgba(44, 39, 56, 0.08); } `; export default function Button({ children, as, disabled = false, ...other }) { return ( <StyledButton disabled={disabled} as={as} {...other}> {children} </StyledButton> ); }
e2545265c47ee58e2280ded132fc3c26401cf507
[ "JavaScript", "Markdown" ]
5
JavaScript
rtabulov/amigoweb-test
e46815f61ba60f892e7007a496e25920467ed7ca
8917d20c700804a7145789c63b5a47580104f0ee
refs/heads/master
<file_sep>$(document).ready(function () { $.fn.bootstrapSwitch.defaults.size = 'normal'; $.fn.bootstrapSwitch.defaults.onText = 'Ja'; $.fn.bootstrapSwitch.defaults.offText = 'Nee'; var friday = $('#friday'); var saturday = $('#saturday'); var sorting = $('#sorting'); var selling = $('#selling'); var bbq = $('#bbq'); var bbqPartner = $('#bbqPartner'); friday.bootstrapSwitch(); saturday.bootstrapSwitch(); sorting.bootstrapSwitch(); selling.bootstrapSwitch(); bbq.bootstrapSwitch(); bbqPartner.bootstrapSwitch(); $('.checkbox label').css('padding-left', 0); var categoryField = $('#category_field'); var bbqPartnerField = $('#bbqPartner_field'); if (selling.bootstrapSwitch('state')) categoryField.removeClass('hidden'); else categoryField.addClass('hidden'); if (bbq.bootstrapSwitch('state')) bbqPartnerField.removeClass('hidden'); else bbqPartnerField.addClass('hidden'); var selected = $('#category :selected').val(); selling.on('switchChange.bootstrapSwitch', function (event, state) { if (state) { categoryField.removeClass('hidden'); $('#category').val(selected) } else { categoryField.addClass('hidden'); $('#category :selected').removeAttr('selected') } }); bbq.on('switchChange.bootstrapSwitch', function (event, state) { if (state) bbqPartnerField.removeClass('hidden'); else bbqPartnerField.addClass('hidden') }); var selected_organisation = $('#organisation').find(':selected'); updateSorting(selected_organisation); if (selected_organisation.val().length == 0) { $('#group option').each(function (i, option) { $(option).addClass('hidden') }); } else { $('#group option').each(function (i, option) { if ($(option).val().length == 0) { $(option).text("Selecteer een groep").removeClass('hidden') } else if ($(option).val().split('#')[0] == selected_organisation.val()) { $(option).removeClass('hidden') } else { $(option).addClass('hidden') } }) } $('#organisation').change(function () { var organisation = $('#organisation').find(':selected'); updateGroups(organisation.val()); updateSorting(organisation) }); function updateGroups(organisation) { if (organisation.length == 0) { $('#group option').each(function (i, option) { if ($(option).val().length == 0) { $(option).text("Selecteer eerst een vereniging").prop('selected', true) } else { $(option).addClass('hidden') } }) } else { $('#group option').each(function (i, option) { if ($(option).val().length == 0) { $(option).text("Selecteer een groep").prop('selected', true).removeClass('hidden') } else if ($(option).val().split('#')[0] == organisation) { $(option).removeClass('hidden') } else { $(option).addClass('hidden') } }) } } function updateSorting(organisation) { if (organisation.text() == "Scouting Kapelle" || organisation.val().length == 0) { $('#sorting_wrapper').addClass('hidden'); $('#sorting').prop('checked', false) } else { $('#sorting_wrapper').removeClass('hidden') } } });<file_sep>@(statistics: Map[String, Map[String, Int]], user: models.User)(implicit messages: Messages) @main(Messages("statistics"), Some(user)) { <div class="container row-eq-height"> <h1>@Messages("statistics")</h1> @for(statistic <- statistics) { <div class="col-md-4"> <h2>@statistic._1</h2> <table class="table table-striped table-bordered"> <tr> <th>@Messages("organisation")</th> <th>@Messages("count")</th> </tr> @for(stats <- statistic._2) { <tr> <td>@stats._1</td> <td>@stats._2</td> </tr> } <tr> <td><strong>@Messages("total")</strong></td> <td><strong>@statistic._2.values.sum</strong></td> </tr> </table> </div> } </div> }
b94de58f0664d406f5d4c869f09e2c89ccba8a4b
[ "JavaScript", "HTML" ]
2
JavaScript
ahassa01/bamboesmanager
f5e6532f7a3de416cb55073fa4880bae35327967
3ba23ab252855936af76149b2cb313188f2d2bbd
refs/heads/master
<file_sep>// // Created by julian.krieger on 9/6/2021. // #include <sstream> #include <iomanip> #include "hack.h" template< typename T > std::string int_to_hex( T i ) { std::stringstream stream; stream << "0x" << std::setfill ('0') << std::setw(sizeof(T)*2) << std::hex << i; return stream.str(); } InternalHack::InternalHack() { this->moduleBase = (uintptr_t)GetModuleHandle(nullptr); } void InternalHack::freezeHealth(bool enable) { if(enable) { mem::Nop((BYTE*)(this->moduleBase + Offset::HEALTH_START), 6); } else { // original code: mov [esi+000024C0],eax mem::Patch((BYTE*)(this->moduleBase + Offset::HEALTH_START), (BYTE*)"\x89\x86\xC0\x24\x00\x00", 6); } } void InternalHack::freezeBombs(bool enable) { if(enable) { mem::Nop((BYTE*)(this->moduleBase + Offset::BOMB_DEC_START), 2); } else { // original code: dec [eax] mem::Patch((BYTE*)(this->moduleBase + Offset::BOMB_DEC_START),(BYTE*)"\xFF\x08", 2); } } void InternalHack::increaseBombs(bool enable) { if(enable) { // code: inc [eax] mem::Patch((BYTE*)(this->moduleBase + Offset::BOMB_DEC_START),(BYTE*)"\xFF\x00", 2); } else { // original code: dec [eax] mem::Patch((BYTE*)(this->moduleBase + Offset::BOMB_DEC_START),(BYTE*)"\xFF\x08", 2); } } void InternalHack::noKeysNeeded(bool enable) { if(enable) { mem::Nop((BYTE*)(this->moduleBase + Offset::KEY_TST_START), 15); } else { /** * Original code: * tst eax, eax * jng isaac-ng.exe+150CF4 * dec eax, * mov [esi+24D8], eax */ auto original = (BYTE*)( "\x85\xC0" "\x0F\x8E\x5C\x01\x00\x00" "\x48" "\x89\x96\xD8\x24\x00\x00" ); mem::Patch((BYTE*)(this->moduleBase + Offset::KEY_TST_START), original, 15); } } void InternalHack::unlimitedMoney(bool enable) { if(enable) { auto newFunc = (BYTE*)( "\xB8\x63\x00\x00\x00" // mov eax, 99 "\x90\x90" // NOP NOP ); mem::Patch((BYTE*)(this->moduleBase + Offset::SET_MONEY_ENTRY), newFunc, 7); } else { auto original = (BYTE*)( "\x8B\x09" //mov ecx, [ecx] "\x85\xC9" //tst ecx, ecx "\x0F\x4F\xC1" //cmovg eax, ecx ); mem::Patch((BYTE*)(this->moduleBase + Offset::SET_MONEY_ENTRY), original, 7); } } <file_sep>// // Created by julian.krieger on 9/6/2021. // #include <windows.h> #include "gui.h" #include "ftxui/component/component.hpp" // for Slider, Checkbox, Vertical, Renderer, Button, Input, Menu, Radiobox, Toggle #include "ftxui/component/screen_interactive.hpp" // for Component, ScreenInteractive #include "ftxui/dom/elements.hpp" // for separator, Element, operator|, size, xflex, text, WIDTH, hbox, vbox, EQUAL, border, GREATER_THAN #include "ftxui/component/event.hpp" #include "hack.h" using namespace ftxui; void InternalGUI::init() { AllocConsole(); // stream console to std out freopen_s(&this->file_ptr, "CONOUT$", "w", stdout); } void InternalGUI::close() { fclose(this->file_ptr); FreeConsole(); } void DemoGUI::init() { } void DemoGUI::close() { } void GUI::draw() { auto screen = ScreenInteractive::TerminalOutput(); // -- Layout ----------------------------------------------------------------- std::wstring healthLabel = L"Toggle Health"; bool healthChecked = false; Component healthBox = Checkbox(&healthLabel, &healthChecked); healthBox = CatchEvent(healthBox, [&](Event event) { if(event == Event::Return || event == Event::Character(' ')) { healthChecked = !healthChecked; this->hack->freezeHealth(healthChecked); return true; } return false; }); std::wstring bombLabel = L"Toggle Freeze Bombs"; bool bombChecked = false; Component bombBox = Checkbox(&bombLabel, &bombChecked); bombBox = CatchEvent(bombBox, [&](Event event) { if(event == Event::Return || event == Event::Character(' ')) { bombChecked = !bombChecked; this->hack->freezeBombs(bombChecked); return true; } return false; }); std::wstring bombIncLabel = L"Toggle Increase Bombs"; bool bombIncChecked = false; Component bombIncBox = Checkbox(&bombIncLabel, &bombIncChecked); bombIncBox = CatchEvent(bombIncBox, [&](Event event) { if(event == Event::Return || event == Event::Character(' ')) { bombIncChecked = !bombIncChecked; this->hack->increaseBombs(bombIncChecked); return true; } return false; }); std::wstring noKeysNeeded = L"Toggle No Keys Needed"; bool noKeysNeededChecked = false; Component noKeysNeededBox = Checkbox(&noKeysNeeded, &noKeysNeededChecked); noKeysNeededBox = CatchEvent(noKeysNeededBox, [&](Event event) { if(event == Event::Return || event == Event::Character(' ')) { noKeysNeededChecked = !noKeysNeededChecked; this->hack->noKeysNeeded(noKeysNeededChecked); return true; } return false; }); std::wstring unlimitedMoney = L"Toggle Unlimited Money"; bool unlimitedMoneyChecked = false; Component unlimitedMoneyBox = Checkbox(&unlimitedMoney, &unlimitedMoneyChecked); unlimitedMoneyBox = CatchEvent(unlimitedMoneyBox, [&](Event event) { if(event == Event::Return || event == Event::Character(' ')) { unlimitedMoneyChecked = !unlimitedMoneyChecked; this->hack->unlimitedMoney(unlimitedMoneyChecked); return true; } return false; }); std::vector<bool> states(3); auto container = Container::Vertical({ healthBox, bombBox, bombIncBox, noKeysNeededBox, unlimitedMoneyBox }); std::vector<Event> keys; auto component = Renderer(container, [&] { return vbox({container->Render()}) | frame | ftxui::size(HEIGHT, LESS_THAN, 10) | border; }); screen.Loop(component); } <file_sep># Isaac-Internal A very basic internal hack for The Binding of Isaac - Rebirth. It uses a [FTXUI TUI](https://github.com/ArthurSonzogni/FTXUI) to make different hacks toggleable. ## Features - Freeze Health (Replace the health subtraction instruction with NOPs) - Freeze Money at 99 - Freeze Bombs at 99 - Freeze Keys at 99 ## Planned Features - Reverse PlayerEntity to gain access to the item pool - Unlock Achievements ## How to use - Clone the project - Cd into the project folder - Run cmake --build cmake-build-debug --target DLL - Inject DLL with any cheap injector, you can use guidedhacking's injector or Cheat Engine for this. Isaac is an indy game, so we don't need to manual map here. ## Other Info - To inspect the GUI without running cheat internals (injecting, accessing and changing memory), run `Demo.exe` in `cmake-build-debug/demo <file_sep># Create a library called "Hello" which includes the source file "hello.cxx". # The extension is already found. Any number of sources could be listed here. add_library (DLL SHARED dllmain.cpp) # Link the executable to the Hello library. Since the Hello library has # public include directories we will use those link directories when building # helloDemo target_link_libraries (DLL LINK_PUBLIC Lib)<file_sep>// // Created by julian.krieger on 9/5/2021. // #include "Offset.h" <file_sep>#include "stdafx.h" #include "proc.h" //https://guidedhacking.com/threads/how-to-hack-any-game-first-internal-hack-dll-tutorial.12142/ DWORD GetProcId(const wchar_t* procName) { DWORD procId = 0; HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnap != INVALID_HANDLE_VALUE) { PROCESSENTRY32 procEntry; procEntry.dwSize = sizeof(procEntry); if (Process32First(hSnap, &procEntry)) { do { WCHAR *procEntryName = nullptr; mbstowcs(procEntryName, procEntry.szExeFile, strlen(procEntry.szExeFile)); if (!_wcsicmp(procEntryName, procName)) { procId = procEntry.th32ProcessID; break; } } while (Process32Next(hSnap, &procEntry)); } } CloseHandle(hSnap); return procId; } uintptr_t GetModuleBaseAddress(DWORD procId, const wchar_t* modName) { uintptr_t modBaseAddr; // This structure contains lots of goodies about a module MODULEENTRY32 modEntry = { 0 }; // Grab a snapshot of all the modules in the specified process HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, procId); if (!hSnap) return NULL; if (hSnap != INVALID_HANDLE_VALUE) { // You have to initialize the size, otherwise it will not work modEntry.dwSize = sizeof(modEntry); // Get the first module in the process if (Module32First(hSnap, &modEntry)) { do { WCHAR *modEntryName = nullptr; mbstowcs(modEntryName, modEntry.szModule, strlen(modEntry.szModule)); // Check if the module name matches the one we're looking for if (!_wcsicmp(modEntryName, modName)) { // If it does, close the snapshot handle and return the base address modBaseAddr = (uintptr_t)modEntry.modBaseAddr; CloseHandle(hSnap); return modBaseAddr; } // Grab the next module in the snapshot } while (Module32Next(hSnap, &modEntry)); } } // We couldn't find the specified module, so return NULL CloseHandle(hSnap); return NULL; } uintptr_t FindDereferencedMultilevelPointerAddress(HANDLE hProc, uintptr_t ptr, const std::vector<unsigned int>& offsets) { uintptr_t addr = ptr; for (unsigned int offset : offsets) { ReadProcessMemory(hProc, (BYTE*)addr, &addr, sizeof(addr), nullptr); addr += offset; } return addr; }<file_sep>cmake_minimum_required(VERSION 3.0) project(IsaacInternal) set(CMAKE_CXX_STANDARD 20) # Recurse into the "Hello" and "Demo" subdirectories. This does not actually # cause another cmake executable to run. The same process will walk through # the project's entire directory structure. add_subdirectory (demo) add_subdirectory (dll) add_subdirectory(lib)<file_sep>// // Created by julian.krieger on 9/5/2021. // #ifndef ISAACEXTERNAL_OFFSET_H #define ISAACEXTERNAL_OFFSET_H enum Offset { HEALTH_START = 0x14FFB6, BOMB_DEC_START = 0x1660A3, // FF08 -> FF00, KEY_TST_START = 0x150B90, // num of keys are tested here, it jumps away if keys goes negative. Replace with 15 NOP LOAD_ITEM_COST = 0x11AC03, SET_MONEY_ENTRY = 0x150653 }; #endif //ISAACEXTERNAL_OFFSET_H <file_sep># Create a library called "Hello" which includes the source file "hello.cxx". # The extension is already found. Any number of sources could be listed here. add_library(Lib "") target_sources(Lib PUBLIC ${CMAKE_CURRENT_LIST_DIR}/gui.cpp ${CMAKE_CURRENT_LIST_DIR}/gui.h PRIVATE ${CMAKE_CURRENT_LIST_DIR}/hack.cpp ${CMAKE_CURRENT_LIST_DIR}/hack.h ${CMAKE_CURRENT_LIST_DIR}/mem.cpp ${CMAKE_CURRENT_LIST_DIR}/mem.h ${CMAKE_CURRENT_LIST_DIR}/offset.cpp ${CMAKE_CURRENT_LIST_DIR}/offset.h ${CMAKE_CURRENT_LIST_DIR}/proc.cpp ${CMAKE_CURRENT_LIST_DIR}/proc.h ${CMAKE_CURRENT_LIST_DIR}/stdafx.h ${CMAKE_CURRENT_LIST_DIR}/stdafx.cpp ${CMAKE_CURRENT_LIST_DIR}/targetver.h ) # --- Fetch FTXUI -------------------------------------------------------------- include(FetchContent) set(FETCHCONTENT_UPDATES_DISCONNECTED TRUE) FetchContent_Declare(ftxui GIT_REPOSITORY https://github.com/ArthurSonzogni/ftxui # Specify a GIT_TAG here. ) FetchContent_GetProperties(ftxui) if(NOT ftxui_POPULATED) FetchContent_Populate(ftxui) add_subdirectory(${ftxui_SOURCE_DIR} ${ftxui_BINARY_DIR} EXCLUDE_FROM_ALL) endif() # ------------------------------------------------------------------------------ target_link_libraries(Lib PUBLIC ftxui::screen PUBLIC ftxui::dom PUBLIC ftxui::component # Not needed for this example. ) # Make sure the compiler can find include files for our Hello library # when other libraries or executables link to Hello target_include_directories (Lib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) target_include_directories(Lib PUBLIC ${CMAKE_CURRENT_LIST_DIR})<file_sep>// // Created by julian.krieger on 9/6/2021. // #ifndef ISAACINTERNAL_GUI_H #define ISAACINTERNAL_GUI_H #include <utility> #include "hack.h" class GUI { public: explicit GUI(Hack* hack){ this->hack = hack; } virtual void init(){}; void draw(); virtual void close(){}; protected: Hack *hack; }; class InternalGUI: public GUI { public: explicit InternalGUI(Hack *hack) : GUI(hack) { file_ptr = nullptr; }; void init() override; void close() override; private: FILE* file_ptr; }; class DemoGUI: public GUI { public: explicit DemoGUI(Hack* hack): GUI(hack) { }; void init() override; void close() override; }; #endif //ISAACINTERNAL_GUI_H <file_sep>// // Created by julian.krieger on 9/6/2021. // #include <gui.h> int main() { auto gui = DemoGUI(new DemoHack); gui.init(); gui.draw(); gui.close(); return 0; } <file_sep>// // Created by julian.krieger on 9/6/2021. // #ifndef ISAACEXTERNAL_HACK_H #define ISAACEXTERNAL_HACK_H #include <iostream> #include "../lib/mem.h" #include "../lib/Offset.h" #include <ftxui/screen/screen.hpp> class Hack { public: virtual void freezeHealth(bool enable){ }; virtual void increaseBombs(bool enable){ }; virtual void freezeBombs(bool enable){ } virtual void unlimitedMoney(bool enable) { } virtual void noKeysNeeded(bool enable){ } Hack() = default; protected: uintptr_t moduleBase; }; class InternalHack: public Hack { public: InternalHack(); void freezeHealth(bool enable) override; void increaseBombs(bool enable) override; void freezeBombs(bool enable) override; void noKeysNeeded(bool enable) override; void unlimitedMoney(bool enable) override; }; class DemoHack: public Hack { public: DemoHack() = default; }; #endif //ISAACEXTERNAL_HACK_H <file_sep>// dllmain.cpp : Defines the entry point for the DLL application. #include <iostream> #include <windows.h> #include <gui.h> //https://guidedhacking.com/threads/how-to-hack-any-game-first-internal-hack-dll-tutorial.12142/ DWORD WINAPI HackThread(HMODULE hModule) { auto hack = new InternalHack(); auto gui = InternalGUI(hack); gui.init(); gui.draw(); gui.close(); FreeLibraryAndExitThread(hModule, 0); return 0; } BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: CloseHandle(CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)HackThread, hModule, 0, nullptr)); case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; default: break; } return TRUE; }
3246d82fecfd75966eca32130e31183b5ba0088e
[ "Markdown", "C", "CMake", "C++" ]
13
C++
juliankrieger/The-Binding-of-Isaac-Rebirth---Internal-Hack
66bf54fa0e08cae4cb26f729d524a237f70b557a
456afd9e79b96dbb6c855f1ae2604efeac4d64b2
refs/heads/master
<repo_name>pp1314add/xm<file_sep>/aishijing/dic/Dictionary.java package com.chuange.aishijing.dic; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; /** * * @author yuany * 字典表 * */ @Entity @Table(name="ASJ_Dict") public class Dictionary { @Id @NotNull @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; private String typeCode; private String name; private String value; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTypeCode() { return typeCode; } public void setTypeCode(String typeCode) { this.typeCode = typeCode; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public String toString() { return "Dictionary [id=" + id + ", typeCode=" + typeCode + ", name=" + name + ", value=" + value + "]"; } public Dictionary(@NotNull Integer id, String typeCode, String name, String value) { super(); this.id = id; this.typeCode = typeCode; this.name = name; this.value = value; } public Dictionary() { super(); // TODO Auto-generated constructor stub } } <file_sep>/alipay/config/AlipayConfig.java package com.chuange.alipay.config; public class AlipayConfig { //pid 沙箱:2016092100562795 public static String partner="2088112211295396"; //收款支付宝账号,同上 public static String seller_id="2088112211295396"; //商户appid public static String APPID="2018102361788558"; //私钥 pkcs8 public static String RSA_PRIVATE_KEY=""; //支付宝公钥 public static String ALIPAY_PUBLIC_KEY=""; //服务器异步通知页面路径 public static String notify_url=""; //页面跳转同步通知页面路径 public static String return_url=""; //请求支付宝的网关地址 public static String URL="https://openapi.alipay.com/gateway.do"; //编码 public static String CHARSET="UTF-8"; //返回格式 public static String FORMAT="json"; //加密类型 public static String SIGNTYPE="RSA2"; } <file_sep>/src/main/java/com/chuange/aishijing/pojo/classessys/Classes.java package com.chuange.aishijing.pojo.classessys; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; /** * * @author yuany * 课程表 */ @Entity @Table(name="ASJ_CLASSES") public class Classes { @Id @NotNull @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String teacher;//讲师 private String classCover;//课程封面 private Double price;//价格 private String castIntroduce;//课程介绍 private String castTitle; @Override public String toString() { return "Classes{" + "id='" + id + '\'' + ", teacher='" + teacher + '\'' + ", classCover='" + classCover + '\'' + ", price=" + price + ", castIntroduce='" + castIntroduce + '\'' + ", castTitle='" + castTitle + '\'' + '}'; } public Classes() { } public Classes(String teacher, String classCover, Double price, String castIntroduce, String castTitle) { this.teacher = teacher; this.classCover = classCover; this.price = price; this.castIntroduce = castIntroduce; this.castTitle = castTitle; } public String getCastTitle() { return castTitle; } public void setCastTitle(String castTitle) { this.castTitle = castTitle; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTeacher() { return teacher; } public void setTeacher(String teacher) { this.teacher = teacher; } public String getClassCover() { return classCover; } public void setClassCover(String classCover) { this.classCover = classCover; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public String getCastIntroduce() { return castIntroduce; } public void setCastIntroduce(String castIntroduce) { this.castIntroduce = castIntroduce; } } <file_sep>/aishijing/service/impl/castsystem/RoleManagerServiceImpl.java package com.chuange.aishijing.service.impl.castsystem; import java.util.ArrayList; import java.util.List; import java.util.Optional; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import com.chuange.aishijing.dao.castsystem.RoleManagerDao; import com.chuange.aishijing.pojo.castsystem.Role; import com.chuange.aishijing.service.RoleManagerService; import com.chuange.aishijing.util.MD5; import com.chuange.aishijing.vo.servicevo.castsystem.RolesVO; import com.mysql.jdbc.StringUtils; @Service @Transactional public class RoleManagerServiceImpl implements RoleManagerService{ @Autowired private RoleManagerDao roleManagerDao; /** * 条件查询 */ @Override public RolesVO queryAllByConditions(Integer pagesize, Integer currentPage, String keywords) { Pageable pageable =PageRequest.of(currentPage - 1,pagesize); Page<Role> pages=roleManagerDao.findAll(new Specification<Role>() { @Override public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) { List<Predicate> list = new ArrayList<Predicate>(); if(!StringUtils.isNullOrEmpty(keywords)) { list.add(criteriaBuilder.like(root.get("castname").as(String.class), "%" + keywords + "%")); list.add(criteriaBuilder.like(root.get("roleName").as(String.class), "%" + keywords + "%")); Predicate[] p = new Predicate[list.size()]; return criteriaBuilder.or(list.toArray(p)); }else { Predicate[] p = new Predicate[list.size()]; return criteriaBuilder.and(list.toArray(p)); } } },pageable); RolesVO roles=new RolesVO(); roles.success("success", new MD5(roles.toString()).compute(),pages); return roles; } /** * 详情 */ @Override public RolesVO queryById(String id) { // TODO Auto-generated method stub Optional<Role> role= roleManagerDao.findById(id); RolesVO vo=new RolesVO(); vo.success("success", new MD5(vo.toString()).compute(), role); return vo; } /** * 删除 */ @Override public void deleteById(String id) { // TODO Auto-generated method stub roleManagerDao.deleteById(id); } /** * 更新 */ @Override public RolesVO updateById(Role role) { // TODO Auto-generated method stub roleManagerDao.saveAndFlush(role); RolesVO vo=new RolesVO(); vo.success("success"); return vo; } /** * 新增 */ @Override public RolesVO insert(Role role) { // TODO Auto-generated method stub RolesVO vo=new RolesVO(); Role r=roleManagerDao.save(role); if(r != null) { vo.success("success"); } return vo; } } <file_sep>/aishijing/service/UserManageService.java package com.chuange.aishijing.service; import java.util.List; import org.springframework.data.domain.Page; import com.chuange.aishijing.dto.UserDTO; import com.chuange.aishijing.pojo.userManage.User; import com.chuange.aishijing.pojo.userManage.UserLable; import com.chuange.aishijing.pojo.userManage.UserMovie; import com.chuange.aishijing.vo.servicevo.usermanage.UsersVO; /** * * @author yuany * 用户管理逻辑层接口 * */ public interface UserManageService { //查询所有用户 public Page<User> queryUserList(Integer pagesize,Integer currentPage); /** * 模糊查询 */ public UsersVO queryUserByConditions(Integer pagesize,Integer currentPage,UserDTO user); /** * 用户详情查询 */ public UsersVO queryById(String id); /** * * @param id * @return影视经历 */ public List<UserMovie> queryMovies(String id); /** * * @param id * @param type * @return标签印象 */ public List<UserLable> queryLables(String id,String type); } <file_sep>/src/main/java/com/chuange/aishijing/dto/classes/OrderQueryDTO.java package com.chuange.aishijing.dto.classes; import javax.validation.constraints.NotNull; /** * @author augus * @create 2018/11/27 12:16 */ public class OrderQueryDTO { @NotNull private long classId;// classid private String purchaser ; public OrderQueryDTO() { } @Override public String toString() { return "OrderQueryDTO{" + "classId=" + classId + ", purchaser='" + purchaser + '\'' + '}'; } public OrderQueryDTO(@NotNull long classId, String purchaser) { this.classId = classId; this.purchaser = purchaser; } public long getClassId() { return classId; } public void setClassId(long classId) { this.classId = classId; } public String getPurchaser() { return purchaser; } public void setPurchaser(String purchaser) { this.purchaser = purchaser; } } <file_sep>/aishijing/service/RoleManagerService.java package com.chuange.aishijing.service; import com.chuange.aishijing.pojo.castsystem.Role; import com.chuange.aishijing.vo.servicevo.castsystem.RolesVO; /** * * @author yuany * 角色管理 * */ public interface RoleManagerService { /** * 查所有 * @param pagesize * @param currentPage * @param keywords * @return */ public RolesVO queryAllByConditions(Integer pagesize, Integer currentPage, String keywords); /** * 详情 * @param id * @return */ public RolesVO queryById(String id); /** * 删除 * @param id */ public void deleteById(String id); /** * 编辑 * @param id */ public RolesVO updateById(Role role); /** * 新增 * @param role * @return */ public RolesVO insert(Role role); } <file_sep>/aishijing/pojo/recommendmanage/HotRole.java package com.chuange.aishijing.pojo.recommendmanage; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; /** * * @author yuany * 热门角色 */ @Entity @Table(name="ASJ_HOTROLE") public class HotRole { @Id @NotNull @GeneratedValue(strategy = GenerationType.AUTO) private String id; private String roleName;//角色名称 private String roleCast;//角色所属脚本 private String showterminal;//显示终端 private String status;//状态 public String getId() { return id; } public void setId(String id) { this.id = id; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getRoleCast() { return roleCast; } public void setRoleCast(String roleCast) { this.roleCast = roleCast; } public String getShowterminal() { return showterminal; } public void setShowterminal(String showterminal) { this.showterminal = showterminal; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Override public String toString() { return "HotRole [id=" + id + ", roleName=" + roleName + ", roleCast=" + roleCast + ", showterminal=" + showterminal + ", status=" + status + "]"; } public HotRole(@NotNull String id, String roleName, String roleCast, String showterminal, String status) { super(); this.id = id; this.roleName = roleName; this.roleCast = roleCast; this.showterminal = showterminal; this.status = status; } public HotRole() { super(); // TODO Auto-generated constructor stub } } <file_sep>/aishijing/dao/castmanager/TeacherManagerDao.java package com.chuange.aishijing.dao.castmanager; import com.chuange.aishijing.pojo.teachersys.TeacherManager; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; /** * Created by Administrator on 2018-11-21. */ public interface TeacherManagerDao extends JpaRepository<TeacherManager,String>,JpaSpecificationExecutor<TeacherManager> { } <file_sep>/aishijing/controller/CastManager/CastManagerController.java package com.chuange.aishijing.controller.CastManager; import com.chuange.aishijing.pojo.castmanage.Cast; import com.chuange.aishijing.pojo.castmanage.CastMember; import com.chuange.aishijing.service.CastManagerService; import com.chuange.aishijing.util.MD5; import com.chuange.aishijing.vo.servicevo.CastManagervo.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * Created by Administrator on 2018-11-15. */ @RestController @EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class}) public class CastManagerController { private final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); @Autowired private CastManagerService castManagerService; @ResponseBody @RequestMapping("/cast") public CastManagerResponseVo cast(@RequestParam Integer page,@RequestParam String key){ CastManagerResponseVo castManagerResponseVo = new CastManagerResponseVo(); CastManagerResponse castManagerResponse = new CastManagerResponse(); Page<Cast> casts = castManagerService.seletCast(page,key); List<Cast> list = new ArrayList<Cast>(); for (Cast cc:casts){ list.add(cc); } castManagerResponse.setCastList(list); castManagerResponse.setTotalPage(casts.getTotalPages()); castManagerResponse.setTotalElements(casts.getTotalElements()); castManagerResponseVo.success("返回成功",new MD5(casts.toString()).compute(),castManagerResponse); return castManagerResponseVo; } @ResponseBody @RequestMapping("/castmember") public CastManagerResponseVo castmember(@RequestParam Integer page,@RequestParam(required = false) String key,@RequestParam String castId){ System.out.println("当前页;"+page+",查询条件:"+key); CastManagerResponseVo castManagerResponseVo = new CastManagerResponseVo(); CastMemberResponse castManagerResponse = new CastMemberResponse(); Page<CastMember> castMembers = castManagerService.seletCastMember(page,key,castId); List<CastMember> list = new ArrayList<CastMember>(); for (CastMember cc:castMembers){ System.out.println(cc); list.add(cc); } castManagerResponse.setCastMemberList(list); castManagerResponse.setTotalPage(castMembers.getTotalPages()); castManagerResponse.setTotalElements(castMembers.getTotalElements()); castManagerResponseVo.success("返回成功",new MD5(castMembers.toString()).compute(),castManagerResponse); return castManagerResponseVo; } @ResponseBody @RequestMapping("/insertcast") public String addcast(@RequestBody AddCastManagerResponse addCastManagerResponse){ String msg = ""; int s= castManagerService.insertorupdateCast(addCastManagerResponse); if(s==1){ msg = "插入数据成功"; }else{ msg = "插入数据失败"; } return msg; } @ResponseBody @RequestMapping("/insertcastmember") public String insertcastmember(@RequestBody CastMember castMember){ String msg = ""; int s= castManagerService.insertorupdateCastMember(castMember); if(s==1){ msg = "success"; }else{ msg = "fail"; } return msg; } @ResponseBody @RequestMapping("/deletecast") public String deletecast(@RequestParam String delId ){ String msg = ""; int s= castManagerService.deleteCast(delId); if(s==1){ msg = "删除数据成功"; }else{ msg = "删除数据失败"; } return msg; } @ResponseBody @RequestMapping("/deletecastmember") public String deletecastmember(@RequestParam String delId ){ String msg = ""; int s= castManagerService.deleteCastMember(delId); if(s==1){ msg = "success"; }else{ msg = "fail"; } return msg; } @ResponseBody @RequestMapping("/findcastbyid") public FindCastByIdResponseVO findcast(@RequestParam String id ){ FindCastByIdResponseVO findCastByIdResponseVO = new FindCastByIdResponseVO(); Cast cast= castManagerService.findCastById(id); findCastByIdResponseVO.success("查询数据成功",new MD5(findCastByIdResponseVO.toString()).compute(),cast); return findCastByIdResponseVO; } @ResponseBody @RequestMapping("/updatecast") public FindCastByIdResponseVO updatecast(@RequestParam AddCastManagerResponse addCastManagerResponse ){ FindCastByIdResponseVO findCastByIdResponseVO = new FindCastByIdResponseVO(); castManagerService.updateCast(addCastManagerResponse); findCastByIdResponseVO.success("更新数据成功"); return findCastByIdResponseVO; } @RequestMapping("/upload") @ResponseBody public String upload(@RequestParam(value="logo",required=false) MultipartFile file, HttpServletRequest request){ System.out.println("file的值:"+file); if (file.isEmpty()) { return new String("文件为空"); } // 获取文件名 String fileName = file.getOriginalFilename(); logger.info("上传的文件名为:" + fileName); // 获取文件的后缀名 String suffixName = fileName.substring(fileName.lastIndexOf(".")); logger.info("上传的后缀名为:" + suffixName); if(".jpg".equals(suffixName.trim())||".png".equals(suffixName.trim())){ // 文件上传后的路径 String filePath = "D://IDEA//course01//src//main//resources//static//download//img//";//服务器路径 // 解决中文问题,liunx下中文路径,图片显示问题 // fileName = UUID.randomUUID() + suffixName; fileName= UUID.randomUUID().toString().replace("-", "")+".png"; File dest = new File(filePath +fileName); // 检测是否存在目录 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } try { //保存图片名称和路径 } catch (IllegalStateException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } return new String("上传的不是图片!"); } } <file_sep>/aishijing/pojo/teachersys/TeacherProfit.java package com.chuange.aishijing.pojo.teachersys; import org.omg.CORBA.PRIVATE_MEMBER; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.util.Date; /** * Created by Administrator on 2018-11-07. * 教师收益 */ @Entity @Table(name="ASJ_TEACHERPROFIT") public class TeacherProfit { @Id @NotNull @GeneratedValue(strategy = GenerationType.AUTO) private String id; private String profitAdd;//收益增加 private Date profitTime;//收益时间 private String couponDeduction;//优惠券抵扣 private String platformDivision;//平台分成 private String paid;//实收 private String profitContent;//收益内容 @Override public String toString() { return "TeacherProfit{" + "id='" + id + '\'' + ", profitAdd='" + profitAdd + '\'' + ", profitTime=" + profitTime + ", couponDeduction='" + couponDeduction + '\'' + ", platformDivision='" + platformDivision + '\'' + ", paid='" + paid + '\'' + ", profitContent='" + profitContent + '\'' + '}'; } public TeacherProfit(String profitAdd, Date profitTime, String couponDeduction, String platformDivision, String paid, String profitContent) { this.profitAdd = profitAdd; this.profitTime = profitTime; this.couponDeduction = couponDeduction; this.platformDivision = platformDivision; this.paid = paid; this.profitContent = profitContent; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getProfitAdd() { return profitAdd; } public void setProfitAdd(String profitAdd) { this.profitAdd = profitAdd; } public Date getProfitTime() { return profitTime; } public void setProfitTime(Date profitTime) { this.profitTime = profitTime; } public String getCouponDeduction() { return couponDeduction; } public void setCouponDeduction(String couponDeduction) { this.couponDeduction = couponDeduction; } public String getPlatformDivision() { return platformDivision; } public void setPlatformDivision(String platformDivision) { this.platformDivision = platformDivision; } public String getPaid() { return paid; } public void setPaid(String paid) { this.paid = paid; } public String getProfitContent() { return profitContent; } public void setProfitContent(String profitContent) { this.profitContent = profitContent; } } <file_sep>/aishijing/service/impl/usermanage/ReportServiceImpl.java package com.chuange.aishijing.service.impl.usermanage; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import com.chuange.aishijing.dao.usermanage.ReportDao; import com.chuange.aishijing.pojo.userManage.UserReport; import com.chuange.aishijing.service.ReportService; import com.chuange.aishijing.util.MD5; import com.chuange.aishijing.vo.servicevo.usermanage.UsersVO; /** * * @author yuany * 举报 * */ @Service @Transactional public class ReportServiceImpl implements ReportService{ @Autowired private ReportDao reportDao; @Override public UsersVO queryReport(Integer pagesize, Integer currentPage, String id) { Sort sort = new Sort(Sort.Direction.DESC,"id"); @SuppressWarnings("deprecation") Pageable pageable =new PageRequest(currentPage - 1,pagesize,sort); Page<UserReport> list=reportDao.findAllByUserId(pageable,id); UsersVO uservo=new UsersVO(); uservo.success("success", new MD5(uservo.toString()).compute(), list); return uservo; } } <file_sep>/aishijing/service/PersonService.java package com.chuange.aishijing.service; import com.chuange.aishijing.dao.PersonRepository; import com.chuange.aishijing.vo.servicevo.PersonServiceVo; /** * Created by Administrator on 2018-10-16. */ public interface PersonService { PersonServiceVo findAll(); PersonServiceVo savePerson(); PersonServiceVo deletePerson(); PersonServiceVo findById(); PersonServiceVo deletePersonEmail(); } <file_sep>/aishijing/controller/usermanage/SealInfoController.java //package com.chuange.aishijing.controller.usermanage; // //import java.util.HashMap; //import java.util.Map; //import java.util.UUID; // //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.boot.autoconfigure.SpringBootApplication; //import org.springframework.stereotype.Controller; //import org.springframework.web.bind.annotation.PostMapping; //import org.springframework.web.bind.annotation.RequestBody; //import org.springframework.web.bind.annotation.RequestMapping; //import org.springframework.web.bind.annotation.RequestParam; //import org.springframework.web.bind.annotation.ResponseBody; // //import com.chuange.aishijing.dto.ReportDTO; //import com.chuange.aishijing.pojo.userManage.UserSealInformation; //import com.chuange.aishijing.pojo.userManage.UserSealInformationLog; //import com.chuange.aishijing.service.SealInfoService; //import com.chuange.aishijing.service.SealService; //import com.chuange.aishijing.vo.servicevo.usermanage.UsersVO; //import com.mysql.jdbc.StringUtils; // ///** // * // * @author yuany // * 封号信息 // * // */ //@Controller //@SpringBootApplication //public class SealInfoController { // @Autowired // private SealInfoService sealInfoService; // @Autowired // private SealService sealService; // /** // * 查询 // * @param id // * @return // */ // @RequestMapping("/seal") // @ResponseBody // public UsersVO querySealInfoByUserId(String id) { // return sealInfoService.querySealInfoByUserId(id); // } // /** // * 更新 // * @param user // * @return // */ // @PostMapping("/insertSeal") // @ResponseBody // public UsersVO saveAndFlush(@RequestBody UserSealInformation seal, // @RequestParam(defaultValue="") String operaName, // @RequestParam(defaultValue="") String operaTime) { // UsersVO vo=sealInfoService.UpdateSealInfo(seal); // if(vo.getMsg().equals("success")){ // UserSealInformationLog seallog=new UserSealInformationLog(); // String period=seal.getFreezingPeriod(); // if(StringUtils.isNullOrEmpty(period) ) { // seallog.setFreezingPeriod("0"); // }else { // seallog.setFreezingPeriod(seal.getFreezingPeriod()); // // } // //UUID id=new UUID(16, 1); // seallog.setId("2"); // seallog.setOperaName(operaName); // seallog.setOperaTime(operaTime); // seallog.setRemark(seal.getRemark()); // seallog.setUserid(seal.getUserId()); // sealService.insertSeal(seallog); // } // return vo; // } //} <file_sep>/aishijing/pojo/sysmanage/ManagementGroup.java package com.chuange.aishijing.pojo.sysmanage; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.util.Date; /** * Created by Administrator on 2018-11-07. * 管理组 */ @Entity @Table(name="ASJ_MANAGERMENTGROUP") public class ManagementGroup { @Id @NotNull @GeneratedValue(strategy = GenerationType.AUTO) private String id; private String managermentgroupName;//管理组名称 private String description;//描述 private Date createTime;//创建时间 private String createUser;//创建人 @Override public String toString() { return "ManagementGroup{" + "id='" + id + '\'' + ", managermentgroupName='" + managermentgroupName + '\'' + ", description='" + description + '\'' + ", createTime=" + createTime + ", createUser='" + createUser + '\'' + '}'; } public ManagementGroup(String managermentgroupName, String description, Date createTime, String createUser) { this.managermentgroupName = managermentgroupName; this.description = description; this.createTime = createTime; this.createUser = createUser; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getManagermentgroupName() { return managermentgroupName; } public void setManagermentgroupName(String managermentgroupName) { this.managermentgroupName = managermentgroupName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getCreateUser() { return createUser; } public void setCreateUser(String createUser) { this.createUser = createUser; } } <file_sep>/alipay/service/AlipayService.java package com.chuange.alipay.service; import java.util.Map; import com.chuange.alipay.bean.AlipayOrderBean; import com.chuange.alipay.bean.OrderBean; public interface AlipayService { //生成订单信息 public void createOrderInfo(AlipayOrderBean alipayOrder); //对订单信息加签并返回 public String getAlipayOrderStr(OrderBean order); //异步返回订单情况 //public String notify(HttpServletRequest request,HttpServletResponse response)throws IOException; //异步请求逻辑处理 public String notify(Map<String,String> conversionParams); //支付完成,返回app,app调用最终付款校验 public Byte checkAlipay(String OutTradeNo); //根据传给支付宝的订单号查询订单信息 public AlipayOrderBean selectByOutTradeNo(String outTradeNo); //更新交易表 public int updateByPrimarykey(AlipayOrderBean alipayOrder); } <file_sep>/src/test/java/com/asj/DemoApplicationTests.java package com.asj; import com.chuange.DemoApplication; import com.chuange.aishijing.pojo.classessys.ClassComments; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureJdbc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.sql.Connection; import java.sql.SQLException; @RunWith(SpringRunner.class) @SpringBootTest public class DemoApplicationTests { @Test public void contextLoads() { SpringApplication.run(ClassComments.class); } } <file_sep>/aishijing/service/impl/AuditSystem/AuditSystemImpl.java package com.chuange.aishijing.service.impl.AuditSystem; import com.chuange.aishijing.dao.auditsystem.AuditSystem; import com.chuange.aishijing.dao.auditsystem.CastCertifiedDao; import com.chuange.aishijing.dao.auditsystem.StarCertifiedDao; import com.chuange.aishijing.pojo.checkSystem.CastCertified; import com.chuange.aishijing.pojo.checkSystem.Certification; import com.chuange.aishijing.pojo.checkSystem.StarCertified; import com.chuange.aishijing.service.AuditSystemService; import com.chuange.aishijing.util.MD5; import com.chuange.aishijing.vo.servicevo.checksystemvo.CheckSystemResponseVO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.transaction.Transactional; /** * Created by Administrator on 2018-11-12. */ @Service @Transactional public class AuditSystemImpl implements AuditSystemService{ private final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); private final Integer size = 5; @Autowired private AuditSystem auditSystem; @Autowired private StarCertifiedDao starCertifiedDao; @Autowired private CastCertifiedDao castCertifiedDao; @Override public Page<Certification> selectAll(Integer page, String key,String key1) { Page<Certification> c = null; //List<Certification> certifications = auditSystem.findAll(); Pageable pageable = PageRequest.of(page - 1, size); if (key.equals("null")&&(key1.equals("")||key1=="")) { System.out.println("进入无条件"); c = auditSystem.findAll(pageable); }else { System.out.println("进入有条件"); Page<Certification> c1 = auditSystem.findAll(new Specification<Certification>() { @Override public Predicate toPredicate(Root<Certification> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) { Predicate p1 = criteriaBuilder.like(root.get("realname").as(String.class), "%" + key + "%"); if(!key1.equals("")) { Predicate p2 = criteriaBuilder.equal(root.get("status").as(String.class), key1); query.where(criteriaBuilder.and(p1,p2)); }else { query.where(criteriaBuilder.and(p1)); } return query.getRestriction(); } }, pageable); for (Certification cc:c1){ System.out.println(c1); } return c1; } return c; } //实名认证审批通过修改状态 @Override public CheckSystemResponseVO updateStatus(String id,String flag) { CheckSystemResponseVO checkSystemResponseVO = new CheckSystemResponseVO(); int s = auditSystem.modifyStatus(id,flag); if(s==1){ String status = auditSystem.findStatus(id); checkSystemResponseVO.success("审批状态更新成功",new MD5(status).compute(),status); }else{ logger.info("审批更新状态失败"); checkSystemResponseVO.fail("审批状态更新失败"); } return checkSystemResponseVO; } //星认证审批通过修改状态 public CheckSystemResponseVO updateStarStatus(String id,String flag) { CheckSystemResponseVO checkSystemResponseVO = new CheckSystemResponseVO(); int s = starCertifiedDao.modifyStatus(id,flag); if(s==1){ String status = starCertifiedDao.findStatus(id); checkSystemResponseVO.success("星认证审批状态更新成功",new MD5(status).compute(),status); }else{ logger.info("星认证审批更新状态失败"); checkSystemResponseVO.fail("星认证审批状态更新失败"); } return checkSystemResponseVO; } @Override public Page<CastCertified> selectCastAll(Integer page, String key,String key1) { Page<CastCertified> c = null; //List<Certification> certifications = auditSystem.findAll(); Pageable pageable = PageRequest.of(page - 1, size); if (key.equals("null")&&(key1.equals("")||key1=="")) { c = castCertifiedDao.findAll(pageable); }else { Page<CastCertified> c1 = castCertifiedDao.findAll(new Specification<CastCertified>() { @Override public Predicate toPredicate(Root<CastCertified> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) { Predicate p1 = criteriaBuilder.like(root.get("username").as(String.class), "%" + key + "%"); if(!key1.equals("")) { Predicate p2 = criteriaBuilder.equal(root.get("handleStatus").as(String.class), key1); query.where(criteriaBuilder.and(p1,p2)); }else { query.where(criteriaBuilder.and(p1)); } return query.getRestriction(); } }, pageable); return c1; } return c; } @Override public CheckSystemResponseVO updateCastStatus(String id, String flag) { CheckSystemResponseVO checkSystemResponseVO = new CheckSystemResponseVO(); int s = castCertifiedDao.modifyStatus(id,flag); if(s==1){ String status = castCertifiedDao.findStatus(id); checkSystemResponseVO.success("剧组认证审批状态更新成功",new MD5(status).compute(),status); }else{ logger.info("剧组认证审批更新状态失败"); checkSystemResponseVO.fail("剧组认证审批状态更新失败"); } return checkSystemResponseVO; } public Page<StarCertified> selectStarAll(Integer page, String key,String key1) { Page<StarCertified> c = null; //List<Certification> certifications = auditSystem.findAll(); Pageable pageable = PageRequest.of(page - 1, size); if (key.equals("null")&&(key1.equals("")||key1=="")) { c = starCertifiedDao.findAll(pageable); }else { Page<StarCertified> c1 = starCertifiedDao.findAll(new Specification<StarCertified>() { @Override public Predicate toPredicate(Root<StarCertified> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) { Predicate p1 = criteriaBuilder.like(root.get("username").as(String.class), "%" + key + "%"); if(!key1.equals("")) { Predicate p2 = criteriaBuilder.equal(root.get("handleStatus").as(String.class), key1); query.where(criteriaBuilder.and(p1,p2)); }else { query.where(criteriaBuilder.and(p1)); } return query.getRestriction(); } }, pageable); return c1; } return c; } } <file_sep>/aishijing/controller/usermanage/ReportController.java package com.chuange.aishijing.controller.usermanage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * * @author yuany * 举报 * */ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.chuange.aishijing.service.ReportService; import com.chuange.aishijing.vo.servicevo.usermanage.UsersVO; @Controller @SpringBootApplication public class ReportController { @Autowired private ReportService reportService; @RequestMapping(value="/report") @ResponseBody public UsersVO queryreport(@RequestParam(value="page", defaultValue="1")Integer page,String id) { Integer pagesize=1; return reportService.queryReport(pagesize, page, id); } } <file_sep>/aishijing/controller/login/LoginController.java package com.chuange.aishijing.controller.login; import com.chuange.aishijing.service.LoginUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController @SpringBootApplication public class LoginController { @Autowired private LoginUserService loginUserService; @ResponseBody @PostMapping("/judge") public String login(@RequestParam String name,@RequestParam String pwd) { String password = loginUserService.selectUser(name); String result=""; if(pwd.equals(password)) { result="success"; }else { result="failed"; } return result; } } <file_sep>/aishijing/pojo/recommendmanage/TrainingRecommend.java package com.chuange.aishijing.pojo.recommendmanage; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; /** * * @author yuany * 培训推荐表 */ @Entity @Table(name="ASJ_TRAININGRECOMMEND") public class TrainingRecommend { @Id @NotNull @GeneratedValue(strategy = GenerationType.AUTO) private String id; private String recommendLoc;//推荐位 private String classname;//课程名称 private String showterminal;//展示终端 private String status;//状态 public String getId() { return id; } public void setId(String id) { this.id = id; } public String getRecommendLoc() { return recommendLoc; } public void setRecommendLoc(String recommendLoc) { this.recommendLoc = recommendLoc; } public String getClassname() { return classname; } public void setClassname(String classname) { this.classname = classname; } public String getShowterminal() { return showterminal; } public void setShowterminal(String showterminal) { this.showterminal = showterminal; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Override public String toString() { return "TrainingRecommend [id=" + id + ", recommendLoc=" + recommendLoc + ", classname=" + classname + ", showterminal=" + showterminal + ", status=" + status + "]"; } public TrainingRecommend(@NotNull String id, String recommendLoc, String classname, String showterminal, String status) { super(); this.id = id; this.recommendLoc = recommendLoc; this.classname = classname; this.showterminal = showterminal; this.status = status; } public TrainingRecommend() { super(); // TODO Auto-generated constructor stub } } <file_sep>/aishijing/vo/servicevo/PersonServiceVo.java package com.chuange.aishijing.vo.servicevo; import com.chuange.aishijing.vo.CommonResponseVO; /** * Created by Administrator on 2018-10-22. */ public class PersonServiceVo extends CommonResponseVO{ } <file_sep>/aishijing/service/impl/LoginUser/IndexServiceImpl.java package com.chuange.aishijing.service.impl.LoginUser; import javax.transaction.Transactional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * * @author yuany * index service * */ import com.chuange.aishijing.dao.loginuser.IndexDao; import com.chuange.aishijing.service.IndexService; import com.chuange.aishijing.util.MD5; import com.chuange.aishijing.vo.servicevo.index.TreeResponseVO; @Service @Transactional public class IndexServiceImpl implements IndexService{ private final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); @Autowired private IndexDao indexDao; @Override public TreeResponseVO queryTreeListByType(String resourceType) { // TODO Auto-generated method stub TreeResponseVO treeResponseVO=new TreeResponseVO(); treeResponseVO.success("success", new MD5(treeResponseVO.toString()).compute(),indexDao.findAllByResourceType(resourceType)); return treeResponseVO; } } <file_sep>/aishijing/dao/usermanage/UserManageDao.java package com.chuange.aishijing.dao.usermanage; import java.util.Optional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.RepositoryDefinition; import com.chuange.aishijing.pojo.userManage.User; @RepositoryDefinition(domainClass = com.chuange.aishijing.pojo.userManage.User.class, idClass = String.class) public interface UserManageDao extends JpaRepository<User, String>,JpaSpecificationExecutor<User>{ /** * 分页全部查询 */ Page<User> findAll(Pageable pageable); /** * 分页模糊查询 */ @Override Page<User> findAll(Specification<User> spec, Pageable pageable); /** * 用户详情查询 */ @Override Optional<User> findById(String id); } <file_sep>/src/main/java/com/chuange/aishijing/dto/classes/AddClassesDTO.java package com.chuange.aishijing.dto.classes; import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.List; /** * 新增课程 * * @author hpy * @create 2018/11/26 21:43 */ public class AddClassesDTO { private Long id; @NotNull private String classtitle;//课程标题(大章节) @NotNull private String teacher;//讲师 @NotNull private Double price;//价格 @NotNull private String castIntroduce;//课程介绍 private String classCover; //课程封面url @NotNull private String castTitle ; @NotNull private List<AddFirstClassesDTO> firstClasses = new ArrayList<AddFirstClassesDTO>(); @Override public String toString() { return "AddClassesDTO{" + "classtitle='" + classtitle + '\'' + ", teacher='" + teacher + '\'' + ", price=" + price + ", castIntroduce='" + castIntroduce + '\'' + ", classCover='" + classCover + '\'' + ", castTitle='" + castTitle + '\'' + ", firstClasses=" + firstClasses + '}'; } public AddClassesDTO() { } public AddClassesDTO(@NotNull String classtitle, @NotNull String teacher, @NotNull Double price, @NotNull String castIntroduce, String classCover, @NotNull String castTitle, @NotNull List<AddFirstClassesDTO> firstClasses) { this.classtitle = classtitle; this.teacher = teacher; this.price = price; this.castIntroduce = castIntroduce; this.classCover = classCover; this.castTitle = castTitle; this.firstClasses = firstClasses; } public void addFirstClasses(AddFirstClassesDTO addFirstClassesDTO){ if(firstClasses ==null){ firstClasses = new ArrayList<AddFirstClassesDTO>(); } firstClasses.add(addFirstClassesDTO); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getClassCover() { return classCover; } public void setClassCover(String classCover) { this.classCover = classCover; } public String getCastTitle() { return castTitle; } public void setCastTitle(String castTitle) { this.castTitle = castTitle; } public String getClasstitle() { return classtitle; } public void setClasstitle(String classtitle) { this.classtitle = classtitle; } public String getTeacher() { return teacher; } public void setTeacher(String teacher) { this.teacher = teacher; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public String getCastIntroduce() { return castIntroduce; } public void setCastIntroduce(String castIntroduce) { this.castIntroduce = castIntroduce; } public List<AddFirstClassesDTO> getFirstClasses() { return firstClasses; } public void setFirstClasses(List<AddFirstClassesDTO> firstClasses) { this.firstClasses = firstClasses; } } <file_sep>/aishijing/vo/servicevo/CastManagervo/FindCastByIdResponseVO.java package com.chuange.aishijing.vo.servicevo.CastManagervo; import com.chuange.aishijing.vo.CommonResponseVO; /** * Created by Administrator on 2018-11-19. */ public class FindCastByIdResponseVO extends CommonResponseVO { } <file_sep>/aishijing/pojo/login/LoginUser.java package com.chuange.aishijing.pojo.login; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; /** * * @author yuany * 用户表 */ @Entity @Table(name="ASJ_LOGINUSER") public class LoginUser { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long id; private String name;//用户名 private String password;//密码 private Date logintime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } public LoginUser(String name, String password, Date logintime) { this.name = name; this.password = <PASSWORD>; this.logintime = logintime; } public Date getLogintime() { return logintime; } public void setLogintime(Date logintime) { this.logintime = logintime; } @Override public String toString() { return "LoginUser [id=" + id + ", name=" + name + ", password=" + password + "]"; } public LoginUser() { super(); // TODO Auto-generated constructor stub } } <file_sep>/aishijing/service/SelectDictService.java package com.chuange.aishijing.service; import com.chuange.aishijing.vo.servicevo.dics.SelectDictsVO; /** * * @author yuany * 字典查询service * */ public interface SelectDictService { public SelectDictsVO selectDictByTypecode(String typeCode); } <file_sep>/src/main/java/com/chuange/aishijing/util/CommonConstant.java package com.chuange.aishijing.util; /** * Created by Administrator on 2018-10-19. */ public class CommonConstant { /** * @字段名 SUCCESS_S : 成功 */ public static final String SUCCESS_S ="S"; /** * @字段名 SUCCESS_F : 失败 */ public static final String SUCCESS_F = "F"; /** * @字段名 SYSTEM_EXCEPTION : 异常 */ public static final String SYSTEM_EXCEPTION="数据库操作异常"; } <file_sep>/aishijing/vo/servicevo/usermanage/UsersVO.java package com.chuange.aishijing.vo.servicevo.usermanage; import java.util.List; import com.chuange.aishijing.pojo.userManage.UserLable; import com.chuange.aishijing.pojo.userManage.UserMovie; import com.chuange.aishijing.vo.CommonResponseVO; public class UsersVO extends CommonResponseVO{ private List<UserMovie> movies; private List<UserLable> friends; private List<UserLable> jobs; private List<UserLable> specials; public List<UserLable> getFriends() { return friends; } public void setFriends(List<UserLable> friends) { this.friends = friends; } public List<UserLable> getJobs() { return jobs; } public void setJobs(List<UserLable> jobs) { this.jobs = jobs; } public List<UserLable> getSpecials() { return specials; } public void setSpecials(List<UserLable> specials) { this.specials = specials; } public List<UserMovie> getMovies() { return movies; } public void setMovies(List<UserMovie> movies) { this.movies = movies; } } <file_sep>/aishijing/controller/usermanage/VedioReportController.java //package com.chuange.aishijing.controller.usermanage; // //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.boot.autoconfigure.SpringBootApplication; //import org.springframework.stereotype.Controller; //import org.springframework.ui.ModelMap; //import org.springframework.web.bind.annotation.RequestBody; //import org.springframework.web.bind.annotation.RequestMapping; //import org.springframework.web.bind.annotation.RequestParam; //import org.springframework.web.bind.annotation.ResponseBody; // //import com.chuange.aishijing.dto.ReportDTO; //import com.chuange.aishijing.pojo.userManage.VideoAndCommentReportManager; //import com.chuange.aishijing.service.VedioReportService; //import com.chuange.aishijing.vo.servicevo.usermanage.UsersVO; ///** // * // * @author yuany // * 举报管理 // * 0 视频 // * 1 评论 // */ //@Controller //@SpringBootApplication //public class VedioReportController { // @Autowired // private VedioReportService vedioReportService; // /** // * 视频举报页面 // * @param modelmap // * @return // */ // @RequestMapping("/vedioReport") // public String getVedioReport(ModelMap modelmap) { // modelmap.addAttribute("pageNum", 0); // modelmap.addAttribute("totalPages", 1); // modelmap.addAttribute("totalElements", 0); // return "ishijing/usermanage/user_vedio_report"; // } // /** // * 评论举报管理页面 // * @param modelmap // * @return // */ // @RequestMapping("/commentReport") // public String getCommentReport(ModelMap modelmap) { // modelmap.addAttribute("pageNum", 0); // modelmap.addAttribute("totalPages", 1); // modelmap.addAttribute("totalElements", 0); // return "ishijing/usermanage/user_comment_report"; // } // //模糊查询 // @RequestMapping(value="/vedioReports") // @ResponseBody // public UsersVO vedioListByconditions(@RequestParam(value="pageNum", defaultValue = "1")Integer pageNum, // @RequestBody(required=false)ReportDTO report,String category) { // Integer pagesize=1; // UsersVO vo=vedioReportService.queryAllBycondition(pagesize, pageNum, report,category); // return vo; // } // /** // * 更新处理状态 // * @param category // * @param processStatus // * @param reportedid // * @return // */ // @RequestMapping("/update") // public String modifiedById(String category,String processStatus,String id) { // String result=""; // if(processStatus.equals("1")) { // result="已冻结"; // }else if(processStatus.equals("2")) { // result="已恢复"; // } // VideoAndCommentReportManager manager=new VideoAndCommentReportManager(); // manager.setProcessResult(result); // manager.setProcessStatus(processStatus); // manager.setId(id); // vedioReportService.modifyById(manager); // if(category.equals("0")) { // return "ishijing/usermanage/user_vedio_report"; // }else { // return "ishijing/usermanage/user_comment_report"; // } // } // @RequestMapping("/delete") // public String deleteById(String id,String category) { // vedioReportService.deleteById(id); // if(category.equals("0")) { // return "ishijing/usermanage/user_vedio_report"; // }else { // return "ishijing/usermanage/user_comment_report"; // } // } //} <file_sep>/aishijing/service/VedioReportService.java package com.chuange.aishijing.service; import com.chuange.aishijing.dto.ReportDTO; import com.chuange.aishijing.pojo.userManage.VideoAndCommentReportManager; import com.chuange.aishijing.vo.servicevo.usermanage.UsersVO; /** * * @author yuany * */ public interface VedioReportService { /** * 举报管理 * @param pagesize * @param currentPage * @param name * @return */ public UsersVO queryAllBycondition(Integer pagesize,Integer currentPage,ReportDTO report,String category); /** * 更新 * @param manager */ public void modifyById(VideoAndCommentReportManager manager); /** * 删除 * @param id */ public void deleteById(String id); } <file_sep>/src/main/java/com/chuange/aishijing/dto/classes/AddFirstClassesDTO.java package com.chuange.aishijing.dto.classes; import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.List; /** * @author augus * @create 2018/11/26 23:12 */ public class AddFirstClassesDTO { @NotNull private String firstSectionName; private String firstSectionId; private List<AddSecondClassDTO> secondClasses = new ArrayList<AddSecondClassDTO>(); @Override public String toString() { return "AddFirstClassesDTO{" + "firstSectionId='" + firstSectionId + '\'' + '}'; } public AddFirstClassesDTO(@NotNull String firstSectionName, String firstSectionId, List<AddSecondClassDTO> secondClasses) { this.firstSectionName = firstSectionName; this.firstSectionId = firstSectionId; this.secondClasses = secondClasses; } public AddFirstClassesDTO() { } public String getFirstSectionId() { return firstSectionId; } public void setFirstSectionId(String firstSectionId) { this.firstSectionId = firstSectionId; } public AddFirstClassesDTO(String firstSectionName, List<AddSecondClassDTO> secondClasses) { this.firstSectionName = firstSectionName; this.secondClasses = secondClasses; } public String getFirstSectionName() { return firstSectionName; } public void setFirstSectionName(String firstSectionName) { this.firstSectionName = firstSectionName; } public void addSecondClasses(AddSecondClassDTO addSecondClassDTO) { if (secondClasses == null) { secondClasses = new ArrayList<AddSecondClassDTO>(); } secondClasses.add(addSecondClassDTO); } public List<AddSecondClassDTO> getSecondClasses() { return secondClasses; } public void setSecondClasses(List<AddSecondClassDTO> secondClasses) { this.secondClasses = secondClasses; } }<file_sep>/aishijing/controller/checksystemcontroller/CheckSystem.java package com.chuange.aishijing.controller.checksystemcontroller; import com.chuange.aishijing.pojo.checkSystem.CastCertified; import com.chuange.aishijing.pojo.checkSystem.Certification; import com.chuange.aishijing.pojo.checkSystem.StarCertified; import com.chuange.aishijing.service.AuditSystemService; import com.chuange.aishijing.util.MD5; import com.chuange.aishijing.vo.servicevo.checksystemvo.CheckSystemResponse; import com.chuange.aishijing.vo.servicevo.checksystemvo.CheckSystemResponseVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2018-11-13. */ @RestController @SpringBootApplication public class CheckSystem { @Autowired private AuditSystemService auditSystemService; @ResponseBody @RequestMapping("/check") public CheckSystemResponseVO check(@RequestParam Integer page,@RequestParam String key,@RequestParam String key1){ System.out.println("key;"+key); System.out.println("key1;"+key1); CheckSystemResponse checkSystemResponse = new CheckSystemResponse(); CheckSystemResponseVO checkSystemResponseVO = new CheckSystemResponseVO(); System.out.println("进入contro"); List<Certification> list = new ArrayList<Certification>(); Page<Certification> certifications = auditSystemService.selectAll(page,key,key1); int totalPages = certifications.getTotalPages(); Long totalElements = certifications.getTotalElements(); System.out.println("总条数:"+certifications.getTotalElements()); for (Certification ss : certifications){ System.out.println(ss); list.add(ss); } checkSystemResponse.setList(list); checkSystemResponse.setTotalElements(totalElements); checkSystemResponse.setTotalPage(totalPages); String md5 = new MD5(checkSystemResponseVO.toString()).compute(); checkSystemResponseVO.success("成功",md5,checkSystemResponse); return checkSystemResponseVO; } @ResponseBody @RequestMapping("/checkPass") public CheckSystemResponseVO checkpass(@RequestParam String id,@RequestParam String flag){ CheckSystemResponseVO checkSystemResponseVO = auditSystemService.updateStatus(id,flag); return checkSystemResponseVO; } @ResponseBody @RequestMapping("/starcheck") public CheckSystemResponseVO startcheck(@RequestParam Integer page,@RequestParam String key,@RequestParam String key1){ CheckSystemResponse checkSystemResponse = new CheckSystemResponse(); CheckSystemResponseVO checkSystemResponseVO = new CheckSystemResponseVO(); List<StarCertified> list = new ArrayList<StarCertified>(); Page<StarCertified> starCertifieds = auditSystemService.selectStarAll(page,key,key1); int totalPages = starCertifieds.getTotalPages(); Long totalElements = starCertifieds.getTotalElements(); System.out.println("总条数:"+starCertifieds.getTotalElements()); for (StarCertified ss : starCertifieds){ System.out.println(ss); list.add(ss); } checkSystemResponse.setStarList(list); checkSystemResponse.setTotalElements(totalElements); checkSystemResponse.setTotalPage(totalPages); String md5 = new MD5(checkSystemResponseVO.toString()).compute(); checkSystemResponseVO.success("成功",md5,checkSystemResponse); return checkSystemResponseVO; } @ResponseBody @RequestMapping("/startcheckPass") public CheckSystemResponseVO startcheckPass(@RequestParam String id,@RequestParam String flag){ CheckSystemResponseVO checkSystemResponseVO = auditSystemService.updateStarStatus(id,flag); return checkSystemResponseVO; } @ResponseBody @RequestMapping("/castcheck") public CheckSystemResponseVO castcheck(@RequestParam Integer page,@RequestParam String key,@RequestParam String key1){ CheckSystemResponse checkSystemResponse = new CheckSystemResponse(); CheckSystemResponseVO checkSystemResponseVO = new CheckSystemResponseVO(); List<CastCertified> list = new ArrayList<CastCertified>(); Page<CastCertified> castCertifieds = auditSystemService.selectCastAll(page,key,key1); int totalPages = castCertifieds.getTotalPages(); Long totalElements = castCertifieds.getTotalElements(); System.out.println("总条数:"+castCertifieds.getTotalElements()); for (CastCertified ss : castCertifieds){ System.out.println(ss); list.add(ss); } checkSystemResponse.setCastCertifiedList(list); checkSystemResponse.setTotalElements(totalElements); checkSystemResponse.setTotalPage(totalPages); String md5 = new MD5(checkSystemResponseVO.toString()).compute(); checkSystemResponseVO.success("成功",md5,checkSystemResponse); return checkSystemResponseVO; } @ResponseBody @RequestMapping("/castcheckPass") public CheckSystemResponseVO castcheckPass(@RequestParam String id,@RequestParam String flag){ CheckSystemResponseVO checkSystemResponseVO = auditSystemService.updateCastStatus(id,flag); return checkSystemResponseVO; } } <file_sep>/aishijing/dao/loginuser/IndexDao.java package com.chuange.aishijing.dao.loginuser; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.RepositoryDefinition; /** * * @author yuany * 获取index页面树结构 */ import com.chuange.aishijing.pojo.tree.Tree; @RepositoryDefinition(domainClass = com.chuange.aishijing.pojo.tree.Tree.class, idClass = String.class) public interface IndexDao extends JpaRepository<Tree, String>{ List<Tree> findAllByResourceType(String resourceType); // TODO Auto-generated method stub } <file_sep>/aishijing/controller/Login.java package com.chuange.aishijing.controller; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * * @author yuany * 登陆逻辑判断 */ @Controller @SpringBootApplication public class Login { @RequestMapping("/logins") public String login() { return "ishijing/login"; } public static void main( String[] args ) { new SpringApplication(Login.class).run(args); } } <file_sep>/src/main/java/com/chuange/aishijing/dto/UploadDTO.java package com.chuange.aishijing.dto; import java.util.Arrays; /** * @author hpy * @create 2018/11/27 16:16 */ public class UploadDTO { private long id ; private String uploadType ; private String uploadName; private String uploadSuffixName; private String uploadPath; @Override public String toString() { return "UploadDTO{" + "id=" + id + ", uploadType='" + uploadType + '\'' + ", uploadName='" + uploadName + '\'' + ", uploadSuffixName='" + uploadSuffixName + '\'' + ", uploadPath='" + uploadPath + '\'' + '}'; } public UploadDTO(long id, String uploadType, String uploadName, String uploadSuffixName, String uploadPath) { this.id = id; this.uploadType = uploadType; this.uploadName = uploadName; this.uploadSuffixName = uploadSuffixName; this.uploadPath = uploadPath; } public UploadDTO() { } public String getUploadSuffixName() { return uploadSuffixName; } public void setUploadSuffixName(String uploadSuffixName) { this.uploadSuffixName = uploadSuffixName; } public String getUploadPath() { return uploadPath; } public void setUploadPath(String uploadPath) { this.uploadPath = uploadPath; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUploadType() { return uploadType; } public void setUploadType(String uploadType) { this.uploadType = uploadType; } public String getUploadName() { return uploadName; } public void setUploadName(String uploadName) { this.uploadName = uploadName; } } <file_sep>/aishijing/service/impl/PersonServiceImpl.java package com.chuange.aishijing.service.impl; import com.chuange.aishijing.dao.PersonRepository; import com.chuange.aishijing.pojo.Person; import com.chuange.aishijing.service.PersonService; import com.chuange.aishijing.util.BusinessException; import com.chuange.aishijing.util.CommonConstant; import com.chuange.aishijing.util.MD5; import com.chuange.aishijing.vo.servicevo.PersonServiceVo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2018-10-16. */ @Service @Transactional public class PersonServiceImpl implements PersonService { private final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); @Autowired private PersonRepository personRepository; //查询所有数据 public PersonServiceVo findAll(){ PersonServiceVo personServiceVo = new PersonServiceVo(); logger.debug("debug....liye"); List<Person> list = new ArrayList<Person>(); String md5 = new MD5(personServiceVo.toString()).compute(); personServiceVo.success("查询成功",md5,personRepository.findAll()); return personServiceVo; } //保存数据 public PersonServiceVo savePerson(){ PersonServiceVo personServiceVo = new PersonServiceVo(); Person person = new Person(); person.setName("丽丽"); person.setAge(24); personRepository.save(person); personServiceVo.success("保存数据成功"); return personServiceVo; } //删除数据 public PersonServiceVo deletePerson(){ PersonServiceVo personServiceVo = new PersonServiceVo(); try { personRepository.deleteById("李野"); System.out.print("删除数据标记"); }catch (Exception e){ e.printStackTrace(); throw new BusinessException(CommonConstant.SYSTEM_EXCEPTION, "系统异常:更新应用信息异常"); } personServiceVo.success("删除数据成功"); return personServiceVo; } //自定义SQL,根据条件查询 public PersonServiceVo findById() { PersonServiceVo personServiceVo = new PersonServiceVo(); String emails = personRepository.findByEmaill("<EMAIL>"); String md5 = new MD5(personServiceVo.toString()).compute(); personServiceVo.success("根据条件查询成功",md5,emails); return personServiceVo; } @Override public PersonServiceVo deletePersonEmail() { PersonServiceVo personServiceVo = new PersonServiceVo(); int s = personRepository.deleteByEmail("11111"); if(s==1){ personServiceVo.success("删除数据成功"); }else{ personServiceVo.fail("删除数据失败"); } return personServiceVo; } } <file_sep>/alipay/dao/AlipayReporsitory.java package com.chuange.alipay.dao; import javax.transaction.Transactional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.RepositoryDefinition; import org.springframework.data.repository.query.Param; import com.chuange.aishijing.pojo.Person; import com.chuange.alipay.bean.AlipayOrderBean; @RepositoryDefinition(domainClass = AlipayOrderBean.class, idClass = Integer.class) public interface AlipayReporsitory extends JpaRepository<Person,String>{ //生成加签订单 void save(AlipayOrderBean order); //根据订单号查询订单信息 @Query(value="select * from order_info where outTradeNo=:tradeno",nativeQuery=true) AlipayOrderBean findByTradeno(@Param("tradeno") String tradeno); //根据主键更新 @Modifying @Transactional int saveAndFlush(AlipayOrderBean order); } <file_sep>/aishijing/dao/usermanage/ReportDao.java package com.chuange.aishijing.dao.usermanage; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.RepositoryDefinition; import com.chuange.aishijing.pojo.userManage.UserReport; /** * * @author yuany * 举报历史 * */ @RepositoryDefinition(domainClass = com.chuange.aishijing.pojo.userManage.UserReport.class, idClass = String.class) public interface ReportDao extends JpaRepository<UserReport, String>{ /** * 举报历史 */ Page<UserReport> findAllByUserId(Pageable pageable,String id); } <file_sep>/src/main/java/com/chuange/aishijing/pojo/classessys/ClassesDetails.java package com.chuange.aishijing.pojo.classessys; import javax.persistence.*; import javax.validation.constraints.NotNull; /** * 课程详情 * * @author augus * @create 2018/11/26 21:59 */ @Entity @Table(name="ASJ_CLASSDETAILS") public class ClassesDetails { @Id @NotNull @GeneratedValue(strategy = GenerationType.AUTO) private long id; //自增 id private String sectionId; // 章节id private String sectionGrade; // 课程等级 (1 大章节 2小章节) private String sectionName; // 章节名称 private String parentId; // 上级章节id private String courseWareUrl;// 课件url private String courseWareName;// 课件url private String courseVideoUrl;// 视频url private String courseVideoName;// 视频url private String classId; // 课程id @Override public String toString() { return "ClassesDetails{" + "id='" + id + '\'' + ", sectionId='" + sectionId + '\'' + ", sectionGrade='" + sectionGrade + '\'' + ", sectionName='" + sectionName + '\'' + ", parentId='" + parentId + '\'' + ", courseWareUrl='" + courseWareUrl + '\'' + ", courseWareName='" + courseWareName + '\'' + ", courseVideoUrl='" + courseVideoUrl + '\'' + ", courseVideoName='" + courseVideoName + '\'' + ", classId='" + classId + '\'' + '}'; } public ClassesDetails() { } public ClassesDetails(String sectionId, String sectionGrade, String sectionName, String parentId, String courseWareUrl, String courseWareName, String courseVideoUrl, String courseVideoName, String classId) { this.sectionId = sectionId; this.sectionGrade = sectionGrade; this.sectionName = sectionName; this.parentId = parentId; this.courseWareUrl = courseWareUrl; this.courseWareName = courseWareName; this.courseVideoUrl = courseVideoUrl; this.courseVideoName = courseVideoName; this.classId = classId; } public String getCourseWareName() { return courseWareName; } public void setCourseWareName(String courseWareName) { this.courseWareName = courseWareName; } public String getCourseVideoName() { return courseVideoName; } public void setCourseVideoName(String courseVideoName) { this.courseVideoName = courseVideoName; } public String getSectionName() { return sectionName; } public void setSectionName(String sectionName) { this.sectionName = sectionName; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getSectionId() { return sectionId; } public void setSectionId(String sectionId) { this.sectionId = sectionId; } public String getSectionGrade() { return sectionGrade; } public void setSectionGrade(String sectionGrade) { this.sectionGrade = sectionGrade; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getCourseWareUrl() { return courseWareUrl; } public void setCourseWareUrl(String courseWareUrl) { this.courseWareUrl = courseWareUrl; } public String getCourseVideoUrl() { return courseVideoUrl; } public void setCourseVideoUrl(String courseVideoUrl) { this.courseVideoUrl = courseVideoUrl; } public String getClassId() { return classId; } public void setClassId(String classId) { this.classId = classId; } } <file_sep>/aishijing/service/impl/castmanager/TeacherManagerImpl.java package com.chuange.aishijing.service.impl.castmanager; import com.chuange.aishijing.dao.castmanager.TeacherManagerDao; import com.chuange.aishijing.pojo.teachersys.TeacherManager; import com.chuange.aishijing.service.TeacherManagerService; import com.mysql.jdbc.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.transaction.Transactional; /** * Created by Administrator on 2018-11-21. */ @Service @Transactional public class TeacherManagerImpl implements TeacherManagerService{ private final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); private final Integer size = 5; @Autowired private TeacherManagerDao teacherManagerDao; public Page<TeacherManager> selectTeacher(Integer page,String key) { Pageable pageable = PageRequest.of(page-1,size); Page<TeacherManager> t = teacherManagerDao.findAll(new Specification<TeacherManager>() { @Override public Predicate toPredicate(Root<TeacherManager> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) { if(!StringUtils.isNullOrEmpty(key)){ System.out.println("有条件查询"); Predicate p1 = criteriaBuilder.like(root.get("teacherName").as(String.class), "%" + key + "%"); query.where(criteriaBuilder.and(p1)); } return query.getRestriction(); } }, pageable); return t; } @Override public int insertorupdateTeacher(TeacherManager teacherManager) { if(teacherManager.getId()!=null){ teacherManagerDao.saveAndFlush(teacherManager); } try { teacherManagerDao.save(teacherManager); }catch (Exception e){ e.printStackTrace(); return 0; } return 1; } @Override public TeacherManager findTeacherById(String id) { TeacherManager teacherManager = teacherManagerDao.getOne(id); if(teacherManager==null){ logger.info("根据id查询失败"); } return teacherManager; } @Override public void deleteTeacherById(String id) { teacherManagerDao.deleteById(id); } } <file_sep>/src/main/java/com/chuange/aishijing/service/UploadService.java package com.chuange.aishijing.service; import com.chuange.aishijing.dto.UploadDTO; import com.chuange.aishijing.pojo.upload.UploadByte; public interface UploadService { Long addUpload(UploadDTO uploadDTO); } <file_sep>/aishijing/dao/castsystem/CastManagerDao.java package com.chuange.aishijing.dao.castsystem; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.RepositoryDefinition; import com.chuange.aishijing.pojo.castsystem.Drama; /** * * @author yuany * 剧本管理 */ @RepositoryDefinition(domainClass = com.chuange.aishijing.pojo.castsystem.Drama.class, idClass = String.class) public interface CastManagerDao extends JpaRepository<Drama, String>{ <S extends Drama> Page<S> findAll(Specification<S> casts, Pageable pageable) ; } <file_sep>/aishijing/controller/Aishijingtest.java package com.chuange.aishijing.controller; import com.chuange.aishijing.service.PersonService; import com.chuange.aishijing.vo.servicevo.PersonServiceVo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; /** * Created by Administrator on 2018-10-16. */ @RestController @ComponentScan(basePackages={"com"}) public class Aishijingtest { private final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); @Autowired private PersonService personService; @RequestMapping(value="/testSelectById", method= RequestMethod.GET) @ResponseBody public PersonServiceVo findbyid(){ return personService.findById(); } @RequestMapping(value="/testSelect", method= RequestMethod.GET) @ResponseBody public PersonServiceVo select(){ return personService.findAll(); } @RequestMapping(value="/testInsert", method= RequestMethod.GET) @ResponseBody public String insert(){ personService.savePerson(); return "INSERTSUCCESS"; } @RequestMapping(value="/testDelete", method= RequestMethod.GET) @ResponseBody public PersonServiceVo delete(){ PersonServiceVo personServiceVo = personService.deletePerson(); if(personServiceVo.getMsg().equals("SUCCESS")){ return personServiceVo; } return personServiceVo; } @RequestMapping(value="/testDeleteByEmail", method= RequestMethod.GET) @ResponseBody public PersonServiceVo deletebyemail(){ PersonServiceVo personServiceVo = personService.deletePersonEmail(); return personServiceVo; } } <file_sep>/src/main/java/com/chuange/aishijing/service/CourserManagerService.java package com.chuange.aishijing.service; import com.chuange.aishijing.dao.courserManager.ClassesCommentsDao; import com.chuange.aishijing.dto.classes.AddClassesDTO; import com.chuange.aishijing.dto.classes.CommentsQueryDTO; import com.chuange.aishijing.dto.classes.OrderQueryDTO; import com.chuange.aishijing.pojo.classessys.ClassComments; import com.chuange.aishijing.pojo.classessys.ClassesSale; import com.chuange.aishijing.pojo.ordermanage.Order; import com.chuange.aishijing.vo.servicevo.classesmanage.CouseVO; import java.util.List; /** * 课程管理接口 */ public interface CourserManagerService { /** * 添加 课程 * @param addClassesDTO * @return */ public boolean addClasses(AddClassesDTO addClassesDTO) throws Exception; /** * 根据课程id 获取课程 * @param classId * @return */ public AddClassesDTO getClasses(long classId); /** * 获取 课程 基本信息价格栏目 * @param classId * @return */ public ClassesSale getClassesSale(long classId); /** * 获取课程的销售情况 * @param classId * @return */ public List<Order> getClassesOrder(long classId) ; /** * 获取课程的销售情况 其他操作 * @param orderQueryDTO * @return */ public List<Order> getClassesOrderByOtherQuery(OrderQueryDTO orderQueryDTO); /** * 获取课程基本信息列表list * @return */ public List<AddClassesDTO> getClassesIdList(); /** * 根据 classid 获取评价列表 * @param classid * @return */ public List<ClassComments> getComments(long classid); /** * 根据 classid 获取评价列表 其他操作 * @param commentsQueryDTO * @return */ public List<ClassComments> getCommentsByOtherQuery(CommentsQueryDTO commentsQueryDTO); /** * 删除评价 * @param commentid * @return */ public boolean delCommentByCommentId(long commentid) throws Exception; } <file_sep>/aishijing/pojo/checkSystem/CastCertified.java package com.chuange.aishijing.pojo.checkSystem; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; /** * * @author yuany /* 剧组认证 */ @Entity @Table(name="ASJ_CASTCERTIFIED") public class CastCertified { @Id @NotNull @GeneratedValue(strategy = GenerationType.AUTO) private String id; private String username;//用户昵称 private String userid;//用户id private String businessLicense;//营业执照 private String recordNum;//备案号 private String shootingProof;//拍摄证明 private String recordProof;//备案证明 private String handleStatus;//审核状态 public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getBusinessLicense() { return businessLicense; } public void setBusinessLicense(String businessLicense) { this.businessLicense = businessLicense; } public String getRecordNum() { return recordNum; } public void setRecordNum(String recordNum) { this.recordNum = recordNum; } public String getShootingProof() { return shootingProof; } public void setShootingProof(String shootingProof) { this.shootingProof = shootingProof; } public String getRecordProof() { return recordProof; } public void setRecordProof(String recordProof) { this.recordProof = recordProof; } public String getHandleStatus() { return handleStatus; } public void setHandleStatus(String handleStatus) { this.handleStatus = handleStatus; } @Override public String toString() { return "CastCertified [id=" + id + ", username=" + username + ", userid=" + userid + ", businessLicense=" + businessLicense + ", recordNum=" + recordNum + ", shootingProof=" + shootingProof + ", recordProof=" + recordProof + ", handleStatus=" + handleStatus + "]"; } public CastCertified(@NotNull String id, String username, String userid, String businessLicense, String recordNum, String shootingProof, String recordProof, String handleStatus) { super(); this.id = id; this.username = username; this.userid = userid; this.businessLicense = businessLicense; this.recordNum = recordNum; this.shootingProof = shootingProof; this.recordProof = recordProof; this.handleStatus = handleStatus; } public CastCertified() { super(); // TODO Auto-generated constructor stub } } <file_sep>/src/main/java/com/chuange/aishijing/dao/orderManager/OrderDao.java package com.chuange.aishijing.dao.orderManager; import com.chuange.aishijing.pojo.ordermanage.Order; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.RepositoryDefinition; import java.util.List; @RepositoryDefinition(domainClass = Order.class, idClass = String.class) public interface OrderDao extends JpaRepository<Order,String> { public List<Order> findAllByClassId(long classId); public List<Order> findAllByClassIdAndPurchaser(long classId,String purchaser); } <file_sep>/aishijing/pojo/userManage/UserLable.java package com.chuange.aishijing.pojo.userManage; import javax.persistence.*; import javax.validation.constraints.NotNull; /** * Created by Administrator on 2018-11-14. */ @Entity @Table(name="ASJ_USERELABLE") public class UserLable { @Id @NotNull @GeneratedValue(strategy = GenerationType.AUTO) private String id; private String userid;//关联user表 private String description;//描述 private String type;//分类 public UserLable(){} public UserLable(String userid, String description, String type) { this.userid = userid; this.description = description; this.type = type; } @Override public String toString() { return "UserLable{" + "id='" + id + '\'' + ", userid='" + userid + '\'' + ", description='" + description + '\'' + ", type='" + type + '\'' + '}'; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getType() { return type; } public void setType(String type) { this.type = type; } } <file_sep>/src/main/java/com/chuange/aishijing/pojo/classessys/ClassComments.java package com.chuange.aishijing.pojo.classessys; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonFormat; /** * * @author yuany * 课程评价表 */ @Entity @Table(name="ASJ_CLASSCOMMENTS") public class ClassComments { @Id @NotNull @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Column(nullable = true) @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss") private Date commentTime;//评论时间 private String commentUser;//评论用户 private String userId;//用户id private String classname;//课程名称 private String commentContent;//评价内容 private long classId; //课程id public long getId() { return id; } public void setId(long id) { this.id = id; } public Date getCommentTime() { return commentTime; } public void setCommentTime(Date commentTime) { this.commentTime = commentTime; } public String getCommentUser() { return commentUser; } public void setCommentUser(String commentUser) { this.commentUser = commentUser; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getClassname() { return classname; } public void setClassname(String classname) { this.classname = classname; } public String getCommentContent() { return commentContent; } public void setCommentContent(String commentContent) { this.commentContent = commentContent; } public long getClassId() { return classId; } public void setClassId(long classId) { this.classId = classId; } @Override public String toString() { return "ClassComments [id=" + id + ", commentTime=" + commentTime + ", commentUser=" + commentUser + ", userId=" + userId + ", classname=" + classname + ", commentContent=" + commentContent + "]"; } public ClassComments(Date commentTime, String commentUser, String userId, String classname, String commentContent, long classId) { this.commentTime = commentTime; this.commentUser = commentUser; this.userId = userId; this.classname = classname; this.commentContent = commentContent; this.classId = classId; } public ClassComments() { super(); // TODO Auto-generated constructor stub } } <file_sep>/aishijing/service/TeacherManagerService.java package com.chuange.aishijing.service; import com.chuange.aishijing.pojo.teachersys.TeacherManager; import org.springframework.data.domain.Page; /** * Created by Administrator on 2018-11-21. */ public interface TeacherManagerService { Page<TeacherManager> selectTeacher(Integer page,String key); int insertorupdateTeacher(TeacherManager teacherManager); TeacherManager findTeacherById(String id); void deleteTeacherById(String id); }
43dcd41b22328c45b027ba7230182ee7d7092173
[ "Java" ]
51
Java
pp1314add/xm
47c729e77c6e0b9e5d5e4ebb107b81c63e83584a
5d3bfd6160669addc739e3d0cd2f4bfa9db7333e
refs/heads/master
<repo_name>creatorkuang/miifang<file_sep>/questions/start.php <?php /** * questions start.php */ elgg_register_event_handler('init', 'system', 'questions_init'); function questions_init() { //register library for questions $root = dirname(__FILE__); elgg_register_library('elgg:questions', "$root/lib/questions.php"); // Register actions $action_dir = "$root/actions"; elgg_register_action('questions/save', "$action_dir/questions/save.php"); elgg_register_action('questions/delete', "$action_dir/questions/delete.php"); elgg_register_action('questions/thumbs', "$action_dir/questions/thumbs.php"); elgg_register_action('references/add', "$action_dir/references/add.php"); elgg_register_action('references/delete', "$action_dir/references/delete.php"); //featured action elgg_register_action('questions/follow', "$action_dir/questions/follow.php"); //register widget elgg_register_widget_type('question-top', elgg_echo("Questions"), elgg_echo("question-top:widget:description")); elgg_register_widget_type('question', elgg_echo("Answers"), elgg_echo("question:widget:description")); elgg_register_widget_type('friendsof', elgg_echo("Followers"), elgg_echo("follower:widget:description")); elgg_register_entity_type('object', 'question'); elgg_register_entity_type('object', 'question-top'); // Extend the main CSS file elgg_extend_view('css/elgg', 'questions/css'); // Add a menu item to the main site menu $item = new ElggMenuItem('questions', elgg_echo('questions:menu'), 'questions/all'); elgg_register_menu_item('site', $item); //register page_handler elgg_register_page_handler('questions', 'questions_page_handler'); // Register a URL handler for questions elgg_register_entity_url_handler('object', 'question', 'question_url'); elgg_register_entity_url_handler('object', 'question-top', 'question_url'); elgg_register_plugin_hook_handler('register', 'menu:entity', 'questions_entity_menu_setup'); elgg_register_plugin_hook_handler('register', 'menu:annotation', 'reference_annotation_menu_setup'); } function questions_page_handler($page) { elgg_load_library('elgg:questions'); elgg_push_breadcrumb(elgg_echo('questions:everyone'), 'questions/all'); $pages = dirname(__FILE__) . '/pages/questions'; switch ($page[0]) { case 'owner': include "$pages/owner.php"; break; case 'friends': include "$pages/friends.php"; break; case 'view': set_input('guid', $page[1]); include "$pages/view.php"; break; case 'add': set_input('guid', $page[1]); include "$pages/add.php"; break; case 'edit': set_input('guid', $page[1]); include "$pages/edit.php"; break; case 'all': include "$pages/all.php"; break; case 'inbox': gatekeeper(); $params=question_get_messages_by_ajax(); break; case 'mine': $params=get_my_questions(); break; case 'answer': $params=get_questions_answer_by_me(); break; default: return false; } echo $params; return true; } function question_url($entity) { global $CONFIG; $title = $entity->title; $title = elgg_get_friendly_title($title); return $CONFIG->url . "questions/view/" . $entity->getGUID() . "/" . $title; } //add a delete link to the reference annotation function reference_annotation_menu_setup($hook, $type, $return, $params) { $annotation = $params['annotation']; if ($annotation->name == 'reference' && $annotation->canEdit()) { $url = elgg_http_add_url_query_elements('action/references/delete', array( 'annotation_id' => $annotation->id, )); $options = array( 'name' => 'delete', 'href' => $url, 'text' => "<span class=\"elgg-icon elgg-icon-delete\"></span>", 'confirm' => elgg_echo('deleteconfirm'), 'encode_text' => false ); $return[] = ElggMenuItem::factory($options); } return $return; } function questions_entity_menu_setup($hook, $type, $return, $params) { if (elgg_in_context('widgets')) { return $return; } $entity = $params['entity']; $handler = elgg_extract('handler', $params, false); foreach ($return as $index => $item) { if (in_array($item->getName(), array('access','likes'))) { unset($return[$index]); } } return $return; }<file_sep>/qq_theme/start.php <?php function qq_theme_init() { elgg_extend_view('css/elgg', 'qq_theme/css'); elgg_register_plugin_hook_handler('index', 'system', 'qq_index'); $menus=array('about','jobs','service','privacy','feedback','contact','apply'); foreach($menus as $menu){ elgg_register_page_handler($menu, $menu.'_page_handler'); } //re-register river page elgg_register_page_handler('activity', 'river_page_handler'); //re-construct the notification setting page elgg_register_page_handler('notifications', 'qq_notifications_page_handler'); // re-construct the avater and profile edit page elgg_register_page_handler('avatar', 'qq_avatar_page_handler'); elgg_register_page_handler('profile', 'qq_profile_page_handler'); elgg_register_page_handler('settings', 'qq_usersettings_page_handler'); //unregister the file page handler and menu and widget elgg_unregister_page_handler('file'); elgg_unregister_plugin_hook_handler('register', 'menu:owner_block', 'file_owner_block_menu'); elgg_unregister_widget_type('filerepo'); // re-construct the friends and friendsof page elgg_register_page_handler('friends', 'qq_friends_page'); elgg_register_page_handler('friendsof', 'qq_friendsof_page'); elgg_register_simplecache_view('qq_theme/css'); elgg_register_simplecache_view('page/elements/header'); // action $root = dirname(__FILE__); elgg_register_action('apply', "$root/actions/apply.php",'public'); elgg_register_action('feedback', "$root/actions/feedback.php"); elgg_register_action('forward', "$root/actions/forward.php"); //unregister comment and add other link elgg_register_plugin_hook_handler('register', 'menu:river', 'question_river_menu_setup'); //ajax controller page elgg_register_page_handler('qq_ajax', 'qq_ajax_page_handler'); elgg_register_library('elgg:qq_ajax', "$root/lib/qq_ajax.php"); } function qq_index() { if (!include_once(dirname(dirname(__FILE__)) . "/qq_theme/pages/index.php")) return false; return true; } function apply_page_handler() { include(dirname(dirname(__FILE__)) . "/qq_theme/pages/apply.php"); return true; } function about_page_handler() { include(dirname(dirname(__FILE__)) . "/qq_theme/pages/about.php"); return true; } function contact_page_handler() { include(dirname(dirname(__FILE__)) . "/qq_theme/pages/contact.php"); return true; } function service_page_handler() { include(dirname(dirname(__FILE__)) . "/qq_theme/pages/service.php"); return true; } function privacy_page_handler() { include(dirname(dirname(__FILE__)) . "/qq_theme/pages/privacy.php"); return true; } function feedback_page_handler() { include(dirname(dirname(__FILE__)) . "/qq_theme/pages/feedback.php"); return true; } function jobs_page_handler() { include(dirname(dirname(__FILE__)) . "/qq_theme/pages/jobs.php"); return true; } function river_page_handler() { include(dirname(dirname(__FILE__)) . "/qq_theme/pages/river.php"); return true; } function qq_friends_page($page) { $username=$page[0]; $user=get_user_by_username($username); set_page_owner($user->getGUID()); include(dirname(dirname(__FILE__)) . "/qq_theme/pages/friends/index.php"); return true; } function qq_friendsof_page($page) { $username=$page[0]; $user=get_user_by_username($username); set_page_owner($user->getGUID()); include(dirname(dirname(__FILE__)) . "/qq_theme/pages/friends/of.php"); return true; } function question_river_menu_setup($hook, $type, $return, $params){ if (elgg_is_logged_in()) { foreach ($return as $index => $item) { if (in_array($item->getName(), array('comment'))) { unset($return[$index]); } } $item = $params['item']; $object = $item->getObjectEntity(); if($item->annotation_id != 0 || !$object || $item->action_type=='follow'){ return $return; } if (elgg_instanceof($object, 'object','question-top')||elgg_instanceof($object, 'object','question')) { $options = array( 'name' => 'question', 'href' => "#question-$object->guid", 'text' => elgg_view_icon('speech-bubble'), 'title' => elgg_echo('question:this'), 'rel' => 'toggle', 'priority' => 50, ); $return[] = ElggMenuItem::factory($options); //forward $item_id=$item->id; $options = array( 'name' => 'forward', 'href'=>elgg_get_site_url().'action/forward?item_id='.$item_id.'&user_id='.elgg_get_logged_in_user_guid(), 'is_action'=>true, 'id' => "forward-$object->guid", 'text' => elgg_view_icon('redo'), 'title' => elgg_echo('forward:this'), 'priority' => 40, ); $return[] = ElggMenuItem::factory($options); } } return $return; } function qq_ajax_page_handler($page){ elgg_load_library('elgg:qq_ajax'); $pages = dirname(__FILE__) . '/pages/qq_ajax'; switch ($page[0]) { case 'question_update': $params=qq_ajax_get_questions(); break; case 'follow_update': $params=qq_ajax_get_follow_update(); break; default: return false; } echo $params; return true; } function qq_notifications_page_handler(){ if (!isset($page[0])) { $page[0] = 'personal'; } $base = elgg_get_plugins_path() . 'notifications'; include(dirname(dirname(__FILE__)) . "/qq_theme/pages/notifications/index.php"); return true; } function qq_avatar_page_handler($page){ global $CONFIG; $user=get_user_by_username($page[1]); if($user){ elgg_set_page_owner_guid($user->getGUID()); } if($page[0]=='edit'){ include(dirname(dirname(__FILE__)) . "/qq_theme/pages/avatar/edit.php"); return true; }else{ return elgg_avatar_page_handler($page); } return false; } function qq_profile_page_handler($page){ global $CONFIG; $user = get_user_by_username($page[0]); elgg_set_page_owner_guid($user->guid); if ($page[1] == 'edit') { include(dirname(dirname(__FILE__)) . "/qq_theme/pages/profile/edit.php"); return true; }else{ return profile_page_handler($page); } return false; } function qq_usersettings_page_handler($page) { global $CONFIG; if (!isset($page[0])) { $page[0] = 'user'; } if (isset($page[1])) { $user = get_user_by_username($page[1]); elgg_set_page_owner_guid($user->guid); } else { $user = elgg_get_logged_in_user_guid(); elgg_set_page_owner_guid($user->guid); } elgg_push_breadcrumb(elgg_echo('settings'), "settings/user/$user->username"); if($page[0]=='user'){ include(dirname(dirname(__FILE__)) . "/qq_theme/pages/settings/account.php"); return true; }else{ return usersettings_page_handler($page); } } elgg_register_event_handler('init', 'system', 'qq_theme_init'); ?><file_sep>/questions/pages/questions/view.php <?php /** * question view page * * @package Elggquestions */ $guid =get_input('guid'); $question = get_entity($guid); $title = $question->title; $proccess=$question->proccess; $level=$question->level; $cat=$question->catagory; questions_prepare_parent_breadcrumbs($question); elgg_push_breadcrumb($title); $question_entity = elgg_view_entity($question, array('full_view' => true)); $q_question=elgg_view('output/url',array( 'href' => '#q-form', 'rel' => 'toggle', 'text' => elgg_echo('question:question'), 'style'=>'border:1px solid #ccc;padding:5px 15px', 'class'=>'brl elgg-button-submit f1h ' )); $question_form = elgg_view_form('questions/save','', array('parent_guid'=>$guid,'proccess'=>$proccess,'catagory'=>$cat,'level'=>$level)); $q_question.=elgg_view_module('widget', '', $question_form,array('id'=>'q-form','class'=>'hidden w900')); $uid=elgg_get_logged_in_user_guid(); $follow=elgg_view('output/url',array( 'href'=>elgg_get_site_url().'action/questions/follow?action_type=follow&question_guid='.$guid, 'text'=>elgg_echo('question:follow'), 'class'=>'elgg-button-submit brs pas', 'is_action' => true )); if (check_entity_relationship($uid, 'follow', $guid)){ $follow=elgg_view('output/url',array( 'href'=>elgg_get_site_url().'action/questions/follow?action_type=unfollow&question_guid='.$guid, 'text'=>elgg_echo('question:unfollow'), 'class'=>'elgg-button-submit brs pas', 'is_action' => true )); } $follow_num=elgg_get_entities_from_relationship(array('relationship'=>'follow','relationship_guid'=>$guid,'count'=>true,'inverse_relationship'=>true)); $follow_num=elgg_echo('question:follownum',array($follow_num)); $owner = $question->getOwnerEntity(); if(elgg_instanceof($owner,'user')){ $owner_name=$owner->name; $owner_icon = elgg_view_entity_icon($owner, 'small'); $ownerdecs=elgg_view('output/longtext', array('value' => $owner->description)); $ownerbrief=$owner->briefdescription; } $metadata = elgg_view_menu('entity', array( 'entity' => $question, 'handler' => 'questions', 'sort_by' => 'priority', 'class' => 'elgg-menu-hz', )); $date = elgg_view_friendly_time($question->time_created); $tags = elgg_view('output/qtags', array('tags' => $question->tags)); $summary = elgg_view('object/elements/summary', array( 'entity' => $question, 'title' => false, 'subtitle' => $metadata.$date, 'content'=>$ownerbrief, 'tags'=>false, )); $image_block = elgg_view_image_block($owner_icon, $summary); // get the mindmap view link if(elgg_instanceof($question,'object','question-top')){ $mindmap_link=elgg_view('output/url',array( 'href'=>elgg_get_site_url().'mindmap/'.$guid, 'text'=>elgg_view_icon('share').elgg_echo('mindmap'), )); } $question_meta=<<<html <div class="mas pbm"> $follow $follow_num $mindmap_link </div> <div class="grey pam brs mlm"> <div class="f1h center"> $owner_name </div> $image_block <div style="background:rgba(255,255,255,1) "class="pas brs"> $ownerdecs </div> </div> html; $reference_add=elgg_view('output/url',array( 'href' => '#popup', 'rel' => 'popup', 'text' => elgg_echo('reference:add'), 'style'=>'border:1px solid #ccc;padding:0px 5px', 'class'=>'fr brm elgg-button-submit', )); $reference_form=elgg_view_form('references/add', array(), array('question_guid'=>$guid)); $reference_add.=elgg_view_module('dropdown', '', $reference_form,array('id'=>'popup','class'=>'hidden w200')); $reference_list=elgg_list_annotations(array( 'guid' => $guid, 'annotation_name' => 'reference', 'limit' => 20, 'full_view'=>true )); if(!$reference_list){ $reference_list=''; } $reference_list=<<<html <div style="background:rgba(255,255,255,1)" class="pas brs"> $reference_list </div> html; $r_title=elgg_echo('question:reference'); $refernce_title=<<<html $r_title $reference_add html; $refenence=elgg_view_module('aside', $refernce_title, $reference_list); $questions_list=elgg_list_entities_from_metadata(array( 'type' => 'object', 'subtype' => 'question', 'metadata_name'=>'parent_guid', 'metadata_value'=>$guid, 'pagination' => true, 'full_view' => false, 'list_class'=>'question-list brs', 'item_class'=>'question-item bx', 'view_toggle_type' => false )); $order_by=get_input('order_by'); switch ($order_by){ case "time": $question_list=elgg_list_entities_from_metadata(array( 'type'=>'object', 'subtype'=>'question', 'metadata_name'=>'parent_guid', 'metadata_value'=>$guid, 'list_class'=>'question-list brs', 'item_class'=>'question-item bx', 'limit'=>5, )); break; default: $question_list=get_better_list_based_on_thumbs($guid); } $list_menu=elgg_view('questions/list_menu',array('guid'=>$guid)); if ($question_list){ $question_list=<<<html <div class="mll mtm"> $list_menu $question_list </div> html; } $content=<<<HTML <div class=" q-top"> <div class="elgg-col-2of3 fl"> <div class="q-top"> $tags $question_entity </div> $question_list </div> <div class="elgg-col-1of3 fl"> $question_meta <div class="mtm mlm grey brs pam"> $refenence </div> </div> </div> <div class="clearfloat mtl"></div> $q_question HTML; $body = elgg_view_layout('one_column', array( 'content' => $content, )); echo elgg_view_page('', $body);<file_sep>/qq_theme/views/default/forms/apply.php <?php /** * apply form * */ ?> <div> <?php echo elgg_view('input/email', array( 'name' => 'email', 'class' => 'elgg-autofocus required', 'placeholder'=>elgg_echo('email'), )); ?> </div> <div> <?php echo elgg_view('input/text', array( 'name' => 'name', 'class' => 'elgg-autofocus', 'placeholder'=>elgg_echo('realname'), )); ?> </div> <div> <?php echo elgg_view('input/plaintext', array( 'name' => 'description', 'class' => 'elgg-autofocus h100', 'placeholder'=>elgg_echo('apply-desc'), )); ?> </div> <div class="elgg-foot"> <?php echo elgg_view('input/submit', array('value' => elgg_echo('apply'),'class'=>'elgg-button-index')); ?> </div> <file_sep>/qq_theme/pages/settings/account.php <?php /** * Elgg user account settings. * * @package Elgg * @subpackage Core */ // Only logged in users gatekeeper(); // Make sure we don't open a security hole ... if ((!elgg_get_page_owner_entity()) || (!elgg_get_page_owner_entity()->canEdit())) { elgg_set_page_owner_guid(elgg_get_logged_in_user_guid()); } $title = elgg_echo('usersettings:user'); $content = elgg_view('core/settings/account'); $params = array( 'content' => $content, 'title' => $title, ); $body = elgg_view_layout('qq_two_column', $params); echo elgg_view_page($title, $body); <file_sep>/qq_theme/pages/friends/index.php <?php /** * Elgg friends page * * @package Elgg.Core * @subpackage Social.Friends */ $owner = elgg_get_page_owner_entity(); if (!$owner) { // unknown user so send away (@todo some sort of 404 error) forward('activity'); } $title = elgg_echo("friends:owned", array($owner->name)); $options = array( 'relationship' => 'friend', 'relationship_guid' => $owner->getGUID(), 'inverse_relationship' => FALSE, 'type' => 'user', 'full_view' => FALSE, 'item_class'=>'elgg-col-1of5 fl', ); $content = elgg_list_entities_from_relationship($options); if (!$content) { $content = elgg_echo('friends:none'); } $params = array( 'content' => $content, 'title' => $title, ); $body = elgg_view_layout('qq_two_column', $params); echo elgg_view_page($title, $body); <file_sep>/questions/languages/zh.php <?php $mapping = array( 'questions:menu' => '问题', 'questions:everyone'=>'所有问题', 'questions:add'=>'提出问题', 'question:save'=>'保存', 'question:edit'=>'编辑问题', 'question:question'=>'提出问题', 'question:follow'=>'关注问题', 'question:unfollow'=>'取消关注', 'question:follownum'=>'已有<b> %s</b> 人关注', 'question:widget:activities'=>'最新信息', 'question:widget:friends'=>'我的关注', 'question:widget:friendsof'=>'我的粉丝', 'question:widget:ask'=>'我的问题', 'question:widget:answer'=>'所答问题', //header menu 'menu:logout'=>"退出", 'menu:profile'=>"个人页面", 'menu:setting'=>"设置", 'menu:account'=>"账户", 'menu:ask'=>"提出问题", //form 'question:form:title'=>'问题:', 'question:form:title:tips'=>'至少6个字以上', 'question:form:description'=>'详细描述:', 'question:form:tags'=>'标签:(英文逗号隔开)', 'question:form:proccess'=>'研究阶段:', 'question:process:review'=>'选题', 'question:process:method'=>'研究方法', 'question:process:design'=>'研究设计', 'question:process:experiment'=>'实验', 'question:process:analysic'=>'数据分析', 'question:process:conclusion'=>'结论', 'question:form:level'=>'问题类别:', 'question:level:what'=>'What', 'question:level:how'=>'How', 'question:level:why'=>'Why', 'question:form:cat'=>'所属领域:', 'question:cat:nature'=>'自然科学', 'question:cat:human'=>'人文科学', 'question:cat:sociaty'=>'社会科学', //reference 'question:reference'=>'提供线索:', 'reference:add'=>'添加', 'references:address'=>'链接', 'reference:posted'=>'添加成功,感谢您的帮助!', 'question:order:time'=>'按时间', 'question:order:vote'=>'按投票', //question all page 'question:list:unlimited'=>'不限', 'question:all:newest'=>'最新的', 'question:all:hottest'=>'最热的', 'question:all:recommended'=>'推荐的', //river message 'river:create:object:default'=>'%s 问: %s?', 'river:reference:object:default'=>'%s 为问题:%s ?添加参考资料:', 'river:follow:object:default'=>' %s 关注了问题: %s ?', 'river-tab:all'=>'所有动态', 'river-tab:question'=>'问题动态', 'river-tab:follow'=>'关注动态', 'river:forward:object:default'=>'%s转发帮问:%s ?', //system message 'questions:saved'=>'问题保存成功!', 'question:notfound'=>'没有找到问题', 'thumbs:already'=>'已经投票过', 'thumbs:notfound'=>'投票对象不存在', 'thumbs:failure'=>'投票保存不成功', 'thumbsup:success'=>'赞成投票成功', 'thumbsdown:success'=>'反对投票成功', //error messgae 'questions:error:no_save'=>'问题保存失败!', 'questions:error:no_title'=>'请输入题目', 'questions:saved'=>'提问成功!', ); add_translation('zh', $mapping); <file_sep>/qq_theme/pages/contact.php <?php $title=elgg_echo('help:contact'); $site_url=elgg_get_site_url(); $content=<<<HTML <div class="pal"> Contact: <a href="mailto:<EMAIL>"><EMAIL></a> </div> HTML; $body=elgg_view_layout('ib_help',array('help_content'=>$content)); echo elgg_view_page($title,$body); ?><file_sep>/questions/views/default/annotation/reference.php <?php /** * Elgg generic comment view * * @uses $vars['annotation'] ElggAnnotation object * @uses $vars['full_view'] Display fill view or brief view */ if (!isset($vars['annotation'])) { return true; } $reference = $vars['annotation']; $entity = get_entity($reference->entity_guid); $reference_owner = get_user($reference->owner_guid); if (!$entity || !$reference_owner) { return true; } $reference_owner_icon = elgg_view_entity_icon($reference_owner, 'tiny'); //Add a menu to the annotation $menu = elgg_view_menu('annotation', array( 'annotation' => $reference, 'sort_by' => 'priority', 'class' => 'elgg-menu-hz float-alt', )); $reference_text = $reference->value; $body = <<<HTML <div class="mbn"> $menu $reference_text </div> HTML; echo elgg_view_image_block($reference_owner_icon, $body); <file_sep>/qq_theme/views/default/page/elements/header.php <?php /** * Elgg page header * In the default theme, the header lives between the topbar and main content area. */ // link back to main site. echo elgg_view('page/elements/header_logo', $vars); if(!elgg_is_logged_in()){ echo elgg_view('output/url',array('href'=>'/','text'=>elgg_view_icon('user').elgg_echo('login'),'class'=>'fr mtm mrs','style'=>'color:white')); }else{ $user=elgg_get_logged_in_user_entity(); //header left menu $htabs=array( 'home' => array( 'text' => elgg_echo('menu:index'), 'href' => 'activity', 'title'=>elgg_echo('menu:index'), 'priority' => 200, ), 'all' => array( 'text' => elgg_echo('menu:all'), 'href' => 'questions/all', 'title'=>elgg_echo('menu:all'), 'priority' => 300, ), 'ask' => array( 'text' => elgg_echo('sitename'), 'href' => 'questions/add/'.elgg_get_logged_in_user_guid(), 'title'=>elgg_echo('sitename'), 'priority' => 400, ), ); foreach ($htabs as $name => $htab) { $htab['name'] = $name; elgg_register_menu_item('htabs', $htab); } $menu=elgg_view_menu('htabs',array('sort_by' => 'priority', 'class' => 'elgg-menu-hz')); echo $menu; $mail=elgg_view('output/url',array('text' =>elgg_echo('messages:message'), 'style'=>"padding:10px 5px;", 'id'=>'inbox', 'href' => '#inbox_link', 'rel' => 'popup', )); $num_messages = (int)messages_count_unread(); if ($num_messages != 0) { $mail .= "<li id=\"header-messages-new\">$num_messages</li>"; } $logout=elgg_view('output/url',array( 'text' =>elgg_view_icon('delete').elgg_echo('menu:logout'), 'href' => '/action/logout', 'is_action' => TRUE,)); $settting=elgg_view('output/url',array( 'text' =>elgg_view_icon('settings').elgg_echo('menu:setting'), 'href' => '/settings/user/'.$user->username, )); $profile=elgg_view('output/url',array( 'text' =>elgg_view_icon('user').elgg_echo('menu:profile'), 'href' => '/profile/'.$user->username, )); $friends=elgg_view('output/url',array( 'text' =>elgg_view_icon('users').elgg_echo('menu:friendsof'), 'href' => '/friendsof/'.$user->username, )); $user_icon = elgg_view('output/img', array( 'src' => $user->getIconURL('tiny'), 'width' =>25, 'height' =>25, )); $account=elgg_view('output/url',array( 'text' =>$user_icon, 'href' => 'javascript:void(0)', 'style'=>"padding:8px 5px 0;", )); $mail_all=elgg_view('output/url',array('href'=>'messages/inbox/'.$user->username,'text' =>elgg_echo('item:object:messages'))); $mail_content=<<<html <div id="inbox-content" class="pbs"></div> $mail_all html; $mail_box=elgg_view_module('dropdown', elgg_echo('messages:new'), $mail_content,array('id'=>'inbox_link','class' => 'hidden w400')); $js=<<<js <script type="text/javascript"> $(document).ready(function(){ $('#menus > li').each(function(){ $(this).hover( function(){ $(this).find('ul:eq(0)').show(); }, function(){ $(this).find('ul:eq(0)').hide(); } ); }); $('#inbox').click(function(){ elgg.get('/questions/inbox', { data:{owner_guid:elgg.get_logged_in_user_guid()}, success: function(resultText, success, xhr) { $('#inbox-content').html(resultText); } }); }); }); </script> js; echo <<<html <span id='menubar' class="fr "> <ul id='menus' class="menus "> <li >$mail$mail_box</li> <li> $account <ul style="display:none"> <li class="children">$profile</li> <li class="children">$friends</li> <li class="children">$settting</li> <li class="children">$logout</li> </ul> </li> </ul> </span> $js html; } ?> <file_sep>/qq_theme/views/default/qq_theme/river_menu.php <?php $tabs=array( 'all' => array( 'text' => elgg_echo("river-tab:all"), 'href' => 'activity', 'priority' => 200, ), 'question' => array( 'text' => elgg_echo("river-tab:question"), 'href' => 'activity?fliter=question', 'priority' => 300, ), 'follow' => array( 'text' => elgg_echo("river-tab:follow"), 'href' => 'activity?fliter=follow', 'priority' => 400, ), ); foreach ($tabs as $name => $tab) { $tab['name'] = $name; elgg_register_menu_item('river_tabs', $tab); } echo elgg_view_menu('river_tabs',array('sort_by' => 'priority', 'class' => 'elgg-menu-hz river-tab')); <file_sep>/qq_theme/pages/notifications/index.php <?php /** * Elgg notifications plugin index * * @package ElggNotifications */ // Ensure only logged-in users can see this page gatekeeper(); elgg_set_page_owner_guid(elgg_get_logged_in_user_guid()); $user = elgg_get_page_owner_entity(); // Set the context to settings elgg_set_context('settings'); $title = elgg_echo('notifications:subscriptions:changesettings'); elgg_push_breadcrumb(elgg_echo('settings'), "settings/user/$user->username"); elgg_push_breadcrumb($title); // Get the form $people = array(); if ($people_ents = elgg_get_entities_from_relationship(array( 'relationship' => 'notify', 'relationship_guid' => elgg_get_logged_in_user_guid(), 'types' => 'user', 'limit' => 99999, ))) { foreach($people_ents as $ent) { $people[] = $ent->guid; } } $body = elgg_view('notifications/subscriptions/form', array('people' => $people)); $params = array( 'content' => $body, 'title' => $title, ); $body = elgg_view_layout('qq_two_column', $params); echo elgg_view_page($title, $body); <file_sep>/questions/pages/questions/all-backup.php <?php /** * All questions * */ if (!elgg_is_logged_in()){ forward(''); } elgg_register_title_button(); $offset = (int)get_input('offset', 0); $selected_tab = get_input('filter','recommend'); switch ($selected_tab) { case 'hottest': $content = elgg_list_entities_from_relationship_count(array( 'type' => 'object', 'subtype' => 'question-top', 'relationship'=>'follow', 'limit' => 6, 'offset' => $offset, 'full_view' => false, 'pagination' => true, 'list_class'=>'question-list brs', 'item_class'=>'question-item bx', 'view_toggle_type' => false )); if (!$content) { $content = elgg_echo('questions:none'); } break; case 'recommend': $content = elgg_list_entities_from_annotation_calculation(array( 'type' => 'object', 'subtype' => 'question-top', 'limit' => 6, 'annotation_names' =>'thumbs', 'offset' => $offset, 'pagination' => true, 'full_view' => false, 'list_class'=>'question-list brs', 'item_class'=>'question-item bx', 'view_toggle_type' => false )); if (!$content) { $content = elgg_echo('questions:none'); } break; case 'newest': default: $content = elgg_list_entities(array( 'type' => 'object', 'subtype' => array('question','question-top'), 'limit' => 6, 'offset' => $offset, 'full_view' => false, 'pagination' => true, 'list_class'=>'question-list brs', 'item_class'=>'question-item bx', 'view_toggle_type' => false )); if (!$content) { $content = elgg_echo('questions:none'); } break; } $fliter = elgg_view('questions/fliter_menu', array('selected' => $selected_tab)); $title = elgg_echo('questions:everyone'); $body = elgg_view_layout('one_column', array( 'fliter'=>$fliter, 'content' => $content, 'title' => $title, 'nav'=>'', )); echo elgg_view_page($title, $body);<file_sep>/README.md # miifang A social network for questioning the question The idea is to answering the question by questioning the asker. Base on Elgg 1.8 , qq_theme and questions and two plugins for elgg, put it under folder "mod". Elgg is an open source social network engine. # MIT LICENSE <file_sep>/qq_theme/views/default/css/elements/reset.php <?php /** * CSS reset * * @package Elgg.Core * @subpackage UI */ ?> /* *************************************** RESET CSS *************************************** */ body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p, blockquote,th,td {margin:0;padding:0;} table {border-collapse:collapse;border-spacing:0;} fieldset,img {border:0} address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal} ol,ul {list-style:none} caption,th {text-align:left} h1,h2,h3,h4,h5,h6 {font-size:100%;font-weight:normal;font-family:century Arial Aladin; line-height: 1.5;} q:before,q:after {content:''} abbr,acronym { border:0} <?php // force vertical scroll bar ?> html, body { height: 100%; margin-bottom: 1px; } img { border-width:0; border-color:transparent; } :focus { outline: 0 none; } ol, ul { list-style: none; } em, i { font-style:italic; } ins { text-decoration:none; } del { text-decoration:line-through; } strong, b { font-weight:bold; } table { border-collapse: collapse; border-spacing: 0; } caption, th, td { text-align: left; font-weight: normal; vertical-align: top; } blockquote:before, blockquote:after, q:before, q:after { content: ""; } blockquote, q { quotes: "" ""; } a { text-decoration: none; } <file_sep>/qq_theme/views/default/page/elements/topbar.php <?php /** * Elgg topbar * The standard elgg top toolbar */ // Elgg logo echo elgg_view_menu('topbar', array('sort_by' => 'priority', array('elgg-menu-hz'))); // elgg tools menu // need to echo this empty view for backward compatibility. $content = elgg_view("navigation/topbar_tools"); if ($content) { elgg_deprecated_notice('navigation/topbar_tools was deprecated. Extend the topbar menus or the page/elements/topbar view directly', 1.8); //echo $content; } <file_sep>/questions/views/default/object/question-top.php <?php /** * View for question object * * @uses $vars['entity'] The question object * @uses $vars['full_view'] Whether to display the full view * */ $full = elgg_extract('full_view', $vars, FALSE); $question = elgg_extract('entity', $vars, FALSE); if (!$question) { return TRUE; } // links for thumbup and down action $t_img=elgg_get_site_url().'mod/questions/graphics'; $t_up=elgg_view('output/img',array('src'=>$t_img.'/thumbup.png','title'=>'thumbs-up')); $t_down=elgg_view('output/img',array('src'=>$t_img.'/thumbdown.png','title'=>'thumbs-down')); $t_up_link=elgg_view('output/confirmlink',array( 'href'=>"action/questions/thumbs?guid={$question->guid}&action_type=up", 'text'=>$t_up, 'is_action'=>true, )); $t_down_link=elgg_view('output/confirmlink',array( 'href'=>"action/questions/thumbs?guid={$question->guid}&action_type=down", 'text'=>$t_down, 'is_action'=>true, )); //count the thumbs up and down amount $t_sum=$question->getAnnotationsSum('thumbs'); if(!$t_sum){ $t_sum=0; } $thumb=<<<html <div class="thumbs mrs"> $t_up_link $t_sum $t_down_link </div> html; $description = $question->description; $title=$question->title; $title_link=elgg_view('output/url',array('href'=>$question->getURL(),'text'=>$title)); $metadata = elgg_view_menu('entity', array( 'entity' => $question, 'handler' => 'questions', 'sort_by' => 'priority', 'class' => 'elgg-menu-hz', )); $owner = $question->getOwnerEntity(); $owner_name=elgg_view('output/url',array('href'=>$owner->geturl(),'text'=>$owner->name)); //$owner_name=$owner->name; $owner_icon = elgg_view_entity_icon($owner, 'small'); $ownerdecs=elgg_get_excerpt($owner->briefdescription); $q_block=elgg_view_image_block($owner_icon, $title_link. $description); $guid=$question->guid; $follow=elgg_view('output/url',array( 'href'=>elgg_get_site_url().'action/questions/follow?action_type=follow&question_guid='.$guid, 'text'=>elgg_echo('question:follow'), 'class'=>'elgg-button-submit brs pas', 'is_action' => true )); if (check_entity_relationship($uid, 'follow', $guid)){ $follow=elgg_view('output/url',array( 'href'=>elgg_get_site_url().'action/questions/follow?action_type=unfollow&question_guid='.$guid, 'text'=>elgg_echo('question:unfollow'), 'class'=>'elgg-button-submit brs pas', 'is_action' => true )); } $follow_num=elgg_get_entities_from_relationship(array('relationship'=>'follow','relationship_guid'=>$guid,'count'=>true,'inverse_relationship'=>true)); $follow_num=elgg_echo('question:follownum',array($follow_num)); if ($full&& !elgg_in_context('gallery')) { echo <<<html $thumb <h2>$title ?</h2> <div class="pas"> $description </div> html; }elseif (elgg_in_context('gallery')) { echo <<<html $thumb <h4> $title_link ? </h4> <div class="pas mtm"> $follow $follow_num </div> html; }else{ echo <<<html <div class="fr mas">$owner_icon</div> <div class="pas mbs"> $thumb <span> $owner_name , $ownerdecs </span> <h3> $title_link ?</h3> $description </div> html; } <file_sep>/questions/actions/questions/save.php <?php $title = strip_tags(get_input('title')); $description = get_input('description'); $tags = get_input('tags'); $proccess = get_input('proccess'); $level = get_input('level'); $cat = get_input('catagory'); $parent_guid = get_input('parent_guid'); if(!$parent_guid){ $parent_guid=elgg_get_logged_in_user_guid(); } $question_guid = (int)get_input('question_guid'); $container=get_entity($parent_guid); elgg_make_sticky_form('question'); if (!$title) { register_error(elgg_echo('questions:error:no_title')); forward(REFERER); } if ($question_guid) { $question = get_entity($question_guid); if (!elgg_instanceof($question,'object') || !$question->canEdit()) { register_error(elgg_echo('questions:error:no_save')); forward(REFERER); } $new_page = false; } else { $question = new ElggObject(); if(!elgg_instanceof($container, 'user')){ $question->subtype = 'question'; }else{ $question->subtype = 'question-top'; } $question->access_id = 1; $question->parent_guid=$parent_guid; $new_page = true; } $question->title = $title; $question->description = $description; $tagarray = string_to_tag_array($tags); $question->tags = $tagarray; $question->proccess = $proccess; $question->level = $level; $question->catagory = $cat; // need to add check to make sure user can write to container if ($question->save()) { elgg_clear_sticky_form('question'); system_message(elgg_echo('questions:saved')); if ($new_page) { create_annotation($question->getGUID(), 'thumbs', 0,integer, 0, 2); add_to_river('river/object/question/create', 'create', elgg_get_logged_in_user_guid(), $question->getGUID(),1,0,0); } forward($question->getURL()); } else { register_error(elgg_echo('questions:error:no_save')); forward(REFERER); } ?><file_sep>/qq_theme/views/default/search/header.php <?php /** * Search box in page header */ if(elgg_is_logged_in()){ echo elgg_view('search/search_box', array('class' => 'elgg-search-header')); }<file_sep>/questions/actions/questions/thumbs.php <?php /** * Question thumb up and down action * */ $entity_guid = (int) get_input('guid'); $action=get_input('action_type'); //check to see if the user has already thumbs up or down the questions if (elgg_annotation_exists($entity_guid, 'thumbs')){ system_message(elgg_echo("thumbs:already")); forward(REFERER); } // Let's see if we can get an entity with the specified GUID $entity = get_entity($entity_guid); if (!$entity) { register_error(elgg_echo("thumbs:notfound")); forward(REFERER); } if($action=="up"||$action=="down"){ $user = elgg_get_logged_in_user_entity(); if($action=="up"){ $annotation = create_annotation($entity->guid, 'thumbs', "1", "", $user->guid, 2); $thumbup=true; }else{ $annotation = create_annotation($entity->guid, 'thumbs', "-1", "", $user->guid, 2); } } // tell user annotation didn't work if that is the case if (!$annotation) { register_error(elgg_echo("thumbs:failure")); forward(REFERER); } if($thumbup){ system_message(elgg_echo("thumbsup:success")); }else{ system_message(elgg_echo("thumbsdown:success")); } forward(REFERER); <file_sep>/questions/views/default/river/relationship/forward.php <?php $object = $vars['item']->getObjectEntity(); $id = $vars['item']->annotation_id; $message=elgg_list_river(array('id'=>$id,'list_class'=>'forward-list')); echo elgg_view('river/elements/layout', array( 'item' => $vars['item'], 'message' => $message, )); <file_sep>/qq_theme/views/default/page/elements/footer.php <?php /** * footer * The standard HTML footer that displays across the site * * @package Elgg * @subpackage Core * */ ?> <div class="wrapper clearfloat "> <ul class="elgg-menu-hz"> <li> <?php echo elgg_view('output/url', array( 'href' => elgg_get_site_url().'about', 'text' =>elgg_echo('about'), 'is_trusted' => true, )); ?></li> <li> <?php echo elgg_view('output/url', array( 'href' => elgg_get_site_url().'contact', 'text' => elgg_echo('contact'), 'is_trusted' => true, )); ?></li> <li> <?php echo elgg_view('output/url', array( 'href' => elgg_get_site_url().'help', 'text' => elgg_echo('help'), 'is_trusted' => true, )); ?></li> <div style="float:right;margin-right:5%;color:#ccc"> &#169;2012 <?php echo elgg_echo('sitename')?> </div> </ul> </div> <?php echo elgg_view_menu('footer', array('sort_by' => 'priority', 'class' => 'elgg-menu-hz mbm')); ?><file_sep>/qq_theme/actions/forward.php <?php $item_id=get_input('item_id'); $user_id=get_input('user_id'); $items=elgg_get_river(array('id'=>$item_id)); $item=$items[0]; $object = $item->getObjectEntity(); $object_owner=$object->owner_guid; if($user_id==$object_owner){ register_error(elgg_echo('could not forward your own questions')); forward(REFERER); } $question_guid=$object->getGUID(); if (!elgg_instanceof($object,'object')) { register_error(elgg_echo('not question')); forward(REFERER); } add_entity_relationship($user_id, 'forward', $question_guid); add_to_river('river/relationship/forward', 'forward', $user_id, $question_guid,'',0,$item_id); forward(REFERER); <file_sep>/qq_theme/views/default/page/layouts/ib_help.php <?php /** * main help center layout * @uses $vars['ib_content'] HTML of main content area */ $nav = elgg_extract('nav', $vars, elgg_view('navigation/breadcrumbs')); if (isset($vars['title'])) { $title=elgg_view_title($vars['title']); $title="<div class=\"elgg-divide-bottom\">$title</div>"; } if (isset($vars['help_content'])) { $ibcontent=$vars['help_content']; } echo "<div class=\"mtl\"><ul class=\"help-sidebar\">"; $menus=array('about','help','jobs','service','privacy','feedback','contact'); foreach ($menus as $menu){ $menu_link=elgg_view('output/url',array( 'href'=>elgg_get_site_url().$menu, 'text'=>elgg_echo('help:'.$menu), 'is_trusted' => true, )); echo "<li>$menu_link</li><hr class=\"separator\">"; } echo <<<HTML </ul> <div class="help-content mbl"> $nav $title $ibcontent </div> </div> HTML; <file_sep>/qq_theme/views/default/page/layouts/qq_two_column.php <?php /** * Layout for main column with one sidebar * * @package Elgg * @subpackage Core * * @uses $vars['content'] Content HTML for the main column * @uses $vars['sidebar'] Optional content that is displayed in the sidebar * @uses $vars['class'] Additional class to apply to layout * @uses $vars['nav'] HTML of the page nav (override) (default: breadcrumbs) */ $class = 'elgg-layout clearfix brs pas mbl'; if (isset($vars['class'])) { $class = "$class {$vars['class']}"; } // navigation defaults to breadcrumbs $nav = elgg_extract('nav', $vars, elgg_view('navigation/breadcrumbs')); $user=elgg_get_logged_in_user_entity(); $user_icon=elgg_view_entity_icon($user,'medium'); $user_name=elgg_view('output/url',array('href'=>$user->getURL(),'text'=>$user->name)); $follow_num=elgg_get_entities_from_relationship(array( 'relationship' => 'friend', 'relationship_guid' => $user->getGUID(), 'inverse_relationship' => FALSE, 'type' => 'user', 'count'=>true, )); if(!$follow_num){ $follow_num=0; } $follower_num=elgg_get_entities_from_relationship(array( 'relationship' => 'friend', 'relationship_guid' => $user->getGUID(), 'inverse_relationship' => true, 'type' => 'user', 'count'=>true, )); if(!$follow_num){ $follow_num=0; } $follow_link=elgg_view('output/url',array( 'text' => '<h3>'.$follow_num.'</h3><span>'.elgg_echo('menu:friends').'</span>', 'href' => 'friends/'.$user->username)); $follower_link=elgg_view('output/url',array( 'text' => '<h3>'.$follower_num.'</h3><span>'.elgg_echo('menu:friendsof').'</span>', 'href' => 'friendsof/'.$user->username)); ?> <div class="container <?php echo $class; ?>" style="background:whitesmoke"> <div class="elgg-col-1of6 fl "> <div class="pas center mtm elgg-divide-bottom"> <?php echo $user_icon ?> <h2><?php echo $user_name ?></h2> <span class="inblock pbs"> <?php echo $follow_link?> </span> <span class="inblock pbs"> <?php echo $follower_link?> </span> </div> <?php $sidebar_tabs=array( 'home' => array( 'text' => elgg_view_icon('refresh').elgg_echo('menu:activity'), 'href' => 'activity', 'priority' => 200, ), 'all' => array( 'text' => elgg_view_icon('search').elgg_echo('sidebar:menu:all'), 'href' => 'questions/all', 'priority' => 300, ), 'ask' => array( 'text' => elgg_view_icon('speech-bubble ').elgg_echo('menu:ask'), 'href' => 'questions/add/'.elgg_get_logged_in_user_guid(), 'priority' => 400, ), ); foreach ($sidebar_tabs as $name => $sidebar_tab) { $sidebar_tab['name'] = $name; elgg_register_menu_item('sidebar_tabs', $sidebar_tab); } $menu1=elgg_view_menu('sidebar_tabs',array('sort_by' => 'priority', 'class' => 'elgg-menu-hz sidebar-menu center')); echo $menu1; echo "<div class=\" elgg-divide-bottom\"></div>"; $sidebar_tab2s=array( 'question' => array( 'text' => elgg_echo('question:widget:ask'), 'href' => 'questions/mine', 'priority' => 200, ), 'answer' => array( 'text' => elgg_echo('question:widget:answer'), 'href' => 'questions/answer', 'priority' => 300, ), 'notification' => array( 'text' => elgg_echo('notifications:subscriptions:changesettings'), 'href' => 'notifications/personal', 'priority' => 400, ), 'settings' => array( 'text' => elgg_echo('menu:account'), 'href' =>'settings/user/'.$user->username, 'priority' => 500, ), 'profile' => array( 'text' => elgg_echo('profile:edit'), 'href' =>'profile/'.$user->username.'/edit', 'priority' => 600, ), ); foreach ($sidebar_tab2s as $name => $sidebar_tab2) { $sidebar_tab2['name'] = $name; elgg_register_menu_item('sidebar_tab2s', $sidebar_tab2); } $menu2=elgg_view_menu('sidebar_tab2s',array('sort_by' => 'priority', 'class' => 'elgg-menu-hz sidebar-menu center')); echo $menu2; echo "<div class=\" elgg-divide-bottom\"></div>"; ?> <?php if (isset($vars['sidebar'])) { echo $vars['sidebar']; }?> </div> <div class="elgg-col-5of6 fl" style="background:white;"> <div class="elgg-main"> <?php echo $nav; if (isset($vars['title'])) { echo elgg_view_title($vars['title']); } if (isset($vars['content'])) { echo $vars['content']; } ?> </div> </div> </div> <file_sep>/qq_theme/views/default/river/elements/responses.php <?php /** * River item footer (you can change river comment style here) * * @uses $vars['item'] ElggRiverItem * @uses $vars['responses'] Alternate override for this item */ // allow river views to override the response content $responses = elgg_extract('responses', $vars, false); if ($responses) { echo $responses; return true; } $item = $vars['item']; $object = $item->getObjectEntity(); if ($item->annotation_id != 0 || !$object||$item->action_type=='follow') { return true; } if(elgg_instanceof($object, 'object','question')||elgg_instanceof($object, 'object','question-top')){ $guid=$object->getGUID(); $subquestions = elgg_get_entities(array( 'type' => 'object', 'subtype' => 'question', 'metadata_name'=>'parent_guid', 'metadata_value'=>$guid, )); if ($subquestions) { ?> <span class="elgg-river-comments-tab"><?php echo elgg_echo('question:question'); ?></span> <?php $questions_list=elgg_list_entities_from_metadata(array( 'type' => 'object', 'subtype' => 'question', 'metadata_name'=>'parent_guid', 'metadata_value'=>$guid, 'limit'=>3, 'pagination'=>false, 'full_view' => false, 'list_class'=>'question-list brs ', 'item_class'=>'question-item bx elgg-river-comments', 'view_toggle_type' => false )); echo $questions_list; } } $container=get_entity($guid); $proccess=$container->proccess; $level=$container->level; $cat=$container->catagory; // question the question form $form_vars = array('id' => "question-{$guid}", 'class' => 'hidden elgg-form-small elgg-river-responses'); echo elgg_view_form('questions/save', $form_vars, array('parent_guid'=>$guid,'proccess'=>$proccess,'catagory'=>$cat,'level'=>$level,'inline'=>true)); ?> <script type="text/javascript"> $(document).ready(function(){ $('#forward-').click(function(){ elgg.action('forward', { data:{item_id:<?php echo $item->id; ?>, user_id:elgg.get_logged_in_user_guid() }, success: function(json) { elgg.system_message("Forward Success!"); }, }); }); }) </script> <file_sep>/questions/views/default/widgets/question/content.php <?php /** * Elgg question widget view * * @package Elggquestion */ $num = $vars['entity']->num_display; $options = array( 'type' => 'object', 'subtype' => 'question', 'container_guid' => $vars['entity']->owner_guid, 'limit' => $num, 'full_view' => FALSE, 'pagination' => FALSE, 'list_type'=>'gallery', 'list_class'=>'question-list', 'item_class'=>'w pbm mbs elgg-divide-bottom', ); $content = elgg_list_entities($options); echo $content; if ($content) { $url = "questions/answer/" . elgg_get_page_owner_entity()->username; $more_link = elgg_view('output/url', array( 'href' => $url, 'text' => elgg_echo('question:more'), 'is_trusted' => true, )); echo "<span class=\"elgg-widget-more\">$more_link</span>"; } else { echo elgg_echo('question:none'); } <file_sep>/qq_theme/views/default/search/layout.php <?php /** * The default search layout(change the layout to ib_two_column) * * @uses $vars['body'] */ $layout=elgg_view_layout('one_sidebar', array('content' => $vars['body'])); if (array_key_exists('type', $vars['params']) && array_key_exists('subtype', $vars['params'])) { if($vars['params']['type']=='object'&&$vars['params']['subtype']=='projects'){ $layout=elgg_view_layout('one_column', array('content' => $vars['body'])); } } echo $layout;<file_sep>/questions/actions/references/delete.php <?php // Ensure we're logged in if (!elgg_is_logged_in()) { forward(); } // Make sure we can get the comment in question $annotation_id = (int) get_input('annotation_id'); if ($reference = elgg_get_annotation_from_id($annotation_id)) { $entity = get_entity($reference->entity_guid); if ($reference->canEdit()) { $reference->delete(); system_message(elgg_echo("reference:deleted")); forward($entity->getURL()); } } else { $url = ""; } register_error(elgg_echo("reference:notdeleted")); forward(REFERER);<file_sep>/qq_theme/actions/apply.php <?php $email = get_input('email'); $name = get_input('name'); $desc = get_input('description'); $body=<<<html $email<br> $desc html; elgg_make_sticky_form('apply'); if (!$email || !$name || !$desc) { register_error(elgg_echo("apply:required")); forward(REFERER); } if(!is_email_address($email)){ register_error(elgg_echo("apply:email:failed")); forward(REFERER); } $subject=elgg_echo('apply').'-'.$name.'-'.$email; $admins=elgg_get_admins(); foreach ($admins as $admin){ $admin_guids[].=$admin->guid; } $recipient_guid = $admin_guids[ mt_rand(0, count($admin_guids) - 1) ]; $result=messages_send($subject, $body, $recipient_guid, 1); if($result){ elgg_clear_sticky_form('apply'); system_message(elgg_echo("apply:success")); }else{ register_error(elgg_echo("apply:failed")); forward(REFERER); }<file_sep>/questions/pages/questions/edit.php <?php /** * edit question page * */ gatekeeper(); $question_guid = get_input('guid'); $question = get_entity($question_guid); if (!elgg_instanceof($question, 'object') || !$question->canEdit()) { register_error(elgg_echo('questions:unknown question')); forward(REFERRER); } $title = elgg_echo('question:edit'); elgg_push_breadcrumb($title); $vars = questions_prepare_form_vars($question); $content = elgg_view_form('questions/save', array(), $vars); $body = elgg_view_layout('one_column', array( 'filter' => '', 'content' => $content, 'title' => $title, )); echo elgg_view_page($title, $body);<file_sep>/questions/views/default/output/qtags.php <?php /** * Elgg tags * Tags can be a single string (for one tag) or an array of strings * * @uses $vars['value'] Array of tags or a string * @uses $vars['type'] The entity type, optional * @uses $vars['subtype'] The entity subtype, optional * @uses $vars['entity'] Optional. Entity whose tags are being displayed (metadata ->tags) * @uses $vars['list_class'] Optional. Additional classes to be passed to <ul> element * @uses $vars['item_class'] Optional. Additional classes to be passed to <li> elements * @uses $vars['icon_class'] Optional. Additional classes to be passed to tags icon image */ if (isset($vars['entity'])) { $vars['tags'] = $vars['entity']->tags; unset($vars['entity']); } if (!empty($vars['subtype'])) { $subtype = "&subtype=" . urlencode($vars['subtype']); } else { $subtype = ""; } if (!empty($vars['object'])) { $object = "&object=" . urlencode($vars['object']); } else { $object = ""; } if (empty($vars['tags']) && !empty($vars['value'])) { $vars['tags'] = $vars['value']; } if (empty($vars['tags']) && isset($vars['entity'])) { $vars['tags'] = $vars['entity']->tags; } if (!empty($vars['tags'])) { if (!is_array($vars['tags'])) { $vars['tags'] = array($vars['tags']); } $list_class = "elgg-qtags"; if (isset($vars['list_class'])) { $list_class = "$list_class {$vars['list_class']}"; } $item_class = "elgg-tag"; if (isset($vars['item_class'])) { $item_class = "$item_class {$vars['item_class']}"; } $icon_class = elgg_extract('icon_class', $vars); foreach($vars['tags'] as $tag) { if (!empty($vars['type'])) { $type = "&type={$vars['type']}"; } else { $type = ""; } $url = elgg_get_site_url() . 'search?q=' . urlencode($tag) . "&search_type=tags{$type}{$subtype}{$object}"; if (is_string($tag)) { $list_items .= "<li class=\"$item_class\">"; $list_items .= elgg_view('output/url', array('href' => $url, 'text' => $tag, 'rel' => 'tag')); $list_items .= '</li>'; } } $list = <<<___HTML <div class="clearfix"> <ul class="$list_class"> $list_items </ul> </div> ___HTML; echo $list; } <file_sep>/qq_theme/views/default/page/elements/head.php <?php /** * The standard HTML head * * @uses $vars['title'] The page title */ // Set title if (empty($vars['title'])) { $title = elgg_get_config('sitename'); } else { $title = elgg_get_config('sitename') . ": " . $vars['title']; } $js = elgg_get_loaded_js('head'); $css = elgg_get_loaded_css(); $version = get_version(); $release = get_version(true); ?> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="ElggRelease" content="<?php echo $release; ?>" /> <meta name="ElggVersion" content="<?php echo $version; ?>" /> <title><?php echo $title; ?></title> <?php echo elgg_view('page/elements/shortcut_icon', $vars); ?> <?php foreach ($css as $link) { ?> <link rel="stylesheet" href="<?php echo $link; ?>" type="text/css" /> <?php } ?> <?php $ie_url = elgg_get_simplecache_url('css', 'ie'); $ie7_url = elgg_get_simplecache_url('css', 'ie7'); $ie6_url = elgg_get_simplecache_url('css', 'ie6'); ?> <!--[if gt IE 7]> <link rel="stylesheet" type="text/css" href="<?php echo $ie_url; ?>" /> <![endif]--> <!--[if IE 7]> <link rel="stylesheet" type="text/css" href="<?php echo $ie7_url; ?>" /> <![endif]--> <!--[if IE 6]> <link rel="stylesheet" type="text/css" href="<?php echo $ie6_url; ?>" /> <![endif]--> <?php foreach ($js as $script) { ?> <script type="text/javascript" src="<?php echo $script; ?>" ></script> <?php } ?> <script type="text/javascript" > <?php echo elgg_view('js/initialize_elgg'); ?> </script> <?php $metatags = elgg_view('metatags', $vars); if ($metatags) { elgg_deprecated_notice("The metatags view has been deprecated. Extend page/elements/head instead", 1.8); echo $metatags; }<file_sep>/questions/actions/references/add.php <?php /** * Elgg add references action * */ $title = strip_tags(get_input('title')); $address = get_input('address'); $container_guid = get_input('container_guid'); if ($address && !preg_match("#^((ht|f)tps?:)?//#i", $address)) { $address = "http://$address"; } // Let's see if we can get an entity with the specified GUID $entity = get_entity($container_guid); if (!$entity) { register_error(elgg_echo("question:notfound")); forward(REFERER); } $referene_link=elgg_view('output/url',array('href'=>$address,'is_trusted'=>true,'text'=>$title,'target'=>'blank')); $user = elgg_get_logged_in_user_entity(); $annotation = create_annotation($entity->guid, 'reference', $referene_link, "", $user->guid, $entity->access_id); // tell user annotation posted if (!$annotation) { register_error(elgg_echo("reference:failure")); forward(REFERER); } // notify if poster wasn't owner if ($entity->owner_guid != $user->guid) { notify_user($entity->owner_guid, $user->guid, elgg_echo('reference:subject'), elgg_echo('reference:body', array( $user->name, $entity->getURL(), $entity->title, $referene_link, )) ); } system_message(elgg_echo("reference:posted")); //add to river add_to_river('river/annotation/reference/create', 'reference', $user->guid, $entity->guid, "", 0, $annotation); // Forward to the page the action occurred on forward(REFERER); <file_sep>/questions/pages/questions/add.php <?php /** * add a new question * */ gatekeeper(); $container_guid = (int) get_input('guid'); $container = get_entity($container_guid); if (!$container) { } $title=elgg_echo("questions:add"); elgg_push_breadcrumb($title); $vars = questions_prepare_form_vars(); $content = elgg_view_form('questions/save', array('id'=>'question_form'), $vars); $body = elgg_view_layout('qq_two_column', array( 'content' => $content, 'title' => $title, )); echo elgg_view_page($title, $body); <file_sep>/questions/views/default/forms/questions/save.php <?php $title = elgg_extract('title', $vars, ''); $description = elgg_extract('description', $vars, ''); $tags = elgg_extract('tags', $vars, ''); $container_guid=elgg_extract('parent_guid', $vars, ''); $container=get_entity($container_guid); $proccess = elgg_extract('proccess', $vars, ''); $level = elgg_extract('level', $vars, ''); $catagory = elgg_extract('catagory', $vars, ''); $inline=elgg_extract('inline', $vars, false); $class='pas'; if (elgg_instanceof($container, 'object', 'question-top')||elgg_instanceof($container, 'object', 'question')){ $class='hidden'; } $names=array('title','description','tags','cat','proccess','level'); foreach ($names as $name){ $name_titles[].=elgg_echo("question:form:".$name); $name_tips[].=elgg_echo("question:form:".$name.":tips"); } $t_ipt=elgg_view("input/text", array('name' =>'title','value' =>$title,'title'=>$name_tips[0])); $d_ipt=elgg_view("input/longtext", array('name' =>'description','value' =>$description)); $tag_ipt=elgg_view("input/tags", array('name' =>'tags','value' =>$tags)); $cat_ipt=elgg_view("input/dropdown", array('name' =>'catagory','value' =>$catagory,'options_values'=>array( 'c_1'=>elgg_echo('question:cat:nature'), 'c_2'=>elgg_echo('question:cat:human'), 'c_3'=>elgg_echo('question:cat:sociaty'), ))); $p_ipt=elgg_view("input/dropdown", array('name' =>'proccess','value' =>$proccess,'options_values'=>array( 'p_1'=>elgg_echo('question:process:review'), 'p_2'=>elgg_echo('question:process:method'), 'p_3'=>elgg_echo('question:process:design'), 'p_4'=>elgg_echo('question:process:experiment'), 'p_5'=>elgg_echo('question:process:analysic'), 'p_6'=>elgg_echo('question:process:conclusion'), ))); $l_ipt=elgg_view("input/dropdown", array('name' =>'level','value' =>$level,'options_values'=>array( 'what'=>elgg_echo('question:level:what'), 'how'=>elgg_echo('question:level:how'), 'why'=>elgg_echo('question:level:why'), ))); $submit=elgg_view('input/submit', array('value' => elgg_echo('question:save'),'class'=>'btn w100')); // inline questions for river and reply $title_input=<<<html <div class="pas"> <h3 class="fl w50 black"> $name_titles[0] </h3> <span class="elgg-col-3of4 fl">$t_ipt</span><h1>?</h1> </div> html; $left_side=<<<html <div class="elgg-col-2of3 fl"> $title_input <div class="pam"> <h3 class="fl"> $name_titles[1] </h3> $d_ipt </div> </div> html; $right_side=<<<html <div class='elgg-col-1of3 fl '> <div class="pas"> <h3 >$name_titles[2] </h3> $tag_ipt </div> <div class=$class > <label>$name_titles[3] </label> $cat_ipt </div> <div class=$class > <label>$name_titles[4]</label> $p_ipt </div> <div class=$class > <label>$name_titles[5] </label> $l_ipt </div> $submit </div> html; if($inline){ $t_link=elgg_view("output/url", array('href'=>'#inline_question-'.$container_guid,'text'=>elgg_echo('question:question'), 'rel'=>'popup','class'=>'block pas btn center')); $inline_body=elgg_view_module('widget', '', $left_side.$right_side,array('id'=>'inline_question-'.$container_guid,'class'=>'hidden w600')); $body=$t_link.$inline_body; }else{ $body=$left_side.$right_side; } echo $body; ?> <div class="elgg-foot pas"> <?php if ($vars['guid']) { echo elgg_view('input/hidden', array( 'name' => 'question_guid', 'value' => $vars['guid'], )); } echo elgg_view('input/hidden', array( 'name' => 'parent_guid', 'value' => $container_guid, )); ?> </div> <file_sep>/qq_theme/pages/apply.php <?php $logo=elgg_view('output/img',array('src'=>elgg_get_site_url().'mod/qq_theme/graphics/logo.png','title'=>'Q&Q')); $logo=elgg_view('output/url',array('href'=>elgg_get_site_url(),'text'=>$logo)); $slogan=elgg_echo('slogan'); $apply=elgg_view_form('apply'); $body=<<<html <div id='index-top' class="pam"> <div class="fl mtm"> $logo <div id='slogan' class="pas"> $slogan </div> </div> <div class="fl w300 mal"> $apply </div> </div> html; echo elgg_view_page($title,$body,'index');<file_sep>/qq_theme/views/default/search/css.php <?php /** * Elgg Search css * */ ?> /********************************** Search plugin ***********************************/ .elgg-search-header { list-style: none; overflow: hidden; display: inline-block; float: right; padding-right: 5px; margin-top: 8px; position: relative; } .elgg-search input[type=text] { width: 230px; } .elgg-search input[type=submit] { display: none; } .elgg-search input[type=text] { -webkit-border-radius: 10px; -moz-border-radius: 10px; border-radius: 10px; border: 1px solid #ccc; color: #eee; font-size: 12px; font-weight: bold; padding: 4px 4px 2px 26px; background: transparent url(<?php echo elgg_get_site_url(); ?>_graphics/elgg_sprites.png) no-repeat 2px -934px; } .elgg-search input[type=text]:focus, .elgg-search input[type=text]:active { background-color: white; background-position: 2px -916px; border: 1px solid #0bf; color: #0054A7; } .search-list li { padding: 5px 0 0; } .search-heading-category { margin-top: 20px; color: #666666; } .search-highlight { background-color: #bbdaf7; } .search-highlight-color1 { background-color: #bbdaf7; } .search-highlight-color2 { background-color: #A0FFFF; } .search-highlight-color3 { background-color: #FDFFC3; } .search-highlight-color4 { background-color: #ccc; } .search-highlight-color5 { background-color: #4690d6; } <file_sep>/questions/views/default/questions/css.php <?php ?> .q-top { background: none repeat scroll 0% 0% white; border-radius: 10px 10px 10px 10px; box-shadow: 1px 1px 5px #CCCCCC; padding: 10px; overflow:hidden; } .q-list { background: none repeat scroll 0% 0% #FFFFFF; padding: 5px; } .thumbs{ float: left; text-align: center; width: 35px; } .grey{ background:rgba(0,0,0,0.1); } .bx{ -webkit-box-shadow:0 0 5px 2px rgba(0, 0, 0, 0.1); -moz-box-shadow: 0 0 5px 2px rgba(0, 0, 0, 0.1); box-shadow: 0 0 5px 2px rgba(0, 0, 0, 0.1); } /* tags*/ .elgg-qtags li{ background: #E1F0F7; padding: 2px 10px; -webkit-border-radius: 10px; -moz-border-radius: 10px; -o-border-radius: 10px; border-radius: 10px; text-decoration: none; margin: 0 5px 5px 0; float: left; } /* list css*/ .question-list{ overflow:hidden; padding:5px; border-top:0; } .question-list li{ border-bottom:0; } .question-item{ padding:5px; border-radius: 10px; margin-bottom:10px; } /*Tags form css*/ div.tags_com{ border:1px solid #dedede; position:static; width:90%; min-height:100px; float:left; margin:2px; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; } .tagsinput{ padding: 0; } input.tags{ border:0 none; width:188px; padding: 0 5px 5px; outline: medium none; color: #999999; background:white; } input[type=text]:focus,.wirte { border: 0; } .tags_com{ overflow:hidden; } .tags_list{ margin-left:0px; list-style:none outside none; padding:5px; } .tags_list li{ display:inline-table; border:1px solid #B7C963; background-color: #C7DA76; color:#666666; padding: 0 5px; margin:0 5px 5px 0; line-height:20px; } .tags_list li span{ padding: 2px; -moz-border-radius:2px 2px 2px 2px; } .tags_list a{ color:#003640; cursor:pointer; text-decoration:none; } .tags_list li a:link{ color:#003640; cursor:pointer; text-decoration:none; } .tags_list li a:visited{ color:#003640; cursor:pointer; text-decoration:none; } .tags_list li a:hover{ color:#FF0000; text-decoration:underline; } .tags_list li a:active{ color:#003640; text-decoration:none; } .selected{ background:#E1F0F7; padding: 1px 5px; -webkit-border-radius: 5px; -moz-border-radius: 5px; -o-border-radius: 5px; }<file_sep>/questions/views/default/forms/references/add.php <?php $title = elgg_extract('title', $vars, ''); $address = elgg_extract('address', $vars, ''); //transfer the question guid to the reference container_guid; $container_guid=elgg_extract('question_guid', $vars, ''); ?> <div> <label><?php echo elgg_echo('title'); ?></label><br /> <?php echo elgg_view('input/text', array('name' => 'title', 'value' => $title)); ?> </div> <div> <label><?php echo elgg_echo('references:address'); ?></label><br /> <?php echo elgg_view('input/text', array('name' => 'address', 'value' => $address)); ?> </div> <div class="elgg-foot"> <?php echo elgg_view('input/hidden', array('name' => 'container_guid', 'value' => $container_guid)); echo elgg_view('input/submit', array('value' => elgg_echo("save"))); ?> </div><file_sep>/questions/views/default/questions/fliter_menu.php <?php /** * All questions listing page navigation * */ $tabs = array( 'newest' => array( 'text' => elgg_echo('question:all:newest'), 'href' => 'questions/all?filter=newest', 'priority' => 400, ), 'hottest' => array( 'text' => elgg_echo('question:all:hottest'), 'href' => 'questions/all?filter=hottest', 'priority' => 300, ), 'recommend' => array( 'text' => elgg_echo('question:all:recommended'), 'href' => 'questions/all?filter=recommend', 'priority' => 200, ), ); // sets default selected item if (strpos(full_url(), 'filter') === false) { if(strpos(full_url(), 'category') === false){ $tabs['recommend']['selected'] = true; } } foreach ($tabs as $name => $tab) { $tab['name'] = $name; elgg_register_menu_item('filter', $tab); } echo elgg_view_menu('filter', array('sort_by' => 'priority', 'class' => 'elgg-menu-hz')); <file_sep>/qq_theme/pages/avatar/edit.php <?php /** * Upload and crop an avatar page */ // Only logged in users gatekeeper(); elgg_set_context('profile_edit'); $title = elgg_echo('avatar:edit'); $entity = elgg_get_page_owner_entity(); $content = elgg_view('core/avatar/upload', array('entity' => $entity)); // only offer the crop view if an avatar has been uploaded if (isset($entity->icontime)) { $content .= elgg_view('core/avatar/crop', array('entity' => $entity)); } $params = array( 'content' => $content, 'title' => $title, ); $body = elgg_view_layout('qq_two_column', $params); echo elgg_view_page($title, $body); <file_sep>/qq_theme/pages/profile/edit.php <?php /** * Edit profile page */ gatekeeper(); $user = elgg_get_page_owner_entity(); if (!$user) { register_error(elgg_echo("profile:notfound")); forward(); } // check if logged in user can edit this profile if (!$user->canEdit()) { register_error(elgg_echo("profile:noaccess")); forward(); } elgg_set_context('profile_edit'); $title = elgg_echo('profile:edit'); $content = elgg_view_form('profile/edit', array(), array('entity' => $user)); $params = array( 'content' => $content, 'title' => $title, ); $body = elgg_view_layout('qq_two_column', $params); echo elgg_view_page($title, $body); <file_sep>/qq_theme/views/default/forms/feedback.php <?php /** * feedback form * */ ?> <div> <?php echo elgg_view('input/text', array( 'name' => 'title', 'class' => 'elgg-autofocus', 'placeholder'=>elgg_echo('feedback:title'), )); ?> </div> <div> <?php echo elgg_view('input/plaintext', array( 'name' => 'description', 'class' => 'elgg-autofocus ', 'placeholder'=>elgg_echo('feedback:desc'), )); ?> </div> <div class="elgg-foot"> <?php echo elgg_view('input/submit', array('value' => elgg_echo('feedback'))); ?> </div> <file_sep>/qq_theme/lib/qq_ajax.php <?php function qq_ajax_get_questions(){ $guid=get_input('guid'); $questions=elgg_get_entities_from_relationship(array( 'type'=>'object', 'subtype'=>array('question','question-top'), 'relationship'=>'follow', 'inverse_relationship'=>FALSE, 'relationship_guid'=>$guid, )); foreach($questions as $question){ $object_guids[].=$question->getGUID(); } if(!$object_guids){ $river=elgg_echo('river:no question'); }else{ $river =elgg_list_river(array( 'object_guids'=>$object_guids, 'action_types'=>array('create','reference'), 'pagenation'=>true, 'limit'=>15 )); } return $river; } function qq_ajax_get_follow_update(){ $guid=get_input('guid'); if(!$guid){ $river=elgg_echo('river:not follow'); }else{ $river=elgg_list_river(array( 'relationship'=>'friend', 'relationship_guid'=>$guid, 'pagenation'=>true, 'limit'=>15 )); } return $river; }<file_sep>/qq_theme/pages/feedback.php <?php $title="Help center"; $site_url=elgg_get_site_url(); $feedback=elgg_view_form('feedback'); $content=<<<HTML <div class="pam"> $feedback </div> HTML; $body=elgg_view_layout('ib_help',array('help_content'=>$content)); echo elgg_view_page($title,$body); ?><file_sep>/questions/actions/questions/follow.php <?php /** * Feature a question * * @package Elggincubator */ $question_guid = get_input('question_guid'); $action = get_input('action_type'); $uid=elgg_get_logged_in_user_guid(); $question = get_entity($question_guid); if (!elgg_instanceof($question,'object')) { register_error(elgg_echo('not question')); forward(REFERER); } //get the action, is it to feature or unfeature if ($action == "follow") { add_entity_relationship($uid, 'follow', $question_guid); system_message(elgg_echo('questions:follow')); add_to_river('river/relationship/follow', 'follow', $uid, $question_guid); } else { remove_entity_relationship($uid, 'follow', $question_guid); system_message(elgg_echo('questions:unfollow')); } forward(REFERER); <file_sep>/qq_theme/views/default/forms/index-login.php <?php /** * Elgg login form * * @package Elgg * @subpackage Core */ ?> <div> <?php echo elgg_view('input/text', array( 'name' => 'username', 'class' => 'elgg-autofocus', 'placeholder'=>elgg_echo('loginusername'), )); ?> </div> <div> <?php echo elgg_view('input/password', array('name' => 'password','placeholder'=>elgg_echo('password'),)); ?> </div> <div class="elgg-foot"> <div class="fl"> <?php echo elgg_view('input/submit', array('value' => elgg_echo('login'),'class'=>'elgg-button-index')); ?> </div> <?php if (isset($vars['returntoreferer'])) { echo elgg_view('input/hidden', array('name' => 'returntoreferer', 'value' => 'true')); } ?> <ul class="elgg-menu elgg-menu-index fr"> <li> <input type="checkbox" name="persistent" value="true" /> <?php echo elgg_echo('user:persistent'); ?> </li> <li> . </li> <li><a class="forgot_link" href="<?php echo elgg_get_site_url(); ?>forgotpassword"> <?php echo elgg_echo('user:password:lost'); ?> </a></li> </ul> </div> <file_sep>/questions/views/default/object/question.php <?php /** * View for question object * */ $question = elgg_extract('entity', $vars, FALSE); $vars=array('entity'=>$question); echo elgg_view('object/question-top',$vars);<file_sep>/qq_theme/pages/about.php <?php $title=elgg_echo('help:privacy'); $site_url=elgg_get_site_url(); $content=<<<HTML <h3>About Miifang:</h3> <p>Miifang is a social Q&A platform that focus on solving question of unknown world.</p> <h3>Vision:</h3> <p>Collective intelligence to explore unknown world.</p> <h3>Why we build miifang?:</h3> <p>As you know, most of the Q&A platform are focus on helping you to solve the problem that someone else in the world might know the answer, which i called solving problem in known world. But for unknown world,maybe nobody could give you the answer,but most of us could help you see the different aspect of the question by questioning you a question and giving you some related references or cues.So we create miifang for collecting intelligence from crowd to give you more useful questions and references so that you could find your way to the answer quickly. </p> HTML; $body=elgg_view_layout('ib_help',array('help_content'=>$content)); echo elgg_view_page($title,$body); ?><file_sep>/questions/views/default/river/annotation/reference/create.php <?php /** * Post reference river view */ $object = $vars['item']->getObjectEntity(); $reference = $vars['item']->getAnnotation(); echo elgg_view('river/elements/layout', array( 'item' => $vars['item'], 'message' => $reference->value, )); <file_sep>/questions/pages/questions/all.php <?php /** * All questions * */ if (!elgg_is_logged_in()){ forward(''); } elgg_register_title_button(); $offset = (int)get_input('offset', 0); $cat=get_input('cat'); $proccess=get_input('proccess'); $level=sanitize_string(get_input('level')); if(!$cat){ $lists=elgg_list_entities(array( 'type' => 'object', 'subtype' => 'question-top', 'limit' => 6, 'offset' => $offset, 'full_view' => false, 'pagination' => true, 'list_class'=>'question-list brs', 'item_class'=>'question-item bx', 'view_toggle_type' => false )); }else{ $cat_value=array('c_1','c_2','c_3'); $p_value=array('p_1','p_2','p_3','p_4','p_5','p_6'); $l_value=array('what','how','why'); if($cat=='null'){ $cat=$cat_value; }else{ $cat_class[array_search($cat,$cat_value)]="class=\"selected\""; } if($proccess=='null'){ $proccess=$p_value; }else{ $p_class[array_search($proccess,$p_value)]="class=\"selected\""; } if($level=='null'){ $level=$l_value; }else{ $l_class[array_search($level,$l_value)]="class=\"selected\""; } $lists=elgg_list_entities_from_metadata(array( 'type' => 'object', 'subtype' => 'question-top', 'metadata_name_value_pairs'=>array( array('name'=>'catagory','value'=>$cat,'operand' => '='), array('name'=>'proccess','value'=>$proccess,'operand' => '='), array('name' =>'level','value' =>$level,'operand' => '='), ), 'limit' => 6, 'offset' => $offset, 'full_view' => false, 'pagination' => true, 'list_class'=>'question-list brs', 'item_class'=>'question-item bx', 'view_toggle_type' => false)); } if(!$lists){ $lists=elgg_echo("No question"); } $cat_name=array(elgg_echo("question:form:cat"),elgg_echo('question:list:unlimited'),elgg_echo('question:cat:nature'),elgg_echo('question:cat:human'),elgg_echo('question:cat:sociaty')); $p_name=array(elgg_echo("question:form:proccess"),elgg_echo('question:list:unlimited'),elgg_echo('question:process:review'),elgg_echo('question:process:method'),elgg_echo('question:process:design'),elgg_echo('question:process:experiment'),elgg_echo('question:process:analysic'),elgg_echo('question:process:conclusion')); $l_name=array(elgg_echo("question:form:level"),elgg_echo('question:list:unlimited'),elgg_echo('question:level:what'),elgg_echo('question:level:how'),elgg_echo('question:level:why')); $fliter=<<<html <div class="mbm pam elgg-divide-bottom " id="fliter_all"> <div class="pbm"> $cat_name[0] <a href="#" id="cat_0" >$cat_name[1]</a> <a href="#" id="cat_1" $cat_class[0] >$cat_name[2]</a> <a href="#" id="cat_2" $cat_class[1] >$cat_name[3]</a> <a href="#" id="cat_3" $cat_class[2] >$cat_name[4]</a> </div> <div class="pbm" > $p_name[0] <a href="#" id="p_0">$p_name[1]</a> <a href="#" id="p_1" $p_class[0] >$p_name[2]</a> <a href="#" id="p_2" $p_class[1] >$p_name[3]</a> <a href="#" id="p_3" $p_class[2] >$p_name[4]</a> <a href="#" id="p_4" $p_class[3] >$p_name[5]</a> <a href="#" id="p_5" $p_class[4] >$p_name[6]</a> <a href="#" id="p_6" $p_class[5] >$p_name[7]</a> </div> <div class="pbs" > $l_name[0] <a href="#" id="level_0">$l_name[1]</a> <a href="#" id="level_1" $l_class[0] >$l_name[2]</a> <a href="#" id="level_2" $l_class[1] >$l_name[3]</a> <a href="#" id="level_3" $l_class[2] >$l_name[4]</a> </div> </div> html; $content=<<<html $fliter $lists html; $title = elgg_echo('questions:everyone'); $body = elgg_view_layout('qq_two_column', array( 'content' => $content, 'title' => $title, 'nav'=>'', )); echo elgg_view_page($title, $body); ?> <script type="text/javascript"> $(document).ready(function(){ var cats=new Array($('#cat_0'),$('#cat_1'),$('#cat_2'),$('#cat_3')) var cats_value=new Array('null','c_1','c_2','c_3') var proccess=new Array($('#p_0'),$('#p_1'),$('#p_2'),$('#p_3'),$('#p_4'),$('#p_5'),$('#p_6')) var p_value=new Array('null','p_1','p_2','p_3','p_4','p_5','p_6') var levels=new Array($('#level_0'),$('#level_1'),$('#level_2'),$('#level_3')) var levels_value=new Array('null','what','how','why') //get the value from url String.prototype.GetValue= function(para) { var reg = new RegExp("(^|&)"+ para +"=([^&]*)(&|$)"); var r = this.substr(this.indexOf("\?")+1).match(reg); if (r!=null) return unescape(r[2]); return null; } var str = location.href; function link(i,j,h){ j[i].click(function(){ location.href=(h[i]) }) } link_b=elgg.config.wwwroot+'questions/all?'; var cat_links=new Array(); cat_links[0]=link_b+"cat="+cats_value[0]+"&level="+str.GetValue("level")+"&proccess="+str.GetValue("proccess"); cat_links[1]=link_b+"cat="+cats_value[1]+"&level="+str.GetValue("level")+"&proccess="+str.GetValue("proccess"); cat_links[2]=link_b+"cat="+cats_value[2]+"&level="+str.GetValue("level")+"&proccess="+str.GetValue("proccess"); cat_links[3]=link_b+"cat="+cats_value[3]+"&level="+str.GetValue("level")+"&proccess="+str.GetValue("proccess"); var p_links=new Array(); p_links[0]=link_b+"cat="+str.GetValue("cat")+"&level="+str.GetValue("level")+"&proccess="+p_value[0]; p_links[1]=link_b+"cat="+str.GetValue("cat")+"&level="+str.GetValue("level")+"&proccess="+p_value[1]; p_links[2]=link_b+"cat="+str.GetValue("cat")+"&level="+str.GetValue("level")+"&proccess="+p_value[2]; p_links[3]=link_b+"cat="+str.GetValue("cat")+"&level="+str.GetValue("level")+"&proccess="+p_value[3]; p_links[4]=link_b+"cat="+str.GetValue("cat")+"&level="+str.GetValue("level")+"&proccess="+p_value[4]; p_links[5]=link_b+"cat="+str.GetValue("cat")+"&level="+str.GetValue("level")+"&proccess="+p_value[5]; p_links[6]=link_b+"cat="+str.GetValue("cat")+"&level="+str.GetValue("level")+"&proccess="+p_value[6]; var level_links=new Array(); level_links[0]=link_b+"cat="+str.GetValue("cat")+"&level="+levels_value[0]+"&proccess="+str.GetValue("proccess"); level_links[1]=link_b+"cat="+str.GetValue("cat")+"&level="+levels_value[1]+"&proccess="+str.GetValue("proccess"); level_links[2]=link_b+"cat="+str.GetValue("cat")+"&level="+levels_value[2]+"&proccess="+str.GetValue("proccess"); level_links[3]=link_b+"cat="+str.GetValue("cat")+"&level="+levels_value[3]+"&proccess="+str.GetValue("proccess"); link(0,cats,cat_links) link(1,cats,cat_links) link(2,cats,cat_links) link(3,cats,cat_links) link(0,proccess,p_links) link(1,proccess,p_links) link(2,proccess,p_links) link(3,proccess,p_links) link(4,proccess,p_links) link(5,proccess,p_links) link(6,proccess,p_links) link(0,levels,level_links) link(1,levels,level_links) link(2,levels,level_links) link(3,levels,level_links) }); </script> <file_sep>/questions/views/default/river/object/question/create.php <?php /** * New question river entry * * @package projects */ $object = $vars['item']->getObjectEntity(); $excerpt = elgg_get_excerpt($object->description,140); if($excerpt){ $excerpt.=elgg_view('output/url',array('href'=>$object->getURL(),'text'=>'...More')); } echo elgg_view('river/elements/layout', array( 'item' => $vars['item'], 'message' =>$excerpt, )); <file_sep>/qq_theme/views/default/css/elements/helpers.php <?php /** * Helpers CSS * * Contains generic elements that can be used throughout the site. * * @package Elgg.Core * @subpackage UI */ ?> .clearfloat { clear: both; } .hidden { display: none; } .centered { margin: 0 auto; } .center { text-align: center; } .float { float: left; } .float-alt { float: right; } .link { cursor: pointer; } .elgg-discover .elgg-discoverable { display: none; } .elgg-discover:hover .elgg-discoverable { display: block; } .elgg-transition:hover { opacity: .7; } /* *************************************** BORDERS AND SEPARATORS *************************************** */ .elgg-border-plain { border: 1px solid #eeeeee; } .elgg-border-transition { border: 1px solid #eeeeee; } .elgg-divide-top { border-top: 1px solid #CCCCCC; } .elgg-divide-bottom { border-bottom: 1px dashed #CCCCCC; } .elgg-divide-left { border-left: 1px solid #CCCCCC; } .elgg-divide-right { border-right: 1px solid #CCCCCC; } /* *************************************** Spacing (from OOCSS) *************************************** */ <?php /** * Spacing classes * Should be used to modify the default spacing between objects (not between nodes of the same object) * Please use judiciously. You want to be using defaults most of the time, these are exceptions! * <type><location><size> * <type>: m = margin, p = padding * <location>: a = all, t = top, r = right, b = bottom, l = left, h = horizontal, v = vertical * <size>: n = none, s = small, m = medium, l = large */ $none = '0'; $small = '5px'; $medium = '10px'; $large = '20px'; echo <<<CSS /* Padding */ .pan{padding:$none} .prn, .phn{padding-right:$none} .pln, .phn{padding-left:$none} .ptn, .pvn{padding-top:$none} .pbn, .pvn{padding-bottom:$none} .pas{padding:$small} .prs, .phs{padding-right:$small} .pls, .phs{padding-left:$small} .pts, .pvs{padding-top:$small} .pbs, .pvs{padding-bottom:$small} .pam{padding:$medium} .prm, .phm{padding-right:$medium} .plm, .phm{padding-left:$medium} .ptm, .pvm{padding-top:$medium} .pbm, .pvm{padding-bottom:$medium} .pal{padding:$large} .prl, .phl{padding-right:$large} .pll, .phl{padding-left:$large} .ptl, .pvl{padding-top:$large} .pbl, .pvl{padding-bottom:$large} /* Margin */ .man{margin:$none} .mrn, .mhn{margin-right:$none} .mln, .mhn{margin-left:$none} .mtn, .mvn{margin-top:$none} .mbn, .mvn{margin-bottom:$none} .mas{margin:$small} .mrs, .mhs{margin-right:$small} .mls, .mhs{margin-left:$small} .mts, .mvs{margin-top:$small} .mbs, .mvs{margin-bottom:$small} .mam{margin:$medium} .mrm, .mhm{margin-right:$medium} .mlm, .mhm{margin-left:$medium} .mtm, .mvm{margin-top:$medium} .mbm, .mvm{margin-bottom:$medium} .mal{margin:$large} .mrl, .mhl{margin-right:$large} .mll, .mhl{margin-left:$large} .mtl, .mvl{margin-top:$large} .mbl, .mvl{margin-bottom:$large} /* border-radius*/ .brs{border-radius: $small $small $small $small;-moz-border-radius:$small $small $small $small;-webkit-border-radius: $small $small $small $small;} .brm{border-radius: $medium $medium $medium $medium;-moz-border-radius:$medium $medium $medium $medium;-webkit-border-radius: $medium $medium $medium $medium;} .brl{border-radius: $large $large $large $large;-moz-border-radius:$large $large $large $large;-webkit-border-radius: $large $large $large $large;} /* button*/ .btn{ background:#F8F8F9; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f8f8f9',endColorstr='#e6e6e8'); background: -webkit-gradient(linear,0 0,0 100%,from(#F8F8F9),to(#E6E6E8)); background: -moz-linear-gradient(top,#F8F8F9,#E6E6E8); -webkit-box-shadow: 0 1px 0 white inset,0 1px 0 rgba(0, 0, 0, .1); -moz-box-shadow: 0 1px 0 #fff inset,0 1px 0 rgba(0,0,0,.1); -o-box-shadow: 0 1px 0 #fff inset,0 1px 0 rgba(0,0,0,.1); box-shadow: 0 1px 0 white inset,0 1px 0 rgba(0, 0, 0, .1); text-shadow: 0 1px 0 white; border: 1px solid #BBB; color: #666!important; } .block{ display:block; } .inblock{ display:inline-block; } .bgwhite{ background:white; } CSS; ?> .f12{font-size:12px} .f13{font-size:13px} .f14{font-size:14px} .f16{font-size:16px} .f20{font-size:20px} .f1h{font-size:1.5em} .f2{font-size:2em} .f2h{font-size:2.5em} .f3{font-size:3em} .fb{font-weight:bold} .fn{font-weight:normal} .t2{text-indent:2em} .lh150{line-height:150%} .lh180{line-height:180%} .lh200{line-height:200%} .unl{text-decoration:underline;} .no_unl{text-decoration:none;} .tl{text-align:left} .tc{text-align:center} .tr{text-align:right} .bc{margin-left:auto;margin-right:auto;} .fl{float:left;display:inline} .fr{float:right;display:inline} .cb{clear:both} .cl{clear:left} .cr{clear:right} .vm{vertical-align:middle} .pr{position:relative} .pa{position:absolute} .abs-right{position:absolute;right:0} .zoom{zoom:1} .none{display:none} .w10{width:10px} .w20{width:20px} .w30{width:30px} .w40{width:40px} .w50{width:50px} .w60{width:60px} .w70{width:70px} .w80{width:80px} .w90{width:90px} .w100{width:100px} .w200{width:200px} .w250{width:250px} .w300{width:300px} .w400{width:400px} .w500{width:500px} .w600{width:600px} .w700{width:700px} .w800{width:800px} .w900{width:900px} .w{width:100%} .w9{width:90%} .h50{height:50px} .h80{height:80px} .h100{height:100px} .h200{height:200px} .h{height:100%} .h9{height:90%} .m10{margin:10px} .m15{margin:15px} .m30{margin:30px} .mt5{margin-top:5px} .mt10{margin-top:10px} .mt15{margin-top:15px} .mt20{margin-top:20px} .mt30{margin-top:30px} .mt50{margin-top:50px} .mt100{margin-top:100px} .mb10{margin-bottom:10px} .mb15{margin-bottom:15px} .mb20{margin-bottom:20px} .mb30{margin-bottom:30px} .mb50{margin-bottom:50px} .mb100{margin-bottom:100px} .ml5{margin-left:5px} .ml10{margin-left:10px} .ml15{margin-left:15px} .ml20{margin-left:20px} .ml30{margin-left:30px} .ml50{margin-left:50px} .ml100{margin-left:100px} .mr5{margin-right:5px} .mr10{margin-right:10px} .mr15{margin-right:15px} .mr20{margin-right:20px} .mr30{margin-right:30px} .mr50{margin-right:50px} .mr100{margin-right:100px} .p10{padding:10px;} .p15{padding:15px;} .p30{padding:30px;} .pt5{padding-top:5px} .pt10{padding-top:10px} .pt15{padding-top:15px} .pt20{padding-top:20px} .pt30{padding-top:30px} .pt50{padding-top:50px} .pb5{padding-bottom:5px} .pb10{padding-bottom:10px} .pb15{padding-bottom:15px} .pb20{padding-bottom:20px} .pb30{padding-bottom:30px} .pb50{padding-bottom:50px} .pb100{padding-bottom:100px} .pl5{padding-left:5px} .pl10{padding-left:10px} .pl15{padding-left:15px} .pl20{padding-left:20px} .pl30{padding-left:30px} .pl50{padding-left:50px} .pl100{padding-left:100px} .pr5{padding-right:5px} .pr10{padding-right:10px} .pr15{padding-right:15px} .pr20{padding-right:20px} .pr30{padding-right:30px} .pr50{padding-right:50px} .pr100{padding-right:100px}<file_sep>/qq_theme/pages/jobs.php <?php $title=elgg_echo('help:jobs'); $site_url=elgg_get_site_url(); $content=<<<HTML <div class="pal"> <h2>Working at miifang:</h2> <p>Miifang is a growing team that just need someone like you who is passion with web application and science research. If you are a geek who believe in Web application innovation could challenge the status quo and totaly believe that your are a genius for this, please contact us <a href="mailto:<EMAIL>"><EMAIL></a> as soon as possible.Let's rock the world together!</p> </div> HTML; $body=elgg_view_layout('ib_help',array('help_content'=>$content)); echo elgg_view_page($title,$body); ?><file_sep>/qq_theme/views/default/page/elements/header_logo.php <?php /** * Elgg header logo */ $site = elgg_get_site_entity(); $site_name = $site->name; $site_url = elgg_get_site_url(); $img=$site_url.'mod/qq_theme/graphics/header_logo.png'; ?> <h2 id="logo"><a href="<?php echo $site_url; ?>"><span><img src=<?php echo$img?> > </span></a></h2> <file_sep>/qq_theme/views/default/page/index.php <?php /** * @uses $vars['title'] The page title * @uses $vars['body'] The main content of the page * @uses $vars['sysmessages'] A 2d array of various message registers, passed from system_messages() */ $css = elgg_get_loaded_css(); $title = elgg_get_config('sitename'); $version = get_version(); $release = get_version(true); // Set the content type header("Content-type: text/html; charset=UTF-8"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="ElggRelease" content="<?php echo $release; ?>" /> <meta name="ElggVersion" content="<?php echo $version; ?>" /> <title><?php echo $title; ?></title> <?php echo elgg_view('page/elements/shortcut_icon', $vars); ?> <?php foreach ($css as $link) { ?> <link rel="stylesheet" href="<?php echo $link; ?>" type="text/css" /> <?php } ?> <?php $ie_url = elgg_get_simplecache_url('css', 'ie'); $ie7_url = elgg_get_simplecache_url('css', 'ie7'); $ie6_url = elgg_get_simplecache_url('css', 'ie6'); ?> <!--[if gt IE 7]> <link rel="stylesheet" type="text/css" href="<?php echo $ie_url; ?>" /> <![endif]--> <!--[if IE 7]> <link rel="stylesheet" type="text/css" href="<?php echo $ie7_url; ?>" /> <![endif]--> <!--[if IE 6]> <link rel="stylesheet" type="text/css" href="<?php echo $ie6_url; ?>" /> <![endif]--> </head> <body> <div class="elgg-page-messages"> <?php echo elgg_view('page/elements/messages', array('object' => $vars['sysmessages'])); ?> </div> <?php echo elgg_view('page/elements/body', $vars); ?> </body> </html><file_sep>/questions/views/default/widgets/question/edit.php <?php /** * Elgg question widget edit view * * @package Elggquestion */ // set default value if (!isset($vars['entity']->num_display)) { $vars['entity']->num_display = 4; } $params = array( 'name' => 'params[num_display]', 'value' => $vars['entity']->num_display, 'options' => array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20), ); $dropdown = elgg_view('input/dropdown', $params); ?> <div> <?php echo elgg_echo('question:num_questions'); ?>: <?php echo $dropdown; ?> </div> <file_sep>/qq_theme/views/default/qq_theme/css.php <?php ?> /******************************* qq-theme css file ********************************/ html{ background-image:url('<?php echo $vars['url']; ?>mod/qq_theme/graphics/bg.png'); background-repeat:repeat; background-size:cover; background-attachment: fixed; } fieldset > div:first-child { margin-top: 15px; } /*index page*/ #index-top{margin-left:30%;margin-top:100px;position:fixed} #index-bottom{background: white;width: 100%;margin-top: 320px;position: fixed;height: 100%;} .elgg-menu-index, .elgg-menu-index li, .elgg-menu-index li a{ display:inline-block; color:white; } #slogan{color:white;font-size:1.4em;width:200px;line-height: 25px;} #apply{margin-left: 45%;margin-top:50px;} /* Submit: This button should convey, "you're about to take some definitive action" */ .elgg-button-index { color: white; text-shadow: 1px 1px 0px black; text-decoration: none; border:1px solid rgba(0,0,0,0.1); background: -webkit-gradient(linear, 0 0, 0 100%, from(rgba(0,0,0,0.1)), color-stop(30%, rgba(0,0,0,0.3)), color-stop(70%, rgba(0,0,0,0.2))); background: -moz-linear-gradient(top, rgba(0,0,0,0.1), rgba(0,0,0,0.3) 30%, rgba(0,0,0,0.1) 70%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='rgba(0,0,0,0.1)', endColorstr='rgba(0,0,0,0.3)'); background-color:rgba(0,0,0,0.1); -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; moz-box-shadow: inset 0px 1px 0px 0px #fff; -webkit-box-shadow: inset 0px 1px 0px 0px #fff; box-shadow: inset 0px 1px 0px 0px #fff; } .elgg-button-index:hover { background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, rgba(0,0,0,0.1)), color-stop(1, rgba(0,0,0,0.3)) ); background:-moz-linear-gradient( center top, rgba(0,0,0,0.1) 5%, rgba(0,0,0,0.3) 100% ); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='rgba(0,0,0,0.1)', endColorstr='rgba(0,0,0,0.3)'); background-color:rgba(0,0,0,0.3); } /* header*/ .elgg-page-header { position: fixed; background: #315CA1 url(<?php echo $vars['url']; ?>_graphics/header_shadow.png) repeat-x bottom left; width: 100%; z-index:2; } .elgg-page-body{ padding-top:60px; } .elgg-page-footer{ z-index:2; } #header-messages-new{ color: white; background-color: red; -webkit-border-radius: 10px; -moz-border-radius: 10px; border-radius: 10px; -webkit-box-shadow: -2px 2px 4px rgba(0, 0, 0, 0.50); -moz-box-shadow: -2px 2px 4px rgba(0, 0, 0, 0.50); box-shadow: -2px 2px 4px rgba(0, 0, 0, 0.50); text-align: center; top: 0px; left: 26px; min-width: 16px; height: 16px; font-size: 10px; font-weight: bold; } .container{ background:white; border-radius: 10px 10px 10px 10px;-moz-border-radius:10px 10px 10px 10px;-webkit-border-radius: 10px 10px 10px 10px; } #logo{display:inline;float:left;margin-right:10px;margin-bottom:0;} #logo a span{ color: white;overflow:hidden;display:block;line-height:0;} #logo a{display:block;} .elgg-page-default .elgg-page-header > .elgg-inner { width: 990px; margin: 0 auto; height: 20px; } ul.elgg-menu-htabs{ display:inline-block; } .elgg-menu-htabs li a{ color:white; margin:10px; padding-top:2px; } .elgg-menu-htabs li.elgg-state-selected { background:#04477c; } #menubar ul.menus li { float:left; list-style:none; margin-right:1px; } #menubar ul.menus li a { padding:2px 10px; display:block; color:#FFF; text-decoration:none; } #menubar ul.menus ul { position:absolute; background:#315CA1; } #menubar ul.menus li a:hover { background:#04477c; } #menubar ul.children { display:none; padding:0; margin:0; } #menubar ul.children li { float:none; margin:0; padding:0; } #menubar ul li .children a { width:90px; } /* sidebar menu*/ ul.sidebar-menu{ padding:5px; } .sidebar-menu li { display:block; padding:5px; } .sidebar-menu li.elgg-state-selected { background:white; -webkit-border-radius: 4px; -moz-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; -moz-box-shadow: 0 1px 1px #b8bbbf; -webkit-box-shadow: 0 1px 1px #B8BBBF; -o-box-shadow: 0 1px 1px #b8bbbf; box-shadow: 0 1px 1px #B8BBBF; } /*river-tab css*/ ul.river-tab{ display:block; } ul.river-tab li { border: 1px solid #eee; border-bottom: 0; background: #666; margin: 0 -25px 0 0; -webkit-border-radius: 15px 15px 0 0; -moz-border-radius: 5px 5px 0 0; border-radius: 15px 15px 0 0; width: 150px; z-index: 0; top: 0; } ul.river-tab li a{ text-decoration: none; display: block; padding: 3px 10px 0; text-align: center; height: 21px; color: white; } ul.river-tab li.elgg-state-selected { border-color: #eee; background: white; z-index: 1; top: 1px; padding-bottom:1px } ul.river-tab li.elgg-state-selected a{ color:#666; position: relative; } .elgg-river-item { padding: 20px 15px; } /*river list*/ .forward-list{ padding:5px; } /* help center css */ .help-sidebar{ float: left; padding: 12px 10px; width: 150px; border: 1px solid #C7CACC; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; position: fixed; -moz-box-shadow: inset 0 0px 3px #ccc; -webkit-box-shadow: inset 0 0px 3px #CCC; -o-box-shadow: inset 0 0px 3px #ccc; box-shadow: inset 0 0px 3px #CCC; } ul.help-sidebar a{ color:#666; } .separator{ border-top: 1px solid #E2E6E8; overflow: hidden; border-bottom: 1px solid #FEFFFE; border-width: 1px 0; } .help-content{ float:right; width: 780px; padding:10px; min-height:600px; display:inline-block; background: white; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; } .help-content p{ line-height:1.2; }<file_sep>/qq_theme/pages/index.php <?php if(elgg_is_logged_in()){ forward('activity'); } $logo=elgg_view('output/img',array('src'=>elgg_get_site_url().'mod/qq_theme/graphics/logo.png','title'=>elgg_echo('sitename'))); $login_url = elgg_get_site_url(); if (elgg_get_config('http_login')) { $login_url = str_replace("http:", "http:", elgg_get_site_url()); } $login=elgg_view_form('index-login', array('action' => "{$login_url}action/login"), array('returntoreferer' => TRUE)); $slogan=elgg_echo('slogan'); $apply=elgg_view('output/url',array('href'=>'register','text'=>elgg_echo('Sign up'),'class'=>'elgg-button-index','style'=>'padding:10px 20px;font-size:2em;')); $footer=elgg_view('page/elements/footer'); $body=<<<html <div id='index-top' class="pam"> <div class="fl mtm"> $logo <div id='slogan' class="pas"> $slogan </div> </div> <div class="fl w300 mal"> $login </div> <div class="clearfloat"></div> </div> <div id='index-bottom'> <div id="apply"> $apply </div> <div style="margin-top:10%;margin-left:30%"> $footer </div> </div> html; echo elgg_view_page($title,$body,'index'); ?><file_sep>/questions/languages/en.php <?php $mapping = array( 'questions:menu' => 'Questions', 'questions:everyone'=>'All questions', 'questions:add'=>'Ask a question', 'question:save'=>'Save', 'question:edit'=>'Edit the question', 'question:question'=>'Question the question', 'question:follow'=>'Follow', 'question:unfollow'=>'Unfollow', 'question:follownum'=>'<b>%s</b> people followed', 'question:widget:activities'=>'Recent news', 'question:widget:friends'=>'My follow', 'question:widget:friendsof'=>'My follower', 'question:widget:ask'=>'My question', 'question:widget:answer'=>'My answer', //header menu 'menu:logout'=>"Logout", 'menu:profile'=>"Profile", 'menu:setting'=>"Setting", 'menu:account'=>"Account", 'menu:ask'=>"Ask question", //form 'question:form:title'=>'Title:', 'question:form:title:tips'=>'at least 6 characters', 'question:form:description'=>'Description:', 'question:form:tags'=>'Tags:(commas seperated)', 'question:form:proccess'=>'Study Stage:', 'question:process:review'=>'Topic', 'question:process:method'=>'Method', 'question:process:design'=>'Design', 'question:process:experiment'=>'Experiment', 'question:process:analysic'=>'Analysic', 'question:process:conclusion'=>'Conclusion', 'question:form:level'=>'Question Level:', 'question:level:what'=>'What', 'question:level:how'=>'How', 'question:level:why'=>'Why', 'question:form:cat'=>'Catagory:', 'question:cat:nature'=>'Science', 'question:cat:human'=>'Humanities', 'question:cat:sociaty'=>'Social Science', 'question:reference'=>'References:', 'reference:add'=>'Add', 'references:address'=>'Link', 'reference:subject'=>'Someone add an reference for you!', 'reference:body'=>' %s in your question(<a href="%s">%s</a>): add reference:%s.', 'question:order:time'=>'By time', 'question:order:vote'=>'By Vote', //question all page 'question:list:unlimited'=>'Unlimited', 'question:all:newest'=>'Newest', 'question:all:hottest'=>'Hottest', 'question:all:recommended'=>'Recommended', //river message 'river:create:object:default'=>'%s ask: %s?', 'river:reference:object:default'=>'%s in question:%s ? add reference:', 'river:follow:object:default'=>' %s follow this question: %s ?', 'river-tab:all'=>'All', 'river-tab:question'=>'Questions', 'river-tab:follow'=>'Following', 'river:forward:object:default'=>'%s forward this question:%s ?', //system message 'questions:saved'=>'Question save.', 'question:notfound'=>'Question Not found', 'thumbs:already'=>'Already voted', 'thumbs:notfound'=>'Vote object did not exist.', 'thumbs:failure'=>'vote failed,pleas try again later.', 'thumbsup:success'=>'Thumbs up success', 'thumbsdown:success'=>'Thumbs down success', //error messgae 'questions:error:no_save'=>'Save failed', 'questions:error:no_title'=>'Please enter title:', 'questions:saved'=>'Submit success.', ); add_translation('en', $mapping); <file_sep>/questions/views/default/questions/list_menu.php <?php $guid=get_input('guid'); $tabs=array( 'time' => array( 'text' => elgg_echo("question:order:time"), 'href' => 'questions/view/'.$guid.'?order_by=time', 'priority' => 300, ), 'vote' => array( 'text' => elgg_echo("question:order:vote"), 'href' => 'questions/view/'.$guid, 'priority' => 200, ), ); if (strpos(full_url(), 'order_by') === false) { $tabs['vote']['selected'] = true; } foreach ($tabs as $name => $tab) { $tab['name'] = $name; elgg_register_menu_item('river_tabs', $tab); } echo elgg_view_menu('river_tabs',array('sort_by' => 'priority', 'class' => 'elgg-menu-hz river-tab')); <file_sep>/questions/actions/questions/delete.php <?php /** * Delete a question * * @package projects */ $guid = get_input('guid'); $question = get_entity($guid); if (elgg_instanceof($question, 'object') && $question->canEdit()) { $container = get_entity($question->container_guid); // Bring all child elements forward $parent = $question->parent_guid; $children = elgg_get_entities_from_metadata(array( 'metadata_name' => 'parent_guid', 'metadata_value' => $question->getGUID() )); if ($children) { foreach ($children as $child) { $child->parent_guid = $parent; } } if ($question->delete()) { system_message(elgg_echo("question:delete:success")); if ($parent) { if ($parent = get_entity($parent)) { forward($parent->getURL()); } } } } register_error(elgg_echo("question:delete:failed")); forward(REFERER); <file_sep>/qq_theme/views/default/page/layouts/one_column.php <?php /** * Elgg one-column layout * * @package Elgg * @subpackage Core * * @uses $vars['content'] Content string * @uses $vars['class'] Additional class to apply to layout * * @uses $vars['fliter'] Additional class to apply to layout */ $class = 'elgg-layout elgg-layout-one-column clearfix'; if (isset($vars['class'])) { $class = "$class {$vars['class']}"; } if (isset($vars['fliter'])) { $fliter = $vars['fliter']; } // navigation defaults to breadcrumbs $nav = elgg_extract('nav', $vars, elgg_view('navigation/breadcrumbs')); if (isset($vars['buttons']) && $vars['buttons']) { $buttons = $vars['buttons']; } else { $buttons = elgg_view_menu('title', array( 'sort_by' => 'priority', 'class' => 'elgg-menu-hz', )); } $title = elgg_extract('title', $vars, ''); $title = elgg_view_title($title, array('class' => 'elgg-heading-main')); ?> <div class="container pbl"> <div class="<?php echo $class; ?>"> <div class="elgg-body elgg-main"> <?php echo $nav; echo <<<html <div class="elgg-head clearfix"> $title$buttons </div> html; echo $fliter; echo $vars['content']; // @deprecated 1.8 if (isset($vars['area1'])) { echo $vars['area1']; } ?> </div> </div> </div><file_sep>/qq_theme/languages/en.php <?php /** * themes chinese language file */ $english = array( 'sitename'=>'Miifang', 'slogan'=>"Questioning the unknown world!", 'apply'=>'Apply account', 'about'=>'About Us', 'contact'=>'Contact Us', 'help'=>'Get Help', 'item:object:question'=>'Answer', 'item:object:question-top'=>'Question', //header menu 'menu:index'=>"Home", 'menu:all'=>"Explore", 'menu:activity'=>'News feed', 'menu:logout'=>"Logout", 'menu:profile'=>"Profile", 'menu:setting'=>"Setting", 'menu:account'=>"Account", 'menu:friends'=>"Following", 'menu:friendsof'=>"Follower", 'menu:ask'=>"Ask question", 'menu:message'=>"Messages", /** * widget */ 'question:more'=>'More...', 'question-top:widget:description'=>'Questions that he ask', 'question-top:widget:description'=>'Questions that he answer', 'question:num_questions'=>'Numbers to display', /** * Friends */ 'friends' => "Following", 'friends:yours' => "Your following", 'friends:owned' => "%s's following", 'friend:add' => "Follow", 'friend:remove' => "Remove follow", 'friends:add:successful' => "You have successfully follow %s.", 'friends:add:failure' => "We couldn't follow %s.", 'friends:remove:successful' => "You have successfully removed following %s .", 'friends:remove:failure' => "We couldn't remove following %s .", 'friends:none' => "No followers yet.", 'friends:none:you' => "You don't have any followers yet.", 'friends:none:found' => "No followers were found.", 'friends:of:none' => "Nobody has followed this user yet.", 'friends:of:none:you' => "Nobody has followed you yet. Start adding content and fill in your profile to let people find you!", 'friends:of:owned' => "People who have followed %s ", 'friends:of' => "Followers", 'friends:collections' => "Followers collections", 'collections:add' => "New collection", 'friends:collections:add' => "New Followers collection", 'friends:addfriends' => "Select Followers", 'friends:collectionname' => "Collection name", 'friends:collectionfriends' => "Followers in collection", 'friends:collectionedit' => "Edit this collection", 'friends:nocollections' => "You do not have any collections yet.", 'friends:collectiondeleted' => "Your collection has been deleted.", 'friends:collectiondeletefailed' => "We were unable to delete the collection. Either you don't have permission, or some other problem has occurred.", 'friends:collectionadded' => "Your collection was successfully created", 'friends:nocollectionname' => "You need to give your collection a name before it can be created.", 'friends:collections:members' => "Collection members", 'friends:collections:edit' => "Edit collection", 'friends:collections:edited' => "Saved collection", 'friends:collection:edit_failed' => 'Could not save collection.', //sidebar menu 'sidebar:menu:all'=>'Explore', //reference messgae 'reference:subject'=>'New reference', 'reference:body'=>' %s in question(<a href="%s">%s</a>):add new reference:%s ��', // apply form 'realname'=>'Real name', 'apply-desc'=>'Personal info(professional background,study field and so on)', // river menu 'river:no question'=>'You are not follow any question yet, try to follow questions that you might interested in.', 'river:no follow'=>'You are not follow any people yet, try to follow some interesting people', 'forward:this'=>'Forward this question:', 'question:this'=>'Question this question', //help 'help:about'=>'About Miifang', 'help:help'=>'Help Center', 'help:jobs'=>'Join Us', 'help:service'=>'Service', 'help:privacy'=>'Privacy', 'help:feedback'=>'Feedback', 'help:contact'=>'Contact Us', 'feedback:title'=>'Title', 'feedback:desc'=>'Please decribe it with more detail.', // messages 'messages' => "All news", 'messages:unreadcount' => "%s unread", 'messages:back' => "back to inbox", 'messages:user' => "%s 's inbox", 'messages:posttitle' => "%s 's message: %s", 'messages:inbox' => "Inbox", 'messages:send' => "Send", 'messages:sent' => "Sent", 'messages:message' => "Message", 'messages:title' => "Subtitle", 'messages:to' => "To:", 'messages:from' => "From:", 'messages:fly' => "Send", 'messages:replying' => "Reply to", 'messages:inbox' => "Inbox", 'messages:sendmessage' => "Send message", 'messages:compose' => "Write message", 'messages:add' => "Write message", 'messages:sentmessages' => "Sent messages", 'messages:recent' => "Recent messages", 'messages:original' => "Original Message", 'messages:yours' => "Your message", 'messages:answer' => "reply", 'messages:toggle' => 'Toggle', 'messages:markread' => 'Markread', 'messages:recipient' => 'Select recipient', 'messages:to_user' => 'To: %s', 'messages:new' => 'New message', 'notification:method:site' => 'Site', 'messages:error' => 'Save failed,please try again later.', 'item:object:messages' => 'All messages', /** * Status messages */ 'messages:posted' => "Your message has sent.", 'messages:success:delete:single' => 'This message has deleted.', 'messages:success:delete' => 'These messages have deleted.', 'messages:success:read' => 'These messages have marked read.', 'messages:error:messages_not_selected' => 'you do not selected any message.', 'messages:error:delete:single' => 'delete failed', /** * Email messages */ 'messages:email:subject' => 'You have new message.', 'messages:email:body' => "You have message from %s : %s If you want to read this message,please click this link:: %s If you want to send message to %s , please click here: %s You could not reply this email.", // system 'reportedcontent:this'=>'Report problem', ); add_translation('en', $english);<file_sep>/qq_theme/pages/river.php <?php /** * Main activity stream list page */ if(!elgg_is_logged_in()){ forward(); } $fliter=get_input('fliter'); $activity = elgg_list_river(array('limit'=>15)); if (!$activity) { $activity = elgg_echo('river:none'); } $t_title1=elgg_echo("river-tab:all"); $t_title2=elgg_echo("river-tab:question"); $t_title3=elgg_echo("river-tab:follow"); $list =<<<html <div class="elgg-border-plain pam"> $activity </div> html; switch ($fliter){ case "question": $tab_content="<div class=\"elgg-border-plain pam\"><div id=\"rt1_content\"></div></div>"; break; case "follow": $tab_content="<div class=\"elgg-border-plain pam\"><div id=\"rt2_content\"></div></div>"; break; default: $tab_content=$list; } $menu=elgg_view('qq_theme/river_menu'); $content=<<<html $menu $tab_content html; $body=elgg_view_layout('qq_two_column',array('content'=>$content)); echo elgg_view_page($title, $body); ?> <script type="text/javascript"> $(document).ready(function(){ //get the value from url String.prototype.GetValue= function(para) { var reg = new RegExp("(^|&)"+ para +"=([^&]*)(&|$)"); var r = this.substr(this.indexOf("\?")+1).match(reg); if (r!=null) return unescape(r[2]); return null; } var str = location.href; fliter=str.GetValue("fliter"); if(fliter=='question'){ elgg.get('/qq_ajax/question_update', { data:{guid:elgg.get_logged_in_user_guid()}, beforeSend:function(XMLHttpRequest) { $('#rt1_content').html("<div class=\"elgg-ajax-loader\"></div>"); }, success: function(resultText, success, xhr) { $('#rt1_content').html(resultText); }, }); }else if (fliter=='follow'){ elgg.get('/qq_ajax/follow_update', { data:{guid:elgg.get_logged_in_user_guid()}, beforeSend:function(XMLHttpRequest) { $('#rt2_content').html("<div class=\"elgg-ajax-loader\"></div>"); }, success: function(resultText, success, xhr) { $('#rt2_content').html(resultText); } }); } }) </script> <file_sep>/questions/lib/questions.php <?php /** * Prepare the add/edit form variables * * @param ElggObject $question A question object. * @return array */ function questions_prepare_form_vars($question = null) { // input names => defaults $values = array( 'title' => '', 'description' => '', 'proccess' => '', 'level' => '', 'catagory' => '', 'access_id' => ACCESS_DEFAULT, 'tags' => '', 'container_guid' => elgg_get_page_owner_guid(), 'guid' => null, 'entity' => $question, ); if ($question) { foreach (array_keys($values) as $field) { if (isset($question->$field)) { $values[$field] = $question->$field; } } } if (elgg_is_sticky_form('question')) { $sticky_values = elgg_get_sticky_values('question'); foreach ($sticky_values as $key => $value) { $values[$key] = $value; } } elgg_clear_sticky_form('question'); return $values; } /** * Recurses the question tree and adds the breadcrumbs for all ancestors * * @param ElggObject $question Page entity */ function questions_prepare_parent_breadcrumbs($question) { if ($question && $question->parent_guid) { $parents = array(); $parent = get_entity($question->parent_guid); while ($parent) { array_push($parents, $parent); $parent = get_entity($parent->parent_guid); } while ($parents) { $parent = array_pop($parents); if(!elgg_instanceof($parent, 'user')){ elgg_push_breadcrumb($parent->title, $parent->getURL()); } } } } /* * $guid the guid of the object * $vars array(); */ function related_objects_base_on_tags($guid,$limit,$vars = array()){ // set the random related tags $object_tags=elgg_get_metadata(array('guids'=>$guid,'metastring_names'=>'tags')); if ($object_tags) { foreach ($object_tags as $tag) { $tag_list[] .=$tag->value_id; } $random_tag_id = $tag_list[ mt_rand(0, count($tag_list) - 1) ]; $ramtag=get_metastring($random_tag_id); $object=get_entity($guid); $type=$object->getType(); $subtype=$object->getSubtype(); $defaults=array( 'full_view'=>false, 'pagination'=>false, ); $vars = array_merge($defaults, $vars); $limit=$limit+1; $sametag_objects=elgg_get_entities_from_metadata(array( 'metadata_names' => 'tags', 'metadata_values' => $ramtag, 'type' => $type, 'subtype'=>$subtype, 'limit'=>$limit )); // delete the same object form related object result foreach ($sametag_objects as $stp){ $stpguids[] .=$stp->getGUID(); } $srlt=array_search("$guid",$stpguids); array_splice($sametag_objects,$srlt,1); return elgg_view_entity_list($sametag_objects,$vars); } } // question get message by ajax function question_get_messages_by_ajax(){ $guid=get_input('owner_guid'); $num_messages = (int)messages_count_unread(); if ($num_messages != 0) { $list = elgg_list_entities_from_metadata(array( 'type' => 'object', 'subtype' => 'messages', 'metadata_name_value_pairs' => array( 'toId' =>$guid, 'readYet' => 0, ), 'owner_guid' => $guid, 'full_view' => false, 'pagination' => false, 'limit'=>5, )); }else{ $list=elgg_echo('messages:nomessages'); } return $list; } function get_my_questions(){ $title=elgg_echo('question:widget:ask'); $owner=elgg_get_logged_in_user_entity(); $questions=elgg_view_title($title); $questions .=elgg_list_entities(array( 'type' => 'object', 'subtype' => 'question-top', 'limit' => 6, 'owner_guid'=>$owner->guid, 'full_view' => false, 'pagination' => true, 'list_class'=>'question-list brs ', 'item_class'=>'question-item bx ', 'view_toggle_type' => false )); $body=elgg_view_layout('qq_two_column',array('content'=>$questions,'nav'=>'')); $page=elgg_view_page($title,$body); return $page; } function get_questions_answer_by_me(){ $title=elgg_echo('question:widget:answer'); $owner=elgg_get_logged_in_user_entity(); $questions=elgg_view_title($title); $questions .=elgg_list_entities(array( 'type' => 'object', 'subtype' => 'question', 'limit' => 6, 'owner_guid'=>$owner->guid, 'full_view' => false, 'pagination' => true, 'list_class'=>'question-list brs ', 'item_class'=>'question-item bx ', 'view_toggle_type' => false )); $body=elgg_view_layout('qq_two_column',array('content'=>$questions,'nav'=>'')); $page=elgg_view_page($title,$body); return $page; } function get_better_list_based_on_thumbs($guid){ $questions=elgg_get_entities_from_metadata(array( 'type'=>'object', 'subtype'=>'question', 'metadata_name'=>'parent_guid', 'metadata_value'=>$guid, )); foreach ($questions as $object){ $q_guids[].=$object->guid; } if($q_guids){ $question_better_list=elgg_list_entities_from_annotation_calculation(array( 'annotation_names'=>'thumbs', 'guids'=>$q_guids, 'list_class'=>'question-list brs', 'item_class'=>'question-item bx', 'limit'=>5, )); }else{ $question_better_list=''; } return $question_better_list; }
2bbf87c7978cfb5c0904f82d4438ee8795e0f520
[ "Markdown", "PHP" ]
67
PHP
creatorkuang/miifang
670863234806a9c12e7fbdf3562033cf717de0c2
1c8a8c5c8e997c351a8059d842b743b8d841d0dd
refs/heads/master
<repo_name>ForgotPS/WeJump<file_sep>/test.py #encoding=utf-8 import math import numpy as np import h5py import matplotlib.pyplot as plt import scipy from PIL import Image from scipy import ndimage import tensorflow as tf from tensorflow.python.framework import ops from cnn_utils import * dataset = "./dataset/images" yaxis = 0 cost_history,coststep=[],[] IMG_SIZE = 128 print('Placeholder') X = tf.placeholder(tf.float32, [None, IMG_SIZE, IMG_SIZE, 3]) Y = tf.placeholder(tf.float32,[None, ]) print('Import Test.bin') img_batch, label_batch = input_pipeline(["./dataset/test.bin"], 1) print('Import Completed.') trainn, testn, train_label, test_label=loaddata(dataset) m=np.shape(testn)[0] print('Total Sample Number:',m) print('Start Sess') with tf.Session() as sess: init = tf.global_variables_initializer() sess.run(init) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) print('Load Model') saver = tf.train.Saver() saver.restore(sess, tf.train.latest_checkpoint("./model")) W = sess.run(weights) B = sess.run(biases) print('Model load successfully.') for i in range(m): imgs, labels = sess.run([img_batch, label_batch]) y_pred = modeltest(imgs,W,B) cost = tf.reduce_sum(tf.square(y_pred - Y)) testcost = sess.run(cost, feed_dict={X: imgs, Y: labels}) cost_history.append(testcost) yaxis = yaxis + 1 coststep.append(yaxis) plt.plot(coststep, cost_history, label="Cost") plt.xlabel("Iteration") plt.ylabel("Cost") plt.title("Cost Graph") plt.legend() plt.show() # print(sess.run(weights)) # print(sess.run(biases)) # cost = tf.reduce_sum(tf.square(y_pred - Y)) # with tf.Session() as sess: # init = tf.global_variables_initializer() # sess.run(init) # for i in range(m): # sess.run(cost, feed_dict={X: imgs, Y: labels}) # print(i,':',cost) # <file_sep>/cnn_utils.py import math import numpy as np import h5py import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.python.framework import ops import json import os from PIL import Image import random def inm_return_presstime(imagename): train_presstime = json.load(open("./dataset/dataset.json")) presstime = train_presstime[imagename] return presstime def fulltofile(fullnames): filename=fullnames.split("\\")[-1] return filename def loaddata(dataset): fullnames = [os.path.join(dataset, image_file) \ for image_file in os.listdir(dataset)] m=np.shape(fullnames)[0] filenames=[] for i in range(m): filenames.append(fulltofile(fullnames[i])) filenumbers= len(filenames) np.random.shuffle(np.arange(len(filenames))) TRAIN_SEC, TEST_SEC = 0.9, 0.1 trainn, testn = fullnames[: int(filenumbers * TRAIN_SEC)], fullnames[int(filenumbers * TRAIN_SEC) :] # print("Sample : train num is %d, test num is %d" % (len(trainn), len(testn))) train_label,test_label=[],[] for trn in range(len(trainn)): train_label.append(inm_return_presstime(fulltofile(trainn[trn]))) for tst in range(len(testn)): test_label.append(inm_return_presstime(fulltofile(testn[tst]))) return trainn, testn, train_label, test_label # print(train_label) # print(test_label) # print(trainn[0]) # print(testn[0]) def set_button_position(im): global swipe_x1, swipe_y1, swipe_x2, swipe_y2 w, h = im.size print(w,h) left = int(w / 2) top = int(1584 * (h / 1920.0)) left = int(random.uniform(left-50, left+50)) top = int(random.uniform(top-10, top+10)) swipe_x1, swipe_y1, swipe_x2, swipe_y2 = left, top, left, top def resize_img(img_path, shape): ''' resize image given by `image_path` to `shape` ''' im = Image.open(img_path) im = im.resize(shape) im = im.convert('RGB') return im def save_as_tfrecord(samples, labels, bin_path): ''' Save images and labels as TFRecord to file: `bin_path` ''' assert len(samples) == len(labels) writer = tf.python_io.TFRecordWriter(bin_path) img_label = list(zip(samples, labels)) np.random.shuffle(img_label) for img, label in img_label: im = resize_img(img, (128, 128)) im_raw = im.tobytes() example = tf.train.Example(features=tf.train.Features(feature={ "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[label])), 'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[im_raw])) })) writer.write(example.SerializeToString()) writer.close() def resize_imgtf(img_path, shape): ''' resize image given by `image_path` to `shape` ''' image = Image.open(img_path) w, h = image.size top = (h - w) / 2 im = image.crop((0, top, w, w + top)) im = im.convert('RGB') im = im.resize(shape) return im def save_tfrecord(samples, labels, bin_path): ''' Save images and labels as TFRecord to file: `bin_path` ''' assert len(samples) == len(labels) writer = tf.python_io.TFRecordWriter(bin_path) img_label = list(zip(samples, labels)) np.random.shuffle(img_label) for img, label in img_label: im = resize_imgtf(img, (128, 128)) im_raw = im.tobytes() example = tf.train.Example(features=tf.train.Features(feature={ "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[label])), 'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[im_raw])) })) writer.write(example.SerializeToString()) writer.close() def loaddatatf(dataset): fullnames = [os.path.join(dataset, image_file) \ for image_file in os.listdir(dataset)] fullnamestf = tf.constant(fullnames) m=np.shape(fullnames)[0] filenames=[] for i in range(m): filenames.append(fulltofile(fullnames[i])) filenumbers= len(filenames) np.random.shuffle(np.arange(len(filenames))) TRAIN_SEC, TEST_SEC = 0.9, 0.1 trainn, testn = fullnames[: int(filenumbers * TRAIN_SEC)], fullnames[int(filenumbers * TRAIN_SEC) :] # print("Sample : train num is %d, test num is %d" % (len(trainn), len(testn))) train_label,test_label=[],[] for trn in range(len(trainn)): train_label.append(inm_return_presstime(fulltofile(trainn[trn]))) for tst in range(len(testn)): test_label.append(inm_return_presstime(fulltofile(testn[tst]))) trainntf=tf.constant(trainn) testntf = tf.constant(testn) train_labeltf, test_labeltf = tf.constant(train_label), tf.constant(test_label), return fullnames,trainn, testn, train_label, test_label, fullnamestf,trainntf, testntf, train_labeltf, test_labeltf def _parse_function(filename, label): image_string = tf.read_file(filename) image_decoded = tf.image.decode_image(image_string) image_resized = tf.image.resize_images(image_decoded, [128, 128]) return image_resized, label # 获取并初始化权重 def init_weights(shape): return tf.Variable(tf.truncated_normal(shape, stddev=0.1)) def conv2d(x,w,b): x = tf.nn.conv2d(x,w,strides = [1,1,1,1],padding = "SAME") x = tf.nn.bias_add(x,b) return tf.nn.relu(x) def pooling(x): return tf.nn.max_pool(x,ksize = [1,2,2,1],strides = [1,2,2,1],padding = "SAME") #init weights weights = { "w1":init_weights([3,3,3,16]), "w2":init_weights([3,3,16,32]), "w3":init_weights([3,3,32,64]), "w4":init_weights([3,3,64,100]), "w5":init_weights([3,3,100,128]), "w6":init_weights([2048,256]), "w7":init_weights([256,64]), "wo":init_weights([64, 1]) } #init biases biases = { "b1":init_weights([16]), "b2":init_weights([32]), "b3":init_weights([64]), "b4":init_weights([100]), "b5":init_weights([128]), "b6":init_weights([256]), "b7":init_weights([64]), "bo":init_weights([1]) } def model(X, weights, biases): l1a = conv2d(X,weights["w1"],biases["b1"]) l1 = pooling(l1a) l2a = conv2d(l1,weights["w2"],biases["b2"]) l2 = pooling(l2a) l3a = conv2d(l2,weights["w3"],biases["b3"]) l3 = pooling(l3a) l4a = conv2d(l3,weights["w4"],biases["b4"]) l4 = pooling(l4a) l5a = conv2d(l4,weights["w5"],biases["b5"]) l5 = pooling(l5a) l6a = tf.reshape(l5,[-1,weights["w6"].get_shape().as_list()[0]]) l6 = tf.nn.relu(tf.matmul(l6a,weights["w6"])+biases["b6"]) l7a = tf.reshape(l6,[-1,weights["w7"].get_shape().as_list()[0]]) l7 = tf.nn.relu(tf.matmul(l7a,weights["w7"])+biases["b7"]) y_pred = tf.add(tf.matmul(l7, weights["wo"]), biases["bo"]) return y_pred def modeltest(X, weights, biases): l1a = conv2d(X,weights["w1"],biases["b1"]) l1 = pooling(l1a) l2a = conv2d(l1,weights["w2"],biases["b2"]) l2 = pooling(l2a) l3a = conv2d(l2,weights["w3"],biases["b3"]) l3 = pooling(l3a) l4a = conv2d(l3,weights["w4"],biases["b4"]) l4 = pooling(l4a) l5a = conv2d(l4,weights["w5"],biases["b5"]) l5 = pooling(l5a) l6a = tf.reshape(l5,[-1,np.shape(weights["w6"])[0]]) l6 = tf.nn.relu(tf.matmul(l6a,weights["w6"])+biases["b6"]) l7a = tf.reshape(l6,[-1,np.shape(weights["w7"])[0]]) l7 = tf.nn.relu(tf.matmul(l7a,weights["w7"])+biases["b7"]) y_pred = tf.add(tf.matmul(l7, weights["wo"]), biases["bo"]) return y_pred def read_and_decode(filename_queue): reader = tf.TFRecordReader() _, serialized_example = reader.read(filename_queue) #return filename and example features = tf.parse_single_example(serialized_example, features={ 'label': tf.FixedLenFeature([], tf.int64), 'img_raw' : tf.FixedLenFeature([], tf.string), }) img = tf.decode_raw(features['img_raw'], tf.uint8) img = tf.reshape(img, [128, 128, 3]) img = tf.cast(img, tf.float32) * (1. / 255) - 0.5 # normalize label = tf.cast(features['label'], tf.int32) #label = tf.sparse_to_dense(label, [1], 10000, 0) return img, label def input_pipeline(filenames, batch_size, num_epochs=None): filename_queue = tf.train.string_input_producer(filenames, num_epochs=num_epochs, shuffle=True) example, label = read_and_decode(filename_queue) min_after_dequeue = 1 num_threads = 2 capacity = min_after_dequeue + (num_threads + 1) * batch_size example_batch, label_batch = tf.train.shuffle_batch( [example, label], batch_size=batch_size, capacity=capacity, num_threads = num_threads, min_after_dequeue=min_after_dequeue) return example_batch, label_batch <file_sep>/train.py #encoding=utf-8 import math import numpy as np import h5py import matplotlib.pyplot as plt import scipy from PIL import Image from scipy import ndimage import tensorflow as tf from tensorflow.python.framework import ops from cnn_utils import * dataset = "./dataset/images" trainn, testn, train_label, test_label=loaddata(dataset) print(trainn) save_as_tfrecord(trainn, train_label, "./dataset/train.bin") save_as_tfrecord(testn, test_label, "./dataset/test.bin") m=np.shape(trainn)[0] IMG_SIZE = 128 # 图像大小 X = tf.placeholder(tf.float32, [None, IMG_SIZE, IMG_SIZE, 3]) Y = tf.placeholder(tf.float32,[None, ]) #init weights weights = { "w1":init_weights([3,3,3,16]), "w2":init_weights([3,3,16,32]), "w3":init_weights([3,3,32,64]), "w4":init_weights([3,3,64,100]), "w5":init_weights([3,3,100,128]), "w6":init_weights([2048,256]), "w7":init_weights([256,64]), "wo":init_weights([64, 1]) } #init biases biases = { "b1":init_weights([16]), "b2":init_weights([32]), "b3":init_weights([64]), "b4":init_weights([100]), "b5":init_weights([128]), "b6":init_weights([256]), "b7":init_weights([64]), "bo":init_weights([1]) } def model(X, weights, biases): l1a = conv2d(X,weights["w1"],biases["b1"]) l1 = pooling(l1a) l2a = conv2d(l1,weights["w2"],biases["b2"]) l2 = pooling(l2a) l3a = conv2d(l2,weights["w3"],biases["b3"]) l3 = pooling(l3a) l4a = conv2d(l3,weights["w4"],biases["b4"]) l4 = pooling(l4a) l5a = conv2d(l4,weights["w5"],biases["b5"]) l5 = pooling(l5a) l6a = tf.reshape(l5,[-1,weights["w6"].get_shape().as_list()[0]]) l6 = tf.nn.relu(tf.matmul(l6a,weights["w6"])+biases["b6"]) l7a = tf.reshape(l6,[-1,weights["w7"].get_shape().as_list()[0]]) l7 = tf.nn.relu(tf.matmul(l7a,weights["w7"])+biases["b7"]) y_pred = tf.add(tf.matmul(l7, weights["wo"]), biases["bo"]) return y_pred # y_pred是预测tensor y_pred = model(X, weights, biases) # 定义损失函数 cost=tf.reduce_sum(tf.square(y_pred - Y)) train_op = tf.train.AdamOptimizer(learning_rate=0.001, beta1=0.9, beta2=0.999, epsilon=1e-08, use_locking=False, name='Adam').minimize(cost) # 获取batch。注意这里是tensor,需要运行 img_batch, label_batch = input_pipeline(["./dataset/train.bin"], 1) iteration = 200 disp_step = 100 idisp_step=1000 save_step = 100 max_step = 200 cost_history=[] step = 0 coststep = [] saver = tf.train.Saver() yaxis=0 with tf.Session() as sess: init = tf.global_variables_initializer() sess.run(init) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) try: # 获取训练数据成功,并且没有到达最大训练次数 while not coord.should_stop() and step < max_step: step += 1 # 运行tensor,获取数据 for i in range(m): imgs, labels = sess.run([img_batch, label_batch]) sess.run(train_op, feed_dict={X: imgs, Y: labels}) cost_history.append(sess.run(cost, feed_dict={X: imgs,Y: labels})) yaxis=yaxis+1 coststep.append(yaxis) if i % idisp_step == 0: cos = sess.run(cost, feed_dict={X: imgs,Y: labels}) print('Epoch:',step ,'Sample %s cost is %.2f' % (i, cos)) # if step % disp_step == 0: # cos = sess.run(cost, feed_dict={X: imgs,Y: labels}) # print('%s cost is %.2f' % (step, cos)) if step % save_step == 0: # 保存当前模型 save_path = saver.save(sess, './model/wejump.ckpt', global_step=step) print("save graph to %s" % save_path) except tf.errors.OutOfRangeError: print("reach epoch limit") finally: coord.request_stop() coord.join(threads) save_path = saver.save(sess, './model/wejump.ckpt', global_step=step) plt.plot(coststep, cost_history, label="Cost") plt.xlabel("Iteration") plt.ylabel("Cost") plt.title("Cost Graph") plt.legend() plt.show() <file_sep>/README.md # WeJump WeChat Jump 使用Python+Tensorflow所写 非科班出身,代码很乱 刷分的就别用了,最多打到50分左右 禁止商用 致谢: 1.辅助程序:https://github.com/wangshub/wechat_jump_game 2.训练样本:https://zhuanlan.zhihu.com/p/32819519 <file_sep>/wejump_an.py #encoding=utf-8 # coding: utf-8 import os import sys import subprocess import time import random from PIL import Image import tensorflow as tf from tensorflow.python.framework import ops from common import screenshot, debug from cnn_utils import * SCALE = 1.02 def set_button_position(im): global swipe_x1, swipe_y1, swipe_x2, swipe_y2 w, h = im.size print(w,h) left = int(w / 2) top = int(1584 * (h / 1920.0)) left = int(random.uniform(left-50, left+50)) top = int(random.uniform(top-10, top+10)) swipe_x1, swipe_y1, swipe_x2, swipe_y2 = left, top, left, top def jump(press_time, SCALE): press_time = int(press_time*SCALE) cmd = 'adb shell input swipe {x1} {y1} {x2} {y2} {duration}'.format( x1=swipe_x1, y1=swipe_y1, x2=swipe_x2, y2=swipe_y2, duration=press_time ) os.system(cmd) def main(): debug.dump_device_info() screenshot.check_screenshot() label=[0] while True: screenshot.pull_screenshot() image = Image.open('./temp.png') set_button_position(image) tempimage=['.\\temp.png'] save_tfrecord(tempimage, label, "./temp/temp.bin") img_batch, label_batch = input_pipeline(["./temp/temp.bin"], 1) with tf.Session() as sess: coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) saver = tf.train.Saver() saver.restore(sess, ("./model/wejump.ckpt-2000")) W = sess.run(weights) B = sess.run(biases) imgs, labels = sess.run([img_batch, label_batch]) press_time = tf.Session().run(modeltest(imgs,W,B))[0][0] print('Presstime:',press_time) jump(press_time, SCALE) time.sleep(random.uniform(2, 2.5)) if __name__ == '__main__': main()
0026ebbb4a8ffbf40e17a88cb3d144c52eaf730f
[ "Markdown", "Python" ]
5
Python
ForgotPS/WeJump
8e9b2d74050d60d601169a18ebc1ca2acf9be05c
21cd7e9c71649889b502a97b5cf1c58705eea7a3
refs/heads/master
<file_sep>import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { NgModule } from '@angular/core'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { AppComponent } from './app.component'; import { ComboBoxComponent } from './combo-box/combo-box.component'; import { DropdownDirective, DropdownMenuDirective, DropdownToggleDirective, DropdownAnchorDirective } from './dropdown/dropdown.directive'; import { DropdownConfig } from './dropdown/dropdown-config'; import { MultiComboBoxComponent } from './mutli-combo-box/multi-combo-box.component'; import { BoxComponent } from './box/box.component'; import { Ng2SearchPipeModule } from 'ng2-search-filter'; @NgModule({ declarations: [ AppComponent, ComboBoxComponent, DropdownDirective, DropdownMenuDirective, DropdownToggleDirective, DropdownAnchorDirective, MultiComboBoxComponent, BoxComponent ], imports: [ BrowserModule, Ng2SearchPipeModule, NgbModule, FormsModule ], providers: [ DropdownConfig ], bootstrap: [AppComponent] }) export class AppModule { }
c96a0c680c33eb9a44aebf447cc48168e64366c2
[ "TypeScript" ]
1
TypeScript
chanzer0/angular-resources
2875ddc5b47bf0e8ea357d1d9b00d931a515d469
96962633bf930170df55216c8434bb74c3d155eb
refs/heads/master
<repo_name>subtleGradient/ruby.tmbundle<file_sep>/Test/here_docs.rb # If you change anything, be sure to verify Ruby syntax # TODO: unresolved issues # # text: # "p << end # print me! # end" # symptoms: # not recognized as a heredoc # solution: # there is no way to distinguish perfectly between the << operator and the start # of a heredoc. Currently, we require assignment to recognize a heredoc. More # refinement is possible. # • Heredocs with indented terminators (<<-) are always distinguishable, however. # • Nested heredocs are not really supportable at present # # text: print <<-'THERE' This is single quoted. The above used #{Time.now} THERE # symtoms: # From Programming Ruby p306; should be a non-interpolated heredoc. # INTERPOLATED HEREDOC p heredoc1 = <<heredoc1 normal text #{ "embedded source" } escaped characters \n\t\a\''\""\\ heredoc1 # >> "normal text embedded source escaped characters \n\t\a''\"\"\\\n" p heredoc1_1 = <<-heredoc1_1 normal text #{ "embedded source" } escaped characters \n\t\a\''\""\\ heredoc1_1 # >> "normal text embedded source escaped characters \n\t\a''\"\"\\\n" p heredoc3 = <<"heredoc 3" normal text #{ "embedded source" } escaped characters \n\t\a\''\""\\ heredoc 3 # >> "normal text embedded source escaped characters \n\t\a''\"\"\\\n" p heredoc3_1 = <<-"heredoc 3.1" normal text #{ "embedded source" } escaped characters \n\t\a\''\""\\ heredoc 3.1 # >> "normal text embedded source escaped characters \n\t\a''\"\"\\\n" # NON-INTERPOLATED HEREDOC p heredoc2 = <<'heredoc2' normal text #{ "embedded source" } escaped characters \n\t\a\''\""\\ heredoc2 # >> "normal text \#{ \"embedded source\" } escaped characters \\n\\t\\a\\''\\\"\"\\\\\n" p heredoc2_1 = <<-'heredoc 2.1' normal text #{ "embedded source" } escaped characters \n\t\a\''\""\\ heredoc 2.1 # >> "normal text \#{ \"embedded source\" } escaped characters \\n\\t\\a\\''\\\"\"\\\\\n" # BUGS # Trailing space p heredoc1 = <<heredoc1 heredoc1 heredoc1 p heredoc1_1 = <<-heredoc1_1 heredoc1_1 heredoc1_1 p heredoc3 = <<"heredoc 3" heredoc 3 heredoc 3 p heredoc3_1 = <<-"heredoc 3.1" heredoc 3.1 heredoc 3.1 p heredoc2 = <<'heredoc2' heredoc2 heredoc2 p heredoc2_1 = <<-'heredoc 2.1' heredoc 2.1 heredoc 2.1 # >> "heredoc1 \n" # >> " heredoc1_1 \n" # >> "heredoc 3 \n" # >> " heredoc 3.1 \n" # >> "heredoc2 \n" # >> " heredoc 2.1 \n" # shouldn't end the heredoc, has "x" before heredoc end p heredoc1 = <<heredoc1 xheredoc1 heredoc1 p heredoc1_1 = <<-heredoc1_1 xheredoc1_1 heredoc1_1 p heredoc3 = <<"heredoc 3" xheredoc 3 heredoc 3 p heredoc3_1 = <<-"heredoc 3.1" xheredoc 3.1 heredoc 3.1 p heredoc2 = <<'heredoc2' xheredoc2 heredoc2 p heredoc2_1 = <<-'heredoc 2.1' xheredoc 2.1 heredoc 2.1 # >> "xheredoc1\n" # >> "xheredoc1_1\n" # >> "xheredoc 3\n" # >> "xheredoc 3.1\n" # >> "xheredoc2\n" # >> "xheredoc 2.1\n" # ========================================== # = Stuff after the heredoc starting thing = # ========================================== # Real world example # From http://eigenclass.org/hiki/ruby+weird+syntax a, b, c = <<E1.chomp, 3, <<E2.split(/\n/).join(" - ") hello world E1 a b c E2 p [a,b,c] # >> ["hello world", 3, "a - b - c"] a, b, c = <<-E1.chomp hello world E1 p [a,b,c] # >> ["hello world", nil, nil] a, b, c = <<-E1.chomp, 3, <<-E2.split(/\n/).join(" - ") hello world E1 a b c E2 p [a,b,c] # >> ["hello world", 3, "a - b - c"] a, b, c = <<-E1, <<-E2, <<-E3 hello world E1 abc E2 123 E3 p [a,b,c] # >> [" hello world\n", " abc\n", " 123\n"] # stuff on same line should be scoped # heredoc contents shouldn't be scoped p <<-heredoc1_1, "fred", 123.0, /regex/ p <<-heredoc1_1, "fred", 123.0, /regex/ heredoc1_1 heredoc1_1 # >> "p <<-heredoc1_1, \"fred\", 123.0, /regex/\n" # >> "fred" # >> 123.0 # >> /regex/
668fd389b98cc65b6766293f69b5ecae0a29cad4
[ "Ruby" ]
1
Ruby
subtleGradient/ruby.tmbundle
6628c8cbcc06a44dbfe3144e889a3a86a5c2e6ea
b1d1584de0ea95e9e13f0abbaa74dc880c83df21
refs/heads/master
<repo_name>shanebarringer/zacks_pizza<file_sep>/app/controllers/home.rb def home end
dfc34287e01b751f2f3a15b9cb14109f94669e7a
[ "Ruby" ]
1
Ruby
shanebarringer/zacks_pizza
a7ce5e2fd13cf8837cdc40311e1936a19bddf817
db2022221a234d6dc899602506a68a5fca58bbd6
refs/heads/master
<repo_name>amandinedaigle/matrice-competence<file_sep>/src/Amandine/MatriceCompetenceBundle/Form/Type/CompetenceType.php <?php namespace Amandine\MatriceCompetenceBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilder; class ComptenceType extends AbstractType{ public function buildForm(FormBuilder $builder,array $options){ $builder->add('intitule'); } public function getDefaultOptions(array $options) { return array( 'data_class' => 'Amandine\MatriceCompetencekBundle\Entity\Competence', ); } public function getName() { return 'Competence'; } } <file_sep>/src/Amandine/MatriceCompetenceBundle/Entity/CategorieCompetence.php <?php namespace Amandine\MatriceCompetenceBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="categorie_competence") */ class CategorieCompetence { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id_categorie; /** * @ORM\Column(type="string") */ protected $intitule; /** * Get id_categorie * * @return integer */ public function getIdCategorie() { return $this->id_categorie; } /** * Set intitule * * @param \varchar $intitule * @return CategorieCompetence */ public function setIntitule($intitule) { $this->intitule = $intitule; return $this; } /** * Get intitule * * @return \varchar */ public function getIntitule() { return $this->intitule; } } <file_sep>/src/Amandine/MatriceCompetenceBundle/AmandineMatriceCompetenceBundle.php <?php namespace Amandine\MatriceCompetenceBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class AmandineMatriceCompetenceBundle extends Bundle { } <file_sep>/src/Amandine/MatriceCompetenceBundle/Entity/Competence.php <?php namespace Amandine\MatriceCompetenceBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="competence") */ class Competence { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id_competence; /** * @ORM\Column(type="string") */ protected $intitule; /** * Get id_competence * * @return integer */ public function getIdCompetence() { return $this->id_competence; } /** * Set intitule * * @param \varchar $intitule * @return Competence */ public function setIntitule($intitule) { $this->intitule = $intitule; return $this; } /** * Get intitule * * @return \varchar */ public function getIntitule() { return $this->intitule; } } <file_sep>/src/Amandine/MatriceCompetenceBundle/Entity/Personnel.php <?php namespace Amandine\MatriceCompetenceBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="Personnel") */ class Personnel { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id_personnel; /** * @ORM\Column(type="string") */ protected $identifiant; /** * Get id_personnel * * @return integer */ public function getIdPersonnel() { return $this->id_personnel; } /** * Set identifiant * * @param \varchar $identifiant * @return Personnel */ public function setIdentifiant(\varchar $identifiant) { $this->identifiant = $identifiant; return $this; } /** * Get identifiant * * @return \varchar */ public function getIdentifiant() { return $this->identifiant; } } <file_sep>/src/Amandine/MatriceCompetenceBundle/Controller/DefaultController.php <?php namespace Amandine\MatriceCompetenceBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\SecurityContext; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; use Amandine\MatriceCompetenceBundle\Entity\Competence; use Amandine\MatriceCompetenceBundle\Form\Type\ComptenceType; /** * @Route("/inde", name="_listecompetence") * @Template() */ class DefaultController extends Controller { /** * @Route("/liste", name="_listecompetence") * @Template() */ public function indexAction() { /* recuperation de la liste de l'ensemble des competences de tout le monde */ $listeCompetence = $this->getDoctrine() ->getRepository('AmandineMatriceCompetenceBundle:Competence') ->findAll(); if (!$listeCompetence) { throw $this->createNotFoundException( 'Aucune competence listé pour l\'instant' ); }else{ print_r($listeCompetence); } /*$listeCompetence[0]['identifiant'] = 'Toto'; $listeCompetence[0]['cat_competence'] = 'Ressources Humaines'; $listeCompetence[0]['competence'] = 'Ecoute';*/ return $this->render('AmandineMatriceCompetenceBundle:Default:index.html.twig', array('liste_competence' => $listeCompetence)); } /** * @Route("/add_form", name="addForm") * @Template("AmandineMatriceCompetenceBundle:Default:formCompetence.html.twig") */ public function addFormAction(){ // creation du formulaire d'ajout de competence $competence = new Competence(); $competence->setIntitule('Langues'); $form = $this->createFormBuilder($competence) ->add('intitule', 'text') ->getForm(); return array('form' => $form->createView()); } /** * @Route("/add", name="_add") * @Template("AmandineMatriceCompetenceBundle:Default:formCompetence.html.twig") */ public function addAction(){ $request = $this->get('request'); $competence = new Competence(); $form = $this->get('form.factory')->create(new CompetenceType(), $competence); // recupération des données du formulaire envoyé if ('POST' === $request->getMethod()) { $form->bindRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($competence); $em->flush(); return $this->redirect($this->generateUrl('_listecompetence')); }else{ return new Response('formulaire non valide'); } }else{ return new Response('Données non envoyées '); } } /** * @Route("/edit/{competenceId}", name="_editcompetence") * @Template("AmandineMatriceCompetenceBundle:Default:formCompetence.html.twig") */ public function editAction($competenceId){ /* modification d'une compétence */ return new Response('Id de la compétence créé : '.$competence->getId()); } /** * @Route("/update", name="_majcompetence") * @Template() */ public function UpdateAction($competence,$cat_competence){ } /** * @Route("/del", name="_deletecompetence") * @Template() */ public function RemoveAction($competence){ } /** * @Route("/login", name="_login") * @Template() */ public function loginAction(Request $request) { echo 'hop'; die(); if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) { $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR); } else { $error = $request->getSession()->get(SecurityContext::AUTHENTICATION_ERROR); } return array( 'last_username' => $request->getSession()->get(SecurityContext::LAST_USERNAME), 'error' => $error, ); } /** * @Route("/login_check", name="_security_check") */ public function securityCheckAction() { // The security layer will intercept this request } /** * @Route("/logout", name="_demo_logout") */ public function logoutAction() { // The security layer will intercept this request } }
5ae713a07201298e8c34108264369e47bd420c33
[ "PHP" ]
6
PHP
amandinedaigle/matrice-competence
4d83e505aad539b60a8faba33110b384ca8318cd
45bf8033eb2e80d6b74ac3d31614dc89aa8081cc
refs/heads/master
<repo_name>stahlleiton/EWKAnalysis2020<file_sep>/Skim/HiForest/skimTree.C #include "skimTree.h" void skimTree(const std::string& type="muon") { const std::string inDir = "";//"/eos/cms/store/group/phys_heavyions/anstahll/"; const std::vector<std::string> inFiles = {inDir+"HiForestAOD_1192.root"}; // prepare multi-threading const int nCores = inFiles.size(); ROOT::EnableImplicitMT(); ROOT::TProcessExecutor mpe(nCores); TH1::AddDirectory(kFALSE); auto fillTree = [=](int idx) { auto c_start = std::clock(); const auto& inFile = inFiles[idx]; const auto& pTag = type; // define variables double lepEta, lepIso; TLorentzVector met, metNoHF, metChg, metChgPtMin4, lepP4T; int lepId, lepCharge, evtID, cent; // define tree TTree* t = new TTree("AnaTree", "AnaTree"); auto& tree = *t; tree.Branch("lepP4T",&lepP4T); tree.Branch("lepEta",&lepEta,"lepEta/D"); tree.Branch("lepCharge",&lepCharge,"lepCharge/I"); tree.Branch("lepIso",&lepIso,"lepIso/D"); tree.Branch("met",&met); tree.Branch("metNoHF",&metNoHF); tree.Branch("metChg",&metChg); tree.Branch("metChgPtMin4",&metChgPtMin4); tree.Branch("evtID",&evtID,"evtID/i"); tree.Branch("cent",&cent,"cent/i"); // get offline RecoReader recoInfo(inFile); // get online information TriggerReader triggerInfo(inFile); // add trigger path to trigger reader const std::string path = (pTag=="muon" ? "HLT_HIL3Mu12_v1" : "HLT_HIEle20Gsf_v1"); triggerInfo.addTrigger(path); // initialize offline information recoInfo.initBranches(pTag); // fill tree const auto nEntries = recoInfo.getEntries(); for (auto iEntry : ROOT::TSeqUL(nEntries)) { if ((iEntry%100000)==0) { std::cout << "[INFO] Core " << idx << ": Processing event " << iEntry << " / " << nEntries << std::endl; } recoInfo.setEntry(iEntry, false, true); triggerInfo.setEntry(iEntry, false, true); // check that event pass event selection if (!recoInfo.passEventSelection()) continue; // initialize variables lepPt=0; lepEta=0; lepPhi=0; lepIso=0; met=TVector2(); metNoHF=TVector2(); metChg=TVector2(); metChgPtMin4=TVector2(); lepId=0; lepCharge=0; evtID=0; cent=0; // extract candidate auto candidate = recoInfo.getCandidate(pTag); if (candidate.p4().Pt()<=25.) continue; // check trigger decision if (!triggerInfo.passTrigger(path)) continue; // check if trigger matched const auto isMatched = (pTag=="muon" ? triggerInfo.isTriggerMatched(candidate.p4(), path) : true); if (!isMatched) continue; // check if QCD event if (candidate.iso() >= (pTag=="muon" ? -0.060000 : 0.080000)) { candidate.setEvtID(2); } // fill tree lepP4T.SetPtEtaPhiM(candidate.p4().Pt(), 0.0, candidate.p4().Phi(), candidate.p4().M()); lepEta = candidate.p4().Eta(); lepCharge = candidate.charge(); lepIso = candidate.iso(); met = candidate.met().at("Full"); metNoHF = candidate.met().at("NoHF"); metChg = candidate.met().at("Chg"); metChgPtMin4 = candidate.met().at("ChgPtMin4"); evtID = candidate.evtID(); cent = candidate.cent(); tree.Fill(); } return t; }; const auto& trees = mpe.Map(fillTree, ROOT::TSeqI(nCores)); TFile ft(Form("output_%s.root", type.c_str()),"RECREATE"); TList list; for (const auto& tree : trees) { list.Add(tree); } TTree *newtree = TTree::MergeTrees(&list); newtree->SetName("AnaTree"); newtree->Write("AnaTree", 2); ft.Close(); } <file_sep>/Skim/HiForest/skimTree.h #ifndef skimTree_h #define skimTree_h #include <TROOT.h> #include <TSystem.h> #include <TFile.h> #include <TH1.h> #include <TEfficiency.h> #include <TTreeReader.h> #include <TTreeReaderValue.h> #include <TTreeReaderArray.h> #include <TLorentzVector.h> #include <TGraphAsymmErrors.h> #include <TCanvas.h> #include <TPad.h> #include <TAxis.h> #include <TLine.h> #include <TLegend.h> #include <TLegendEntry.h> #include <ROOT/TProcessExecutor.hxx> #include <ROOT/TSeq.hxx> #include <iostream> #include <map> #include <set> #include <vector> #include <string> #include <dirent.h> #include <memory> class TreeReaderBase { public: TreeReaderBase(){}; TreeReaderBase(const std::string& path) { setFile(path); }; ~TreeReaderBase() { if (file_ && file_->IsOpen()) file_->Close(); }; // getters Long64_t getEntries() const { if (reader_.empty()) { return 0; } return reader_.begin()->second->GetEntries(false); }; // setters void setFile(const std::string& path) { file_.reset(TFile::Open(path.c_str(), "READ")); if (!file_->IsOpen() || file_->IsZombie()) { throw std::runtime_error("[ERROR] File "+path+" failed to open!"); } }; void setEntry(const Long64_t& i, const bool& checkValue, const bool& onDemand) { if (i<0) { throw std::runtime_error(Form("[ERROR] Invalid index: %lld", i)); } onDemand_ = onDemand; index_ = i; checkValue_ = checkValue; if (!onDemand_) { for (const auto& r : reader_) { loadEntry(r.first); } } }; protected: void checkValue(ROOT::Internal::TTreeReaderValueBase* value) const { if (value==NULL) { throw std::runtime_error("[ERROR] Value pointer is null"); } else if (value->GetSetupStatus() < 0) { throw std::runtime_error(Form("[ERROR] Status %d when setting up reader for %s", value->GetSetupStatus(), value->GetBranchName())); } }; virtual void checkValues(const std::string& tree) const { std::cout << tree << std::endl; }; void setTreeReader(const std::string& name, const std::string& dir) { if (reader_.find(name)!=reader_.end() || !file_) return; reader_[name].reset(new TTreeReader(dir.c_str(), file_.get())); if (!reader_.at(name)->GetTree()) { throw std::runtime_error("[ERROR] Failed to open "+dir+" !"); } currentEntry_[name] = -1; }; void loadTreeEntry(TTreeReader* r) const { if (!r) return; const auto status = r->SetEntry(index_); if (status!=TTreeReader::kEntryValid) { std::string msg = ""; if (status==TTreeReader::kEntryNotLoaded) { msg = "no entry has been loaded yet"; } else if (status==TTreeReader::kEntryNoTree) { msg = "the tree does not exist"; } else if (status==TTreeReader::kEntryNotFound) { msg = "the tree entry number does not exist"; } else if (status==TTreeReader::kEntryChainSetupError) { msg = "problem in accessing a chain element, e.g. file without the tree"; } else if (status==TTreeReader::kEntryChainFileError) { msg = "problem in opening a chain's file"; } else if (status==TTreeReader::kEntryDictionaryError) { msg = "problem reading dictionary info from tree"; } //else if (status==TTreeReader::kEntryLast) { msg = "last entry was reached"; } throw std::runtime_error("[ERROR] Invalid entry: "+msg); } }; void loadEntry(const std::string& tree) const { if (index_!=currentEntry_.at(tree)) { loadTreeEntry(reader_.at(tree).get()); if (checkValue_) { checkValues(tree); } const_cast<std::map<std::string, Long64_t >* >(&currentEntry_)->at(tree) = index_; } }; std::unique_ptr<TFile> file_; std::map<std::string, std::unique_ptr<TTreeReader> > reader_; bool checkValue_, onDemand_; Long64_t index_; std::map<std::string, Long64_t > currentEntry_; }; class TriggerReader : public TreeReaderBase { public: TriggerReader(const std::string& path) { setFile(path); setTreeReader("HltTree", "hltanalysis/HltTree"); evtI_["runN"].reset(new TTreeReaderValue<int>(*reader_.at("HltTree"), "Run")); evtUL_["eventN"].reset(new TTreeReaderValue<ULong64_t>(*reader_.at("HltTree"), "Event")); }; // getters std::pair<Long64_t, Long64_t> getEventNumber() const { if (onDemand_) { loadEntry("HltTree"); } if (evtUL_.find("eventN")==evtUL_.end()) { return {0, 0}; } return {*evtI_.at("runN")->Get(), *evtUL_.at("eventN")->Get()}; }; bool passTrigger(const std::string& path) const { // set entry on demand for HltTree if (onDemand_) { loadEntry("HltTree"); } return *evtI_.at(path)->Get(); }; bool isTriggerMatched(const TLorentzVector& p4, const std::string& path) const { // set entry on demand for TriggerObject if (onDemand_) { loadEntry(path); } // define delta R threshold const auto dR = (path.rfind("HLT_HIL3",0)==0 ? 0.1 : 0.3); const auto dPt = (path.rfind("HLT_HIL1",0)==0 ? 2.0 : 10.0); // check trigger objects bool isMatch = false; for (size_t i=0; i<obj_.at(path).at("eta")->Get()->size(); i++) { // compare object momenta TLorentzVector trigP4; trigP4.SetPtEtaPhiM(obj_.at(path).at("pt")->Get()->at(i), obj_.at(path).at("eta")->Get()->at(i), obj_.at(path).at("phi")->Get()->at(i), p4.M()); isMatch = (path.rfind("HLT_HIL1",0)==0 ? std::abs(trigP4.Eta()-p4.Eta()) < 0.2 : trigP4.DeltaR(p4) < dR) && std::abs(trigP4.Pt()-p4.Pt())/p4.Pt() < dPt; if (isMatch) break; } return isMatch; }; // setters void addTrigger(const std::string& name) { if (name.rfind("HLT_",0)!=0) { throw std::runtime_error("[ERROR] Invalid trigger name "+name+" !"); } if (evtI_.find(name)!=evtI_.end()) return; const auto nm = name.substr(0,name.rfind("_v")+2); setTreeReader(name, "hltobject/"+nm); evtI_[name].reset(new TTreeReaderValue<int>(*reader_.at("HltTree"), name.c_str())); for (const auto& var : {"pt", "eta", "phi"}) { obj_[name][var].reset(new TTreeReaderValue<std::vector<double> >(*reader_.at(name), var)); } }; using TreeReaderBase::setEntry; bool setEntry(const std::pair<Long64_t, Long64_t>& evtN, const bool& checkValue=true, const bool& onDemand=true) { const auto index = reader_.at("HltTree")->GetTree()->GetEntryNumberWithIndex(evtN.first, evtN.second); if (index<0) { return false; } setEntry(index, checkValue, onDemand); return true; }; private: void checkValues(const std::string& tree) const { if (tree=="HltTree") { for (const auto& r : evtI_ ) { checkValue(r.second.get()); } for (const auto& r : evtUL_) { checkValue(r.second.get()); } } else if (obj_.find(tree)!=obj_.end()) { for (const auto& o : obj_.at(tree)) { checkValue(o.second.get()); } } }; std::map<std::string, std::unique_ptr<TTreeReaderValue<int> > > evtI_; std::map<std::string, std::unique_ptr<TTreeReaderValue<ULong64_t> > > evtUL_; std::map<std::string, std::map<std::string, std::unique_ptr<TTreeReaderValue<std::vector<double> > > > > obj_; }; class RecoReader : public TreeReaderBase { public: RecoReader(const std::string& path) { setFile(path); setTreeReader("ggHiNtuplizerGED", "ggHiNtuplizerGED/EventTree"); setTreeReader("skimanalysis", "skimanalysis/HltTree"); setTreeReader("hiEvtAnalyzer", "hiEvtAnalyzer/HiTree"); setTreeReader("pfcandAnalyzer", "pfcandAnalyzer/pfTree"); setTreeReader("hiFJRhoAnalyzerFinerBins", "hiFJRhoAnalyzerFinerBins/t"); initEventInfo(); initPF(); initRho(); }; typedef std::map<std::string, TLorentzVector> metMap; class Candidate { public: Candidate() {}; ~Candidate() {}; typedef TLorentzVector vector; // getters vector p4 () const { return p4_; }; int charge () const { return charge_; }; double iso () const { return iso_; }; int cent () const { return cent_; }; int evtID () const { return evtId_; }; metMap met () const { return metM_; }; // setters void setP4 (const vector& p4) { p4_ = p4; }; void setCharge(const int& chg) { charge_ = chg; }; void setIso (const double& iso) { iso_ = iso; }; void setCent (const int& cnt) { cent_ = cnt; }; void setEvtID (const int& evtId) { evtId_ = evtId; }; void setMET (const metMap& metM) { metM_ = metM; }; private: vector p4_; int charge_; double iso_; int cent_; int evtId_; metMap metM_; }; struct orderByPt { inline bool operator() (const Candidate& i, const Candidate& j) { return (i.p4().Pt() > j.p4().Pt()); } }; typedef std::vector<Candidate> CandidateCollection; // getters Candidate getCandidate(const std::string& type) const { if (onDemand_) { loadEntry("ggHiNtuplizerGED"); } if (getSize(type)==0) return Candidate(); // loop over leptons CandidateCollection candidates; for (size_t i=0; i<getSize(type); i++) { if (passParticleCut(type, i)) { candidates.push_back(Candidate()); const auto& lepChg = (type=="muon" ? objI_.at("muCharge")->Get()->at(i) : objI_.at("eleCharge")->Get()->at(i)); candidates.back().setCharge(lepChg); candidates.back().setP4(getP4(type, i)); candidates.back().setIso(getIso(type, i)); } } if (candidates.empty()) return Candidate(); std::sort(candidates.begin(), candidates.end(), orderByPt()); auto& candidate = *candidates.begin(); if (candidate.p4().Pt()<25.) return Candidate(); // extract MET const auto metM = getMET(); // extract event info const auto cent = getCentrality(); int evtID = 0; if (evtID==0 && candidates.size()>1 && std::next(candidates.begin(), 1)->p4().Pt()>15) { evtID = 1; } // Drell-Yan for (size_t i1=0; i1<candidates.size(); i1++) { for (size_t i2=i1+1; i2<candidates.size(); i2++) { const auto& cand1 = candidates[i1]; const auto& cand2 = candidates[i2]; if (cand1.charge()==cand.2.charge()) continue; const auto mass = (cand1.p4()+cand2.p4()).M(); if (mass>70. && mass<110.) { evtID = 3; break; } } if (evtID==3) break; } // add information candidate.setMET(metM); candidate.setCent(cent); candidate.setEvtID(evtID); // return candidate return candidate; }; bool passEventSelection() const { if (onDemand_) { loadEntry("skimanalysis"); } return *skimI_.at("evtSel")->Get(); }; int getCentrality() const { if (onDemand_) { loadEntry("hiEvtAnalyzer"); } return *evtI_.at("hiBin")->Get(); }; // setters void initBranches(const std::string& type) { if (type=="electron") { initElectron(); } else if (type=="muon" ) { initMuon(); } }; private: void checkValues(const std::string& tree) const { if (tree=="ggHiNtuplizerGED") { for (const auto& o : objI_) { checkValue(o.second.get()); } for (const auto& o : objF_) { checkValue(o.second.get()); } } else if (tree=="hiEvtAnalyzer") { for (const auto& o : evtI_ ) { checkValue(o.second.get()); } for (const auto& o : evtUI_) { checkValue(o.second.get()); } for (const auto& o : evtUL_) { checkValue(o.second.get()); } } else if (tree=="skimanalysis") { for (const auto& o : skimI_ ) { checkValue(o.second.get()); } } else if (tree=="pfcandAnalyzer") { for (const auto& o : objI_) { checkValue(o.second.get()); } for (const auto& o : objF_) { checkValue(o.second.get()); } } else if (tree=="hiFJRhoAnalyzerFinerBins") { for (const auto& o : objD_) { checkValue(o.second.get()); } } }; size_t getSize(const std::string& type) const { if (type=="electron") { return (objF_.find("elePt")!=objF_.end() ? objF_.at("elePt")->Get()->size() : 0); } else if (type=="muon" ) { return (objF_.find("muPt" )!=objF_.end() ? objF_.at("muPt" )->Get()->size() : 0); } return 0; }; TLorentzVector getP4(const std::string& type, const size_t& i) const { TLorentzVector p4; if (getSize(type)==0) { return p4; } else if (type=="electron") { p4.SetPtEtaPhiM(objF_.at("elePt")->Get()->at(i), objF_.at("eleSCEta")->Get()->at(i), objF_.at("eleSCPhi")->Get()->at(i), 0.000511); } else if (type=="muon" ) { p4.SetPtEtaPhiM(objF_.at("muPt" )->Get()->at(i), objF_.at("muEta" )->Get()->at(i), objF_.at("muPhi" )->Get()->at(i), 0.10565837); } return p4; }; double getUE(const double& rho, const double& rho0, const double& a, const double& b, const double& c, const double& d, const double& e) const { const auto logRho0 = std::log(rho0); const double f = (a*rho0*rho0 + b*rho0 + c) - (d*logRho0*logRho0 + e*logRho0); const auto logRho = std::log(rho); return (rho <= rho0 ? a*rho*rho + b*rho + c : d*logRho*logRho + e*logRho + f); }; double getUE(const double& rho, const std::string& type, const double& coneSize=0.2) const { if (type=="electron" && coneSize==0.3) { return getUE(rho, 119.996446, 0.000941, 0.235722, 2.665041, 54.666635, -466.732790); } else if (type=="electron" && coneSize==0.2) { return getUE(rho, 94.772523, 0.000452, 0.101356, 2.222826, 11.076515, -87.827324); } else if (type=="muon" && coneSize==0.3) { return getUE(rho, 108.767334, 0.002178, 0.054611, 7.039144, 0.000000, 68.794928); } else if (type=="muon" && coneSize==0.2) { return getUE(rho, 120.000000, 0.001890, -0.016016, 5.744579, 0.000000, 39.198389); } throw std::logic_error(Form("Wrong inputs for UE: %s, %g", type.c_str(), coneSize)); return 0; }; double getIso(const std::string& type, const size_t& i, const double& coneSize=0.2, const double& vetoArea=0.015, const double& pTMin=0.5) const { // set entry on demand if (onDemand_) { loadEntry("pfcandAnalyzer"); } if (onDemand_) { loadEntry("hiFJRhoAnalyzerFinerBins"); } // get lepton kinematics const auto lepP4 = getP4(type, i); // loop over PF particles double sumPt = 0.0; for (size_t iPF=0; iPF<objF_.at("pfPt")->Get()->size(); iPF++) { const auto& pfPt = objF_.at("pfPt" )->Get()->at(iPF); if (pfPt < pTMin) continue; const auto& pfEta = objF_.at("pfEta")->Get()->at(iPF); const auto& pfPhi = objF_.at("pfPhi")->Get()->at(iPF); TLorentzVector pfP4; pfP4.SetPtEtaPhiM(pfPt, pfEta, pfPhi, 0); double deltaR = pfP4.DeltaR(lepP4); if ( (deltaR < coneSize) && (deltaR >= vetoArea) ) { sumPt += pfPt; } } // compute underlying event correction (rho-based) double rho = -1.; for (size_t iRho=0; iRho<objD_.at("etaMin")->Get()->size(); iRho++) { const auto& rhoVal = objD_.at("rho")->Get()->at(iRho); const auto& rhoEtaMin = objD_.at("etaMin")->Get()->at(iRho); const auto& rhoEtaMax = objD_.at("etaMax")->Get()->at(iRho); if (lepP4.Eta()>=rhoEtaMin && lepP4.Eta()<rhoEtaMax) { rho = rhoVal; break; } } if (rho<0) { throw std::logic_error(Form("Rho not found for lepton eta: %g", lepP4.Eta())); } const auto ue = getUE(rho, type, coneSize); // return corrected relative lepton isolation return ((sumPt - ue)/lepP4.Pt()); }; metMap getMET() const { // set entry on demand if (onDemand_) { loadEntry("pfcandAnalyzer"); } // get MET metMap metM; const std::vector<std::string> catList({"Full", "Chg", "NoHF", "ChgPtMin4"}); for (const auto& cat : catList) { metM[cat] = TLorentzVector(0., 0., 0., 0.); } for (size_t iPF=0; iPF<objF_.at("pfPt")->Get()->size(); iPF++) { const auto& pfId = objI_.at("pfId")->Get()->at(iPF); const auto& pfPt = objF_.at("pfPt" )->Get()->at(iPF); const auto& pfEta = objF_.at("pfEta")->Get()->at(iPF); const auto& pfPhi = objF_.at("pfPhi")->Get()->at(iPF); const auto& trkNHit = objF_.at("trkNHit")->Get()->at(iPF); TLorentzVector vec; vec.SetPtEtaPhiM(pfPt, 0.0, pfPhi, 0.0); for (const auto& cat : catList) { auto& met = metM.at(cat); if (cat=="Full") { met -= vec; } else if (cat=="Chg" && trkNHit>0) { met -= vec; } else if (cat=="ChgPtMin4" && trkNHit>0 && pfPt>4.) { met -= vec; } else if (cat=="NoHF" && pfId<6 && std::abs(pfEta)<3.0) { met -= vec; } } } return metM; }; bool passParticleCut(const std::string& type, const size_t& i) const { if (getSize(type)==0) { return false; } else if (type=="electron") { return passElectronCut(i); } else if (type=="muon" ) { return passMuonCut(i); } return false; }; bool passElectronCut(const size_t& i) const { // set entry on demand if (onDemand_) { loadEntry("hiEvtAnalyzer"); } // check kinematics if (objF_.at("elePt")->Get()->at(i) <= 20.) return false; if ((std::abs(objF_.at("eleSCEta")->Get()->at(i)) >= 1.4 && std::abs(objF_.at("eleSCEta")->Get()->at(i)) <= 1.6) || std::abs(objF_.at("eleSCEta")->Get()->at(i)) >= 2.1) return false; // use Loose ID working points for PbPb 2018 float cutSigmaIEtaIEta, cutdEtaSeedAtVtx, cutdPhiAtVtx, cutEoverPInv, cutHoverEBc; if (*evtI_.at("hiBin")->Get() <= 60) { if (std::abs(objF_.at("eleSCEta")->Get()->at(i)) < 1.479) { cutSigmaIEtaIEta = 0.013451; cutdEtaSeedAtVtx = 0.003814; cutdPhiAtVtx = 0.037586; cutEoverPInv = 0.017664; cutHoverEBc = 0.161613; } else { cutSigmaIEtaIEta = 0.046571; cutdEtaSeedAtVtx = 0.006293; cutdPhiAtVtx = 0.118592; cutEoverPInv = 0.020135; cutHoverEBc = 0.131705; } } else { if (std::abs(objF_.at("eleSCEta")->Get()->at(i)) < 1.479) { cutSigmaIEtaIEta = 0.010867; cutdEtaSeedAtVtx = 0.003284; cutdPhiAtVtx = 0.020979; cutEoverPInv = 0.077633; cutHoverEBc = 0.126826; } else { cutSigmaIEtaIEta = 0.033923; cutdEtaSeedAtVtx = 0.006708; cutdPhiAtVtx = 0.083766; cutEoverPInv = 0.019279; cutHoverEBc = 0.097703; } } const bool passID = objF_.at("eleSigmaIEtaIEta_2012")->Get()->at(i) < cutSigmaIEtaIEta && std::abs(objF_.at("eledEtaSeedAtVtx")->Get()->at(i)) < cutdEtaSeedAtVtx && std::abs(objF_.at("eledPhiAtVtx")->Get()->at(i)) < cutdPhiAtVtx && objF_.at("eleEoverPInv")->Get()->at(i) < cutEoverPInv && objF_.at("eleHoverEBc")->Get()->at(i) < cutHoverEBc && std::abs(objF_.at("eleIP3D")->Get()->at(i)) < 0.03 && objI_.at("eleMissHits")->Get()->at(i) <= 1; return passID; }; bool passMuonCut(const size_t& i) const { // check kinematics const auto& eta = objF_.at("muEta")->Get()->at(i); const auto& pt = objF_.at("muPt")->Get()->at(i); const bool inAcc = (std::abs(eta)<2.4 && pt>=15.0); if (!inAcc) return false; // use Tight ID working points for PbPb 2018 const bool passID = objI_.at("muIsGlobal")->Get()->at(i) && objI_.at("muIsPF")->Get()->at(i) && objI_.at("muStations")->Get()->at(i) > 1 && objF_.at("muChi2NDF")->Get()->at(i) < 10. && objI_.at("muMuonHits")->Get()->at(i) > 0 && objI_.at("muTrkLayers")->Get()->at(i) > 5 && objI_.at("muPixelHits")->Get()->at(i) > 0 && std::abs(objF_.at("muD0")->Get()->at(i)) < 0.2 && std::abs(objF_.at("muDz")->Get()->at(i)) < 0.5; return passID; }; void initEventInfo() { evtUI_["runN"].reset(new TTreeReaderValue<UInt_t>(*reader_.at("hiEvtAnalyzer"), "run")); evtUL_["eventN"].reset(new TTreeReaderValue<ULong64_t>(*reader_.at("hiEvtAnalyzer"), "evt")); evtI_["hiBin"].reset(new TTreeReaderValue<int>(*reader_.at("hiEvtAnalyzer"), "hiBin")); skimI_["evtSel"].reset(new TTreeReaderValue<int>(*reader_.at("skimanalysis"), "collisionEventSelectionAODv2")); }; void initElectron() { for (const auto& var : {"eleCharge", "eleMissHits"}) { objI_[var].reset(new TTreeReaderValue<std::vector<int> >(*reader_.at("ggHiNtuplizerGED"), var)); } for (const auto& var : {"elePt", "eleSCEta", "eleSCPhi", "eleSigmaIEtaIEta_2012", "eledEtaSeedAtVtx", "eledPhiAtVtx", "eleEoverPInv", "eleHoverEBc", "eleIP3D"}) { objF_[var].reset(new TTreeReaderValue<std::vector<float> >(*reader_.at("ggHiNtuplizerGED"), var)); } }; void initMuon() { for (const auto& var : {"muCharge", "muIsGlobal", "muIsPF", "muIDTight", "muStations", "muTrkLayers", "muPixelHits", "muMuonHits"}) { objI_[var].reset(new TTreeReaderValue<std::vector<int> >(*reader_.at("ggHiNtuplizerGED"), var)); }; for (const auto& var : {"muPt", "muEta", "muPhi", "muD0", "muDz", "muChi2NDF"}) { objF_[var].reset(new TTreeReaderValue<std::vector<float> >(*reader_.at("ggHiNtuplizerGED"), var)); } }; void initPF() { for (const auto& var : {"pfId"}) { objI_[var].reset(new TTreeReaderValue<std::vector<int> >(*reader_.at("pfcandAnalyzer"), var)); }; for (const auto& var : {"pfPt", "pfEta", "pfPhi", "trkNHit"}) { objF_[var].reset(new TTreeReaderValue<std::vector<float> >(*reader_.at("pfcandAnalyzer"), var)); } }; void initRho() { for (const auto& var : {"etaMin", "etaMax", "rho"}) { objD_[var].reset(new TTreeReaderValue<std::vector<double> >(*reader_.at("hiFJRhoAnalyzerFinerBins"), var)); } }; std::map<std::string, std::unique_ptr<TTreeReaderValue<UInt_t> > > evtUI_; std::map<std::string, std::unique_ptr<TTreeReaderValue<ULong64_t> > > evtUL_; std::map<std::string, std::unique_ptr<TTreeReaderValue<int> > > evtI_, skimI_; std::map<std::string, std::unique_ptr<TTreeReaderValue<std::vector<int> > > > objI_; std::map<std::string, std::unique_ptr<TTreeReaderValue<std::vector<float> > > > objF_; std::map<std::string, std::unique_ptr<TTreeReaderValue<std::vector<double> > > > objD_; }; bool existDir(const std::string& dir) { bool exist = false; const auto& dirp = gSystem->OpenDirectory(dir.c_str()); if (dirp) { gSystem->FreeDirectory(dirp); exist = true; } return exist; }; void makeDir(const std::string& dir) { if (existDir(dir)==false){ std::cout << "[INFO] DataSet directory: " << dir << " doesn't exist, will create it!" << std::endl; gSystem->mkdir(dir.c_str(), kTRUE); } }; #endif // ifndef skimTree_h
c0799e2b98897349326d3119208dacaf7600efc4
[ "C", "C++" ]
2
C
stahlleiton/EWKAnalysis2020
d444a98462f51d0c23ad5046b421ec27f77b774d
0db8ea1f9dd44917960b697d2baf1aa408ef785c
refs/heads/master
<file_sep><?php define('DB_HOST', 'localhost'); define('DB_USER', 'id8936460_amuminho1819'); define('DB_PASSWORD', '<PASSWORD>'); define('DB_NAME', 'id8936460_luxdb'); ?><file_sep># AMU Aplicações Multimédia e Ubíquas - Monitor de Nível de Iluminação (Android App) <file_sep>package com.example.luxapp.Activities; import android.app.ActivityOptions; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.example.luxapp.R; import butterknife.ButterKnife; import butterknife.OnClick; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); } @OnClick(R.id.btn_begin) public void reg(){ // Register Activity transition try { Intent intent = new Intent(MainActivity.this, RegisterActivity.class); startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(MainActivity.this).toBundle()); } catch(Exception e) { e.printStackTrace(); } } } <file_sep>-- Lux Android App - Database Script Creation 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='TRADITIONAL,ALLOW_INVALID_DATES'; -- ----------------------------------------------------- -- Schema luxdb -- ----------------------------------------------------- -- ----------------------------------------------------- -- Schema luxdb -- ----------------------------------------------------- CREATE SCHEMA IF NOT EXISTS `luxdb` DEFAULT CHARACTER SET utf8 ; USE `luxdb` ; -- ----------------------------------------------------- -- Table `luxdb`.`User` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `luxdb`.`User` ( `ID` INT NOT NULL AUTO_INCREMENT, `Name` VARCHAR(45) NOT NULL, `Email` VARCHAR(45) NOT NULL, `Password` VARBINARY(45) NOT NULL, PRIMARY KEY (`ID`)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `luxdb`.`Protocol` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `luxdb`.`Protocol` ( `ID` INT NOT NULL AUTO_INCREMENT, `Type` VARCHAR(45) NOT NULL, `Description` LONGTEXT NOT NULL, PRIMARY KEY (`ID`)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `luxdb`.`Experiment` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `luxdb`.`Experiment` ( `ID` INT NOT NULL AUTO_INCREMENT, `AndroidVersion` VARCHAR(45) NOT NULL, `Brand` VARCHAR(45) NOT NULL, `Model` VARCHAR(45) NOT NULL, `User_ID` INT NOT NULL, `Protocol_ID` INT NOT NULL, PRIMARY KEY (`ID`), INDEX `fk_Experiencia_Utilizador1_idx` (`User_ID` ASC), INDEX `fk_Experiment_Protocol1_idx` (`Protocol_ID` ASC), CONSTRAINT `fk_Experiencia_Utilizador1` FOREIGN KEY (`User_ID`) REFERENCES `luxdb`.`User` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_Experiment_Protocol1` FOREIGN KEY (`Protocol_ID`) REFERENCES `luxdb`.`Protocol` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `luxdb`.`Sample` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `luxdb`.`Sample` ( `ID` INT NOT NULL AUTO_INCREMENT, `Latitude` DOUBLE NOT NULL, `Longitude` DOUBLE NOT NULL, `Luminosity` DOUBLE NOT NULL, `Timestamp` TIMESTAMP NOT NULL, `Experiment_ID` INT NOT NULL, PRIMARY KEY (`ID`), INDEX `fk_Amostra_Experiencia_idx` (`Experiment_ID` ASC), CONSTRAINT `fk_Amostra_Experiencia` FOREIGN KEY (`Experiment_ID`) REFERENCES `luxdb`.`Experiment` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; <file_sep><?php require_once "constants.php"; $con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); ?><file_sep><?php require_once "connect.php"; if(!$con){ echo "Falha na conexão à Base de Dados"; }else{ if($_SERVER['HTTP_USER_AGENT'] == "LuxApp"){ if($_SERVER["REQUEST_METHOD"] == "POST") { $latitude = $_POST['latitude']; $longitude = $_POST['longitude']; $luminosity = $_POST['luminosity']; $timestamp = $_POST['timestamp']; $experimentID = $_POST['experimentID']; if($latitude == "" || $longitude == "" || $luminosity == "" || $timestamp == "" || $experimentID == ""){ echo "Falha no envio de dados, alguns campos estão vazio..."; }else{ $sql = "INSERT INTO Sample (Latitude, Longitude, Luminosity, Timestamp, Experiment_ID) VALUES ('$latitude', '$longitude', '$luminosity', '$timestamp', '$experimentID');"; if(mysqli_query($con,$sql)){ echo "Dados enviados com sucesso!"; }else{ echo "Falha no envio dos dados..."; } mysqli_close($con); } }else{ echo "Erro no método do pedido. O método deve ser POST. Os seus dados não foram inseridos."; } } } ?><file_sep>package com.example.luxapp.Fragments; import com.example.luxapp.Activities.MapDisplay; import com.example.luxapp.R; import android.os.Bundle; import android.support.v4.app.Fragment; import android.widget.Button; import android.widget.Toast; import com.example.luxapp.BuildConfig; import com.example.luxapp.Classes.*; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.app.ActivityOptions; import android.app.Service; import android.content.Intent; import android.content.IntentSender; import android.content.pm.PackageManager; import android.graphics.Color; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.location.Location; import android.net.Uri; import android.os.Build; import android.os.Looper; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.util.Log; import android.widget.ProgressBar; import android.widget.TextView; import com.android.volley.AuthFailureError; import com.android.volley.NetworkError; import com.android.volley.NoConnectionError; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.ServerError; import com.android.volley.TimeoutError; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.common.api.ResolvableApiException; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationCallback; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationResult; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResponse; import com.google.android.gms.location.LocationSettingsStatusCodes; import com.google.android.gms.location.SettingsClient; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.karumi.dexter.Dexter; import com.karumi.dexter.PermissionToken; import com.karumi.dexter.listener.PermissionDeniedResponse; import com.karumi.dexter.listener.PermissionGrantedResponse; import com.karumi.dexter.listener.PermissionRequest; import com.karumi.dexter.listener.single.PermissionListener; import java.text.DateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class Park_f5 extends Fragment implements SensorEventListener{ public Park_f5() {} // ENTITIES private Experiment experiment; private Sample sample; private HashMap<Integer, Sample> samples; // LIGHT SENSOR private SensorManager sensorManager; private Sensor sensor; private SensorEvent event; private int sample_N; private int index; private ProgressBar pBar; private static final String TAG = Park_f5.class.getSimpleName(); @BindView(R.id.updated_on) TextView txtUpdatedOn; @BindView(R.id.btn_start_park) Button btnStartUpdates; @BindView(R.id.btn_stop_park) Button btnStopUpdates; // location last updated time private String mLastUpdateTime; // location updates interval - 1sec private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 1000; // fastest updates interval - 1 sec // location updates will be received if another app is requesting the locations // than your app can handle private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 1000; private static final int REQUEST_CHECK_SETTINGS = 100; // bunch of location related apis private FusedLocationProviderClient mFusedLocationClient; private SettingsClient mSettingsClient; private LocationRequest mLocationRequest; private LocationSettingsRequest mLocationSettingsRequest; private LocationCallback mLocationCallback; private Location mCurrentLocation; // boolean flag to toggle the ui private Boolean mRequestingLocationUpdates; private Activity activity; private int userID; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); activity = getActivity(); userID = (Integer) activity.getIntent().getExtras().get("userID"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.park_step5, container, false); ButterKnife.bind(this,view); // initialize the necessary libraries init(); // restore the values from saved instance state restoreValuesFromBundle(savedInstanceState); // initialize light sensor sensorManager = (SensorManager) activity.getSystemService(Service.SENSOR_SERVICE); sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); // progress bar pBar = activity.findViewById(R.id.progressBar); btnStopUpdates.setVisibility(View.INVISIBLE); return view; } private void init() { mFusedLocationClient = LocationServices.getFusedLocationProviderClient(activity); mSettingsClient = LocationServices.getSettingsClient(activity); mLocationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { super.onLocationResult(locationResult); // location is received mCurrentLocation = locationResult.getLastLocation(); mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); updateLocationUI(); } }; mRequestingLocationUpdates = false; mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder(); builder.addLocationRequest(mLocationRequest); mLocationSettingsRequest = builder.build(); index = 0; // EXPERIMENT experiment = new Experiment(); experiment.setAndroidVersion(Build.VERSION.RELEASE); experiment.setBrand(Build.BRAND); experiment.setModel(Build.MODEL); experiment.setProtocolId(3); experiment.setUserId(userID); } /** * Restoring values from saved instance state */ private void restoreValuesFromBundle(Bundle savedInstanceState) { if (savedInstanceState != null) { if (savedInstanceState.containsKey("is_requesting_updates")) { mRequestingLocationUpdates = savedInstanceState.getBoolean("is_requesting_updates"); } if (savedInstanceState.containsKey("last_known_location")) { mCurrentLocation = savedInstanceState.getParcelable("last_known_location"); } if (savedInstanceState.containsKey("last_updated_on")) { mLastUpdateTime = savedInstanceState.getString("last_updated_on"); } } updateLocationUI(); } /** * Update the UI displaying the location data * and toggling the buttons */ private void updateLocationUI() { if (mCurrentLocation != null) { // location last updated time txtUpdatedOn.setText("Última amostra: " + mLastUpdateTime); // SAMPLE sample = new Sample(); // Coordinates sample.setLatitude(mCurrentLocation.getLatitude()); sample.setLongitude(mCurrentLocation.getLongitude()); // Light - level of luminosity if (event.sensor.getType() == Sensor.TYPE_LIGHT) sample.setLuminosity(event.values[0]); experiment.addSample(sample); } toggleButtons(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean("is_requesting_updates", mRequestingLocationUpdates); outState.putParcelable("last_known_location", mCurrentLocation); outState.putString("last_updated_on", mLastUpdateTime); } private void toggleButtons() { if (mRequestingLocationUpdates) { btnStartUpdates.setEnabled(false); btnStopUpdates.setEnabled(true); } else { btnStartUpdates.setEnabled(true); btnStopUpdates.setEnabled(false); } } /** * Starting location updates * Check whether location settings are satisfied and then * location updates will be requested */ private void startLocationUpdates() { mSettingsClient .checkLocationSettings(mLocationSettingsRequest) .addOnSuccessListener(activity, new OnSuccessListener<LocationSettingsResponse>() { @SuppressLint("MissingPermission") @Override public void onSuccess(LocationSettingsResponse locationSettingsResponse) { Log.i(TAG, "All location settings are satisfied."); Toast.makeText(activity.getApplicationContext(), "A experiência começou!", Toast.LENGTH_SHORT).show(); //noinspection MissingPermission mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper()); updateLocationUI(); } }) .addOnFailureListener(activity, new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { int statusCode = ((ApiException) e).getStatusCode(); switch (statusCode) { case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: Log.i(TAG, "Location settings are not satisfied. Attempting to upgrade " + "location settings "); try { // Show the dialog by calling startResolutionForResult(), and check the // result in onActivityResult(). ResolvableApiException rae = (ResolvableApiException) e; rae.startResolutionForResult(activity, REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException sie) { Log.i(TAG, "PendingIntent unable to execute request."); } break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: String errorMessage = "Location settings are inadequate, and cannot be " + "fixed here. Fix in Settings."; Log.e(TAG, errorMessage); Toast.makeText(activity, errorMessage, Toast.LENGTH_LONG).show(); } updateLocationUI(); } }); } // START EXPERIMENT @OnClick(R.id.btn_start_park) public void startLocationButtonClick() { btnStartUpdates.setVisibility(View.INVISIBLE); btnStopUpdates.setVisibility(View.VISIBLE); Dexter.withActivity(activity) .withPermission(Manifest.permission.ACCESS_FINE_LOCATION) .withListener(new PermissionListener() { @Override public void onPermissionGranted(PermissionGrantedResponse response) { mRequestingLocationUpdates = true; startLocationUpdates(); } @Override public void onPermissionDenied(PermissionDeniedResponse response) { if (response.isPermanentlyDenied()) { // open device settings when the permission is // denied permanently openSettings(); } } @Override public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) { token.continuePermissionRequest(); } }).check(); } // STOP EXPERIMENT @OnClick(R.id.btn_stop_park) public void stopLocationButtonClick() { mRequestingLocationUpdates = false; stopLocationUpdates(); // STOP sendData(); // SEND DATA } public void stopLocationUpdates() { // Removing location updates mFusedLocationClient .removeLocationUpdates(mLocationCallback) .addOnCompleteListener(activity, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { Toast.makeText(activity.getApplicationContext(), "A experiência foi concluida!", Toast.LENGTH_SHORT).show(); toggleButtons(); } }); } // SHOW MAP public void showMapRoute() { samples = experiment.getSamples(); if (!samples.isEmpty()) { try { Intent intent = new Intent(activity, MapDisplay.class); intent.putExtra("Samples", samples); intent.putExtra("userID", userID); intent.putExtra("experimentID", experiment.getId()); startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(activity).toBundle()); } catch(Exception e) { e.printStackTrace(); } } else { Toast.makeText(activity.getApplicationContext(), "Experiência tem de ser concluida", Toast.LENGTH_SHORT).show(); } } // SEND DATA public void sendData() { samples = experiment.getSamples(); pBar = activity.findViewById(R.id.progressBar); // SEND EXPERIMENT AND SAMPLES TO DB if (experiment != null && !samples.isEmpty()) { pBar.getProgressDrawable().setColorFilter(Color.GREEN, android.graphics.PorterDuff.Mode.SRC_IN); Toast.makeText(activity.getApplicationContext(), "A enviar dados...", Toast.LENGTH_SHORT).show(); // SEND Experiment sendExperiment(); }else { pBar.getProgressDrawable().setColorFilter(Color.RED, android.graphics.PorterDuff.Mode.SRC_IN); Toast.makeText(activity.getApplicationContext(), "A experiência tem de ser concluida primeiro!", Toast.LENGTH_SHORT).show(); } } // SEND EXPERIMENT public void sendExperiment() { // POST DATA StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.EXPERIMENT_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { if(!response.contains("Falha no envio dos dados...")){ experiment.setId(Integer.parseInt(response)); System.out.println("INFO:"); System.out.println("EXPERIMENT: " + experiment.toString()); // SEND Samples sample_N = samples.size() - 1; sample = samples.get(index); sample.setExperimentID(experiment.getId()); System.out.println("SAMPLE: "+sample.toString()); sendSample(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if(error instanceof TimeoutError){ Toast.makeText(activity, "Timeout Error", Toast.LENGTH_SHORT).show(); }else if(error instanceof NoConnectionError){ Toast.makeText(activity, "No Connection Error", Toast.LENGTH_SHORT).show(); }else if(error instanceof AuthFailureError){ Toast.makeText(activity, "Authentication Failure Error", Toast.LENGTH_SHORT).show(); }else if(error instanceof NetworkError){ Toast.makeText(activity, "Network Error", Toast.LENGTH_SHORT).show(); }else if(error instanceof ServerError){ Toast.makeText(activity, "Server Error", Toast.LENGTH_SHORT).show(); }else if(error instanceof ParseError){ Toast.makeText(activity, "JSON Parse Error", Toast.LENGTH_SHORT).show(); } } }){ @Override protected Map<String,String> getParams(){ Map<String,String> params = new HashMap<String,String>(); params.put(Constants.KEY_ANDROID,experiment.getAndroidVersion()); params.put(Constants.KEY_BRAND,experiment.getBrand()); params.put(Constants.KEY_MODEL,experiment.getModel()); params.put(Constants.KEY_PROTOCOL_ID,String.valueOf(experiment.getProtocolId())); params.put(Constants.KEY_USER_ID,String.valueOf(experiment.getUserId())); return params; } @Override public Map<String,String> getHeaders() throws AuthFailureError{ Map<String,String> headers = new HashMap<String,String>(); headers.put("User-Agent","LuxApp"); return headers; } }; MySingleton.getInstance(activity).addToRequestQueue(stringRequest); } // SEND SAMPLE public void sendSample() { // POST DATA StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.SAMPLE_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { if(response.contains("Dados enviados com sucesso!")) { // Last sample if (index == sample_N) { pBar.setProgress(100); Toast.makeText(activity, response, Toast.LENGTH_SHORT).show(); showMapRoute(); // SHOW MAP }else{ index++; sample = samples.get(index); sample.setExperimentID(experiment.getId()); System.out.println("SAMPLE: "+sample.toString()); sendSample(); } }else{ pBar.getProgressDrawable().setColorFilter(Color.RED, android.graphics.PorterDuff.Mode.SRC_IN); Toast.makeText(activity, response, Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if(error instanceof TimeoutError){ Toast.makeText(activity, "Timeout Error", Toast.LENGTH_SHORT).show(); }else if(error instanceof NoConnectionError){ Toast.makeText(activity, "No Connection Error", Toast.LENGTH_SHORT).show(); }else if(error instanceof AuthFailureError){ Toast.makeText(activity, "Authentication Failure Error", Toast.LENGTH_SHORT).show(); }else if(error instanceof NetworkError){ Toast.makeText(activity, "Network Error", Toast.LENGTH_SHORT).show(); }else if(error instanceof ServerError){ Toast.makeText(activity, "Server Error", Toast.LENGTH_SHORT).show(); }else if(error instanceof ParseError){ Toast.makeText(activity, "JSON Parse Error", Toast.LENGTH_SHORT).show(); } } }){ @Override protected Map<String,String> getParams(){ Map<String,String> params = new HashMap<String,String>(); params.put(Constants.KEY_LAT,String.valueOf(sample.getLatitude())); params.put(Constants.KEY_LONG,String.valueOf(sample.getLongitude())); params.put(Constants.KEY_LUM,String.valueOf(sample.getLuminosity())); params.put(Constants.KEY_TIME,sample.getTimestamp().toString()); params.put(Constants.KEY_EXP_ID,String.valueOf(sample.getExperimentID())); return params; } @Override public Map<String,String> getHeaders() throws AuthFailureError{ Map<String,String> headers = new HashMap<String,String>(); headers.put("User-Agent","LuxApp"); return headers; } }; MySingleton.getInstance(activity).addToRequestQueue(stringRequest); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { // Check for the integer request code originally supplied to startResolutionForResult(). case REQUEST_CHECK_SETTINGS: switch (resultCode) { case Activity.RESULT_OK: Log.e(TAG, "User agreed to make required location settings changes."); // Nothing to do. startLocationupdates() gets called in onResume again. break; case Activity.RESULT_CANCELED: Log.e(TAG, "User chose not to make required location settings changes."); mRequestingLocationUpdates = false; break; } break; } } private void openSettings() { Intent intent = new Intent(); intent.setAction( Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", BuildConfig.APPLICATION_ID, null); intent.setData(uri); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } @Override public void onResume() { super.onResume(); // LIGHT SENSOR sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL); // Resuming location updates depending on button state and // allowed permissions if (mRequestingLocationUpdates && checkPermissions()) { startLocationUpdates(); } updateLocationUI(); } private boolean checkPermissions() { int permissionState = ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION); return permissionState == PackageManager.PERMISSION_GRANTED; } @Override public void onPause() { super.onPause(); // LIGHT SENSOR sensorManager.unregisterListener(this); if (mRequestingLocationUpdates) { // pausing location updates stopLocationUpdates(); } } // LIGHT SENSOR @Override public void onSensorChanged(SensorEvent event1) { event = event1; } // LIGHT SENSOR @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } } <file_sep><?php require_once "connect.php"; if(!$con){ echo "Falha na conexão à Base de Dados"; }else{ if($_SERVER['HTTP_USER_AGENT'] == "LuxApp"){ if($_SERVER["REQUEST_METHOD"] == "POST") { $email = $_POST['email']; $qry_dupe = "SELECT id FROM User WHERE email = '$email'"; $result_id = mysqli_query($con, $qry_dupe); if(mysqli_num_rows($result_id) <=0){ $sql = "INSERT INTO User (email) VALUES ('$email')"; mysqli_query($con,$sql); } $result_id = mysqli_query($con, $qry_dupe); $id = mysqli_fetch_array($result_id); $data = $id[0]; if($data){ echo $data; } else{ echo "Falha no registo..."; } mysqli_close($con); }else{ echo "Erro no método do pedido. O método deve ser POST. Os seus dados não foram inseridos."; } } } ?><file_sep><?php require_once "connect.php"; if(!$con){ echo "Falha na conexão à Base de Dados"; }else{ if($_SERVER['HTTP_USER_AGENT'] == "LuxApp"){ if($_SERVER["REQUEST_METHOD"] == "POST") { $email = $_POST['email']; $password = $_POST['password']; if($email == "" || $password == ""){ echo "Alguns campos estão vazios. Por favor, preencha todos os campos de forma válida."; }else{ $enc_pw = md5($password); $qry_dupe = "SELECT * FROM User WHERE email = '$email' AND password = '$<PASSWORD>'"; $dupe_results = mysqli_query($con, $qry_dupe); if(mysqli_num_rows($dupe_results) >0){ $sql2 = "SELECT max(id) FROM User"; $result_id = mysqli_query($con,$sql2); $row = mysqli_fetch_array($result_id); $data = $row[0]; if($data){ echo $data; } }else{ echo "Falha no login, os campos são inválidos!"; } mysqli_close($con); } }else{ echo "Erro no método do pedido. O método deve ser POST. Os seus dados não foram inseridos."; } } } ?><file_sep><?php require_once "connect.php"; if(!$con){ echo "Falha na conexão à Base de Dados"; }else{ if($_SERVER['HTTP_USER_AGENT'] == "LuxApp"){ if($_SERVER["REQUEST_METHOD"] == "POST") { $android_version = $_POST['android_version']; $model = $_POST['model']; $brand = $_POST['brand']; $user_id = $_POST['user_id']; $protocol_id = $_POST['protocol_id']; if($android_version == "" || $model == "" || $brand == "" || $user_id == "" || $protocol_id == ""){ echo "Falha no envio de dados, alguns campos estão vazio..."; }else{ $sql = "INSERT INTO Experiment (AndroidVersion, Brand, Model, User_ID, Protocol_ID) VALUES ('$android_version', '$brand', '$model', '$user_id', '$protocol_id');"; if(mysqli_query($con,$sql)){ $sql2 = "SELECT max(id) FROM Experiment"; $result_id = mysqli_query($con,$sql2); $row = mysqli_fetch_array($result_id); $data = $row[0]; if($data){ echo $data; } }else{ echo "Falha no envio dos dados..."; } mysqli_close($con); } }else{ echo "Erro no método do pedido. O método deve ser POST. Os seus dados não foram inseridos."; } } } ?><file_sep>package com.example.luxapp.Fragments; import com.example.luxapp.R; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import butterknife.BindView; import butterknife.OnClick; public class BusStop_f1 extends Fragment{ public BusStop_f1() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.bs_step1, container, false); } } <file_sep><?php require_once "connect.php"; if(!$con){ echo "Falha na conexão à Base de Dados"; }else{ if($_SERVER['HTTP_USER_AGENT'] == "LuxApp"){ if($_SERVER["REQUEST_METHOD"] == "POST") { $experimentID = $_POST['experimentID']; $sql = "SET @row_number = 0;"; $sql2 = "SELECT num FROM (SELECT (@row_number:=@row_number + 1) AS num, Avg_Lux, ID FROM Experiment ORDER BY Avg_Lux DESC) as T WHERE ID = '$experimentID';"; if(mysqli_query($con,$sql)){ $rank = mysqli_query($con,$sql2); $row = mysqli_fetch_array($rank); $data = $row[0]; if($data){ echo $data; }else{ echo "Falha na conexão..."; } } mysqli_close($con); }else{ echo "Erro no método do pedido. O método deve ser POST. Os seus dados não foram inseridos."; } } } ?><file_sep><?php require_once "connect.php"; if(!$con){ echo "Falha na conexão à Base de Dados"; }else{ if($_SERVER['HTTP_USER_AGENT'] == "LuxApp"){ if($_SERVER["REQUEST_METHOD"] == "POST") { $experimentID = $_POST['experimentID']; $lux = $_POST['lux']; $sql = "UPDATE Experiment SET Avg_Lux = '$lux' WHERE ID = '$experimentID';"; if(mysqli_query($con,$sql)) echo $experimentID; mysqli_close($con); }else{ echo "Erro no método do pedido. O método deve ser POST. Os seus dados não foram inseridos."; } } } ?><file_sep><?php require_once "connect.php"; if(!$con){ echo "Falha na conexão à Base de Dados"; }else{ if($_SERVER['HTTP_USER_AGENT'] == "LuxApp"){ if($_SERVER["REQUEST_METHOD"] == "POST") { $name = $_POST['name']; $email = $_POST['email']; $password = $_POST['password']; if($name == "" || $email == "" || $password == ""){ echo "Alguns campos estão vazios. Por favor, preencha todos os campos de forma válida."; }else{ $qry_dupe = "SELECT * FROM User WHERE email = '$email'"; $dupe_results = mysqli_query($con, $qry_dupe); if(mysqli_num_rows($dupe_results) >0){ echo "Este e-mail já está a ser utilizado noutra conta..."; }else{ $enc_pw = md5($password); $sql = "INSERT INTO User (name, email, password) VALUES ('$name','$email','$enc_pw')"; if(mysqli_query($con,$sql)){ echo "Registado com sucesso!"; }else{ echo "Falha no registo..."; } mysqli_close($con); } } }else{ echo "Erro no método do pedido. O método deve ser POST. Os seus dados não foram inseridos."; } } } ?><file_sep>package com.example.luxapp.Activities; import com.android.volley.AuthFailureError; import com.android.volley.NetworkError; import com.android.volley.NoConnectionError; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.ServerError; import com.android.volley.TimeoutError; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.example.luxapp.R; import com.example.luxapp.Classes.*; import android.app.ActivityOptions; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.maps.model.JointType; import com.google.android.gms.maps.model.PolylineOptions; import com.google.android.gms.maps.model.RoundCap; import java.util.HashMap; import java.util.Map; import butterknife.ButterKnife; import butterknife.OnClick; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.LatLng; /** * Reference: https://github.com/googlesamples/android-play-location/tree/master/LocationUpdates */ public class MapDisplay extends AppCompatActivity implements OnMapReadyCallback { private int userID; private int experimentID; private double avg_lux; private HashMap<Integer, Sample> samples; private TextView quality; private TextView rank; // MAP private MapView mapView; private GoogleMap gmap; private static final String TAG = MapDisplay.class.getSimpleName(); private static final String MAP_VIEW_BUNDLE_KEY = "MapViewBundleKey"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map_display); ButterKnife.bind(this); experimentID = (Integer) getIntent().getExtras().get("experimentID"); userID = (Integer) getIntent().getExtras().get("userID"); quality = findViewById(R.id.quality); rank = findViewById(R.id.rank); avg_lux = 0; // initializate map view Bundle mapViewBundle = null; if (savedInstanceState != null) { mapViewBundle = savedInstanceState.getBundle(MAP_VIEW_BUNDLE_KEY); } mapView = findViewById(R.id.map_view); mapView.onCreate(mapViewBundle); mapView.getMapAsync(this); } // SHOW INFO public void showInfo() { // SHOW MAP // Samples from experiment samples = (HashMap<Integer, Sample>) getIntent().getExtras().get("Samples"); // ROUTE ON MAP // PLOT PolylineOptions plo = new PolylineOptions(); LatLng coord = new LatLng(40.0332629, -7.8896263) ; for( Sample s : samples.values()) { coord = new LatLng(s.getLatitude(), s.getLongitude()); plo.add(coord); } gmap.setMinZoomPreference(17); gmap.moveCamera(CameraUpdateFactory.newLatLng(coord)); plo.color(Color.GREEN); plo.geodesic(true); plo.startCap(new RoundCap()); plo.width(20); plo.jointType(JointType.BEVEL); gmap.addPolyline(plo); // SHOW STATISTICS (LUX QUALITY + RANK) // CALCULATE AVG_LUX double al = 0; for(Sample s : samples.values()) al+=s.getLuminosity(); avg_lux = al/(samples.size()); setExpLux(); // QUALITY getExpQuality(); } void setExpLux(){ StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.LUX_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { // GET RANK getExpRank(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (error instanceof TimeoutError) { Toast.makeText(MapDisplay.this, "Timeout Error", Toast.LENGTH_SHORT).show(); } else if (error instanceof NoConnectionError) { Toast.makeText(MapDisplay.this, "No Connection Error", Toast.LENGTH_SHORT).show(); Log.v("Error",error.toString()); } else if (error instanceof AuthFailureError) { Toast.makeText(MapDisplay.this, "Authentication Failure Error", Toast.LENGTH_SHORT).show(); } else if (error instanceof NetworkError) { Toast.makeText(MapDisplay.this, "Network Error", Toast.LENGTH_SHORT).show(); } else if (error instanceof ServerError) { Toast.makeText(MapDisplay.this, "Server Error", Toast.LENGTH_SHORT).show(); } else if (error instanceof ParseError) { Toast.makeText(MapDisplay.this, "JSON Parse Error", Toast.LENGTH_SHORT).show(); } } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put(Constants.KEY_EXP_ID, String.valueOf(experimentID)); params.put(Constants.KEY_LUX,String.valueOf(avg_lux)); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<String, String>(); headers.put("User-Agent", "LuxApp"); return headers; } }; MySingleton.getInstance(MapDisplay.this).addToRequestQueue(stringRequest); } void getExpQuality(){ if (avg_lux <= 10) { quality.setText("Má"); quality.setTextColor(Color.RED); } if (avg_lux>10 && avg_lux <=25) { quality.setText("Razoável"); quality.setTextColor(Color.YELLOW); } if (avg_lux>25 && avg_lux <40) { quality.setText("Boa"); quality.setTextColor(Color.GREEN); } if (avg_lux>=40) { quality.setText("Excelente"); quality.setTextColor(Color.GREEN); } } void getExpRank(){ StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.RANK_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { if(!response.contains("Falha na conexão...")){ int rank_temp = Integer.parseInt(response); if (rank_temp<=10) rank.setTextColor(Color.GREEN); else { if (rank_temp > 10 && rank_temp < 20) rank.setTextColor(Color.YELLOW); else rank.setTextColor(Color.RED); } rank.setText(response); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (error instanceof TimeoutError) { Toast.makeText(MapDisplay.this, "Timeout Error", Toast.LENGTH_SHORT).show(); } else if (error instanceof NoConnectionError) { Toast.makeText(MapDisplay.this, "No Connection Error", Toast.LENGTH_SHORT).show(); Log.v("Error",error.toString()); } else if (error instanceof AuthFailureError) { Toast.makeText(MapDisplay.this, "Authentication Failure Error", Toast.LENGTH_SHORT).show(); } else if (error instanceof NetworkError) { Toast.makeText(MapDisplay.this, "Network Error", Toast.LENGTH_SHORT).show(); } else if (error instanceof ServerError) { Toast.makeText(MapDisplay.this, "Server Error", Toast.LENGTH_SHORT).show(); } else if (error instanceof ParseError) { Toast.makeText(MapDisplay.this, "JSON Parse Error", Toast.LENGTH_SHORT).show(); } } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put(Constants.KEY_EXP_ID, String.valueOf(experimentID)); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<String, String>(); headers.put("User-Agent", "LuxApp"); return headers; } }; MySingleton.getInstance(MapDisplay.this).addToRequestQueue(stringRequest); } // CLOSE @OnClick(R.id.btn_menu) public void menu(){ // Menu Activity transition try { Intent intent = new Intent(MapDisplay.this, MenuActivity.class); intent.putExtra("userID", userID); startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(MapDisplay.this).toBundle()); } catch(Exception e) { e.printStackTrace(); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // MAP Bundle mapViewBundle = outState.getBundle(MAP_VIEW_BUNDLE_KEY); if (mapViewBundle == null) { mapViewBundle = new Bundle(); outState.putBundle(MAP_VIEW_BUNDLE_KEY, mapViewBundle); } mapView.onSaveInstanceState(mapViewBundle); } @Override public void onResume() { super.onResume(); // MAP mapView.onResume(); } @Override protected void onPause() { super.onPause(); // MAP mapView.onStop(); } // MAP @Override protected void onStart() { super.onStart(); mapView.onStart(); } // MAP @Override protected void onStop() { super.onStop(); mapView.onStop(); } // MAP @Override protected void onDestroy() { mapView.onDestroy(); super.onDestroy(); } // MAP @Override public void onLowMemory() { super.onLowMemory(); mapView.onLowMemory(); } // MAP @Override public void onMapReady(GoogleMap googleMap) { // MAP gmap = googleMap; gmap.setMinZoomPreference(7); LatLng portugal = new LatLng(40.0332629, -7.8896263); gmap.moveCamera(CameraUpdateFactory.newLatLng(portugal)); // SHOW INFO showInfo(); } }<file_sep>package com.example.luxapp.Activities; import com.example.luxapp.R; import com.example.luxapp.Classes.*; import android.app.ActivityOptions; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.AutoCompleteTextView; import android.widget.EditText; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.NetworkError; import com.android.volley.NoConnectionError; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.ServerError; import com.android.volley.TimeoutError; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import java.util.HashMap; import java.util.Map; import butterknife.ButterKnife; import butterknife.OnClick; public class LoginActivity extends AppCompatActivity { // UI references. private AutoCompleteTextView email; private EditText password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ButterKnife.bind(this); // Set up the login form. email = findViewById(R.id.email); password = findViewById(R.id.password); } @OnClick(R.id.btnlogin) public void login() { // Login Toast.makeText(LoginActivity.this, "A entrar...", Toast.LENGTH_SHORT).show(); StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.LOGIN_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { if(!response.contains("Falha no login, os campos são inválidos!")){ // Menu Activity transition try { Intent intent = new Intent(LoginActivity.this, MenuActivity.class); intent.putExtra("userID", Integer.parseInt(response)); startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(LoginActivity.this).toBundle()); finish(); } catch(Exception e) { e.printStackTrace(); } } else Toast.makeText(LoginActivity.this, response, Toast.LENGTH_SHORT).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (error instanceof TimeoutError) { Toast.makeText(LoginActivity.this, "Timeout Error", Toast.LENGTH_SHORT).show(); } else if (error instanceof NoConnectionError) { Toast.makeText(LoginActivity.this, "No Connection Error", Toast.LENGTH_SHORT).show(); } else if (error instanceof AuthFailureError) { Toast.makeText(LoginActivity.this, "Authentication Failure Error", Toast.LENGTH_SHORT).show(); } else if (error instanceof NetworkError) { Toast.makeText(LoginActivity.this, "Network Error", Toast.LENGTH_SHORT).show(); } else if (error instanceof ServerError) { Toast.makeText(LoginActivity.this, "Server Error", Toast.LENGTH_SHORT).show(); } else if (error instanceof ParseError) { Toast.makeText(LoginActivity.this, "JSON Parse Error", Toast.LENGTH_SHORT).show(); } } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put(Constants.KEY_EMAIL, email.getText().toString().trim()); params.put(Constants.KEY_PASSWORD, <PASSWORD>.getText().toString().trim()); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<String, String>(); headers.put("User-Agent", "LuxApp"); return headers; } }; MySingleton.getInstance(LoginActivity.this).addToRequestQueue(stringRequest); } }
46d82643a4e8abc07d3d73f5f5d09809023ae65f
[ "Markdown", "Java", "PHP", "SQL" ]
16
PHP
Nexturn/AMU
b39e3309972fcfc3a53ed7348df795549bad0b33
d406b3ca746e8e36b334e3e1abbb6343984cd275
refs/heads/master
<repo_name>wostlund/systems-06signal<file_sep>/makefile compile: sig.c gcc sig.c -o driver run: driver ./driver clean: *~ rm *~ <file_sep>/sig.c #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <fcntl.h> #include <sys/stat.h> #include <unistd.h> static void sighandler(int signo) { if(signo == SIGUSR1) { printf(" The parent process of the current signal is %d\n", getppid()); }else if(signo == SIGINT) { umask(0000); printf(" Exiting due to the signal %d\n", signo); int a = open("file.txt", O_RDWR | O_APPEND, 0666); write(a, "Exited due to SIGINT\n", sizeof("Exited due to SIGINT\n")); close(a); exit(0); } } int main() { signal(SIGINT, sighandler); signal(SIGUSR1, sighandler); while(1){ printf("The pid of the current signal is %d\n", getpid()); sleep(1); } return 1; }
41a760499baff7a91bb76f023e0a90beb3f736a2
[ "C", "Makefile" ]
2
Makefile
wostlund/systems-06signal
e1effcc6bcadc9b060fdb3b2bf98dc210dd70d77
3bf1acc98efa62a27dc291aa3973d7f9bc7ebe36
refs/heads/master
<repo_name>ajzajac/ttt-10-current-player-bootcamp-prep-000<file_sep>/lib/current_player.rb def turn_count(board) turns = 0 board.each do |tile| if tile == "X" || tile == "O" turns += 1 end end turns end def current_player(board) if turn_count(board) % 2 == 0 "X" else "O" end end
8319e9842a5ec5be840a31dc595ae17bf818ede5
[ "Ruby" ]
1
Ruby
ajzajac/ttt-10-current-player-bootcamp-prep-000
55eecb66036095f75c271797f1bd1996663325f4
a6847b3e9ab6e531dc208f17a0ad2c099c0ad460
refs/heads/master
<file_sep>AE-Tools ======== <file_sep>// ==UserScript== // @name AE-Tools // @namespace e3e6.entellitrak // @include *.entellitrak.com* // @exclude *.entellisql.create.request.do // @version 7 // ==/UserScript== // [1] wrap the script in a closure (opera, ie) // do not spoil the global scope // The script can be transformed into a bookmarklet easily :) (function(window, undefined ) { // [2] normalized window var w; if (typeof unsafeWindow != undefined){ w = unsafeWindow } else { w = window; } // You can inject almost any javascript library here. // Just pass the w as the window reference, // e.g. jquery.min.js embedding: // (function(a,b){function ci(a) ... a.jQuery=a.$=d})(w); // [3] do not run in frames if (w.self != w.top){ return; } // [4] additional url check. // Google Chrome do not treat @match as intended sometimes. // if (/http:\/\/userscripts.org/.test(w.location.href)){ // Below is the userscript code itself var isProductionMode = true; /** * Dev. paths */ var scriptsDev = [//"http://code.jquery.com/jquery-1.10.1.min.js", "http://localhost:801/external/aeTools.js"]; var styleDev = ["http://localhost:801/external/aeTools.css"]; /** * Production paths */ var scriptsProd = [//"http://code.jquery.com/jquery-1.9.1.js", "https://rawgithub.com/e3e6/AE-Tools/master/js/aeTools.js", ]; var styleProd = ["https://rawgithub.com/e3e6/AE-Tools/master/css/aeTools.css"]; /** * Inser script element to page */ function insertScriptSrc(scriptsList){ var length = scriptsList.length; var element = null; for (var i = 0; i < length; i++) { element = scriptsList[i]; debug(">> append: " + element); var script = document.createElement("script"); script.src = element; document.getElementsByTagName("head")[0].appendChild(script); } } /** * */ function insertCssSrc(scriptsList){ var length = scriptsList.length; var element = null; for (var i = 0; i < length; i++) { element = scriptsList[i]; debug(">> append: " + element); var fileref=document.createElement("link"); fileref.setAttribute("rel", "stylesheet"); fileref.setAttribute("type", "text/css"); fileref.setAttribute("href", element); document.getElementsByTagName("head")[0].appendChild(fileref); } } /** * Write to console if exist */ function debug(text){ if(window.console){ console.info(text); } } /** * Entry */ /** * Entry */ if(isProductionMode){ insertScriptSrc(scriptsProd); insertCssSrc(styleProd); }else{ insertScriptSrc(scriptsDev); insertCssSrc(styleDev); } // } })(window);
fab9cdec17b1a7bc7d7c39d9f78776744920705c
[ "Markdown", "JavaScript" ]
2
Markdown
e3e6/AE-Tools
60de1e9adfb1139de81ac4ec4d9abd22b2adefef
5cf088f318c94f591efb547d6e94e4efd84509ba