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 | <file_sep>
<?php
session_start();
if(!isset($_SESSION['admin_email']))
{
echo "<script>window.open('login/login.php,'_self')</script>";
}
else
{
?>
<?php
include ("includes/db.php");
?>
<html>
<head>
<title>kshop</title>
<link rel="stylesheet" type="text/css" href="styles/global.css" />
<meta name="viewport" content="width=device-width, initial-scale: 1.0, user-scalabe=0" />
<script src="scripts/jquery-1.11.1.min.js"></script>
<script src="scripts/general.js"></script>
</head>
<body>
<div id="header">
<div class="logo"><a href="#">K<span>SHOP</span></a></div>
</div>
<a class="mobile" href="#">MENU</a>
<div id="container">
<div class="sidebar">
<ul id="nav">
<li><a class="selected" href="#">Dashboard</a></li>
<!-- Get request sending the url variables get request-->
<li><a href="index.php?insert_product">Insert New Product</a></li>
<li><a href="index.php?insert_cat">Insert New Category</a></li>
<li><a href="index.php?insert_brand">Insert New Brand</a></li>
<li><a href="index.php?view_products">View All Products</a></li>
<li><a href="index.php?view_cats">View All Categories</a></li>
<li><a href="index.php?view_brands">View All Brand</a></li>
<li><a href="index.php?view_customers">View Customers</a></li>
<li><a href="index.php?view_orders">View Orders Details</a></li>
<li><a href="index.php?view_payments">View Payments</a></li>
<li><a href="logout.php">Admin Logout</a></li>
</ul>
</div>
<div class="content">
<h1>Dashboard: K-Shop. Welcome, <?php echo @$_SESSION['admin_email'];
// @ sign means show no error if get var is not present ?></h1>
<p>
<?php include ("includes/db.php");
if(isset($_GET['insert_product']))
{
// if the get request was insert product
include("insert_products.php");
}
else if(isset($_GET['view_products']))
{
// if the get request was insert product
include("view_products.php");
}
else if(isset($_GET['edit_pro']))
{
// if the get request was insert product
include("edit_pro.php");
}
else if(isset($_GET['insert_cat']))
{
// if the get request was insert product
include("insert_cat.php");
}
else if(isset($_GET['view_cats']))
{
// if the get request was insert product
include("view_cats.php");
}
else if(isset($_GET['edit_cat']))
{
// if the get request was insert product
include("edit_cat.php");
}
else if(isset($_GET['delete_cat']))
{
// if the get request was insert product
include("delete_cat.php");
}
else if(isset($_GET['insert_brand']))
{
// if the get request was insert product
include("insert_brand.php");
}
else if(isset($_GET['view_brands']))
{
// if the get request was insert product
include("view_brands.php");
}
else if(isset($_GET['edit_brand']))
{
// if the get request was insert product
include("edit_brand.php");
}
else if(isset($_GET['delete_brand']))
{
// if the get request was insert product
include("delete_brand.php");
}
else if(isset($_GET['view_customers']))
{
// if the get request was insert product
include("view_customers.php");
}
else if(isset($_GET['view_orders']))
{
// if the get request was insert product
include("view_orders.php");
}
else if(isset($_GET['view_payments']))
{
// if the get request was insert product
include("view_payments.php");
}
?>
</p>
</div>
</div>
</body>
</html>
<?php } //if session is activated.. closing else of top else block ?><file_sep><?php
//retrieving the relevant information before html is rendered
include("includes/db.php");
if(isset($_GET['edit_brand']))
{
//initial get request
$brand_id = $_GET['edit_brand'];
$edit_brand = "Select * from brands where brand_id='$brand_id'";
$run_edit = mysqli_query($con,$edit_brand);
$row_brand = mysqli_fetch_array($run_edit);
$brand_edit_id = $row_brand['brand_id'];
$brand_title = $row_brand['brand_title'];
}//End of get request
?>
<html>
<head>
<title>Edit This Brand </title>
</head>
<style type ="text/css">
form{ margin:20%;}
</style>
<body>
<form action="" method="post">
<b> Edit this Brand </b>
<input type = "text" name="brand_title" value="<?php echo $brand_title;?>"/>
<input type = "Submit" name="update_brand" value="Update Brand" />
</form>
</body>
</html>
<?php
//The submit button will send the "postback" and the bellow code will execute in postback
if(isset($_POST['update_brand']))
{
$brand_titleTemp=$_POST['brand_title'];
$update_brand = "update brands SET brand_title='$brand_titleTemp' WHERE brand_id='$brand_edit_id'";
$run_update = mysqli_query($con,$update_brand);
if($run_update)
{
echo "<script>alert('Brand has been Updated!')</script>";
echo "<script>window.open('index.php?view_brands','_self')</script>";
}
}
?><file_sep>$(document).ready(function(){
$("a.mobile").click(function(){
$(".sidebar").slideToggle('fast');
});
window.onresize = function(event) {
if($(window).width() > 320) {
$(".sidebar").show();
}
};
});<file_sep><html>
<head>
</head>
<body>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;border-color:#aabcfe;}
.tg td{font-family:Arial, sans-serif;font-size:17px;padding:10px 30px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#aabcfe;color:#669;background-color:#e8edff;}
.tg th{font-family:Arial, sans-serif;font-size:17px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#aabcfe;color:#039;background-color:#b9c9fe;}
.tg .tg-0ord{text-align:right}
.tg .tg-ifyx{background-color:#D2E4FC;text-align:right}
.tg .tg-s6z2{text-align:center}
.tg .tg-vn4c{background-color:#D2E4FC}
</style>
<?php
if(isset($_GET['view_payments'])) { ?>
<table class="tg">
<tr>
<th class="tg-s6z2" colspan="8">View All Payments</th>
</tr>
<tr>
<td class="tg-vn4c">Payment ID </td>
<td class="tg-vn4c">Invoice Number </td>
<td class="tg-vn4c">Amount </td>
<td class="tg-vn4c">Payment Method </td>
<td class="tg-vn4c">Reference No. </td>
<td class="tg-vn4c">Date </td>
</tr>
<!--Retrieving data from php script here...-->
<?php
//database connection
include("includes/db.php");
$i=0;
$get_payments = "select * from payments";
//sql querry to retrive the data
$run_payments = mysqli_query($con,$get_payments);
while($row_payments = mysqli_fetch_array($run_payments))
{
$payment_id = $row_payments['payment_id'];
$invoice = $row_payments['invoice_no'];
$amount = $row_payments['amount'];
$payment_m=$row_payments['payment_mode'];
$ref_no=$row_payments['ref_no'];
$date=$row_payments['payment_date'];
$i++; // this is for numbering the product id starting with 1+
//whatever data comes in from this loop, they are assigned to the table columns bellow
?> <!-- This is the closing tag for php. We read all the data from php but OUR WHILE LOOP HAS NOT BEEN YET ENDED...-->
<tr align="center">
<td><?php echo $payment_id;?> </td>
<td bgcolor="FFCCCC"><?php echo $invoice;?> </td>
<td><?php echo $amount;?> </td>
<td><?php echo $payment_m;?> </td>
<td><?php echo $ref_no;?> </td>
<td><?php echo $date;?> </td>
<?php } ?> <!-- CLOSING THE } OF WHILE LOOP HERE... WE HAVE SUCCESSFULLY POPULATED THE VALUES-->
</table>
</tr>
<?php } ?>
</body>
</html><file_sep><?php
session_start();
include("includes/db.php");
if (isset($_GET['order_id']))
{
$order_id=$_GET['order_id'];
}
?>
<html>
<head>
</head>
<body bgcolor="#000000" >
<?php
if (isset($_GET['update_id']))
{
$order_id=$_GET['update_id'];
}
?>
<form action="confirm.php?update_id=<?php echo $order_id ?>" method="post">
//checking if update id is present
<?php
if (isset($_GET['update_id']))
{
$order_id=$_GET['update_id'];
}
?>
<table width="500" align="center" border="2" bgcolor="#CCCCCC">
<tr align="center">
<td colspan="5" ><h2> Please confrim your payment</h2></td>
</tr>
<tr>
<td>Invoice Number: </td>
<td> <input type="text" required name="invoice_no" /> </td>
</tr>
<tr>
<td>Amount: </td>
<td> <input type="text" required name="amount" /> </td>
</tr>
<tr>
<td>Select Payment Option: </td>
<td> <select required name="payment_method">
<option>Select Payment</option>
<option>Bank Transfer</option>
<option>Paypal</option>
<option>Western Union</option>
</select>
</td>
</tr>
<tr>
<td>Transaction/ReferenceID: </td>
<td> <input type="text" required name="ref_no" /> </td>
</tr>
<tr>
<td>Payment Date:</td>
<td> <input type="text" required name="date" /> </td>
</tr>
<tr align="center">
<td colspan="5"> <input type="submit" name="confirm" value="Confirm Payment"/> </td>
</tr>
</table>
</form>
</body>
<html>
<?php
if(isset($_POST['confirm']))
{
$update_id=$_GET['update_id'];
$invoice=$_POST['invoice_no'];
$amount=$_POST['amount'];
$payment_method=$_POST['payment_method'];
$ref_no=$_POST['ref_no'];
$date=$_POST['date'];
$complete ="completed";
//$update_id=
$invoice_check="select * from customer_orders WHERE order_id='$order_id'";
$run_invoice_check=mysqli_query($con,$invoice_check);
$run_invoice_row=mysqli_fetch_array($run_invoice_check);
$database_invoice_number=$run_invoice_row['invoice_no'];
if($database_invoice_number==$invoice)
{
$insert_payment="INSERT into payments(invoice_no,amount,payment_mode,ref_no,payment_date) values('$invoice','$amount','$payment_method',
'$ref_no','$date')";
$run_payment=mysqli_query($con,$insert_payment);
$update_order = "UPDATE customer_orders SET order_status='$complete' where order_id='$order_id'";
$run_order=mysqli_query($con,$update_order);
//$update_pending_order = "UPDATE pending_orders SET order_status='$complete' where invoice_no='$invoice'";
//$run_pending_order=mysqli_query($con,$update_pending_order);
if($run_payment)
{
echo "<script>alert('Thank you, Order will be processed within 24 hours!!')</script>";
echo "<script>window.open('my_account.php','_self')</script>";
$update_pending_order = "UPDATE pending_orders SET order_status='$complete' where invoice_no='$invoice'";
$run_pending_order=mysqli_query($con,$update_pending_order);
}
}
else
{
echo "<script>alert('Invalid invoice number. Please check your invoice number by clicking MY ORDERS in your account')</script>";
}
}
?>
<file_sep><form action="" method="post" >
<table width="700" border="2">
<tr>
<td colspan="4"> <h2> Change your password </h2> </td>
</tr>
<tr>
<td align="left"> <h3> Current Password : </h3> </td>
<td align="left"> <input type="password" name="old_pass" required /></td>
</tr>
<tr>
<td align="left"> <h3> Enter New Password : </h3> </td>
<td align="left"> <input type="password" name="new_pass" required /></td>
</tr>
<tr>
<td align="left"> <h3> Confirm New Password: </h3> </td>
<td align="left"> <input type="password" name="new_pass_again" required /></td>
</tr>
<tr align="center">
<td colspan="4"><input type="submit" name="change_pass" value="Change Password"/></td>
</tr>
</form>
<?php
include("includes/db.php");
$current_user=$_SESSION['customer_email'];
//validating password
if(isset($_POST['change_pass'])) //if user clicks change pass
{
$old_pass=$_POST['old_pass'];
$new_pass = $_POST['new_pass'];
$new_pass_again=$_POST['new_pass_again'];
//validating old password
$get_real_pass="select * from customers where customer_pass='$<PASSWORD>'";
$run_real_pass=mysqli_query($con,$get_real_pass);
$check_pass=mysqli_num_rows($run_real_pass);
if($check_pass==0)
{
echo "<script> alert('Invalid current password!')</script>";
exit();
}
if($new_pass!=$new_pass_again)
{
echo "<script> alert('New password did not match!!')</script>";
exit();
}
else
{
$update_pass="update customers set customer_pass='<PASSWORD>' WHERE customer_email='$current_user'";
$run_pass=mysqli_query($con,$update_pass);
if($run_pass)
{
echo "<script> alert('Password changed successfully!')</script>";
echo "<script>window.open('my_account.php','_self')</script>";
}
else
{
echo "<script> alert('Error occured!!!')</script>";
echo "<script>window.open('my_account.php','_self')</script>";
}
}
}
?><file_sep><html>
<head></head>
<body>
<form action="" method="post" bgcolor="#BDBD9D">
<table align="center" width="600">
<tr align="center">
<td> <h3> Do you really want to delete your account ? </h3> </td>
</tr>
<tr align="left">
<td colspan="2"><input type="submit" name="yes" value="Yes, Delete My account"/></td>
<td ><input type="submit" name="no" value="No,Take me away"/></td>
</tr>
</table>
</form>
<?php
include("includes/db.php");
$c=$_SESSION['customer_email'];
if(isset($_POST['yes']))
{
$delete_customer="delete from customers where customer_email='$c'";
$run_delete=mysqli_query($con,$delete_customer);
if($run_delete)
{
session_destroy();
echo "<script> alert('Your account has been deleted,Good Bye!')</script>";
echo "<script>window.open('../index.php','_self')</script>";
}
else
{
echo "<script> alert('Failed')</script>";
}
}
if(isset($_POST['no']))
{
echo "<script>window.open('my_account.php','_self')</script>";
}
?>
</body>
</html>
<file_sep><?php
include("includes/db.php");
//when admin clicks delete, the product id is passed / stored in a get variable
// we can use this variable to delete the product with that specific ID
if(isset($_GET['delete_order'])){
$delete_id = $_GET['delete_order'];
$delete_order = "DELETE FROM pending_orders WHERE order_id='$delete_id'";
$run_delete = mysqli_query($con,$delete_order);
if($run_delete){
echo "<script>alert('Order has been deleted!')</script>";
echo "<script>window.open('index.php?view_orders','_self')</script>";
}
}
?><file_sep># kshop :shopping_cart:
k-Shop is my final year university project, an ecommerce website still under development.
<br>
## Stack :hammer_and_wrench:
:point_right: html <br>
:point_right: css <br>
:point_right: jquery <br>
:point_right: php <br>
:point_right: mysql <br>
:point_right: boostrap <br>
:point_right: ajax <br>
Feel free to clone and use or contribute to this work.
Note that its not 100% complete, some links might be broken as I haven't worked on it since I presented it at my final year defense in the university.
New modifications/suggestions are welcome.
:bowtie: Cheers...
<file_sep><html>
<head>
</head>
<body>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;border-color:#aabcfe;}
.tg td{font-family:Arial, sans-serif;font-size:17px;padding:10px 30px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#aabcfe;color:#669;background-color:#e8edff;}
.tg th{font-family:Arial, sans-serif;font-size:17px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#aabcfe;color:#039;background-color:#b9c9fe;}
.tg .tg-0ord{text-align:right}
.tg .tg-ifyx{background-color:#D2E4FC;text-align:right}
.tg .tg-s6z2{text-align:center}
.tg .tg-vn4c{background-color:#D2E4FC}
</style>
<?php
if(isset($_GET['view_orders'])) { ?>
<table class="tg">
<tr>
<th class="tg-s6z2" colspan="8">View All Customers Orders</th>
</tr>
<tr>
<td class="tg-vn4c">Order No </td>
<td class="tg-vn4c">Customer Email </td>
<td class="tg-vn4c">Invoice No. </td>
<td class="tg-vn4c">Product ID </td>
<td class="tg-vn4c">Quantity </td>
<td class="tg-vn4c">Status </td>
<td class="tg-vn4c">Delete </td>
</tr>
<!--Retrieving data from php script here...-->
<?php
//database connection
include("includes/db.php");
$i=0;
$get_orders = "select * from pending_orders";
//sql querry to retrive the data
$run_orders = mysqli_query($con,$get_orders);
while($row_orders = mysqli_fetch_array($run_orders))
{
$order_id = $row_orders['order_id'];
$c_id = $row_orders['customer_id'];
$invoice = $row_orders['invoice_no'];
$p_id = $row_orders['product_id'];
$qty=$row_orders['qty'];
$status=$row_orders['order_status'];
$i++; // this is for numbering the product id starting with 1+
//whatever data comes in from this loop, they are assigned to the table columns bellow
?> <!-- This is the closing tag for php. We read all the data from php but OUR WHILE LOOP HAS NOT BEEN YET ENDED...-->
<tr align="center">
<?php
$get_customer="select * from customers where customer_id='$c_id'";
$run_customer=mysqli_query($con,$get_customer);
$row_customer=mysqli_fetch_array($run_customer);
$customer_email = $row_customer['customer_email'];
?>
<td><?php echo $i;?> </td>
<td><?php echo $customer_email;?> </td>
<td><?php echo $invoice;?> </td>
<td><?php echo $p_id;?> </td>
<td><?php echo $qty;?> </td>
<td><?php
if($status=='Pending')
{
$status='Pending';
}
else if($status=='Complete')
{
$status='Complete';
}
echo $status;?> </td>
<td> <a href="delete_order.php?delete_order=<?php echo $order_id;?>"> Delete </a> </td>
<?php } ?> <!-- CLOSING THE } OF WHILE LOOP HERE... WE HAVE SUCCESSFULLY POPULATED THE VALUES-->
</table>
</tr>
<?php } ?>
</body>
</html><file_sep><html>
<head>
</head>
<body>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;border-color:#aabcfe;}
.tg td{font-family:Arial, sans-serif;font-size:17px;padding:10px 30px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#aabcfe;color:#669;background-color:#e8edff;}
.tg th{font-family:Arial, sans-serif;font-size:17px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#aabcfe;color:#039;background-color:#b9c9fe;}
.tg .tg-0ord{text-align:right}
.tg .tg-ifyx{background-color:#D2E4FC;text-align:right}
.tg .tg-s6z2{text-align:center}
.tg .tg-vn4c{background-color:#D2E4FC}
</style>
<?php
if(isset($_GET['view_customers'])) { ?>
<table class="tg">
<tr>
<th class="tg-s6z2" colspan="8">View All Customers</th>
</tr>
<tr>
<td class="tg-vn4c">ID </td>
<td class="tg-vn4c">Name </td>
<td class="tg-vn4c">Email </td>
<td class="tg-vn4c">Image </td>
<td class="tg-vn4c">Country </td>
<td class="tg-vn4c">Delete </td>
</tr>
<!--Retrieving data from php script here...-->
<?php
//database connection
include("includes/db.php");
$i=0;
$get_pro = "select * from customers";
//sql querry to retrive the data
$run_pro = mysqli_query($con,$get_pro);
while($row_pro = mysqli_fetch_array($run_pro))
{
$c_id = $row_pro['customer_id'];
$c_name = $row_pro['customer_name'];
$c_email = $row_pro['customer_email'];
$c_image = $row_pro['customer_image'];
$c_country=$row_pro['customer_country'];
$i++; // this is for numbering the product id starting with 1+
//whatever data comes in from this loop, they are assigned to the table columns bellow
?> <!-- This is the closing tag for php. We read all the data from php but OUR WHILE LOOP HAS NOT BEEN YET ENDED...-->
<tr align="center">
<td><?php echo $c_id;?> </td>
<td><?php echo $c_name;?> </td>
<td><?php echo $c_email;?> </td>
<td> <img src="../customer/customer_photos/<?php echo $c_image;?>" width="70" height="70" </td>
<td> <?php echo $c_country;?> </td>
<td> <a href="delete_c.php?delete_c=<?php echo $c_id;?>"> Delete </a> </td>
<?php } ?> <!-- CLOSING THE } OF WHILE LOOP HERE... WE HAVE SUCCESSFULLY POPULATED THE VALUES-->
</table>
</tr>
<?php } ?>
</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=iso-8859-1" />
<title>Customer Login</title>
</head>
<body>
<?php
@session_start(); //no error if it's not initialised
include("includes/db.php");
//include("functions/functions.php");
?>
<div>
<form action="checkout.php" method="post">
<table width="600" align="center">
<tr>
<td align="right"><b>Your Email: </b></td>
<td align="left"><input type="text" name="customer_email" value=""/><br/></td>
</tr>
<tr>
<td align="right"><b>Your Password: </b></td>
<td align="left"><input type="password" name="customer_pass" value=""/><br/></td>
</tr>
<tr>
<tr>
<td colspan="5"><a href="checkout.php?forgot_pass">Forgot Password</a></td>
</tr>
<td colspan="5"><input type="submit" name="customer_login" value="Login"/></td>
</tr>
</table>
</form>
<?php
if(isset($_GET['forgot_pass']))
{
echo "
<br><br>
<div align='center'>
<b> Enter your email please </b>
<form action='' method='post'>
<input type='text' name='c_email' required placeholder='Enter your email'/>
<br>
<input type='submit' name='forgot_pass' value='Send me password' />
</form>
</div>
";
//if forgot button is clicked
if(isset($_POST['forgot_pass']))
{
//get user email
//email textbox/forgot pass
$c_email=$_POST['c_email'];
$sel_c="select * from customers where customer_email='$c_email'";
$run_c=mysqli_query($con,$sel_c);
//check if email was found in the database
$check_c=mysqli_num_rows($run_c);
$row_c=mysqli_fetch_array($run_c);
$c_name=$row_c['customer_name'];
$c_pass=$row_c['customer_pass'];
if($check_c==0)
{
echo "<script>alert('Email was not found in our database!!') </script>";
exit();
}
else
{
//composing message
echo "OK";
$from='<EMAIL>';
$subject='Password Recovery';
$headers = "From: <EMAIL>";
$message="You have requested for your password.Your Password is : <PASSWORD> ";
mail($c_email, $subject, $message,$headers);
echo "<script>alert('Password is sent, please check your email!!') </script>";
echo "<script>window.open('checkout.php','_self')</script>";
//using google smtp
/*require_once "Mail.php";
$from2 = '<from.gmail.com>';
$to = '<to.yahoo.com>';
$subject = 'Hi!';
$body = "Hi,\n\nHow are you?";
$headers = array(
'From' => $from2,
'To' => $to,
'Subject' => $subject
);
$smtp = Mail::factory('smtp', array(
'host' => 'ssl://smtp.gmail.com',
'port' => '465',
'auth' => true,
'username' => 'john<EMAIL>',
'password' => '<PASSWORD>'
));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo('<p>' . $mail->getMessage() . '</p>');
} else {
echo('<p>Message successfully sent!</p>');
}
*/
}
}
}
?>
<h4 align="center"><a href="customer_register.php">New Customer Registers Here</a></h4>
</div>
<?php
//fires out when user clicks login
if(isset($_POST['customer_login']))
{
//checking if the user/customer login credentials exist in the database.
$customer_email = $_POST['customer_email'];
$customer_pass = $_POST['customer_pass'];
$select_customer = "SELECT * FROM customers where customer_email='$customer_email' AND customer_pass='$customer_<PASSWORD>'";
$run_customer = mysqli_query($con,$select_customer);
$check_customer=mysqli_num_rows($run_customer);
$get_ip = getRealIpAddress(); //there is an include on the top
//if there are any items that needs to be checked out we will direct them to checkout page when the user is logged in
$sel_cart = "select * from cart where ip_add='$get_ip'";
$run_cart = mysqli_query($con,$sel_cart);
$check_cart = mysqli_num_rows($run_cart);
if($check_customer==0)
{
echo "<script>alert('Password/email address is incorrect') </script>";
exit(); //returning
}
if($check_customer==1 AND $check_cart==0)
{
$_SESSION['customer_email']=$customer_email;
//redirect
echo "<script>window.open('/kshop/customer/my_account.php','_self')</script>";
}
else
{
$_SESSION['customer_email']=$customer_email;
//echo "<script>window.open('payment_options.php','_self')</script>";
echo "<script>alert('You have successfully logged in!!')</script>";
echo "<script>window.open('checkout.php','_self')</script>";
//include("payment_options.php");
}
}
?>
</body>
</html>
<file_sep><?php
@session_start(); //no error if it's not initialized
include("includes/db.php");
//getting the customer id
global $db;
$c= $_SESSION['customer_email'];
$get_c = "select * from customers where customer_email='$c'";
$run_c=mysqli_query($db,$get_c);
$row_c = mysqli_fetch_array($run_c);
$customer_id=$row_c['customer_id'];
?>
<table width="780" align="center" bgcolor="#6699FF">
<tr>
<th> Order No </th>
<th> Due Amount</th>
<th> Invoice Number</th>
<th> Total Products </th>
<th> Order Date</th>
<th> Paid/Unpaid</th>
<th> Status</th>
</tr>
<?php
$get_orders="select * from customer_orders where customer_id='$customer_id'";
$run_orders=mysqli_query($con,$get_orders);
$i=0;
while ($row_orders=mysqli_fetch_array($run_orders)) {
$order_id=$row_orders['order_id'];
$due_amount=$row_orders['due_amount'];
$invoice_no=$row_orders['invoice_no'];
$total_products=$row_orders['total_products'];
$date=$row_orders['order_date'];
$Status=$row_orders['order_status'];
$i++;
if($Status=='Pending')
{
$Status='Unpaid';
}
else
{
$Status='Paid';
}
echo "
<tr align='center'>
<td> $i </td>
<td> #$due_amount </td>
<td> $invoice_no </td>
<td> $total_products </td>
<td> $date </td>
<td> $Status </td>
<td> <a href='confirm.php?order_id=$order_id' target='_blank'> Confirm if Paid </td>
";
}
?>
</table>
<file_sep><?php
include("includes/db.php");
include("functions/functions.php");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>Search Result | K-Shop</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/prettyPhoto.css" rel="stylesheet">
<link href="css/price-range.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<link href="css/responsive.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<script src="js/respond.min.js"></script>
<![endif]-->
</head><!--/head-->
<body>
<header id="header"><!--header-->
<div class="header_top"><!--header_top-->
<div class="container">
<div class="row">
<div class="col-sm-6">
<div class="contactinfo">
<ul class="nav nav-pills">
<li><a href="#"><i class="fa fa-phone"></i> +2349039933771 </a></li>
<li><a href="#"><i class="fa fa-envelope"></i> <EMAIL></a></li>
</ul>
</div>
</div>
<div class="col-sm-6">
<div class="social-icons pull-right">
<ul class="nav navbar-nav">
<li><a href="http://www.fb.com/kingston.fortune2"><i class="fa fa-facebook"></i></a></li>
<li><a href="http://www.twitter.com/@chun__king"><i class="fa fa-twitter"></i></a></li>
<li><a href="http://www.linkedin.com/kingstonfortune"><i class="fa fa-linkedin"></i></a></li>
<li><a href="http://www.dribbble.com/kingstonfortune"><i class="fa fa-dribbble"></i></a></li>
<li><a href="http://plus.google.com/kingstonfortune"><i class="fa fa-google-plus"></i></a></li>
</ul>
</div>
</div>
</div>
</div>
</div><!--/header_top-->
<div class="header-middle"><!--header-middle-->
<div class="container">
<div class="row">
<div class="col-sm-4">
<div class="logo pull-left">
<a href="index.php"><img src="images/home/logo1.png" alt="" /></a>
</div>
</div>
<div class="col-sm-8">
<div class="shop-menu pull-right">
<ul class="nav navbar-nav">
<li><a href="cart.html"><i class="fa fa-shopping-cart"></i> Cart</a></li>
<li><a href="login.html"><i class="fa fa-lock"></i> Login</a></li>
</ul>
</div>
</div>
</div>
</div>
</div><!--/header-middle-->
<div class="header-bottom"><!--header-bottom-->
<div class="container">
<div class="row">
<div class="col-sm-9">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="mainmenu pull-left">
<ul class="nav navbar-nav collapse navbar-collapse">
<li><a href="index.php" class="active">Home</a></li>
<li><a href="all_products.php">All Products</a></li>
<li><a href="Products.html">My Account</a></li>
<li><a href="Products.html">Shopping Cart</a></li>
<li><a href="Contact.html">Contact Us</a></li>
</ul>
</div>
</div>
<!--Search Box starts-->
<div>
<form method="get" action="results.php" enctype="multipart/form-data">
<input type="text" name="user_query" placeholder="Search a Product"/>
<input type="submit" name="search" value="Search"/>
</form>
</div>
<!--Search Box ends-->
</div>
</div>
</div><!--/header-bottom-->
</header><!--/header-->
<section id="slider"><!--slider-->
<div class="container">
<div class="row">
<div class="col-sm-12">
<div id="slider-carousel" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#slider-carousel" data-slide-to="0" class="active"></li>
<li data-target="#slider-carousel" data-slide-to="1"></li>
<li data-target="#slider-carousel" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<div class="item active">
<div class="col-sm-6">
<h1><span>K</span>-Shop</h1>
<h2>K-Shop</h2>
<p>Delivering the very best of consumer products around the world. Every one of our products gives you 100% satisfaction. </p>
<button type="button" class="btn btn-default get">Get it now</button>
</div>
<div class="col-sm-6">
<img src="images/home/videocam.jpg" class="girl img-responsive" alt="" />
</div>
</div>
<div class="item">
<div class="col-sm-6">
<h1><span>K</span>-Shop</h1>
<h2>K-Shop</h2>
<p>Delivering the very best of consumer products around the world. Every one of our products gives you 100% satisfaction. </p>
</div>
<div class="col-sm-6">
<img src="images/home/tablet.jpg" class="girl img-responsive" alt="" />
</div>
</div>
<div class="item">
<div class="col-sm-6">
<h1><span>K</span>-Shop</h1>
<h2>K-Shop</h2>
<p>Delivering the very best of consumer products around the world. Every one of our products gives you 100% satisfaction. </p>
<button type="button" class="btn btn-default get">Get it now</button>
</div>
<div class="col-sm-6">
<img src="images/home/smarttv.jpg" class="girl img-responsive" alt="" />
<
</div>
</div>
</div>
<a href="#slider-carousel" class="left control-carousel hidden-xs" data-slide="prev">
<i class="fa fa-angle-left"></i>
</a>
<a href="#slider-carousel" class="right control-carousel hidden-xs" data-slide="next">
<i class="fa fa-angle-right"></i>
</a>
</div>
</div>
</div>
</div>
</section><!--/slider-->
<section>
<div class="container">
<div class="row">
<div class="col-sm-3">
<div class="left-sidebar">
<h2>Categories</h2>
<div class="panel-group category-products" id="accordian"><!--category-products start-->
<div class="category-tab ul li ">
<ul class="nav nav-pills nav-stacked" id="categories">
<?php getCategories(); ?>
</ul>
</div>
</div><!--/category-products ends-->
<div class="brands_products"><!--brands_products start-->
<h2>Brands</h2>
<div class="category-tab ul li ">
<ul class="nav nav-pills nav-stacked" id="brands">
<?php getBrands();
?>
</ul>
</div>
</div><!--/brands_products Ends-->
<div class="shipping text-center"><!--shipping stars-->
<img src="images/home/shipping.jpg" alt="" />
</div><!--/shipping Ends-->
</div>
</div>
<div class="col-sm-9 padding-right">
<div class="features_items" id="products_box"><!--features_items start-->
<h2 class="title text-center">Featured Items</h2>
<?php
if(isset($_GET['search']))
{
$user_keyword = $_GET['user_query'];
$get_products = "select * from products where product_keywords LIKE '%$user_keyword%'";
$run_products = mysqli_query($con, $get_products);
while($row_products= mysqli_fetch_array($run_products))
{
$pro_id = $row_products['product_id'];
$pro_title = $row_products['product_title'];
$pro_cat = $row_products['cat_id'];
$pro_brand = $row_products['brand_id'];
$pro_desc = $row_products['product_desc'];
$pro_price = $row_products['product_price'];
$pro_image = $row_products['product_img1'];
echo "
<div id='single_product'>
<h3>$pro_title</h3>
<img src='admin_area/product_images/$pro_image' width='160' height='160'/><br>
<p><b>Price: £$pro_price</b></p>
<a href='details.php?pro_id=$pro_id' style='float:left;'>Details</a>
<a href='index.php?add_cart=$pro_id'><button style='float:right;'>Add to Cart</button></a>
</div>
";
}//while
}//if
?>
</div><!--features_items Ends-->
</div><!--/category-tab-->
</div>
</div>
</div>
</section>
<footer id="footer"><!--Footer-->
<div class="footer-top">
<div class="container">
<div class="row">
<div class="col-sm-2">
<div class="companyinfo">
<h3><span>K</span>-Shop</h3>
<p>We provide the very best of consumer products all around the globe.</p>
</div>
</div>
<div class="col-sm-7">
<div class="col-sm-3">
<div class="video-gallery text-center">
<a href="#">
<div class="iframe-img">
<img src="images/home/iframe1.png" alt="" />
</div>
<div class="overlay-icon">
<i class="fa fa-play-circle-o"></i>
</div>
</a>
<p>Cliffs Of Moher</p>
<h2>24 April 2015</h2>
</div>
</div>
<div class="col-sm-3">
<div class="video-gallery text-center">
<a href="#">
<div class="iframe-img">
<img src="images/home/iframe2.png" alt="" />
</div>
<div class="overlay-icon">
<i class="fa fa-play-circle-o"></i>
</div>
</a>
<p>St Patrick's Day</p>
<h2>17 March 2015</h2>
</div>
</div>
<div class="col-sm-3">
<div class="video-gallery text-center">
<a href="#">
<div class="iframe-img">
<img src="images/home/iframe3.png" alt="" />
</div>
<div class="overlay-icon">
<i class="fa fa-play-circle-o"></i>
</div>
</a>
<p>Map Of Nigeria</p>
<h2>24 DEC 2015</h2>
</div>
</div>
<div class="col-sm-3">
<div class="video-gallery text-center">
<a href="#">
<div class="iframe-img">
<img src="images/home/iframe4.png" alt="" />
</div>
<div class="overlay-icon">
<i class="fa fa-play-circle-o"></i>
</div>
</a>
<p>Fupre Campus</p>
<h2>24 May 2015</h2>
</div>
</div>
</div>
<div class="col-sm-3">
<div class="address">
<img src="images/home/map.png" alt="" />
<p>K-Shop, A Product of Fortune - Fupre, Nigeria</p>
</div>
</div>
</div>
</div>
</div>
<div class="footer-bottom">
<div class="container">
<div class="row">
<p class="pull-left">Copyright © 2015 K-Shop Inc. All rights reserved.</p>
<p class="pull-right">Designed by <span><a target="_blank">King Fortune</a></span></p>
</div>
</div>
</div>
</footer><!--/Footer-->
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.scrollUp.min.js"></script>
<script src="js/price-range.js"></script>
<script src="js/jquery.prettyPhoto.js"></script>
<script src="js/main.js"></script>
</body>
</html><file_sep><html>
<head>
</head>
<body>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;border-color:#aabcfe;}
.tg td{font-family:Arial, sans-serif;font-size:17px;padding:10px 30px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#aabcfe;color:#669;background-color:#e8edff;}
.tg th{font-family:Arial, sans-serif;font-size:17px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#aabcfe;color:#039;background-color:#b9c9fe;}
.tg .tg-0ord{text-align:right}
.tg .tg-ifyx{background-color:#D2E4FC;text-align:right}
.tg .tg-s6z2{text-align:center}
.tg .tg-vn4c{background-color:#D2E4FC}
</style>
<?php
if(isset($_GET['view_products'])) { ?>
<table class="tg">
<tr>
<th class="tg-s6z2" colspan="10">Products Description</th>
</tr>
<tr>
<td class="tg-vn4c">Product ID </td>
<td class="tg-vn4c">Title </td>
<td class="tg-vn4c">Image </td>
<td class="tg-vn4c">Price </td>
<td class="tg-vn4c">Total Sold </td>
<td class="tg-vn4c">Total Pending </td>
<td class="tg-vn4c">Status </td>
<td class="tg-vn4c">Edit </td>
<td class="tg-vn4c">Delete </td>
</tr>
<!--Retrieving data from php script here...-->
<?php
//database connection
include("includes/db.php");
$i=0;
$get_pro = "select * from products";
//sql querry to retrive the data
$run_pro = mysqli_query($con,$get_pro);
while($row_pro = mysqli_fetch_array($run_pro))
{
$p_id = $row_pro['product_id'];
$p_title = $row_pro['product_title'];
$p_img = $row_pro['product_img1'];
$p_price = $row_pro['product_price'];
$status = $row_pro['status'];
$i++; // this is for numbering the product id starting with 1+
//whatever data comes in from this loop, they are assigned to the table columns bellow
?> <!-- This is the closing tag for php. We read all the data from php but OUR WHILE LOOP HAS NOT BEEN YET ENDED...-->
<tr>
<td> <?php echo $i; ?> </td>
<td> <?php echo $p_title; ?></td>
<td> <img src="product_images/<?php echo $p_img;?>" width="50" height="50" </td>
<td> <?php echo $p_price;?> </td>
<td>
<?php
//total order of this product
$get_sold = "select * from pending_orders where product_id='$p_id' AND order_status='completed'";
$run_sold = mysqli_query($con,$get_sold);
$count = mysqli_num_rows($run_sold);
echo $count;
?>
</td>
<td>
<?php
//total order of this product
$get_sold = "select * from pending_orders where product_id='$p_id' AND order_status='Pending'";
$run_sold = mysqli_query($con,$get_sold);
$count = mysqli_num_rows($run_sold);
echo $count;
?>
</td>
<td> <?php echo $status; ?></td>
<td> <a href="index.php?edit_pro=<?php echo $p_id;?>"> Edit </a> </td>
<td> <a href="delete_pro.php?delete_pro=<?php echo $p_id;?>"> Delete </a> </td>
</tr>
<?php } ?> <!-- CLOSING THE } OF WHILE LOOP HERE... WE HAVE SUCCESSFULLY POPULATED THE VALUES-->
</table>
<?php } ?>
</body>
</html><file_sep><?php
include("includes/db.php");
//when admin clicks delete, the product id is passed / stored in a get variable
// we can use this variable to delete the product with that specific ID
if(isset($_GET['delete_brand'])){
$delete_id = $_GET['delete_brand']; // this is the key that containing the value of a specific brand_id
$delete_brand = "DELETE FROM brands WHERE brand_id='$delete_id'";
$run_delete = mysqli_query($con,$delete_brand);
if($run_delete){
echo "<script>alert('One Brand has been deleted!')</script>";
echo "<script>window.open('index.php?view_brands','_self')</script>";
}
}
?><file_sep>
<?php
@session_start();
include("includes/db.php");
if(isset($_GET['edit_account']))
{
$customer_email = $_SESSION['customer_email'];
$get_customer = "select * from customers where customer_email='$customer_email'";
$run_customer=mysqli_query($con,$get_customer);
if($run_customer)
{
//CAN DO SOMETHING HERE
}
$row=mysqli_fetch_array($run_customer);
$id=$row['customer_id'];
$name=$row['customer_name'];
$email=$row['customer_email'];
$country=$row['customer_country'];
$city=$row['customer_city'];
$contact=$row['customer_contact'];
$address=$row['customer_address'];
$image=$row['customer_image'];
}
?>
<html>
<head></head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<table align="center" width="600">
<tr>
<td colspan="8" align="center"> <h2> Update your account:</h2></h2></td>
</tr>
<tr>
<td align="center">Customer Name: </td>
<td> <input type="text" name="c_name" value="<?php echo $name;?>"> </td>
</tr>
<tr>
<td align="center">Customer Email: </td>
<td> <input type="text" name="c_email" value="<?php echo $email;?>"> </td>
</tr>
<tr>
<td align="center">Customer Contact: </td>
<td> <input type="text" name="c_contact" value="<?php echo $contact;?>"> </td>
</tr>
<tr>
<td align="center">Customer country: </td>
<td>
<select name="c_country:" width="30" disabled>
<option value="<?php echo $country; ?>"><?php echo $country;?> </option>
<option> Nigeria </option>
<option> Ghana </option>
<option> United Kingdom </option>
<option> United States </option>
<option> Japan </option>
</select>
</td>
</tr>
<tr>
<td align="center">Customer City: </td>
<td> <input type="text" name="c_city" value="<?php echo $city;?>"> </td>
</tr>
<tr>
<td align="center">Customer Address: </td>
<td> <input type="text" name="c_address" value="<?php echo $address;?>"> </td>
</tr>
<tr>
<td align="center">Customer Image: </td>
<td> <input type="file" name="c_image" size="60" > <img src="customer_photos/<?php echo $image; ?>" width="60" height="60"> </td>
</tr>
<tr>
<td align="center" colspan="8"> <input type="submit" name="update_account" value="Update Now"> </td>
<tr>
</table>
</form>
</body>
</html>
<?php
//for updating
if(isset($_POST['update_account']))
{
$update_id=$id;
$c_name=$_POST['c_name'];
$c_email=$_POST['c_email'];
$c_city=$_POST['c_city'];
$c_contact=$_POST['c_contact'];
$c_address=$_POST['c_address'];
$c_image = $_FILES['c_image']['name'];
$c_image_tmp = $_FILES['c_image']['tmp_name'];
move_uploaded_file($c_image_tmp, "customer_photos/$c_image");
//$update_c="update customers set customer_name='$c_name',customer_email='$c_email,customer_pass='$<PASSWORD>',customer_city='$c_city', customer_contact='$c_contact', customer_address='$c_address' WHERE customer_id='$update_id' ";
$update_c="update customers set customer_name='$c_name',customer_email='$c_email',customer_contact='$c_contact',customer_city='$c_city',customer_address='$c_address',customer_image='$c_image' where customer_id ='$id' ";
$run_c=mysqli_query($con,$update_c);
if($run_c)
{
echo "<script> alert('your account has been updated')</script>";
}
else
{
echo "<script> alert('Couldnt update')</script>";
echo "<script>window.open('my_account.php','_self')</script>";
}
}
?>
<file_sep><html>
<head>
<title>Insert Category </title>
</head>
<style type ="text/css">
form{ margin:20%;}
</style>
<body>
<form action="" method="post">
<b> Insert New Category </b> <input type = "text" name="cat_title" />
<input type = "Submit" name="insert_cat" value="Insert" />
</form>
<?php
include("includes/db.php");
if(isset($_POST['insert_cat'])){ //button click-> postback request
$cat_title = $_POST['cat_title'];
if($cat_title!=""){
$insert_category = "INSERT INTO categories (cat_title) values ('$cat_title')";
$run_cat = mysqli_query($con,$insert_category);
if($run_cat){ //true
echo "<script>alert('New Category has been inserted!')</script>";
echo "<script>window.open('index.php?view_cats','_self')</script>";
}//End of if
}
else{
echo "<script>alert('Category name cannot be empty!')</script>";
}
}//End of postback here
?>
</body>
</html><file_sep><?php
//retrieving the relevant information before html is rendered
include("includes/db.php");
if(isset($_GET['edit_cat']))
{
//initial get request
$cat_id = $_GET['edit_cat'];
$edit_cat = "Select * from categories where cat_id='$cat_id'";
$run_edit = mysqli_query($con,$edit_cat);
$row_edit = mysqli_fetch_array($run_edit);
$cat_edit_id = $row_edit['cat_id'];
$cat_title = $row_edit['cat_title'];
}//End of get request
?>
<html>
<head>
<title>Edit This Category </title>
</head>
<style type ="text/css">
form{ margin:20%;}
</style>
<body>
<form action="" method="post">
<b> Edit this Category </b>
<input type = "text" name="cat_title" value="<?php echo $cat_title;?>"/>
<input type = "Submit" name="update_cat" value="Update Category" />
</form>
</body>
</html>
<?php
//The submit button will send the "postback" and the bellow code will execute in postback
if(isset($_POST['cat_title']))
{
$cat_titleTemp=$_POST['cat_title'];
$update_cat = "update categories SET cat_title='$cat_titleTemp' WHERE cat_id='$cat_edit_id'";
$run_update = mysqli_query($con,$update_cat);
if($run_update)
{
echo "<script>alert('Category has been Updated!')</script>";
echo "<script>window.open('index.php?view_cats','_self')</script>";
}
}
?><file_sep><?php
//logging out admin by destroying the session
session_start();
session_destroy();
echo "<script>alert('Good Bye!! :)')</script>";
echo "<script>window.open('login/login.php','_self')</script>";
?><file_sep><html>
<head>
<title>Insert Category </title>
</head>
<style type ="text/css">
form{ margin:20%;}
</style>
<body>
<form action="" method="post">
<b> Insert New Brand </b> <input type = "text" name="brand_title" />
<input type = "Submit" name="insert_brand" value="Insert" />
</form>
<?php
include("includes/db.php");
if(isset($_POST['insert_brand'])){ //button click-> postback request
$brand_title = $_POST['brand_title'];
if($brand_title!=""){
$insert_brand = "INSERT INTO brands (brand_title) values ('$brand_title')";
$run_brand = mysqli_query($con,$insert_brand);
if($run_brand){ //true
echo "<script>alert('New Brand has been inserted!')</script>";
echo "<script>window.open('index.php?view_brands','_self')</script>";
}//End of if
}
else{
echo "<script>alert('Category name cannot be empty!')</script>";
}
}//End of postback here
?>
</body>
</html><file_sep><?php
include("includes/db.php");
//when admin clicks delete, the product id is passed / stored in a get variable
// we can use this variable to delete the product with that specific ID
if(isset($_GET['delete_pro'])){
$delete_id = $_GET['delete_pro'];
$delete_pro = "DELETE FROM products WHERE product_id='$delete_id'";
$run_delete = mysqli_query($con,$delete_pro);
if($run_delete){
echo "<script>alert('Product has been deleted!')</script>";
echo "<script>window.open('index.php?view_products','_self')</script>";
}
}
?><file_sep><?php
session_start();
include("includes/db.php");
include("functions/functions.php");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link href="scripts/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="scripts/bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet">
<link href="./css/bootstrap.min.css" rel="stylesheet" media="screen">
<!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link href="styles/custom.css" rel="stylesheet" type="text/css" />
<script src="email/validation.js" type="text/javascript"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>Contact Us | K-Shop</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/prettyPhoto.css" rel="stylesheet">
<link href="css/price-range.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<link href="css/responsive.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<script src="js/respond.min.js"></script>
<![endif]-->
</head><!--/head-->
<body>
<header id="header"><!--header-->
<div class="header_top"><!--header_top-->
<div class="container">
<div class="row">
<div class="col-sm-6">
<div class="contactinfo">
<ul class="nav nav-pills">
<li><a href="#"><i class="fa fa-phone"></i> +2349039933771 </a></li>
<li><a href="#"><i class="fa fa-envelope"></i> <EMAIL></a></li>
</ul>
</div>
</div>
<div class="col-sm-6">
<div class="social-icons pull-right">
<ul class="nav navbar-nav">
<li><a href="http://www.fb.com/kingston.fortune2"><i class="fa fa-facebook"></i></a></li>
<li><a href="http://www.twitter.com/@chun__king"><i class="fa fa-twitter"></i></a></li>
<li><a href="http://www.linkedin.com/kingstonfortune"><i class="fa fa-linkedin"></i></a></li>
<li><a href="http://www.dribbble.com/kingstonfortune"><i class="fa fa-dribbble"></i></a></li>
<li><a href="http://plus.google.com/kingstonfortune"><i class="fa fa-google-plus"></i></a></li>
</ul>
</div>
</div>
</div>
</div>
</div><!--/header_top-->
<div class="header-middle"><!--header-middle-->
<div class="container">
<div class="row">
<div class="col-sm-4">
<div class="logo pull-left">
<a href="index.php"><img src="images/home/logo1.png" alt="" /></a>
</div>
</div>
<div class="col-sm-8">
<div class="shop-menu pull-right">
<ul class="nav navbar-nav">
<li><a href="cart.php"><i class="fa fa-shopping-cart"></i> Cart</a></li>
<?php
if(!isset($_SESSION['customer_email']))
{
//echo "<a href='checkout.php'> Login</a>";
echo "<li><a href='checkout.php'><i class='fa fa-lock'></i> Login</a></li>";
}
else
{
echo "<li><a href='logout.php'><i class='fa fa-lock'></i> Logout</a></li>";
}
?>
</ul>
</div>
</div>
<?php
cart();
?>
<?php
if(!isset($_SESSION['customer_email']))
{
echo "<b> Welcome Guest! </b>";
}
else
{
$userName = $_SESSION['customer_email'];
echo "<b style='color: #fdb45e;'> Welcome: $userName! </b>";
}
?>
<b style=" color: #fdb45e;">Shopping Cart:</b>
<span>-Total Items: <?php itemsFromCart(); ?> - Total Price: #<?php getTotalPrice(); ?></span>
</div>
</div>
</div><!--/header-middle-->
<div class="header-bottom"><!--header-bottom-->
<div class="container">
<div class="row">
<div class="col-sm-9">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="mainmenu pull-left">
<ul class="nav navbar-nav collapse navbar-collapse">
<li><a href="index.php">Home</a></li>
<li><a href="all_products.php">All Products</a></li>
<li><a href="customer/my_account.php">My Account</a></li>
<li><a href="cart.php">Shopping Cart</a></li>
<li><a href="contact.php" class="active">Contact Us</a></li>
<li><a href="admin_area/login/login.php"><b>Admin Login</b></a></li>
</ul>
</div>
</div>
<!--Search Box starts-->
<div>
<form method="get" action="results.php" enctype="multipart/form-data">
<input type="text" name="user_query" placeholder="Search a Product"/>
<input type="submit" name="search" value="Search"/>
</form>
</div>
<!--Search Box ends-->
</div>
</div>
</div><!--/header-bottom-->
</header><!--/header-->
<section id="slider"><!--slider-->
<div class="container">
<div class="row">
<div class="col-sm-12">
<div id="slider-carousel" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#slider-carousel" data-slide-to="0" class="active"></li>
<li data-target="#slider-carousel" data-slide-to="1"></li>
<li data-target="#slider-carousel" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<div class="item active">
<div class="col-sm-6">
<h1><span>K</span>-Shop</h1>
<h2>K-Shop
<br></h2>
<p>Delivering the very best of consumer products around the world. Every one of our products gives you 100% satisfaction.</p>
<button type="button" class="btn btn-default get">Get it now</button>
</div>
<div class="col-sm-6">
<img src="images/home/videocam.jpg" class="girl img-responsive" alt="" />
</div>
</div>
<div class="item">
<div class="col-sm-6">
<h1><span>K</span>-Shop</h1>
<h2>K-Shop</h2>
<p>Delivering the very best of consumer products around the world. Every one of our products gives you 100% satisfaction. </p>
</div>
<div class="col-sm-6">
<img src="images/home/tablet.jpg" class="girl img-responsive" alt="" />
</div>
</div>
<div class="item">
<div class="col-sm-6">
<h1><span>K</span>-Shop</h1>
<h2>K-Shop</h2>
<p>Delivering the very best of consumer products around the world. Every one of our products gives you 100% satisfaction.</p>
<button type="button" class="btn btn-default get">Get it now</button>
</div>
<div class="col-sm-6">
<img src="images/home/smarttv.jpg" class="girl img-responsive" alt="" />
<
</div>
</div>
</div>
<a href="#slider-carousel" class="left control-carousel hidden-xs" data-slide="prev">
<i class="fa fa-angle-left"></i>
</a>
<a href="#slider-carousel" class="right control-carousel hidden-xs" data-slide="next">
<i class="fa fa-angle-right"></i>
</a>
</div>
</div>
</div>
</div>
</section><!--/slider-->
<section>
<div class="container">
<div class="row">
<div class="col-sm-3">
<div class="left-sidebar">
<h2>Categories</h2>
<div class="panel-group category-products" id="accordian"><!--category-products start-->
<div class="category-tab ul li ">
<ul class="nav nav-pills nav-stacked" id="categories">
<?php getCategories(); ?>
</ul>
</div>
</div><!--/category-products ends-->
<div class="brands_products"><!--brands_products start-->
<h2>Brands</h2>
<div class="category-tab ul li ">
<ul class="nav nav-pills nav-stacked" id="brands">
<?php getBrands();
?>
</ul>
</div>
</div><!--/brands_products Ends-->
<div class="shipping text-center"><!--shipping stars-->
<img src="images/home/shipping.jpg" alt="" />
</div><!--/shipping Ends-->
</div>
</div>
<div class="col-sm-20 padding-right">
<?php
//$ip = getRealIpAddress();
//echo $ip;
?>
<div class="features_items" id="products_box"><!--features_items start-->
<h2 class="title text-center">Contact Form</h2>
<!-- a row has to be in a container -->
<div class="container">
<!-- Contacts -->
<div id="contacts">
<div class="row">
<!-- Alignment -->
<div class="col-sm-offset-2 col-sm-6">
<!-- Form itself -->
<form class="well" id="contactForm" action="" method="post" novalidate>
<div class="control-group">
<div class="controls">
<input type="text" class="form-control" placeholder="<NAME>" name="name" required data-validation-required-message="Please enter your name" />
<p class="help-block"></p>
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="email" class="form-control" placeholder="Email" name="email" required data-validation-required-message="Please enter your email" />
</div>
</div> <br>
<div class="control-group">
<div class="controls">
<textarea rows="10" cols="100" class="form-control" placeholder="Message" name="message" required data-validation-required-message="Please enter your message" minlength="5" data-validation-minlength-message="Min 5 characters" maxlength="999" style="resize:none"></textarea>
</div>
</div>
<div id="success"> </div> <!-- For success/fail messages -->
<button type="submit" name="sendMessage" class="btn btn-primary pull-right">Send</button><br />
</form>
</div>
</div>
</div>
</div>
</div><!--features_items Ends-->
</div><!--/category-tab-->
</div>
</div>
</div>
</section>
<footer id="footer"><!--Footer-->
<div class="footer-top">
<div class="container">
<div class="row">
<div class="col-sm-2">
<div class="companyinfo">
<h3><span>K</span>-Shop</h3>
<p>We provide the very best of consumer products all around the globe.</p>
</div>
</div>
<div class="col-sm-7">
<div class="col-sm-3">
<div class="video-gallery text-center">
<a href="#">
<div class="iframe-img">
<img src="images/home/iframe1.png" alt="" />
</div>
<div class="overlay-icon">
<i class="fa fa-play-circle-o"></i>
</div>
</a>
<p>Cliffs Of Moher</p>
<h2>24 April 2015</h2>
</div>
</div>
<div class="col-sm-3">
<div class="video-gallery text-center">
<a href="#">
<div class="iframe-img">
<img src="images/home/iframe2.png" alt="" />
</div>
<div class="overlay-icon">
<i class="fa fa-play-circle-o"></i>
</div>
</a>
<p>St Patrick's Day</p>
<h2>17 March 2015</h2>
</div>
</div>
<div class="col-sm-3">
<div class="video-gallery text-center">
<a href="#">
<div class="iframe-img">
<img src="images/home/iframe3.png" alt="" />
</div>
<div class="overlay-icon">
<i class="fa fa-play-circle-o"></i>
</div>
</a>
<p>Map Of Nigeria</p>
<h2>24 DEC 2015</h2>
</div>
</div>
<div class="col-sm-3">
<div class="video-gallery text-center">
<a href="#">
<div class="iframe-img">
<img src="images/home/iframe4.png" alt="" />
</div>
<div class="overlay-icon">
<i class="fa fa-play-circle-o"></i>
</div>
</a>
<p>Fupre Campus</p>
<h2>24 May 2015</h2>
</div>
</div>
</div>
<div class="col-sm-3">
<div class="address">
<img src="images/home/map.png" alt="" />
<p>K-Shop, A Product of Fortune - Fupre, Nigeria</p>
</div>
</div>
</div>
</div>
</div>
<div class="footer-bottom">
<div class="container">
<div class="row">
<p class="pull-left">Copyright © 2015 K-Shop Inc. All rights reserved.</p>
<p class="pull-right">Designed by <span><a target="_blank">King Fortune</a></span></p>
</div>
</div>
</div>
</footer><!--/Footer-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="./js/bootstrap.min.js"></script>
<script src="./js/jqBootstrapValidation.js"></script>
<script src="./js/contact_me.js"></script>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.scrollUp.min.js"></script>
<script src="js/price-range.js"></script>
<script src="js/jquery.prettyPhoto.js"></script>
<script src="js/main.js"></script>
</body>
</html>
<?php
//sending contact us to website admin..
if(isset($_POST['sendMessage']))
{
// check if fields passed are empty
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
// create email body and send it
$to = '<EMAIL>';
$email_subject = "Contact form submitted by: $name";
$email_body = "You have received a new message. \n\n".
" Here are the details:\n \n Name: $name \n ".
"Email: $email_address\n Message \n $message";
$headers = "From: <EMAIL>\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
echo "<script>alert('Thank you, your message has been sent')</script>";
return true;
}
?>
<file_sep><?php
include ("includes/db.php");
if(isset($_GET['edit_pro']))
{
// here we are retrieving the information for "ONE / Specific "
//Product so we can modify its details
$edit_id = $_GET['edit_pro'];
$get_edit = "select * from products where product_id = '$edit_id'";
$run_edit = mysqli_query($con,$get_edit);
$row_edit = mysqli_fetch_array($run_edit);
$update_id = $row_edit['product_id'];
$p_title = $row_edit['product_title'];
$cat_id = $row_edit['cat_id'];
$brand_id = $row_edit['brand_id'];
$p_image1 = $row_edit['product_img1'];
$p_image2 = $row_edit['product_img2'];
$p_image3 = $row_edit['product_img3'];
$p_price = $row_edit['product_price'];
$p_desc = $row_edit['product_desc'];
$p_keyords = $row_edit['product_keywords'];
}
//getting brand information for specific product
$get_cat = "select * from categories where cat_id='$cat_id'";
$run_cat = mysqli_query($con,$get_cat);
$cat_row = mysqli_fetch_array($run_cat);
$cat_edit_title= $cat_row['cat_title'];
//getting brand information for specific product
$get_brand ="select * from brands where brand_id='$brand_id'";
$run_brand = mysqli_query($con,$get_brand);
$brand_row = mysqli_fetch_array($run_brand);
$brand_edit_title= $brand_row['brand_title'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>Update or Edit Product</title>
<script src="//tinymce.cachefly.net/4.1/tinymce.min.js"></script>
<script>
tinymce.init({selector:'textarea'});
</script>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/prettyPhoto.css" rel="stylesheet">
<link href="css/price-range.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<link href="css/responsive.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<script src="js/respond.min.js"></script>
<![endif]-->
</head><!--/head-->
<body>
<form method="post" action="" enctype="multipart/form-data">
<table width="700" align="center" border="1" bgcolor="#00FF00">
<tr>
<td align="right"><b>Product Title</b></td>
<td><input type="text" name="product_title" size="40" value="<?php echo $p_title; ?>"/> </td>
</tr>
<tr>
<td align="right"><b>Product Category</b></td>
<td>
<select name="product_cat">
<option size="40" value="<?php echo $cat_id; ?>"> <?php echo $cat_edit_title;?> </option>
<?php
$sel_category = "select * from categories";
$run_category = mysqli_query($con, $sel_category);
while($row_category = mysqli_fetch_array($run_category)){
$cat_id= $row_category['cat_id'];
$cat_title= $row_category['cat_title'];
echo "<option value='$cat_id'>$cat_title</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td align="right"><b>Product Brand</b></td>
<td>
<select name="product_brand">
<option value="<?php echo $brand_id; ?>"> <?php echo $brand_edit_title;?></option>
<?php
$sel_brands = "select * from brands";
$run_brands = mysqli_query($con, $sel_brands );
while($row_brands = mysqli_fetch_array($run_brands)){
$brand_id= $row_brands['brand_id'];
$brand_title= $row_brands['brand_title'];
echo "<option value='$brand_id'>$brand_title</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td align="right"><b>Product Image 1</b></td>
<td><input type="file" name="product_img1" />
<img src = "product_images/<?php echo $p_image1; ?>" width="80" height="80"/> </td>
</tr>
<tr>
<td align="right"><b>Product Image 2</b></td>
<td><input type="file" name="product_img2"/>
<img src = "product_images/<?php echo $p_image2; ?>" width="80" height="80"/> </td>
</tr>
<tr>
<td align="right"><b>Product Image 3</b></td>
<td><input type="file" name="product_img3"/>
<img src = "product_images/<?php echo $p_image3; ?>" width="80" height="80"/> </td>
</tr>
<tr>
<td align="right"><b>Product Price</b> </td>
<td><input type="text" name="product_price" value="<?php echo $p_price; ?>" /> </td>
</tr>
<tr>
<td align="right"><b>Product Descrition</b></td>
<td><textarea name="product_desc" cols="41" rows="5"><?php echo $p_desc; ?></textarea> </td>
</tr>
<tr>
<td align="right"><b>Product Keywords</b></td>
<td><input type="text" name="product_keywords" size="40" value="<?php echo $p_keyords; ?>"/></td>
</tr>
<tr align="center">
<td colspan="2"><input type="submit" name="update_product" value="Update Product" /></td>
</tr>
</table>
</form>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.scrollUp.min.js"></script>
<script src="js/price-range.js"></script>
<script src="js/jquery.prettyPhoto.js"></script>
<script src="js/main.js"></script>
</body>
</html>
<?php
if(isset($_POST['update_product']))
{
// text data variables
$product_title = $_POST['product_title'];
$product_cat = $_POST['product_cat'];
$product_brand = $_POST['product_brand'];
$product_price = $_POST['product_price'];
$product_desc = $_POST['product_desc'];
$status = 'on';
$product_keywords = $_POST['product_keywords'];
// image names
$product_img1 = $_FILES['product_img1']['name'];
$product_img2 = $_FILES['product_img2']['name'];
$product_img3 = $_FILES['product_img3']['name'];
//Image temp names
$temp_name1 = $_FILES['product_img1']['tmp_name'];
$temp_name2 = $_FILES['product_img2']['tmp_name'];
$temp_name3 = $_FILES['product_img3']['tmp_name'];
//the image1, user must upload atleast one image when uploading the the product.
//$product_img1=$p_image1;
if($product_title =='' OR $product_cat=='' OR $product_desc =='' OR $product_keywords=='' OR $product_img1=='' OR $product_price=='' OR $product_brand==''){
echo "<script>alert('Please fill all the fields!')</script>";
exit();
}
else
{
//uploading images to its folder
move_uploaded_file($temp_name1,"product_images/$product_img1");
move_uploaded_file($temp_name2,"product_images/$product_img2");
move_uploaded_file($temp_name3,"product_images/$product_img3");
$update_product = "Update products set cat_id='$product_cat',brand_id='$product_brand',date='NOW()',product_title='$product_title',product_img1='$product_img1',
product_img2='$product_img2',product_img3='$product_img3',product_price='$product_price',
product_desc='$product_desc',product_keywords='$product_keywords' WHERE product_id = '$update_id'";
$run_update = mysqli_query($con, $update_product);
if($run_update)
{
echo "<script>alert('Product updated Successful!!')</script>";
//once the product has been successfully updated we are redirecting to the product page.
echo "<script>window.open('index.php?view_products','_self')</script>";
}
else
{
echo "<script>alert('Product could not be added!')</script>";
}
}//else
}//if post
?>
<file_sep><html>
<head>
</head>
<body>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;border-color:#aabcfe;}
.tg td{font-family:Arial, sans-serif;font-size:17px;padding:10px 30px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#aabcfe;color:#669;background-color:#e8edff;}
.tg th{font-family:Arial, sans-serif;font-size:17px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#aabcfe;color:#039;background-color:#b9c9fe;}
.tg .tg-0ord{text-align:right}
.tg .tg-ifyx{background-color:#D2E4FC;text-align:right}
.tg .tg-s6z2{text-align:center}
.tg .tg-vn4c{background-color:#D2E4FC}
</style>
<?php
if(isset($_GET['view_brands'])) { ?>
<table class="tg">
<tr>
<th class="tg-s6z2" colspan="8">Brands Description</th>
</tr>
<tr>
<td class="tg-vn4c">Brands ID </td>
<td class="tg-vn4c">Title </td>
<td class="tg-vn4c">Edit </td>
<td class="tg-vn4c">Delete </td>
</tr>
<!--Retrieving data from php script here...-->
<?php
//database connection
include("includes/db.php");
$i=0;
$get_brands = "select * from brands";
//sql querry to retrive the data
$run_brands = mysqli_query($con,$get_brands);
while($row_brand = mysqli_fetch_array($run_brands))
{
$brand_id = $row_brand['brand_id'];
$brand_title = $row_brand['brand_title'];
//$i++; // this is for numbering the product id starting with 1+
//whatever data comes in from this loop, they are assigned to the table columns bellow
?> <!-- This is the closing tag for php. We read all the data from php but OUR WHILE LOOP HAS NOT BEEN YET ENDED...-->
<tr>
<td> <?php echo $brand_id; ?> </td>
<td> <?php echo $brand_title; ?></td>
<td> <a href="index.php?edit_brand=<?php echo $brand_id;?>"> Edit </a> </td>
<td> <a href="index.php?delete_brand=<?php echo $brand_id;?>"> Delete </a> </td>
</tr>
<?php } ?> <!-- CLOSING THE } OF WHILE LOOP HERE... WE HAVE SUCCESSFULLY POPULATED THE VALUES-->
</table>
<?php } ?>
</body>
</html><file_sep><?php
//session_start();
include("includes/db.php");
?>
<!DOCTYPE html>
<html>
<head>
<title>Payment Options</title>
</head>
<body>
<?php
//for receiving orders from customers
//retriving information from customer table where ip matches
//the current ip
$customer_email = $_SESSION["customer_email"];
$get_customer="select * from customers where customer_email='$customer_email'";
$run_customer=mysqli_query($con,$get_customer);
$customer=mysqli_fetch_array($run_customer);
$customer_id=$customer['customer_id'];
$customer_name=$customer['customer_name'];
$ip_add = getRealIpAddress();
$total =0;
$select_price = "select * from cart where ip_add = '$ip_add'";
$run_price = mysqli_query($db, $select_price);
$status='Pending';//initial status of a product
$invoice_no = mt_rand();//generate random number
$count_pro=mysqli_num_rows($run_price); //total products
$i=0;
$message="
<html>
<body>
<p>
Hello <b style='color:blue;'> $customer_name, </b> <br>
Please find your order summary bellow. Please login to your account and make a payment for any pending orders </p>
<table width='600' align='center' bgcolor='FFCC99' border='2'>
<tr> <h2> Your Order Summary.<br>
Invoice Number: $invoice_no </br></h2></tr>
<tr>
<th> Product Name </b> </th>
<th> Quantity </b> </th>
<th> Total Price </b> </th>
</tr>
";
while($record=mysqli_fetch_array($run_price))
{
$product_id = $record['p_id'];
$prod_price = "select * from products where product_id = '$product_id'";
$run_product_price = mysqli_query($db, $prod_price);
while($p_price=mysqli_fetch_array($run_product_price))
{
$product_name=$p_price['product_title'];
$product_price = array($p_price['product_price']); //get product price from table column in DB
$value = array_sum($product_price)."\r\n"; // sum all the values
$total += $value;
$i++;
}
$productDetails =
$message.="
<tr>
<td> $product_name </td></tr>";
//$productDetails.=$product_name.":".$value.",
//";
//end of while
//getting quantity form the cart
$get_cart ="Select * from cart WHERE ip_add = '$ip_add'";
$run_cart=mysqli_query($con,$get_cart);
$get_qty= mysqli_fetch_array($run_cart);
$qty=$get_qty['qty']; //saving qty from database to local variable
if($qty==0)
{
//change the variable
$qty=1;
$sub_total =$total;
}
else
{
$qty=$qty;
$sub_total=$total*$qty;
}
}
?>
<div align="center">
<h2> Payment Options</h2>
<b> Click Buy Now to Pay with Paypal
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<!-- Identify your business so that you can collect the payments. -->
<input type="hidden" name="business" value="<EMAIL>">
<!-- Specify a Buy Now button. -->
<input type="hidden" name="cmd" value="_xclick">
<!-- Specify details about the item that buyers will purchase. -->
<input type="hidden" name="item_name" value="<?php echo $productDetails ?>">
<input type="hidden" name="amount" value="<?php echo $sub_total?>">
<input type="hidden" name="currency_code" value="USD">
<!-- Display the payment button. -->
<input type="image" name="submit" border="0"
src="https://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif"
alt=">> PayPal - The safer, easier way to pay online <<">
<img alt="" border="0" width="1" height="1"
src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" >
</form>
</a> <b> Or <a href="order.php?c_id=<?php echo $customer_id;?>">Pay Offline </a> </b>
<br><br><br><br>
<b> If you have selected to pay offline then please check your email or account for your invoice number of your order. <b>
</div>
</body>
</html><file_sep><?php
$con = mysqli_connect("localhost","kshop007_admin","doyoulikeCHEESE00977$","kshop");
?>
<file_sep><?php
//establishing the connection
$db = mysqli_connect("localhost","kshop007_admin","doyoulikeCHEESE00977$","kshop");
//gettting IP Address
function getRealIpAddress()
{
if(!empty($_SERVER['HTTP_CLIENT_IP'])) // check ip from share internet
{
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
else if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //check if IP is passed from proxy
{
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
function getDefault()
{
global $db;
$c= $_SESSION['customer_email'];
$get_c = "select * from customers where customer_email='$c'";
echo "<script>alert('default customerid $get_c ') </script>";
$run_c=mysqli_query($db,$get_c);
$row_c = mysqli_fetch_array($run_c);
$customer_id=$row_c['customer_id'];
if(!isset($_GET['my_orders'])){
if(!isset($_GET['edit_account'])){
if(!isset($_GET['change_pass'])){
if(!isset($_GET['delete_account'])){
$get_orders= "select * from customer_orders where customer_id='$customer_id' AND order_status='pending'";
$run_orders=mysqli_query($db,$get_orders);
$count_orders = mysqli_num_rows($run_orders);
if($count_orders>0)
{
echo "
<div style='padding:10px'>
<h1 style='color:red;'> Important!!</h1>
<h2> You Have $count_orders pending orders.</h3>
<h3> Please see your orders details by clicking this <a href='my_account.php?my_orders'> LINK </a>
</h3>
</div>
";
}
else
{
echo "
<div style='padding:10px'>
<br> </br>
<h2 style='color:red;'> You Have NO pending orders.</h3>
<h3> You can see your order history by clicking this <a href='my_account.php?my_orders'> LINK </a>
<br> </h3>
</div>
";
}
}
}
}
}
}//function
// creating a script for cart
function cart()
{
if(isset($_GET['add_cart']))
{
global $db;
$p_id = $_GET['add_cart'];
$ip_add = getRealIpAddress();
$check_product = "select * from cart where ip_add = '$ip_add' AND p_id ='$p_id'";
$run_check = mysqli_query($db, $check_product);
if(mysqli_num_rows($run_check) > 0)
{
echo "";
}
else
{
$ip_add = getRealIpAddress();
echo "<script>alert('$ip_add')</script>";
$query = "insert into cart (p_id, ip_add) values ('$p_id ','$ip_add')";
$run_query = mysqli_query($db, $query);
echo "<script>window.open('index.php','_self')</script>";
}
}// outer if
}
// get number of items from cart
function itemsFromCart()
{
if(!isset($_GET['add_cat']))
{
global $db;
$ip_add = getRealIpAddress();
$get_items = "select * from cart where ip_add = '$ip_add'";
$run_items = mysqli_query($db, $get_items);
$count_items = mysqli_num_rows($run_items);
}
else
{
global $db;
$ip_add = getRealIpAddress();
$get_items = "select * from cart where ip_add = '$ip_add'";
$run_items = mysqli_query($db, $get_items);
$count_items = mysqli_num_rows($run_items);
}
echo $count_items;
}
//get total price for items in cart
function getTotalPrice()
{
$ip_add = getRealIpAddress();
global $db;
$total =0;
$select_price = "select * from cart where ip_add = '$ip_add'";
$run_price = mysqli_query($db, $select_price);
while($record=mysqli_fetch_array($run_price))
{
$product_id = $record['p_id'];
$prod_price = "select * from products where product_id = '$product_id'";
$run_product_price = mysqli_query($db, $prod_price);
while($p_price=mysqli_fetch_array($run_product_price))
{
$product_price = array($p_price['product_price']); //get product price from table column in DB
$value = array_sum($product_price); // sum all the values
$total += $value;
}
}
echo $total;
}
//get products to display
function getPro()
{
global $db;
if(!isset($_GET['cat'])){
if(!isset($_GET['brand'])){
$get_products = "select * from products order by rand() LIMIT 0,6";
$run_products = mysqli_query($db, $get_products);
while($row_products= mysqli_fetch_array($run_products))
{
$pro_id = $row_products['product_id'];
$pro_title = $row_products['product_title'];
$pro_cat = $row_products['cat_id'];
$pro_brand = $row_products['brand_id'];
$pro_desc = $row_products['product_desc'];
$pro_price = $row_products['product_price'];
$pro_image = $row_products['product_img1'];
echo "
<div id='single_product'>
<h3>$pro_title</h3>
<img src='admin_area/product_images/$pro_image' width='160' height='160'/><br>
<p><b>Price: GBP$pro_price</b></p>
<a href='details.php?pro_id=$pro_id' style='float:left;'>Details</a>
<a href='index.php?add_cart=$pro_id'><button style='float:right;'>Add to Cart</button></a>
</div>
";
}//while
}//inner if
}//if
}
//get category products
function getCatPro()
{
global $db;
if(isset($_GET['cat'])){
$cat_id = $_GET['cat']; //getting and assigning cat id from database
$get_cat_pro = "select * from products where cat_id ='$cat_id'";
$run_cat_pro = mysqli_query($db, $get_cat_pro);
$count = mysqli_num_rows($run_cat_pro);
if($count==0)
{
echo "<h1>No Products found in this category!</h1>";
}
while($row_cat_pro= mysqli_fetch_array($run_cat_pro))
{
$pro_id = $row_cat_pro['product_id'];
$pro_title = $row_cat_pro['product_title'];
$pro_cat = $row_cat_pro['cat_id'];
$pro_brand = $row_cat_pro['brand_id'];
$pro_desc = $row_cat_pro['product_desc'];
$pro_price = $row_cat_pro['product_price'];
$pro_image = $row_cat_pro['product_img1'];
echo "
<div id='single_product'>
<h3>$pro_title</h3>
<img src='admin_area/product_images/$pro_image' width='160' height='160'/><br>
<p><b>Price: GBP $pro_price</b></p>
<a href='details.php?pro_id=$pro_id' style='float:left;'>Details</a>
<a href='index.php?add_cart=$pro_id'><button style='float:right;'>Add to Cart</button></a>
</div>
";
}//while
}//if
}
//get bran products
function getBrandPro()
{
global $db;
if(isset($_GET['brand'])){
$brand_id = $_GET['brand']; //getting and assigning cat id from database
$get_brand_pro = "select * from products where brand_id ='$brand_id'";
$run_brand_pro = mysqli_query($db, $get_brand_pro);
$count = mysqli_num_rows($run_brand_pro);
if($count==0)
{
echo "<h1>No Products found under this brand!</h1>";
}
while($row_brand_pro= mysqli_fetch_array($run_brand_pro))
{
$pro_id = $row_brand_pro['product_id'];
$pro_title = $row_brand_pro['product_title'];
$pro_cat = $row_brand_pro['cat_id'];
$pro_brand = $row_brand_pro['brand_id'];
$pro_desc = $row_brand_pro['product_desc'];
$pro_price = $row_brand_pro['product_price'];
$pro_image = $row_brand_pro['product_img1'];
echo "
<div id='single_product'>
<h3>$pro_title</h3>
<img src='admin_area/product_images/$pro_image' width='160' height='160'/><br>
<p><b>Price: GBP $pro_price</b></p>
<a href='details.php?pro_id=$pro_id' style='float:left;'>Details</a>
<a href='index.php?add_cart=$pro_id'><button style='float:right;'>Add to Cart</button></a>
</div>
";
}//while
}//if
}
//get the brands to display
function getBrands()
{
global $db;
$get_brand = "select * from brands";
$run_brand = mysqli_query($db, $get_brand);
while($row_brand = mysqli_fetch_array($run_brand)){
$brand_id= $row_brand['brand_id'];
$brand_title= $row_brand['brand_title'];
echo "<li><a href='index.php?brand=$brand_id'>$brand_title</a></li>";
}
}
//get categories to display
function getCategories()
{
global $db;
$get_category = "select * from categories";
$run_category = mysqli_query($db, $get_category);
while($row_category = mysqli_fetch_array($run_category)){
$cat_id= $row_category['cat_id'];
$cat_title= $row_category['cat_title'];
echo "<li><a href='index.php?cat=$cat_id'>$cat_title</a></li>";
}
}
?>
<file_sep><?php
session_start();
if(!isset($_SESSION['admin_email']))
{
echo "<script>window.open('login/login.php,'_self')</script>";
}
else
{
?>
<?php
include ("includes/db.php");
?>
<html>
<head>
<title>K-Shop</title>
<link rel="stylesheet" type="text/css" href="styles/global.css" />
<meta name="viewport" content="width=device-width, initial-scale: 1.0, user-scalabe=0" />
<script src="scripts/jquery-1.11.1.min.js"></script>
<script src="scripts/general.js"></script>
</head>
<body>
<div id="header">
<div class="logo"><a href="#">K-<span>Shop</span></a></div>
</div>
<a class="mobile" href="#">MENU</a>
<div id="container">
<div class="sidebar">
<ul id="nav">
<li><a class="selected" href="#">Dashboard</a></li>
<!-- Get request sending the url variables get request-->
<li><a href="index.php?insert_product">Insert New Product</a></li>
<li><a href="index.php?insert_cat">Insert New Category</a></li>
<li><a href="index.php?insert_brand">Insert New Brand</a></li>
<li><a href="index.php?view_products">View All Products</a></li>
<li><a href="index.php?view_cats">View All Categories</a></li>
<li><a href="index.php?view_brands">View All Brand</a></li>
<li><a href="index.php?view_customers">View Customers</a></li>
<li><a href="index.php?view_orders">View Orders</a></li>
<li><a href="index.php?view_orders?view_payments">View Payments</a></li>
<li><a href="#">Pending Orders</a></li>
<li><a href="logout.php">Admin Logout</a></li>
</ul>
</div>
<div class="content">
<h1>Dashboard</h1>
<?php include ("includes/db.php");
if(isset($_GET['insert_product']))
{
// if the get request was insert product
include("insert_products.php");
}
?>
</p>
</div>
</div>
</body>
</html>
<?php } //if session is activated.. closing else of top else block ?><file_sep>
<?php
session_start();
if(!isset($_SESSION['admin_email']))
{
echo "<script>window.open('login/login.php,'_self')</script>";
}
else
{
?>
<?php
include ("includes/db.php");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>Insert New Product</title>
<script src="//tinymce.cachefly.net/4.1/tinymce.min.js"></script>
<script>
tinymce.init({selector:'textarea'});
</script>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/prettyPhoto.css" rel="stylesheet">
<link href="css/price-range.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<link href="css/responsive.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<script src="js/respond.min.js"></script>
<![endif]-->
</head><!--/head-->
<body>
<form method="post" action="insert_products.php" enctype="multipart/form-data">
<table width="700" align="center" border="1" bgcolor="#00FF00">
<tr>
<td align="right"><b>Product Title</b></td>
<td><input type="text" name="product_title" size="40"/></td>
</tr>
<tr>
<td align="right"><b>Product Category</b></td>
<td>
<select name="product_cat">
<option size="40">Select a Category</option>
<?php
$sel_category = "select * from categories";
$run_category = mysqli_query($con, $sel_category);
while($row_category = mysqli_fetch_array($run_category)){
$cat_id= $row_category['cat_id'];
$cat_title= $row_category['cat_title'];
echo "<option value='$cat_id'>$cat_title</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td align="right"><b>Product Brand</b></td>
<td>
<select name="product_brand">
<option>Select a Brand</option>
<?php
$sel_brands = "select * from brands";
$run_brands = mysqli_query($con, $sel_brands );
while($row_brands = mysqli_fetch_array($run_brands)){
$brand_id= $row_brands['brand_id'];
$brand_title= $row_brands['brand_title'];
echo "<option value='$brand_id'>$brand_title</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td align="right"><b>Product Image 1</b></td>
<td><input type="file" name="product_img1"/></td>
</tr>
<tr>
<td align="right"><b>Product Image 2</b></td>
<td><input type="file" name="product_img2"/></td>
</tr>
<tr>
<td align="right"><b>Product Image 3</b></td>
<td><input type="file" name="product_img3"/></td>
</tr>
<tr>
<td align="right"><b>Product Price</b></td>
<td><input type="text" name="product_price" size="40"/></td>
</tr>
<tr>
<td align="right"><b>Product Descrition</b></td>
<td><textarea name="product_desc" cols="41" rows="5"></textarea></td>
</tr>
<tr>
<td align="right"><b>Product Keywords</b></td>
<td><input type="text" name="product_keywords" size="40"/></td>
</tr>
<tr align="center">
<td colspan="2"><input type="submit" name="insert_products" value="Insert Product" /></td>
</tr>
</table>
</form>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.scrollUp.min.js"></script>
<script src="js/price-range.js"></script>
<script src="js/jquery.prettyPhoto.js"></script>
<script src="js/main.js"></script>
</body>
</html>
<?php
if(isset($_POST['insert_products']))
{
// text data variables
$product_title = $_POST['product_title'];
$product_cat = $_POST['product_cat'];
$product_brand = $_POST['product_brand'];
$product_price = $_POST['product_price'];
$product_desc = $_POST['product_desc'];
$status = 'on';
$product_keywords = $_POST['product_keywords'];
// image names
$product_img1 = $_FILES['product_img1']['name'];
$product_img2 = $_FILES['product_img2']['name'];
$product_img3 = $_FILES['product_img3']['name'];
//Image temp names
$temp_name1 = $_FILES['product_img1']['tmp_name'];
$temp_name2 = $_FILES['product_img2']['tmp_name'];
$temp_name3 = $_FILES['product_img3']['tmp_name'];
if($product_title =='' OR $product_cat=='' OR $product_desc =='' OR $product_keywords=='' OR $product_img1=='' OR $product_price=='' OR $product_brand==''){
echo "<script>alert('Please fill all the fields!')</script>";
exit();
}
else
{
//uploading images to its folder
move_uploaded_file($temp_name1,"product_images/$product_img1");
move_uploaded_file($temp_name2,"product_images/$product_img2");
move_uploaded_file($temp_name3,"product_images/$product_img3");
$insert_products = "insert into products (cat_id,brand_id,date,product_title,product_img1,product_img2,product_img3, product_price,product_desc,status)values('$product_cat','$product_brand',NOW(),'$product_title','$product_img1','$product_img2','$product_img3','$product_price','$product_desc','$status')";
$run_product = mysqli_query($con, $insert_products);
if($run_product)
{
echo "<script>alert('Product Insert Successful!!')</script>";
}
else
{
echo "<script>alert('Product could not be added!')</script>";
}
}//else
}//if post
?>
<?php } //if session is activated.. closing else of top else block ?><file_sep>
<?php
include("includes/db.php");
include("functions/functions.php");
//retrieving customer id that was passed from payment page
if(isset($_GET['c_id'])){
$customer_id=$_GET['c_id']; //local variable to save a customer id
$c_email ="select * from customers WHERE customer_id='$customer_id'";
//sending email
$run_email=mysqli_query($con,$c_email);
$row_customer=mysqli_fetch_array($run_email);
$customer_email=$row_customer['customer_email'];
$customer_name=$row_customer['customer_name'];
}
//getting products information/no. of items from cart
$ip_add = getRealIpAddress();
$total =0;
$select_price = "select * from cart where ip_add = '$ip_add'";
$run_price = mysqli_query($db, $select_price);
$status='Pending';//initial status of a product
$invoice_no = mt_rand();//generate random number
$count_pro=mysqli_num_rows($run_price); //total products
$i=0;
$message="
<html>
<body>
<p>
Hello <b style='color:blue;'> $customer_name, </b> <br>
Please find your order summary bellow. Please login to your account and make a payment for any pending orders. </p>
<table width='600' align='center' bgcolor='FFCC99' border='2'>
<tr> <h2> Your Order Summary.<br>
Invoice Number: $invoice_no </br></h2></tr>
<tr>
<th> Product Name </b> </th>
<th> Quantity </b> </th>
<th> Total Price </b> </th>
</tr>
";
while($record=mysqli_fetch_array($run_price))
{
$product_id = $record['p_id'];
$prod_price = "select * from products where product_id = '$product_id'";
$run_product_price = mysqli_query($db, $prod_price);
while($p_price=mysqli_fetch_array($run_product_price))
{
$product_name=$p_price['product_title'];
$product_price = array($p_price['product_price']); //get product price from table column in DB
$value = array_sum($product_price); // sum all the values
$total += $value;
$i++;
}
$message.="
<tr>
<td> $product_name </td>";
//end of while
//getting quantity form the cart
$get_cart ="Select * from cart WHERE ip_add = '$ip_add'";
$run_cart=mysqli_query($con,$get_cart);
$get_qty= mysqli_fetch_array($run_cart);
$qty=$get_qty['qty']; //saving qty from database to local variable
if($qty==0)
{
//change the variable
$qty=1;
$sub_total =$total;
}
else
{
$qty=$qty;
$sub_total=$total*$qty;
}
//if($run_order)
//{
echo "<script>window.open('my_account.php','_self')</script>";
$empty_cart="delete from cart where ip_add='$ip_add'"; //empty the cart once the order has been submitted
$run_empty=mysqli_query($con,$empty_cart);
$insert_to_pending_order="insert into pending_orders(customer_id,invoice_no,product_id,qty,order_status) values('$customer_id','$invoice_no','$product_id','$qty','$status')";
$run_pending_order=mysqli_query($con,$insert_to_pending_order);
$message.="<td> $qty </td>
<td> #$value </td>
</tr>";
}
$message.="
<tr>
<td> YOUR SUBTOTAL IS # $sub_total </td>
</tr></table>
<h3> Thank you for your order </h3>
</body>
</html>
";
//SENDING INVOICE TO CUSTOMER
//}
$insert_order="insert into customer_orders(customer_id,due_amount,invoice_no,total_products,order_date,order_status) values('$customer_id','$sub_total','$invoice_no','$count_pro',NOW(),'$status')";
$run_order = mysqli_query($con,$insert_order);
echo "<script>alert('Order details sent!! $message') </script>";
$subject = 'Your Order Details';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'To: echo $customer_email'. "\r\n";
$headers .= 'From: <EMAIL>';
// Mail it
mail($customer_email, $subject, $message, $headers);
?>
<file_sep><?php
session_start();
include("includes/db.php");
include("functions/functions.php");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>Checkout | K-Shop</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/prettyPhoto.css" rel="stylesheet">
<link href="css/price-range.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<link href="css/responsive.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<script src="js/respond.min.js"></script>
<![endif]-->
</head><!--/head-->
<body>
<header id="header"><!--header-->
<div class="header_top"><!--header_top-->
<div class="container">
<div class="row">
<div class="col-sm-6">
<div class="contactinfo">
<ul class="nav nav-pills">
<li><a href="#"><i class="fa fa-phone"></i> +2349039933771 </a></li>
<li><a href="#"><i class="fa fa-envelope"></i> <EMAIL></a></li>
</ul>
</div>
</div>
<div class="col-sm-6">
<div class="social-icons pull-right">
<ul class="nav navbar-nav">
<li><a href="http://www.fb.com/kingston.fortune2"><i class="fa fa-facebook"></i></a></li>
<li><a href="http://www.twitter.com/@chun__king"><i class="fa fa-twitter"></i></a></li>
<li><a href="http://www.linkedin.com/kingstonfortune"><i class="fa fa-linkedin"></i></a></li>
<li><a href="http://www.dribbble.com/kingstonfortune"><i class="fa fa-dribbble"></i></a></li>
<li><a href="http://plus.google.com/kingstonfortune"><i class="fa fa-google-plus"></i></a></li>
</ul>
</div>
</div>
</div>
</div>
</div><!--/header_top-->
<div class="header-middle"><!--header-middle-->
<div class="container">
<div class="row">
<div class="col-sm-4">
<div class="logo pull-left">
<a href="index.php"><img src="images/home/logo1.png" alt="" /></a>
</div>
</div>
<div class="col-sm-8">
<div class="shop-menu pull-right">
<ul class="nav navbar-nav">
<li><a href="cart.php"><i class="fa fa-shopping-cart"></i> Cart</a></li>
<?php
if(!isset($_SESSION['customer_email']))
{
//echo "<a href='checkout.php'> Login</a>";
echo "<li><a href='checkout.php'><i class='fa fa-lock'></i> Login</a></li>";
}
else
{
echo "<li><a href='logout.php'><i class='fa fa-lock'></i> Logout</a></li>";
}
?>
</ul>
</div>
</div>
<?php
cart();
?>
<b>Welcome Guest!></b>
<b style=" color: #fdb45e;">Shopping Cart:</b>
<span>-Total Items: <?php itemsFromCart(); ?> - Total Price: #<?php getTotalPrice(); ?></span>
?>
</div>
</div>
</div><!--/header-middle-->
<div class="header-bottom"><!--header-bottom-->
<div class="container">
<div class="row">
<div class="col-sm-9">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="mainmenu pull-left">
<ul class="nav navbar-nav collapse navbar-collapse">
<li><a href="index.php" class="active">Home</a></li>
<li><a href="all_products.php">All Products</a></li>
<li><a href="Accounts.php">My Account</a></li>
<li><a href="ShoppingCart.php">Shopping Cart</a></li>
<li><a href="contact.php">Contact Us</a></li>
<li><a href="admin_area/insert_products.php">Admin Login</a></li>
</ul>
</div>
</div>
<!--Search Box starts-->
<div>
<form method="get" action="results.php" enctype="multipart/form-data">
<input type="text" name="user_query" placeholder="Search a Product"/>
<input type="submit" name="search" value="Search"/>
</form>
</div>
<!--Search Box ends-->
</div>
</div>
</div><!--/header-bottom-->
</header><!--/header-->
<section id="slider"><!--slider-->
<div class="container">
<div class="row">
<div class="col-sm-12">
<div id="slider-carousel" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#slider-carousel" data-slide-to="0" class="active"></li>
<li data-target="#slider-carousel" data-slide-to="1"></li>
<li data-target="#slider-carousel" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<div class="item active">
<div class="col-sm-6">
<h1><span>K</span>-Shop</h1>
<h2>K-Shop</h2>
<p>Delivering the very best of consumer products around the world. Every one of our products gives you 100% satisfaction.</p>
<button type="button" class="btn btn-default get">Get it now</button>
</div>
<div class="col-sm-6">
<img src="images/home/videocam.jpg" class="girl img-responsive" alt="" />
</div>
</div>
<div class="item">
<div class="col-sm-6">
<h1><span>K</span>-Shop</h1>
<h2>K-Shop</h2>
<p>Delivering the very best of consumer products around the world. Every one of our products gives you 100% satisfaction. </p>
</div>
<div class="col-sm-6">
<img src="images/home/tablet.jpg" class="girl img-responsive" alt="" />
</div>
</div>
<div class="item">
<div class="col-sm-6">
<h1><span>K</span>-Shop</h1>
<h2>K-Shop</h2>
<p>Delivering the very best of consumer products around the world. Every one of our products gives you 100% satisfaction.</p>
<button type="button" class="btn btn-default get">Get it now</button>
</div>
<div class="col-sm-6">
<img src="images/home/smarttv.jpg" class="girl img-responsive" alt="" />
<
</div>
</div>
</div>
<a href="#slider-carousel" class="left control-carousel hidden-xs" data-slide="prev">
<i class="fa fa-angle-left"></i>
</a>
<a href="#slider-carousel" class="right control-carousel hidden-xs" data-slide="next">
<i class="fa fa-angle-right"></i>
</a>
</div>
</div>
</div>
</div>
</section><!--/slider-->
<section>
<div class="container">
<div class="row">
<div class="col-sm-3">
<div class="left-sidebar">
<h2>Categories</h2>
<div class="panel-group category-products" id="accordian"><!--category-products start-->
<div class="category-tab ul li ">
<ul class="nav nav-pills nav-stacked" id="categories">
<?php getCategories(); ?>
</ul>
</div>
</div><!--/category-products ends-->
<div class="brands_products"><!--brands_products start-->
<h2>Brands</h2>
<div class="category-tab ul li ">
<ul class="nav nav-pills nav-stacked" id="brands">
<?php getBrands();
?>
</ul>
</div>
</div><!--/brands_products Ends-->
<div class="shipping text-center"><!--shipping stars-->
<img src="images/home/shipping.jpg" alt="" />
</div><!--/shipping Ends-->
</div>
</div>
<div class="col-sm-9 padding-right">
<form action="customer_register.php" method="post" enctype="multipart/form-data"/>
<table width ="750" align="center">
<tr>
<td> <h2> Create an Account </h2> </td>
</tr>
<tr>
<td align="right"><b>Customer Name: </b> </td>
<td> <input type="text" name="customer_name" required /> </td>
</tr>
<tr>
<td align="right"><b>Customer Email: </b> </td>
<td> <input type="text" name="customer_email" required /> </td>
</tr>
<tr>
<td align="right"><b>Customer Password: </b> </td>
<td> <input type="password" name="customer_pass" required /> </td>
</tr>
<tr>
<td align="right"><b>Confirm Password: </b> </td>
<td> <input type="password" name="customer_pass_confirm" required /> </td>
</tr>
<tr>
<td align="right"><b>Customer Country: </b> </td>
<td>
<select name="customer_country">
<option> Select a Country</option>
<option> Nigeria </option>
<option> United Kingdom </option>
<option> United States </option>
<option> China </option>
<option> India </option>
<option> France </option>
</select>
</td>
</tr>
<tr>
<td align="right"><b>Customer city: </b> </td>
<td> <input type="text" name="customer_city" required /> </td>
</tr>
<tr>
<td align="right"><b>Customer Mobile no: </b> </td>
<td> <input type="text" name="customer_contact" required /> </td>
</tr>
<tr>
<td align="right"><b>Customer Address: </b> </td>
<td> <input type="text" name="customer_address" required /> </td>
</tr>
<tr>
<td align="right"><b>Customer Image: </b> </td>
<td> <input type="file" name="customer_image" required /> </td>
</tr>
<tr align="center">
<td colspan="10"> <input type="submit" name="register" value="Submit" /> </td>
</tr>
</form>
</div><!--features_items Ends-->
</div><!--/category-tab-->
</div>
</div>
</div>
</section>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.scrollUp.min.js"></script>
<script src="js/price-range.js"></script>
<script src="js/jquery.prettyPhoto.js"></script>
<script src="js/main.js"></script>
</body>
</html>
<?php
if(isset($_POST['register']))
{
$customer_pass = $_POST['customer_pass'];
$customer_pass_confirm = $_POST['customer_pass_confirm'];
if($customer_pass==$customer_pass_confirm)
{
$customer_name = $_POST['customer_name'];
$customer_email = $_POST['customer_email'];
$customer_country = $_POST['customer_country'];
$customer_city = $_POST['customer_city'];
$customer_contact = $_POST['customer_contact'];
$customer_address= $_POST['customer_address'];
$customer_image = $_FILES['customer_image']['name'];
$customer_image_temp = $_FILES['customer_image']['tmp_name'];
$customer_ip = getRealIpAddress();
$insert_customer = "insert into customers(customer_name,customer_email,customer_pass,customer_country,customer_city,customer_contact,customer_address,customer_image,customer_ip)
values ('$customer_name','$customer_email','$customer_pass','$customer_country','$customer_city','$customer_contact','$customer_address','$customer_image','$customer_ip')";
$run_customer = mysqli_query($con,$insert_customer);
//uploading a customer photo
move_uploaded_file($customer_image_temp, "customer/customer_photos/$customer_image");
//checking if this user have anything in the cart if yes we will redirect to payment page
$sel_cart = "select * from cart where ip_add='$customer_ip'";
$run_cart = mysqli_query($con,$sel_cart);
$check_cart = mysqli_num_rows($run_cart);
if($check_cart>0)
{
//create a session
$_SESSION['customer_email'] = $customer_email;
echo "<script>alert('Account has been created') </script>";
echo "<script>window.open('checkout.php','_self')</script>";
}
else
{
$_SESSION['customer_email'] = $customer_email;
echo "<script>alert('Account has been created') </script>";
echo "<script>window.open('index.php','_self')</script>";
}
}//end of password checking
else
{
echo "<script>alert('Password did not match') </script>";
}
}
?> | 5b959cdb00765f0c6e16dfd0095c065d7a598ae6 | [
"JavaScript",
"Markdown",
"PHP"
] | 32 | PHP | chunkingz/kshop | 5601854bb04fb9ee86fd9ff8bc39befb52e07c30 | 6521617c6e8d789d73989bd55a59a9b7821d8a06 |
refs/heads/master | <repo_name>MinKruger/AngularProject<file_sep>/README.md
Unfortunately the Project has not been completed, please do not use<file_sep>/routes/app.js
var express = require('express');
var router = express.Router();
var User = require('../Data/models/user');
router.get('/', function (req, res, next) {
res.render('index');
});
router.get('/message', function (req, res, next) {
res.render('node');
});
router.get('/newaccount', function (req, res, next) {
res.render('register');
});
router.post('/node-mongodb-mongoose-user', function (req, res, next) {
var emailVar = req.body.emailBody;
var userObject = new User({
login: emailVar,
password: '<PASSWORD>',
email: 'valueTeste',
});
userObject.save();
res.redirect('/node-mongodb-mongoose-user');
});
router.post('/register', function (req, res, next) {
var emailVar = req.body.email;
var loginVar = req.body.login;
var senhaVar = req.body.senha;
var userObject = new User({
login: loginVar,
password: <PASSWORD>,
email: emailVar,
});
userObject.save();
res.redirect('/node-mongodb-mongoose-user-busca');
});
router.get('/node-mongodb-mongoose-user-busca', function (req, res, next) {
User.findOne({}, function(err, documents){
if(err)
return res.send('Error');
res.render('node', {login: documents});
});
});
router.get('/teste', function (req, res, next) {
res.render('login');
});
router.get('/dashboard', function (req, res, next) {
var loginVar = req.body.login;
User.find({ login: loginVar }, function(err, documents){
if(err)
return res.send('Error');
res.render('node', {login: documents});
});
});
module.exports = router;
| d6feacf7dab406d696ae1c4a6763468fcf77b9e8 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | MinKruger/AngularProject | e80a96cb95db82b0a84a9205e9270600542f824a | e4a3146e39654950b833f4d8c9ef96e6cce6f337 |
refs/heads/master | <file_sep>import { ImageInfo } from "../IPictureWallStates";
export interface IMasonryLayoutProps {
images: ImageInfo[];
domElement: HTMLElement;
}
<file_sep>export interface ImageInfo {
url: string;
title: string;
description: string;
}
export interface IPictureWallStates {
images: ImageInfo[];
}<file_sep>export interface IPictureWallProps {
description: string;
domElement: HTMLElement;
}
<file_sep>declare interface IPictureWallWebPartStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
}
declare module 'PictureWallWebPartStrings' {
const strings: IPictureWallWebPartStrings;
export = strings;
}
| a5f60a879202492470a77e86527fc71aba706644 | [
"TypeScript"
] | 4 | TypeScript | shrenky/spfx-picturewall | 0091f904b76c6bdba27a69a7ca70e5b8f552f3fc | 465b5502e1c5ae29aee83b51817f7ebed4f5168a |
refs/heads/master | <repo_name>mickeymv/socialFootprint<file_sep>/source/root/appslogin.php
<?php
@ob_start();
session_start();
// Check, if username session is NOT set then this page will jump to login page
if (!isset($_SESSION['username'])) {
header('Location: index.php');
}
require_once __DIR__ . '/facebook-sdk-v5/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => '1646244812311215',
'app_secret' => '<KEY>',
'default_graph_version' => 'v2.5',
]);
$helper = $fb->getRedirectLoginHelper();
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="appslogin_css.css">
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: 772dtbul04ktif
authorize: true
onLoad: onLinkedInLoad
scope: r_emailaddress
</script>
<title>Apps login</title>
<meta name="google-signin-scope" content="profile email https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/plus.profiles.read">
<meta name="google-signin-client_id" content="318733159872-p0249g76untk8tob74o888elp6u4r1m5.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
</head>
<body>
<div>
<?php
$attributes= array();
$attributes['name'] = array(); $attributes['name']['visible'] = 0; $attributes['name']['weight'] = 0.50; $attributes['name']['attr'] = 'Name';
$attributes['profilePicture'] = array(); $attributes['profilePicture']['visible'] = 1; $attributes['profilePicture']['weight'] = 0.20; $attributes['profilePicture']['attr'] = 'Profile Picture';
$attributes['Phone number'] = array(); $attributes['Phone number']['visible'] = 0; $attributes['Phone number']['weight'] = 0.12; $attributes['Phone number']['attr'] = 'Phone number';
$attributes['gender'] = array(); $attributes['gender']['visible'] = 0; $attributes['gender']['weight'] = 0.04; $attributes['gender']['attr'] = 'Gender';
$attributes['hometown'] = array(); $attributes['hometown']['visible'] = 0; $attributes['hometown']['weight'] = 0.18; $attributes['hometown']['attr'] = 'Hometown';
$attributes['currentlocation'] = array(); $attributes['currentlocation']['visible'] = 0; $attributes['currentlocation']['weight'] = 0.36; $attributes['currentlocation']['attr'] = 'Current Location';
$attributes['dob'] = array(); $attributes['dob']['visible'] = 0; $attributes['dob']['weight'] = 0.34; $attributes['dob']['attr'] = 'Date of Birth';
$attributes['language'] = array(); $attributes['language']['visible'] = 0; $attributes['language']['weight'] = 0.02; $attributes['language']['attr'] = 'Language';
$attributes['checkins'] = array(); $attributes['checkins']['visible'] = 0; $attributes['checkins']['weight'] = 0.18; $attributes['checkins']['attr'] = 'Checkins';
$attributes['nickname'] = array(); $attributes['nickname']['visible'] = 0; $attributes['nickname']['weight'] = 0.06; $attributes['nickname']['attr'] = 'Nickname';
$attributes['relationshipstatus'] = array(); $attributes['relationshipstatus']['visible'] = 0; $attributes['relationshipstatus']['weight'] = 0.02; $attributes['relationshipstatus']['attr'] = 'Relationship Status';
$attributes['industry'] = array(); $attributes['industry']['visible'] = 0; $attributes['industry']['weight'] = 0.13; $attributes['industry']['attr'] = 'Industry';
$attributes['email'] = array(); $attributes['email']['visible'] = 0; $attributes['email']['weight'] = 0.20; $attributes['email']['attr'] = 'Email';
$attributes['status'] = array(); $attributes['status']['visible'] = 0; $attributes['status']['weight'] = 0.06; $attributes['status']['attr'] = 'Status';
$attributes['Projects'] = array(); $attributes['Projects']['visible'] = 0; $attributes['Projects']['weight'] = 0.02; $attributes['Projects']['attr'] = 'Projects';
$attributes['Skills'] = array(); $attributes['Skills']['visible'] = 0; $attributes['Skills']['weight'] = 0.06; $attributes['Skills']['attr'] = 'Skills';
$attributes['Occupation'] = array(); $attributes['Occupation']['visible'] = 0; $attributes['Occupation']['weight'] = 0.13; $attributes['Occupation']['attr'] = 'Occupation';
$attributes['Family'] = array(); $attributes['Family']['visible'] = 0; $attributes['Family']['weight'] = 0.13; $attributes['Family']['attr'] = 'Family';
$attributes['Education'] = array(); $attributes['Education']['visible'] = 0; $attributes['Education']['weight'] = 0.13; $attributes['Education']['attr'] = 'Education';
$attributes['Work'] = array(); $attributes['Work']['visible'] = 0; $attributes['Work']['weight'] = 0.13; $attributes['Work']['attr'] = 'Work';
echo '<script type="text/javascript">var attributes = '.json_encode($attributes)."</script>"?>
<span><?php echo "<b>Current User: </b>".$_SESSION['username']?></span>
<span>
<button onclick="onLogoutClick()">Log Out</button>
</span>
</div>
<div id="container">
<div id="one">
<h3>FACEBOOK</h3>
<div>
<?php
if(!isset($_SESSION['fb_access_token']))
{
try{
$accessToken = $helper->getAccessToken();
}
catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
}
catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if(!isset($accessToken))
{
$permissions = ['public_profile','user_friends','email','user_relationships','user_relationship_details','user_about_me', 'user_religion_politics','user_tagged_places','user_events','user_posts','user_location','user_hometown','user_birthday']; // optional
//$permissions = ['public_profile','user_friends','user_events','user_posts'];
$loginUrl = $helper->getLoginUrl('http://localhost/appslogin.php',$permissions);
echo '<a href="' . htmlspecialchars($loginUrl) . '"><image src="fbLogin.png"></a>';
}
else
{
$oAuth2Client = $fb->getOAuth2Client();
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
$tokenMetadata->validateExpiration();
if (! $accessToken->isLongLived()) {
try {
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
}
catch (Facebook\Exceptions\FacebookSDKException $e) {
echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>";
}
}
$_SESSION['fb_access_token'] = (string) $accessToken;
$fb->setDefaultAccessToken($_SESSION['fb_access_token']);
}
}
else
{
$accessToken = $_SESSION['fb_access_token'];
$fb->setDefaultAccessToken($accessToken);
}
if(isset($accessToken))
{
$response = $fb->get('/me');
$graphObject = $response->getGraphObject();
$uid = $graphObject['id'];
$name = $graphObject['name'];
$attributes['name']['visible'] = 1;
$text =" ";
$userNode = $fb->get('/'.$uid.'?fields=name,email,hometown,location,birthday,locale,picture,gender,languages,link,relationship_status')->getGraphUser();
//echo $userNode;
$text.= (isset($userNode['gender']))? 'attributes.gender.visible=1;':'';
$gender = (isset($userNode['gender']))? ($userNode['gender']):'HIDDEN';
$text.= (isset($userNode['email']))? 'attributes.email.visible = 1;' :'';
$email = (isset($userNode['email']))? ($userNode['email']):'HIDDEN';
$text.= (isset($userNode['hometown']))? 'attributes.hometown.visible = 1;':'';
$hometown = (isset($userNode['hometown']))? ($userNode['hometown']['name']):'HIDDEN';
$text.= (isset($userNode['location']))? 'attributes.currentlocation.visible = 1;':'';
$location = (isset($userNode['location']))? ($userNode['location']['name']):'HIDDEN';
$text.= (isset($userNode['birthday']))? 'attributes.dob.visible = 1;':'';
$birthdate = (isset($userNode['birthday']))? ($userNode['birthday']->format('Y/m/d')):'HIDDEN';
$text.= (isset($userNode['relationship_status']))? 'attributes.relationshipstatus.visible = 1;':'';
$relationship_status = (isset($userNode['relationship_status']))? ($userNode['relationship_status']):'HIDDEN';
$fbId = $userNode['id'];
$link = $userNode['link'];
$text.= (isset($userNode['languages']))?'attributes.language.visible = 1;':'';
$languageList = (isset($userNode['languages']))? ($userNode['languages']):NULL;
$languages = "";
if($languageList!=NULL)
foreach($languageList as $language)
$languages = $languages.$language['name'] .",";
else
$languages = "HIDDEN";
$profile_pic_url = "http://graph.facebook.com/".$fbId."/picture?type=large";
$likes = $fb->get('/me/likes')->getGraphEdge();
echo "<img alt='Profile Pic' style='width:100px;height:100px;' src=\"" . $profile_pic_url . "\" >";
echo " <a href=\"" .$link . "\">Profile URL</a>";
$response = $fb->get('/me?fields=birthday,events');
$graphObject = $response->getGraphObject();
$text.= (isset($graphObject['feed']))? 'attributes.checkins.visible = 1;':'';
$checkins = (isset($graphObject['feed']))? ($graphObject['feed']):NULL;
echo '<script type="text/javascript">'.$text.'console.log(attributes)</script>';
echo "<br><b>Name: </b>".$name."<br>";
echo "<b>Gender: </b>" . $gender ."<br>";
echo "<b>Email Id: </b>" . $email ."<br>";
echo "<b>Hometown: </b>" . $hometown."<br>";
echo "<b>Current location: </b>" . $location."<br>";
echo "<b>DOB: </b>" .$birthdate."<br>";
echo "<b>Languages: </b>".$languages."<br>";
echo "<b>Relationship Status: </b>".$relationship_status."<br>";
echo "<b>Checkins: </b><br>";
if($checkins!=NULL)
{
echo '<table border="1">';
echo '<tr style="font-weight:bold"><td>PLACE</td><td>DATE</td><td>TIME</td></tr>';
foreach($checkins as $checkin)
{
$datetime = $checkin['created_time'];
$response = $fb->get('/'.$checkin['id'].'?fields=privacy,place');
$graphObject = $response->getGraphObject();
$privacy = $graphObject['privacy']['value'];
if($privacy != "EVERYONE" && $privacy != "")
continue;
echo '<tr>';
echo '<td>'.$graphObject['place']['name'].'</td>';
echo '<td>'.$datetime->format('Y/m/d').'</td>';
echo '<td>'.$datetime->format('H:m:s').'</td>';
echo '</tr>';
}
echo '</table>';
}
else
echo "HIDDEN";
}
?>
</div>
</div>
<div id="two">
<h3>LINKEDIN</h3>
<div>
<script type="in/Login"></script>
<div id='profile' style="visibility: hidden">
<img src="" id="ProfilePic" alt="Profile Pic" style="width:100px;height:100px;">
<span id="ProfileURL"></span>
<div><b>First Name: </b><span id='FirstName'></span></div>
<div><b>LastName: </b><span id='LastName'></span></div>
<div><b>headline: </b><span id='headline'></span></div>
<div><b>UserId: </b><span id='UserId'></span></div>
<div><b>Location: </b><span id='Location'></span></div>
<div><b>Industry: </b><span id='Industry'></span></div>
<div><b>Summary: </b><span id='Summary'></span></div>
<div><b>EmailAddress: </b><span id='EmailAddress'></span></div>
<div id="Positionsdiv" style="visibility: hidden"><b>Work: </b><table border="1"><tbody id="Positions"></tbody></table></div>
</div>
</div>
</div>
<div id="three">
<h3>Google+</h3>
<div>
<div id='gprofileLogin' class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
<div id='gprofile' style="visibility: hidden">
<img src="" id="gProfilePic" alt="Profile Pic" style="width:100px;height:100px;">
<span id="gProfileURL"></span>
<div><b>Name: </b><span id='gFirstName'></span></div>
<div><b>NickName: </b><span id='gnickname'></span></div>
<div><b>birthday: </b><span id='gbirthday'></span></div>
<div><b>Gender: </b><span id='ggender'></span></div>
<div><b>Email: </b><span id='gEmailAddress'></span></div>
<div><b>Current Location: </b><span id='gcurrentLocation'></span></div>
<div><b>Language: </b><span id='glanguage'></span></div>
<div><b>Places Lived: </b><span id='gplacesLived'></span></div>
<div><b>Relationship Status: </b><span id='grelationshipStatus'></span></div>
<div><b>Occupation: </b><span id='goccupation'></span></div>
<div><b>Education: </b><span id='geducation'></span></div>
<div><b>Work: </b><span id='gwork'></span></div>
</div>
</div>
</div>
</div>
</br></br>
<div>
<div><button onclick="onCalculateClick()">Calculate</button> <span id="tgggw" style="visibility: hidden"></span></div>
<span id="tw" style="visibility: hidden"><b> Total Weight = <span id='totalweight'></span></span> </br>
<span id="twh" style="visibility: hidden"><b> Threshold = <span id='totalweightff'></span></span></br>
<table border="1" id='wtt' style="visibility: hidden"><tbody id="weightTable"></tbody></table>
</div>
<!-- Faceook scripts -->
<script type="text/javascript">
function onCalculateClick() {
var threshold= attributes['profilePicture']['weight']+attributes['name']['weight'];
document.getElementById("wtt").style.visibility='visible';
document.getElementById("tw").style.visibility='visible';
document.getElementById("tgggw").style.visibility='visible';
document.getElementById("twh").style.visibility='visible';
var totalWeight=0;
var tbody = document.getElementById('weightTable');
tbody.innerHTML = '';
th = "<tr><th>Attribute</th><th>Weight</th</tr>"
tbody.innerHTML += th;
for (var key in attributes)
{
var tr = "<tr>";
tr += "<td>" + attributes[key].attr + "</td><td>" + attributes[key].weight + "</td></tr>";
totalWeight += attributes[key].visible*attributes[key].weight;
tbody.innerHTML += tr;
}
document.getElementById('totalweightff').innerHTML = threshold;
document.getElementById('totalweight').innerHTML = totalWeight.toFixed(2);
document.getElementById('tgggw').innerHTML = (totalWeight.toFixed(2) <=threshold) ?'SAFE':'VULNERABLE';
if(document.getElementById('tgggw').innerHTML=='SAFE')
document.getElementById('tgggw').style.backgroundColor = 'green';
else
document.getElementById('tgggw').style.backgroundColor = 'red';
}
function onSignIn(googleUser) {
// Useful data for your client-side scripts:
var data = googleUser.getBasicProfile();
var id_token = googleUser.getAuthResponse().id_token;
document.getElementById("gprofileLogin").setAttribute("style","height:0px");
document.getElementById("gprofile").style.visibility='visible';
document.getElementById("gprofileLogin").style.visibility='hidden';
document.getElementById("gFirstName").innerHTML = data.getName(); attributes.name.visible = 1;
document.getElementById("gEmailAddress").innerHTML = data.getEmail(); attributes.email.visible = 1;
document.getElementById("gProfilePic").src = data.getImageUrl();
var apikey="AIzaSyCKXsT-m5yTZo3Ki0GecHfUBpa-L0WOUbk";
var url = "https://www.googleapis.com/plus/v1/people/"+data.getId()+"?fields=ageRange%2Cbirthday%2CcurrentLocation%2Cgender%2Clanguage%2Cnickname%2CplacesLived%2CrelationshipStatus%2Curl%2Coccupation%2Corganizations&key="+ apikey;
var representationOfDesiredState = "The";
var client = new XMLHttpRequest();
client.open("GET", url, false);
client.send(representationOfDesiredState);
var userData = JSON.parse(client.responseText);
var aggender = (userData.gender != undefined)?userData.gender:'HIDDEN';
var agbirthday = (userData.birthday != undefined)?userData.birthday:'HIDDEN';
var agcurrentLocation = (userData.currentLocation != undefined)?userData.currentLocation:'HIDDEN';
var aglanguage = (userData.language != undefined)? userData.language:'HIDDEN';
var agnickname = (userData.nickname != undefined)?userData.nickname:'HIDDEN';
var agplacesLived = (userData.placesLived != undefined)?userData.placesLived[0].value:'HIDDEN';
var agrelationshipStatus = (userData.relationshipStatus != undefined)?userData.relationshipStatus:'HIDDEN';
var agoccupation = (userData.occupation != undefined)? userData.occupation:'HIDDEN';
var agorganizations = (userData.organizations != undefined)?userData.organizations:'HIDDEN';
if (userData.url != undefined)
document.getElementById("gProfileURL").innerHTML = "<a href='" + userData.url + "'>Profile URL</a>";
document.getElementById("ggender").innerHTML = aggender;
if(aggender !='HIDDEN')
attributes.gender.visible = 1;
document.getElementById("gbirthday").innerHTML = agbirthday;
if(agbirthday !='HIDDEN')
attributes.dob.visible = 1;
document.getElementById("gcurrentLocation").innerHTML = agcurrentLocation;
if(agcurrentLocation !='HIDDEN')
attributes.currentlocation.visible = 1;
document.getElementById("glanguage").innerHTML = aglanguage;
console.log(aglanguage);
if(aglanguage !='HIDDEN')
attributes.language.visible = 1;
document.getElementById("gnickname").innerHTML =agnickname;
if(agnickname !='HIDDEN')
attributes.nickname.visible = 1;
document.getElementById("gplacesLived").innerHTML = agplacesLived;
if(agplacesLived !='HIDDEN')
attributes.checkins.visible = 1;
document.getElementById("grelationshipStatus").innerHTML = agrelationshipStatus;
if(agrelationshipStatus !='HIDDEN')
attributes.relationshipstatus.visible = 1;
document.getElementById("goccupation").innerHTML = agoccupation;
if(agoccupation !='HIDDEN')
attributes.Occupation.visible = 1;
if(agoccupation !='HIDDEN' && Object.keys(agorganizations).length!=0)
{
val=agorganizations;
for (var i = 0; i < Object.keys(val).length; i++)
{
if(val[i].type =='school')
{
document.getElementById("geducation").innerHTML += "</br>"+val[i].name + " ( " + val[i].startDate + " - " + val[i].endDate+ " ) " ;
attributes.Education.visible = 1;
}
else if(val[i].type =='work')
{
document.getElementById("gwork").innerHTML += "</br>"+val[i].name + " ( " + val[i].startDate + " - " + val[i].endDate+ " ) " ;
attributes.Work.visible = 1;
}
}
}
};
// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
IN.Event.on(IN, "auth", getProfileData);
}
function onLogoutClick()
{
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('google+ User signed out.');
});
IN.User.logout(afterLogout);
}
function afterLogout()
{
window.location = "logout.php";
}
// Handle the successful return from the API call
function onSuccess(data) {
document.getElementById("profile").style.visibility='visible';
document.getElementById("FirstName").innerHTML = data.firstName;
document.getElementById("LastName").innerHTML = data.lastName;
attributes.name.visible = 1;
document.getElementById("headline").innerHTML = data.headline;
if(data.headline != undefined || data.headline !='')
attributes.status.visible = 1;
document.getElementById("UserId").innerHTML = data.id;
document.getElementById("ProfilePic").src = data.pictureUrl;
document.getElementById("Location").innerHTML = data.location.name;
if(data.location.name != undefined && data.location.name !='')
attributes.currentlocation.visible = 1;
document.getElementById("Industry").innerHTML = data.industry;
if(data.industry != undefined && data.industry !='')
attributes.industry.visible = 1;
document.getElementById("Summary").innerHTML = data.summary;
if(data.summary != undefined && data.summary!='')
attributes.status.visible = 1;
obj = data.positions;
if(obj._total != 0)
document.getElementById("Positionsdiv").style.visibility='visible'
var tbody = document.getElementById('Positions');
for (var i = 0; i < obj._total; i++)
{
val = obj.values;
var tr = "<tr>";
tr += "<td>" + val[i].title + "</td><td>" + val[i].company.name + "</td><td>" + val[i].endDate.month + "/" + val[i].endDate.year + "</td><td>" + val[i].isCurrent + "</td></tr>";
tbody.innerHTML += tr;
}
document.getElementById("ProfileURL").innerHTML = "<a href='" + data.publicProfileUrl + "'>Profile URL</a>";
document.getElementById("EmailAddress").innerHTML = data.emailAddress;
if(data.emailAddress != undefined && data.emailAddress !='')
attributes.email.visible = 1;
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
// Use the API call wrapper to request the member's basic profile data
function getProfileData() {
IN.API.Raw("/people/~:(id,firstName,lastName,headline,picture-url,location,industry,summary,positions,public-profile-url,email-address)?format=json").result(onSuccess).error(onError);
}
</script>
</body>
</html>
<file_sep>/README.md
# socialFootprint
A facebook plugin which tells you how much your social media footprint is public and how susceptible you are to identity theft or malicious stalking.
<file_sep>/source/root/index.php
<?php
session_start();
if (isset($_SESSION['username'])) {
header('Location: appslogin.php');
}
?>
<html>
<head>
<title>Social FootPrint</title>
</head>
<body>
<h3>User Registration</h3>
<table border="0">
<form method="POST" action="loginproc.php">
<tr><td>Username</td><td>:</td><td><input type="text" name="username" size="20"> </td></tr>
<tr><td> </td><td> </td><td><input type="submit" value="Login"></td></tr>
</form>
</table>
</body>
</html><file_sep>/source/root/loginproc.php
<?php
// Inialize session
session_start();
header('Location: appslogin.php');
$_SESSION['username'] = $_POST['username'];
?><file_sep>/source/loaddata.sql
INSERT INTO Attribute_Weights (attr_name,attr_weight) VALUES('first_name',0.10),
('last_name',0.40),
('profile_picture',0.25),
('gender',0.05),
('age',0.15),
('date_of_birth',0.40),
('email_address',0.50),
('phone_number',0.75),
('marital_status',0.35),
('current_location',0.80),
('previous_location',0.60),
('working_at',0.75),
('prev_working_at',0.25),
('studying_at',0.65),
('prev_studying_at',0.20),
('father_name',0.70),
('mother_name',0.80),
('mother_maiden_name',1.0),
('family_information',0.65),
('checkins',1);
<file_sep>/source/dbscript.sql
create table if not exists Attribute_Weights
( attr_name VARCHAR(50) not null,
attr_weight DECIMAL(8,4) NOT NULL
);
create TEMPORARY table curr_user
( attr_name VARCHAR(50) ,
attr_weight DECIMAL(8,4)
);
insert into curr_user(
select a.attr_name, a.attr_weight from user_attributes u inner join Attribute_Weights a ON a.attr_name = u.attribute);
create table if not exists temp_user_weights
(first_name DECIMAL(8,4) DEFAULT 0,
last_name DECIMAL(8,4) DEFAULT 0,
profile_picture DECIMAL(8,4) DEFAULT 0,
gender DECIMAL(8,4) DEFAULT 0,
age DECIMAL(8,4) DEFAULT 0,
date_of_birth DECIMAL(8,4) DEFAULT 0,
email_address DECIMAL(8,4) DEFAULT 0,
phone_number DECIMAL(8,4) DEFAULT 0,
marital_status DECIMAL(8,4) DEFAULT 0,
current_location DECIMAL(8,4) DEFAULT 0,
previous_location DECIMAL(8,4) DEFAULT 0,
working_at DECIMAL(8,4) DEFAULT 0,
prev_working_at DECIMAL(8,4) DEFAULT 0,
studying_at DECIMAL(8,4) DEFAULT 0,
prev_studying_at DECIMAL(8,4) DEFAULT 0,
father_name DECIMAL(8,4) DEFAULT 0,
mother_name DECIMAL(8,4) DEFAULT 0,
mother_maiden_name DECIMAL(8,4) DEFAULT 0,
family_information DECIMAL(8,4) DEFAULT 0,
checkins DECIMAL(8,4) DEFAULT 0);
//what will come from UI
create TEMPORARY table user_attributes
(
attribute VARCHAR(50)
);
INSERT INTO user_attributes(attribute) VALUES ('first_name'),('last_name'),('profile_picture'),('gender'),('date_of_birth'),('email_address'),('current_location')
| d28ecb49d25b8d574c482bbec225c20c6d6715f4 | [
"Markdown",
"SQL",
"PHP"
] | 6 | PHP | mickeymv/socialFootprint | 1115b3b8f039077f5a5795bb468687d574fd177b | 76b91ad039d3cb9ceb9421fb224d1c48782eccb1 |
refs/heads/main | <file_sep>//Canvas container
var p5div = document
.querySelector('#p5sketch');
//Canvas size
var w, h;
//P5.js sketch
var p5sketch = ( p5 ) => {
p5.setup = () => {
w = p5div.clientWidth;
h = p5div.clientHeight;
p5.createCanvas(w,h);
};
p5.windowResized = () => {
w = p5div.clientWidth;
h = p5div.clientHeight;
p5.resizeCanvas(w,h);
}
var t1 = 0, t2 = 0,
t3 = 0, t4 = 0;
var dt1 = p5.random(0.01, 0.001),
dt2 = p5.random(0.02, 0.002),
dt3 = p5.random(0.03, 0.003),
dt4 = p5.random(0.04, 0.004);
var rnd = p5.random(10, 80),
wrnd = w/2,
hrnd = h;
p5.draw = () => {
p5.clear();
p5.noFill();
p5.stroke("#101010");
if(p5.frameCount%200==0){
rnd = p5.random(10, 80);
wrnd = p5.random(0, w);
hrnd = p5.random(0, h);
}
for(let i=1; i<100; i++){
p5.triangle(
wrnd, hrnd,
p5.abs(p5.sin(t1+i*rnd))*w,
p5.abs(p5.cos(t2+i*rnd))*h,
p5.abs(p5.sin(t3+i*rnd))*w,
p5.abs(p5.cos(t4+i*rnd))*h
);
}
t1 += dt1;
t2 += dt2;
t3 += dt3;
t4 += dt4;
}
}
//P5.js sketch instance
var p5inst = new p5(p5sketch, p5div);<file_sep>A Pen created at CodePen.io. You can find this one at https://codepen.io/filippoguida/pen/zeLKEp.
In rule-based art the draw is thi direct result of logic-based systems to implemented to direct the design and creation of the object. The artist forces the draw to conform to certain arbitrary rules, whom represent the artwork itself. This p5.js script create changing texture using only triangles disposed in strategic points on the canvas. | 3f11a50c83e5151026cd3ec340f574c4b95adfbb | [
"JavaScript",
"Text"
] | 2 | JavaScript | zgendao/neurogenesis_landing | 5b44615c842c5045681c7ee2b3dcf88550fb7449 | 82ce8c000e445d21c87e53d143d82d1d518d4549 |
refs/heads/master | <file_sep>package jp.ac.uryukyu.ie.e205742;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class BattleMasterTest {
@Test
public void attackTest(){
int defHp=50;
var master = new BattleMaster("悟空",100,20,70);
master.order.get(0).killerTechniques.get(0).execute(master.order.get(0), master.order.get(1));
master.order.get(1).killerTechniques.get(0).execute(master.order.get(1), master.order.get(0));
assertEquals(defHp, master.order.get(0).getHp());
}
}
<file_sep>package jp.ac.uryukyu.ie.e205742;
import java.util.ArrayList;
public class BattleMaster {
ArrayList<Character> order = new ArrayList<>();
public String name;
public int Hp;
public int ATK;
public int vaitality;
/**
* コンストラクタ
* @param _name 悟空の名前
* @param _Hp 悟空の体力
* @param _ATK 悟空の攻撃力
* @param _vaitality 悟空の気力
*/
public BattleMaster(String _name,int _Hp,int _ATK,int _vaitality){
Goku goku = new Goku(_name,_Hp,_ATK,_vaitality);
goku.addKillerTechnique(new Attack());
goku.addKillerTechnique(new SpiritBullet("かめはめ波", 30, 10));
goku.addKillerTechnique(new SpiritBullet("元気玉", 50, 20));
Freeza freeza = new Freeza("フリーザ",500,50,150);
freeza.addKillerTechnique(new Attack());
freeza.addKillerTechnique(new SpiritBullet("デスビーム", 100, 20));
freeza.addKillerTechnique(new SpiritBullet("デスボール", 200, 40));
order.add(goku);
order.add(freeza);
}
/**
* プレイヤーと敵のステータスを表示する
*/
public void showStatus() { //全キャラクタのステータスを表示(テスト用)
for(var ch : order) {
ch.showStatus();
}
}
/**
* 1ターンバトルを行う
*/
public void battle() {
for(var ch : order) {
ch.act(order);
}
}
/**
* プレイヤーまたは敵のHpが0以下になるまで戦いを続けるメソッド
*/
public void Battle(){
while(true){
showStatus();
battle();
if(order.get(0).getHp()<=0 || order.get(1).getHp()<=0){
System.out.println("戦闘終了");
break;
}
}
}
}
<file_sep>package jp.ac.uryukyu.ie.e205742;
import java.util.ArrayList;
/**
* 全てのキャラクターの元の設計図を作るクラス
*/
abstract class Character {
private String name; //キャラクターの名前
public int Hp; //キャラクターの体力
private int ATK; //キャラクターの攻撃力
private int vitality; //キャラクターの気力
/**
* 名前を返すメソッド
* @return 名前
*/
public String getName(){ return name; }
/**
* 体力を返すメソッド
* @return 体力
*/
public int getHp(){ return Hp;}
/**
* 攻撃力を返すメソッド
* @return 攻撃力
*/
public int getATK(){ return ATK;}
/**
* 気力量を返すメソッド
* @return 気力
*/
public int getVitality(){ return vitality;}
/**
* 引数でもらったダメージ量をHpから引く
* @param value ダメージ量
*/
public void damage(int value){
this.Hp -= value;
}
/**
* 引数で受け取った使用した気力量をvitalityから引く
* @param mp 使用した気力量
*/
public void useMp(int mp){
this.vitality -= mp;
}
/**
* コンストラクタ
* @param _name 名前
* @param _Hp 体力
* @param _vitality 気力
*/
public Character(String _name, int _Hp, int _ATK, int _vitality){
this.name=_name;
this.Hp=_Hp;
this.ATK=_ATK;
this.vitality=_vitality;
}
ArrayList<KillerTechnique> killerTechniques = new ArrayList<>();
/**
* 必殺技を追加するメソッド
* @param _killerTechnique キャラが持つ必殺技
*/
public void addKillerTechnique(KillerTechnique _killerTechnique) {
killerTechniques.add(_killerTechnique);
}
/**
* 今のキャラが持つステータスを表示する
*/
public void showStatus() {
System.out.printf("%s:体力 %d 気力 %d\n", name, Hp, vitality);
}
/**
* 引数から敵を受け取り敵に対して攻撃を行うメソッド
* @param targets 敵
*/
abstract void act(ArrayList<Character> targets);
}
<file_sep>package jp.ac.uryukyu.ie.e205742;
import java.util.ArrayList;
import java.util.Random;
/**
* フリーザを召喚するためのクラス
*/
public class Freeza extends Character {
/**
* コンストラクタ
* @param name 名前
* @param Hp 体力
* @param ATK 攻撃力
* @param vitality 気力
*/
public Freeza(String name,int Hp,int ATK,int vitality){
super(name,Hp,ATK,vitality);
}
/**
* 引数で受け取った敵に対してランダムで必殺技を選び攻撃するメソッド
*/
@Override
public void act(ArrayList<Character> targets){
var rand = new Random();
int index = rand.nextInt(killerTechniques.size());
killerTechniques.get(index).execute(this, targets.get(0));
}
}
<file_sep>package jp.ac.uryukyu.ie.e205742;
import java.util.ArrayList;
import java.util.Random;
/**
* ベジットを召喚するためのクラス
*/
public class Vejitto extends Goku{
/**
* コンストラクタ
* @param _name 名前
* @param _Hp 体力
* @param _ATK 攻撃力
* @param _vitality 気力
*/
public Vejitto(String _name,int _Hp,int _ATK,int _vitality){
super(_name,_Hp,_ATK,_vitality);
}
@Override
public void act(ArrayList<Character> targets){
var rand = new Random();
int index = rand.nextInt(killerTechniques.size());
killerTechniques.get(index).execute(this, targets.get(1));
}
}
| aac65d772e1dfef448c01214157dac4dc3d4c810 | [
"Java"
] | 5 | Java | e205742/Report6 | 422ec98767332826cbc8bf0f17f59e0bf406f947 | 1cfb944f4548b0f0b21b9af738ded87024e4a2b1 |
refs/heads/master | <file_sep>const ap = new APlayer({
container: document.getElementById('aplayer'),
fixed: true,
autoplay: true,
audio: [
{
name: "Summertime",
artist: 'K-391',
url: 'http://music.163.com/song/media/outer/url?id=32166628.mp3',
cover: 'https://cdn.jsdelivr.net/gh/lwsblog/images@master/img/20200512211912.jpg',
},
{
name: "Sunburst",
artist: 'Tobu,Itro',
url: 'http://music.163.com/song/media/outer/url?id=28830411.mp3',
cover: 'https://cdn.jsdelivr.net/gh/lwsblog/images@master/img/20200512212036.jpg',
},
{
name: "Blue Lights",
artist: 'Fumos',
url: 'http://music.163.com/song/media/outer/url?id=1376760895.mp3',
cover: 'https://cdn.jsdelivr.net/gh/lwsblog/images@master/img/20200512212222.jpg',
},
{
name: "Fragments",
artist: '千坂',
url: 'http://music.163.com/song/media/outer/url?id=453130276.mp3',
cover: 'https://cdn.jsdelivr.net/gh/lwsblog/images@master/img/20200512213235.jpg',
},
{
name: "All In",
artist: 'L3V3LS',
url: 'http://music.163.com/song/media/outer/url?id=425684642.mp3',
cover: 'https://cdn.jsdelivr.net/gh/lwsblog/images@master/img/20200512213458.jpg',
},
]
}); | f5f6d45a07dd7f033597593fc8f0f7d657257a7a | [
"JavaScript"
] | 1 | JavaScript | lwsblog/lwsblog.github.io | 6c773fa1d944ecd2a534da13c8c834e0dc5947c9 | ce903327518c49fc8ddb301428782cd3fa66ee5b |
refs/heads/main | <repo_name>lightweightcoder/4.2.2-4.2.3-4.2.4-4.3<file_sep>/models/index.mjs
import { Sequelize } from 'sequelize';
import allConfig from '../config/config.js';
import itemModel from './item.mjs';
import categoryModel from './category.mjs';
import cartModel from './cart.mjs';
import cartsItemModel from './cartsItem.mjs';
const env = process.env.NODE_ENV || 'development';
const config = allConfig[env];
const db = {};
const sequelize = new Sequelize(
config.database,
config.username,
config.password,
config,
);
db.Item = itemModel(sequelize, Sequelize.DataTypes);
db.Category = categoryModel(sequelize, Sequelize.DataTypes);
db.Cart = cartModel(sequelize, Sequelize.DataTypes);
db.CartsItem = cartsItemModel(sequelize, Sequelize.DataTypes);
// in order for the many-to-many to work we must mention the join table here.
db.Item.belongsToMany(db.Category, { through: 'ItemsCategories' });
db.Category.belongsToMany(db.Item, { through: 'ItemsCategories' });
// Connect Item and Cart models.
// Note: It's possible to use a Sequelize model class (i.e. CartsItem)
// to connect the models Item and Cart instead of the table name (i.e. CartsItems).
db.Item.belongsToMany(db.Cart, { through: db.CartsItem });
db.Cart.belongsToMany(db.Item, { through: db.CartsItem });
// Define 1-M associations between CartsItems table and associated tables
// to access CartsItem attributes from Item and Cart instances
db.Item.hasMany(db.CartsItem);
db.CartsItem.belongsTo(db.Item);
db.Cart.hasMany(db.CartsItem);
db.CartsItem.belongsTo(db.Cart);
db.sequelize = sequelize;
db.Sequelize = Sequelize;
export default db;
<file_sep>/seeders/20201215112829-fake-data.js
module.exports = {
up: async (queryInterface) => {
// Define category data
const categoryData = [
{
name: 'fish',
createdAt: new Date(),
updatedAt: new Date(),
},
{
name: 'fruit',
createdAt: new Date(),
updatedAt: new Date(),
},
{
name: 'healthy',
createdAt: new Date(),
updatedAt: new Date(),
},
{
name: 'canned',
createdAt: new Date(),
updatedAt: new Date(),
},
];
// Bulk insert categories
const [
fishCategory,
fruitCategory,
healthyCategory,
cannedCategory,
] = await queryInterface.bulkInsert('Categories', categoryData, {
returning: true,
});
// Define item data
const itemData = [
{
name: 'banana',
createdAt: new Date(),
updatedAt: new Date(),
},
{
name: 'tuna',
createdAt: new Date(),
updatedAt: new Date(),
},
{
name: 'peach',
createdAt: new Date(),
updatedAt: new Date(),
},
];
// Bulk insert items
const [banana, tuna, peach] = await queryInterface.bulkInsert(
'Items',
itemData,
{ returning: true },
);
// Define item category data based on generated items and categories
const itemCategoryData = [
// banana is a fruit
{
ItemId: banana.id,
CategoryId: fruitCategory.id,
createdAt: new Date(),
updatedAt: new Date(),
},
// banana is healthy
{
ItemId: banana.id,
CategoryId: healthyCategory.id,
createdAt: new Date(),
updatedAt: new Date(),
},
// tuna is fish
{
ItemId: tuna.id,
CategoryId: fishCategory.id,
createdAt: new Date(),
updatedAt: new Date(),
},
// tuna is canned
{
ItemId: tuna.id,
CategoryId: cannedCategory.id,
createdAt: new Date(),
updatedAt: new Date(),
},
// peach is fruit
{
ItemId: peach.id,
CategoryId: fruitCategory.id,
createdAt: new Date(),
updatedAt: new Date(),
},
// peach is canned
{
ItemId: peach.id,
CategoryId: cannedCategory.id,
createdAt: new Date(),
updatedAt: new Date(),
},
];
// Bulk insert item categories
await queryInterface.bulkInsert('ItemsCategories', itemCategoryData);
// Define cart data, 2 carts
const cartData = [
{
createdAt: new Date(),
updatedAt: new Date(),
},
{
createdAt: new Date(),
updatedAt: new Date(),
},
];
// Bulk insert carts
const [cart1, cart2] = await queryInterface.bulkInsert('Carts', cartData, {
returning: true,
});
// Define cart item data, i.e. put items in cart
const cartsItemData = [
{
quantity: 1,
ItemId: peach.id,
CartId: cart1.id,
},
{
quantity: 3,
ItemId: peach.id,
CartId: cart1.id,
},
{
quantity: 2,
ItemId: banana.id,
CartId: cart1.id,
},
{
quantity: 4,
ItemId: peach.id,
CartId: cart2.id,
},
];
// Bulk insert cart items
await queryInterface.bulkInsert('CartsItems', cartsItemData);
},
down: async (queryInterface) => {
// Delete rows from tables with foreign key references first
await queryInterface.bulkDelete('ItemsCategories', null, {});
await queryInterface.bulkDelete('CartsItems', null, {});
await queryInterface.bulkDelete('Items', null, {});
await queryInterface.bulkDelete('Categories', null, {});
await queryInterface.bulkDelete('Carts', null, {});
},
};
<file_sep>/index.mjs
import db from './models/index.mjs';
db.Cart.findAll({
include: {
model: db.Item,
include: [db.Category, db.CartsItem],
},
})
.then((carts) => {
// console.log(carts[0]);
// console.log(carts[0].Items);
console.log(carts[0].Items[1].CartsItems.length);
// console.log(carts[0].Items[1].CartsItems[0]);
// console.log(carts[0].Items[0].CartsItem.quantity);
// console.log(carts[0].Items[1].Categories[0].name);
// console.log(carts[0].Items[1].Categories[1].name);
// console.log(carts[0].Items[0].Categories[0].name);
})
.catch((error) => console.log(error));
<file_sep>/models/cartsItem.mjs
export default function cartsItemModel(sequelize, DataTypes) {
return sequelize.define(
'CartsItem',
{
quantity: {
type: DataTypes.INTEGER,
},
},
{
// timestamps: false prevents Sequelize from adding
// createdAt and updatedAt timestamp fields
// https://sequelize.org/master/class/lib/model.js~Model.html#static-method-init
timestamps: false,
},
);
}
<file_sep>/get-category-from-item.mjs
import db from './models/index.mjs';
db.Item.findOne({
where: {
name: [process.argv[2]]
}
})
.then((item) => item.getCategory())
.then((itemCategory) => console.log( itemCategory ))
.catch((error) => console.log(error));<file_sep>/get-items-from-category.mjs
import db from './models/index.mjs';
db.Category.findOne({
where: {
name: [process.argv[2]]
}
})
.then((category) => category.getItems())
.then((categoryItems) => console.log( categoryItems ))
.catch((error) => console.log(error));<file_sep>/migrations/20201215112009-create-item-table.js
module.exports = {
up: async (queryInterface, Sequelize) => {
// Create Items and Categories First
await queryInterface.createTable('Categories', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
name: {
type: Sequelize.STRING,
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
},
});
await queryInterface.createTable('Items', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
name: {
type: Sequelize.STRING,
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
},
});
await queryInterface.createTable('ItemsCategories', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
CategoryId: {
type: Sequelize.INTEGER,
references: {
model: 'Categories',
key: 'id',
},
},
ItemId: {
type: Sequelize.INTEGER,
references: {
model: 'Items',
key: 'id',
},
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
},
});
await queryInterface.createTable('Carts', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
},
});
await queryInterface.createTable('CartsItems', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
quantity: {
type: Sequelize.INTEGER,
},
CartId: {
type: Sequelize.INTEGER,
references: {
model: 'Carts',
key: 'id',
},
},
ItemId: {
type: Sequelize.INTEGER,
references: {
model: 'Items',
key: 'id',
},
},
});
},
down: async (queryInterface, Sequelize) => {
// Drop tables with foreign key references first
await Promise.all([
queryInterface.dropTable('ItemsCategories'),
queryInterface.dropTable('CartsItems'),
]);
await Promise.all([
queryInterface.dropTable('Items'),
queryInterface.dropTable('Categories'),
queryInterface.dropTable('Carts'),
]);
},
};
| e8f5444459197a67389800f2d1cd85f62b27b951 | [
"JavaScript"
] | 7 | JavaScript | lightweightcoder/4.2.2-4.2.3-4.2.4-4.3 | b8fb1707700ccb13e8fb208595e5deef5bb48219 | 190c8bf36cd1978d3e81b0d9cb7eede0279a19b7 |
refs/heads/main | <file_sep>using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using WebApplication.webServiceReference;
using System.Web.Security;
namespace WebApplication
{
public partial class WebForm2 : System.Web.UI.Page
{
private bool ValidateUser(string userName, string passWord)
{
if ((null == userName) || (0 == userName.Length) || (userName.Length > 15))
{
System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of userName failed.");
return false;
}
if ((null == passWord) || (0 == passWord.Length) || (passWord.Length > 25))
{
System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of passWord failed.");
return false;
}
WebService1 ws = new WebService1();
return true;
}
public void createLogin(Object sender, EventArgs e)
{
try
{
String usernameTb = username.Text.ToString();
String passwordTb = password.Text.ToString();
if (ValidateUser(usernameTb, passwordTb))
{
WebService1 ws = new WebService1();
Userdata userdataRes = ws.login(usernameTb, passwordTb);
if (userdataRes.id != 0 && userdataRes.loguedAs.Equals("DOCTOR"))
{
createCoockie("id", userdataRes.id.ToString());
HttpCookie userInfo = new HttpCookie("doctor");
userInfo["doctor"] = "true";
userInfo.Expires.Add(new TimeSpan(0, 1, 0));
Response.Cookies.Add(userInfo);
FormsAuthentication.RedirectFromLoginPage(usernameTb, false);
Response.Redirect(Page.ResolveClientUrl("./doctor/Doctor.aspx"));
}
else if (userdataRes.id != 0 && userdataRes.loguedAs.Equals("PACIENT"))
{
createCoockie("id", userdataRes.id.ToString());
HttpCookie userInfo = new HttpCookie("doctor");
userInfo["doctor"] = "false";
userInfo.Expires.Add(new TimeSpan(0, 1, 0));
Response.Cookies.Add(userInfo);
FormsAuthentication.RedirectFromLoginPage(usernameTb, false);
Response.Redirect(Page.ResolveClientUrl("./patient/patient.aspx?id=" + userdataRes.id.ToString()));
}
}
}
catch (Exception ex)
{
}
}
void createCoockie(string name, string value)
{
HttpCookie userInfo = new HttpCookie(name);
userInfo[name] = value;
userInfo.Expires.Add(new TimeSpan(0, 10, 0));
Response.Cookies.Add(userInfo);
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
}<file_sep>using Microsoft.Data.Sqlite;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Services;
namespace ProyectoIngles
{
/// <summary>
/// Descripción breve de WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// Para permitir que se llame a este servicio web desde un script, usando ASP.NET AJAX, quite la marca de comentario de la línea siguiente.
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
public String DBpath;
public SQLiteConnection conn;
[WebMethod]
public string HelloWorld()
{
return "Hola a todos";
}
/*********************************************************************************************
*
* INSERTS
*
*********************************************************************************************/
[WebMethod]
public void insertHistoric(int doctorId, int pacientId, string diagnose, string treatment, string date)
{
Database databaseObject = new Database();
string query = "INSERT INTO Historic (`DoctorID`,`PacientID`,`Diagnose`,`Treatment`, `Date`) VALUES (@DoctorID,@PacientID,@Diagnose,@Treatment,@Date)";
SQLiteCommand myCommand = new SQLiteCommand(query, databaseObject.myConnection);
databaseObject.OpenConnection();
myCommand.Parameters.AddWithValue("@DoctorID", doctorId);
myCommand.Parameters.AddWithValue("@PacientID", pacientId);
myCommand.Parameters.AddWithValue("@Diagnose", diagnose);
myCommand.Parameters.AddWithValue("@Treatment", treatment);
myCommand.Parameters.AddWithValue("@Date", date);
var result = myCommand.ExecuteNonQuery();
databaseObject.CloseConnection();
Console.WriteLine("Rows Added : {0}", result);
}
[WebMethod]
public void InsertDoctor(string dni, string name, string password)
{
Database databaseObject = new Database();
string query = "INSERT INTO Doctor (`DNI`, `Name`, `Password`) VALUES (@DNI,@Name,@Password)";
SQLiteCommand myCommand = new SQLiteCommand(query, databaseObject.myConnection);
databaseObject.OpenConnection();
myCommand.Parameters.AddWithValue("@DNI", dni);
myCommand.Parameters.AddWithValue("@Name", name);
String md5password = md5Encrypt(password);
myCommand.Parameters.AddWithValue("@Password", md5password);
var result = myCommand.ExecuteNonQuery();
databaseObject.CloseConnection();
Console.WriteLine("Rows Added : {0}", result);
}
private Pacient getLatestPacient()
{
Database databaseObject = new Database();
Pacient pacient = null;
string query = "SELECT * FROM Pacient ORDER BY ID DESC LIMIT 1";
SQLiteCommand myCommand = new SQLiteCommand(query, databaseObject.myConnection);
databaseObject.OpenConnection();
SQLiteDataReader result = myCommand.ExecuteReader();
if (result.HasRows)
{
while (result.Read())
{
pacient = new Pacient(Convert.ToInt32(result["ID"]), Convert.ToString(result["DNI"]), Convert.ToString(result["Name"]));
}
}
databaseObject.CloseConnection();
return pacient;
}
[WebMethod]
public int insertPacient(string doctorId, string dni, string name, string password)
{
int id = 0;
Database databaseObject = new Database();
string query = "INSERT INTO Pacient (`DNI`, `Name`, `Password`) VALUES (@DNI,@Name,@Password)";
SQLiteCommand myCommand = new SQLiteCommand(query, databaseObject.myConnection);
databaseObject.OpenConnection();
myCommand.Parameters.AddWithValue("@DNI", dni);
myCommand.Parameters.AddWithValue("@Name", name);
String md5password = md5Encrypt(password);
myCommand.Parameters.AddWithValue("@Password", <PASSWORD>);
SQLiteDataReader result = myCommand.ExecuteReader();
if (result.HasRows)
{
while (result.Read())
{
id = Convert.ToInt32(result["ID"]);
}
databaseObject.CloseConnection();
Console.WriteLine("Rows Added : {0}", result);
}
Pacient pacient = getLatestPacient();
insertHistoric(Convert.ToInt32(doctorId), pacient.id, "initial diagnose", "initial treatment", DateTime.Now.ToString());
return pacient.id;
}
/*********************************************************************************************
*
* SELECTS
*
*********************************************************************************************/
[WebMethod]
public List<Pacient> getAllDoctorPacients(int doctorId)
{
Database databaseObject = new Database();
List<Pacient> pacientList = new List<Pacient>();
string query = "SELECT * FROM Historic WHERE DoctorID = @DoctorID GROUP By PacientID; ";
SQLiteCommand myCommand = new SQLiteCommand(query, databaseObject.myConnection);
databaseObject.OpenConnection();
myCommand.Parameters.AddWithValue("@DoctorID", doctorId);
SQLiteDataReader result = myCommand.ExecuteReader();
if (result.HasRows)
{
while (result.Read())
{
Pacient pacient = getPacientInfo(Convert.ToInt32(result["PacientID"]));
pacientList.Add(pacient);
}
}
databaseObject.CloseConnection();
return pacientList;
}
[WebMethod]
public List<Historic> getAllPacientRecords(int pacientId)
{
Database databaseObject = new Database();
List<Historic> pacientList = new List<Historic>();
string query = "SELECT * FROM Historic WHERE PacientID=@PacientID;";
SQLiteCommand myCommand = new SQLiteCommand(query, databaseObject.myConnection);
databaseObject.OpenConnection();
myCommand.Parameters.AddWithValue("@PacientID", pacientId);
SQLiteDataReader result = myCommand.ExecuteReader();
if (result.HasRows)
{
while (result.Read())
{
Historic pacient = new Historic(Convert.ToInt32(result["ID"]), Convert.ToInt32(result["DoctorID"]), Convert.ToInt32(result["PacientID"]), Convert.ToString(result["Diagnose"]), Convert.ToString(result["Treatment"]), Convert.ToString(result["Date"])); //Console.WriteLine("ID: {0} - Name: {1}", result["ID"], result["Name"], result["DNI"]);
pacientList.Add(pacient);
}
}
databaseObject.CloseConnection();
return pacientList;
}
[WebMethod]
public Pacient getPacientInfo(int pacientId)
{
Database databaseObject = new Database();
Pacient pacient = null;
string query = "SELECT * FROM Pacient WHERE ID = @id;";
SQLiteCommand myCommand = new SQLiteCommand(query, databaseObject.myConnection);
databaseObject.OpenConnection();
myCommand.Parameters.AddWithValue("@id", pacientId);
SQLiteDataReader result = myCommand.ExecuteReader();
if (result.HasRows)
{
while (result.Read())
{
pacient = new Pacient(Convert.ToInt32(result["ID"]), Convert.ToString(result["DNI"]), Convert.ToString(result["Name"]));
}
}
databaseObject.CloseConnection();
return pacient;
}
[WebMethod]
public Doctor getDoctorInfo(int doctorId)
{
Database databaseObject = new Database();
Doctor doctor = null;
string query = "SELECT * FROM Doctor WHERE ID = @id;";
SQLiteCommand myCommand = new SQLiteCommand(query, databaseObject.myConnection);
databaseObject.OpenConnection();
myCommand.Parameters.AddWithValue("@id", doctorId);
SQLiteDataReader result = myCommand.ExecuteReader();
if (result.HasRows)
{
while (result.Read())
{
doctor = new Doctor(Convert.ToInt32(result["ID"]), Convert.ToString(result["DNI"]), Convert.ToString(result["Name"]), Convert.ToString(result["Password"]));
}
}
databaseObject.CloseConnection();
return doctor;
}
[WebMethod]
public List<Doctor> getAllDoctors()
{
Database databaseObject = new Database();
List<Doctor> doctorList = new List<Doctor>();
string query = "SELECT * FROM Doctor";
SQLiteCommand myCommand = new SQLiteCommand(query, databaseObject.myConnection);
databaseObject.OpenConnection();
SQLiteDataReader result = myCommand.ExecuteReader();
if (result.HasRows)
{
while (result.Read())
{
Doctor doctor = new Doctor(Convert.ToInt32(result["ID"]), Convert.ToString(result["DNI"]), Convert.ToString(result["Name"]), Convert.ToString(result["Password"]));
doctorList.Add(doctor);
}
}
databaseObject.CloseConnection();
return doctorList;
}
/*********************************************************************************************
*
* LOGIN STUFF
*
*********************************************************************************************/
[WebMethod]
public String loginPacient(string dni, string password)
{
Database databaseObject = new Database();
string resultStr = "EMPTY";
string query = "SELECT ID FROM Pacient WHERE DNI = @DNI AND Password = @<PASSWORD>;";
SQLiteCommand myCommand = new SQLiteCommand(query, databaseObject.myConnection);
databaseObject.OpenConnection();
myCommand.Parameters.AddWithValue("@DNI", dni);
String md5password = md5Encrypt(password);
myCommand.Parameters.AddWithValue("@Password", md5password);
SQLiteDataReader result = myCommand.ExecuteReader();
if (result.HasRows)
{
while (result.Read())
{
resultStr = Convert.ToString(result["ID"]);
}
}
databaseObject.CloseConnection();
return resultStr;
}
public String loginDoctor(string dni, string password)
{
Database databaseObject = new Database();
string resultStr = "EMPTY";
string query = "SELECT ID FROM Doctor WHERE DNI = @DNI AND Password = @<PASSWORD>;";
SQLiteCommand myCommand = new SQLiteCommand(query, databaseObject.myConnection);
databaseObject.OpenConnection();
myCommand.Parameters.AddWithValue("@DNI", dni);
String md5password = md5Encrypt(password);
myCommand.Parameters.AddWithValue("@Password", md<PASSWORD>);
SQLiteDataReader result = myCommand.ExecuteReader();
if (result.HasRows)
{
while (result.Read())
{
resultStr = Convert.ToString(result["ID"]);
}
}
databaseObject.CloseConnection();
return resultStr;
}
[WebMethod]
public Userdata login(string dni, string password)
{
string doctorCheck = loginDoctor(dni, password);
string pacientCheck = loginPacient(dni, password);
if (!doctorCheck.Equals("EMPTY"))
{
return new Userdata(Convert.ToInt32(doctorCheck), "DOCTOR");
}
else if (!pacientCheck.Equals("EMPTY"))
{
return new Userdata(Convert.ToInt32(pacientCheck), "PACIENT");
}
else
{
return new Userdata(0, "EMPTY");
}
}
public string md5Encrypt(string text)
{
Encoding unicode = Encoding.Unicode;
byte[] textInbyteArray = unicode.GetBytes(text);
using (MD5 md5Hash = MD5.Create())
{
byte[] data = md5Hash.ComputeHash(textInbyteArray);
string passwordMD5 = BitConverter.ToString(data).Replace("-", string.Empty);
return passwordMD5;
}
}
/*********************************************************************************************
*
* UPDATES
*
*********************************************************************************************/
[WebMethod]
public void updateDoctor(string doctorId, string dni, string name, string password)
{
Database databaseObject = new Database();
string query = "UPDATE Doctor SET DNI = @dni, Name = @name, Password = <PASSWORD> WHERE ID = @doctorId; ";
SQLiteCommand myCommand = new SQLiteCommand(query, databaseObject.myConnection);
databaseObject.OpenConnection();
myCommand.Parameters.AddWithValue("@name", name);
myCommand.Parameters.AddWithValue("@dni", dni);
String md5password = md5Encrypt(password);
myCommand.Parameters.AddWithValue("@password", <PASSWORD>);
myCommand.Parameters.AddWithValue("@doctorId", doctorId);
myCommand.ExecuteNonQuery();
databaseObject.CloseConnection();
}
[WebMethod]
public void updatePacient(string pacientId, string dni, string name)
{
Database databaseObject = new Database();
string query = "UPDATE Pacient SET DNI = @dni, Name = @name WHERE ID = @pacientId; ";
SQLiteCommand myCommand = new SQLiteCommand(query, databaseObject.myConnection);
databaseObject.OpenConnection();
myCommand.Parameters.AddWithValue("@name", name);
myCommand.Parameters.AddWithValue("@dni", dni);
myCommand.Parameters.AddWithValue("@pacientId", pacientId);
myCommand.ExecuteNonQuery();
databaseObject.CloseConnection();
}
[WebMethod]
public void updateClinicalRecords(string id, string diagnose, string treatment, string date)
{
Database databaseObject = new Database();
string query = "UPDATE Historic SET Diagnose = @diagnose, Treatment = @treatment, Date = @date WHERE ID = @id; ";
SQLiteCommand myCommand = new SQLiteCommand(query, databaseObject.myConnection);
databaseObject.OpenConnection();
myCommand.Parameters.AddWithValue("@id", id);
myCommand.Parameters.AddWithValue("@diagnose", diagnose);
myCommand.Parameters.AddWithValue("@treatment", treatment);
myCommand.Parameters.AddWithValue("@date", date);
myCommand.ExecuteNonQuery();
databaseObject.CloseConnection();
}
/*********************************************************************************************
*
* UPDATES
*
*********************************************************************************************/
[WebMethod]
public void deleteDoctor(string doctorId)
{
Database databaseObject = new Database();
string query = "DELETE FROM Doctor WHERE ID = @doctorId; ";
SQLiteCommand myCommand = new SQLiteCommand(query, databaseObject.myConnection);
databaseObject.OpenConnection();
myCommand.Parameters.AddWithValue("@doctorId", doctorId);
myCommand.ExecuteNonQuery();
databaseObject.CloseConnection();
}
[WebMethod]
public void deletePacient(string pacientId)
{
Database databaseObject = new Database();
string query = "DELETE FROM Pacient WHERE ID = @pacientId; ";
SQLiteCommand myCommand = new SQLiteCommand(query, databaseObject.myConnection);
databaseObject.OpenConnection();
myCommand.Parameters.AddWithValue("@pacientId", pacientId);
myCommand.ExecuteNonQuery();
databaseObject.CloseConnection();
deleteClinicalRecordsWithPacientId(pacientId);
}
[WebMethod]
public void deleteClinicalRecord(string recordId)
{
Database databaseObject = new Database();
string query = "DELETE FROM Historic WHERE ID = @recordId; ";
SQLiteCommand myCommand = new SQLiteCommand(query, databaseObject.myConnection);
databaseObject.OpenConnection();
myCommand.Parameters.AddWithValue("@recordId", recordId);
myCommand.ExecuteNonQuery();
databaseObject.CloseConnection();
}
[WebMethod]
public void deleteClinicalRecordsWithPacientId(string pacientId)
{
Database databaseObject = new Database();
string query = "DELETE FROM Historic WHERE PacientID = @pacientId; ";
SQLiteCommand myCommand = new SQLiteCommand(query, databaseObject.myConnection);
databaseObject.OpenConnection();
myCommand.Parameters.AddWithValue("@pacientId", pacientId);
myCommand.ExecuteNonQuery();
databaseObject.CloseConnection();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using System.Data.SQLite;
namespace ProyectoIngles
{
public class Database
{
public SQLiteConnection myConnection;
private string DBpath = "C:\\Users\\DANI\\source\\repos\\ProyectoIngles\\ProyectoIngles\\BaseDeDatos.db;";
public Database()
{
myConnection = new SQLiteConnection("Data Source = " + DBpath + " Version = 3; ");
if (!File.Exists("C:\\Users\\DANI\\source\\repos\\ProyectoIngles\\ProyectoIngles\\BaseDeDatos.db"))
{
SQLiteConnection.CreateFile("C:\\Users\\DANI\\source\\repos\\ProyectoIngles\\ProyectoIngles\\BaseDeDatosCreada.db");
System.Console.WriteLine("Database file created");
}
}
public void OpenConnection()
{
if (myConnection.State != System.Data.ConnectionState.Open)
{
myConnection.Open();
}
}
public void CloseConnection()
{
if (myConnection.State != System.Data.ConnectionState.Closed)
{
myConnection.Clone();
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebApplication.webServiceReference;
namespace WebApplication.doctor
{
public partial class WebForm2 : System.Web.UI.Page
{
WebService1 ws;
private bool ValidateUser(string userName, string passWord)
{
if ((null == userName) || (0 == userName.Length) || (userName.Length > 15))
{
System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of userName failed.");
return false;
}
if ((null == passWord) || (0 == passWord.Length) || (passWord.Length > 25))
{
System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of passWord failed.");
return false;
}
return true;
}
protected void Page_Load(object sender, EventArgs e)
{
ws = new WebService1();
}
public void add(Object sender, EventArgs e)
{
try
{
String usernameTb = addUsername.Text.ToString();
String passwordTb = addPassword.Text.ToString();
String dniTb = dniTextbox.Text.ToString();
if (ValidateUser(usernameTb, passwordTb))
{
string doctorID = Request.Cookies.Get("id").Value;
string doctorIdFixed = doctorID.Replace("id=", "");
int id = ws.insertPacient(doctorIdFixed, dniTb, usernameTb, passwordTb);
Response.Redirect(Page.ResolveClientUrl("../patient/patient.aspx?id=" + id));
}
}
catch (Exception ex)
{
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ProyectoIngles
{
public class Historic
{
public int id { get; set; }
public int DoctorId { get; set; }
public int PacientId { get; set; }
public string diagnose { get; set; }
public string treatment { get; set; }
public string date { get; set; }
public Historic(int id, int doctorId, int pacientId, string diagnose, string treatment, string date)
{
this.id = id;
DoctorId = doctorId;
PacientId = pacientId;
this.diagnose = diagnose;
this.treatment = treatment;
this.date = date;
}
public Historic() { }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using WebApplication.webServiceReference;
using System.Web.Security;
namespace WebApplication
{
public partial class WebForm2 : System.Web.UI.Page
{
private bool ValidateUser(string userName, string passWord)
{
// Check for invalid userName.
// userName must not be null and must be between 1 and 15 characters.
if ((null == userName) || (0 == userName.Length) || (userName.Length > 15))
{
System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of userName failed.");
return false;
}
// Check for invalid passWord.
// passWord must not be null and must be between 1 and 25 characters.
if ((null == passWord) || (0 == passWord.Length) || (passWord.Length > 25))
{
System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of passWord failed.");
return false;
}
WebService1 ws = new WebService1();
return true;
}
public void createLogin(Object sender, EventArgs e)
{
String usernameTb = username.Text.ToString();
String passwordTb = password.Text.ToString();
if (ValidateUser(usernameTb, passwordTb))
{
if (usernameTb == "doctor" && passwordTb == "<PASSWORD>")
{
HttpCookie userInfo = new HttpCookie("doctor");
userInfo["doctor"] = "true";
userInfo.Expires.Add(new TimeSpan(0, 1, 0));
Response.Cookies.Add(userInfo);
FormsAuthentication.RedirectFromLoginPage(usernameTb, false);
Response.Redirect(Page.ResolveClientUrl("./doctor/Doctor.aspx"));
}
if (usernameTb == "mew" && passwordTb == "mew")
{
HttpCookie userInfo = new HttpCookie("doctor");
userInfo["doctor"] = "false";
userInfo.Expires.Add(new TimeSpan(0, 1, 0));
Response.Cookies.Add(userInfo);
FormsAuthentication.RedirectFromLoginPage(usernameTb, false);
Response.Redirect(Page.ResolveClientUrl("./patient/patient.aspx"));
}
}
Response.Write(username);
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ProyectoIngles
{
public class Pacient
{
public int id { get; set; }
public string dni { get; set; }
public string name { get; set; }
public string password { get; set; }
public Pacient(int id, string dni, string name, string password)
{
this.id = id;
this.dni = dni;
this.name = name;
this.password = password;
}
public Pacient(int id, string dni, string name)
{
this.id = id;
this.dni = dni;
this.name = name;
this.password = "*****";
}
public Pacient() { }
}
}<file_sep>using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebApplication.webServiceReference;
namespace WebApplication
{
public partial class WebForm4 : System.Web.UI.Page
{
private string path = @"C:\Users\DANI\source\repos\ProyectoIngles\ProyectoIngles\data.json";
string id = "";
int idInt = 0;
string isDoctor = "";
string doctorIDfixed = "";
WebService1 ws;
List<Historic> historicList;
protected void Page_Load(object sender, EventArgs e)
{
try
{
ws = new WebService1();
id = Request.QueryString["id"];
idInt = Convert.ToInt32(id);
isDoctor = Request.Cookies.Get("doctor").Value;
string doctorID = Request.Cookies.Get("id").Value;
doctorIDfixed = doctorID.Replace("id=", "");
Pacient patient = ws.getPacientInfo(idInt);
patientDniTb.Text = patient.dni;
patientNameTb.Text = patient.name;
editPatientBtn.Visible = false;
deleteBtn.Visible = false;
divAddHistoric.Visible = false;
createJSON.Visible = false;
sectionCardPatient.Visible = false;
if (id != null && isDoctor == "doctor=true")
{
divAddHistoric.Visible = true;
editPatientBtn.Visible = true;
deleteBtn.Visible = true;
createJSON.Visible = true;
sectionCardPatient.Visible = true;
}
historicList = ws.getAllPacientRecords(idInt).ToList();
if (historicList.Count > 0)
{
foreach (Historic informer in historicList)
{
tbody.InnerHtml += "<tr> <th scope='row'>" + informer.id + "</th> <td><a href=" + "./ datoUsuario.aspx>" +
informer.diagnose + "</a></td> <td>" + informer.date + "</td> <td>" + informer.treatment + "</td> </tr>";
//Console.WriteLine($"Element # {informer}");
}
}
}
catch (Exception ex)
{
}
}
public void editPatient(Object sender, EventArgs e)
{
try
{
if (id != null && isDoctor == "doctor=true")
{
string dni = patientDniTb.Text.ToString();
string name = patientNameTb.Text.ToString();
ws.updatePacient(id, dni, name);
}
}
catch (Exception ex)
{
}
}
public void createJson(Object sender, EventArgs e)
{
Pacient patient = ws.getPacientInfo(idInt);
string data = JsonConvert.SerializeObject(patient);
string historic = JsonConvert.SerializeObject(historicList);
File.WriteAllText(path, "[" + data.ToString() + historic.ToString() + "]");
Response.Write("<script>alert('Json created succesfully');</script>");
}
public void deletePatientdoc(Object sender, EventArgs e)
{
try
{
if (id != null && isDoctor == "doctor=true")
{
ws.deletePacient(id);
}
}
catch (Exception ex)
{
}
}
public void addHistoric(Object sender, EventArgs e)
{
String diagnoseStr = diagnose.Text.ToString();
String treatmentStr = treatment.Text.ToString();
String dateStr = date.Text.ToString();
ws.insertHistoric(Convert.ToInt32(doctorIDfixed), idInt, diagnoseStr, treatmentStr, dateStr);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ProyectoIngles
{
public class Userdata
{
public int id { get; set; }
public string loguedAs { get; set; }
public Userdata(int id, string loguedAs)
{
this.id = id;
this.loguedAs = loguedAs;
}
public Userdata() { }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebApplication.webServiceReference;
namespace WebApplication
{
public partial class WebForm6 : System.Web.UI.Page
{
WebService1 webServiceReference = new WebService1();
//WebService1 ws = new WebService1();
private bool ValidateUser(string userName, string passWord)
{
// Check for invalid userName.
// userName must not be null and must be between 1 and 15 characters.
if ((null == userName) || (0 == userName.Length) || (userName.Length > 15))
{
System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of userName failed.");
return false;
}
// Check for invalid passWord.
// passWord must not be null and must be between 1 and 25 characters.
if ((null == passWord) || (0 == passWord.Length) || (passWord.Length > 25))
{
System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of passWord failed.");
return false;
}
return true;
}
protected void Page_Load(object sender, EventArgs e)
{
}
public void add(Object sender, EventArgs e)
{
String usernameTb = addUsername.Text.ToString();
String passwordTb = addPassword.Text.ToString();
if (ValidateUser(usernameTb, passwordTb))
{
}
Response.Write(addUsername);
//string passwordMD5 = md5Encrypt(passwordTb);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebApplication.webServiceReference;
namespace WebApplication.doctor
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
WebService1 ws = new WebService1();
string doctorID = Request.Cookies.Get("id").Value;
string id = doctorID.Replace("id=", "");
List<Pacient> historicList = ws.getAllDoctorPacients(Convert.ToInt32(id)).ToList();
/*tbody.InnerHtml = "<tr> <th scope='row'>1</th> <td><a href=" + "./ datoUsuario.aspx>" +
historicList[0].diagnose + "</a></td> <td>" + historicList[0].date + "</td> <td>" + historicList[0].treatment + "</td> </tr>";
*/
if (historicList.Count > 0)
{
foreach (Pacient patient in historicList)
{
tbodydoctor.InnerHtml += "<tr> <th scope='row'>" + patient.id + "</th> <td><a href=" + "../patient/patient.aspx?id=" + patient.id + ">" +
patient.name + "</a></td> <td>" + patient.dni + "</td> </tr>";
//Console.WriteLine($"Element # {informer}");
}
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication
{
public partial class WebForm3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string cookie = Request.Cookies.Get("doctor").Value;
if (cookie == "doctor=false")
{
Response.Redirect(Page.ResolveClientUrl("patient/patient.aspx"));
}
if (cookie != "doctor=true")
{
Response.Redirect(Page.ResolveClientUrl("../Login.aspx"));
}
}
}
} | 76754a227f88a4b853a4fe24d2c471d4d7b29a7a | [
"C#"
] | 12 | C# | dpoqramGTI/proyectoIngles | 6f697ac0c4d5e686591c47e5e691e3646cd59729 | edbefaf35c4cbadc9df0310d09c5515a89d7930b |
refs/heads/main | <file_sep>#やり方
(1)回路を組む
・使うもの
★Aruduino Uno
★LED
★ ブザー
★ 雨センサー
・配線
LED + =>DIGITAL11
LED- => POWER GND
雨センサー AO => ANALOG A0
雨センサー VCC => POWER 5V
雨センサー GND => POWER GND
ブザー+ => DIGITAL 10
ブザー- => DIGITAL GND
(2)コードをダウンロードする
(3)Aruduinno IDE でコードを開く
(4)ツール>シリアルモニタで数値を確認
(5)ツール>シリアルポートを自分のマイコンに設定
(6)書き込む
<file_sep>
// Viral Science
// Rain Detection Module
int rainsense= A0; // analog sensor input pin 0
int buzzerout= 10; // digital output pin 10 - buzzer output
int countval= 0; // counter value starting from 0 and goes up by 1 every second
int ledout= 11; // digital output pin 11 - led output
void setup(){
Serial.begin(9600);
pinMode(buzzerout, OUTPUT);
pinMode(ledout, OUTPUT);
pinMode(rainsense, INPUT);
}
void loop(){
int rainSenseReading = analogRead(rainsense);
Serial.println(rainSenseReading); // シリアルモニタに文字を映す
delay(250);
//===数値をいじるときは以下の数値をいじってください===
//(1)雨センサーの値がxを超えたら => (rainSensereading >< x)
//(2)その値がy秒間続いたら => (countval >= y)
if (countval >= 0.5){ //2秒以上数えられたら
Serial.print("Heavy rain"); //シリアルモニタに出力
digitalWrite(buzzerout, HIGH); //ブザーがなる
digitalWrite(ledout, HIGH); // LEDがひかる
}
//雨センサーの数値を220で判断するコード(環境によって変わるかと思います)
if (rainSenseReading <220){ //雨センサーが220を超えたら
countval++; // カウントを増やす(ここのカウントは上のcountvalに連携している)
}
else if (rainSenseReading >220) { //220を超えたら雨は降っていないとみなす
digitalWrite(buzzerout, LOW); // ブザーを消す
digitalWrite(ledout, LOW); // LEDを消す
countval = 0; // カウントをリセットする
}
delay(1000);
}
| 6084301df262d67fc3c1f521ed0b0aabb1847f57 | [
"Markdown",
"C++"
] | 2 | Markdown | i-am-ethan/aruduinoRain | 65e0ca40f9e00239ed21109e6ebef6aa66157e1d | fadfe642f1b07514ffdda2b59324f38b266de84c |
refs/heads/main | <repo_name>pandu-supriyono/opwegdenhaag.nl<file_sep>/content/pages/intervisie.md
---
title: Intervisie
date: 2021-03-12T00:00:00+01:00
---
##### Intervisie
Vrijwilligers doen nogal wat indrukken op tijdens hun vrijwilligerswerk. Soms zijn er vragen hoe met bepaalde situaties om te gaan. Tijdens terugkomavonden kunnen vrijwilligers ervaringen delen en elkaar vragen stellen en adviezen geven hoe iets aan te pakken. Dit gebeurt onder begeleiding met gebruik van een intervisiemethode.
Naast intervisie vinden er evaluatiemomenten plaats. Tijdens de contactperiode van een jaar zijn er evaluatiemomenten met de projectleider, het maatje en de vrijwilliger. Hierbij worden de ervaringen besproken en afspraken gemaakt over de voortgang van het contact. <file_sep>/content/home.md
---
kop_groot: Op Weg - het maatjesproject voor psychose in Den Haag
kop_ondertitel: Onze opgeleide maatjes helpen (voormalige) patiënten van het Centrum
Eerste Psychose (CEP), zoals de naam al zegt, Op Weg naar zelfstandigheid en herstel
in de maatschappij
samenvatting: 'Een maatje is een vrijwilliger die voor een periode van ten minste
een jaar regelmatig optrekt met een cliënt. Wat houdt dat precies in? Samen werken
aan doelen, maar ook alledaagse activiteiten doen! Denk aan koffie drinken, wandelen,
sporten of naar een museum gaan. Jullie spreken elke week of om de week met elkaar
af en bepalen samen wat jullie gaan doen. Na een jaar is de cliënt in staat zelfstandig
deel te nemen aan de maatschappij en is er een sociaal netwerk opgebouwd. Eigenlijk
is het een vorm van georganiseerde vriendschap: een maatje is een kameraad, géén
hulpverlener.'
samenvatting_actueel: In deze rubriek vind je de laatste nieuwsberichten over het
Maatjesproject Op Weg en informatie over allerlei zaken die te maken hebben met
de zorg voor mensen die een eerste psychose hebben gehad.
---
<file_sep>/content/pages/privacyverklaring.md
---
title: Privacyverklaring
date: 2021-01-19T00:00:00.000+01:00
---
Wij vinden de privacy van zowel de bezoekers van deze website als die van de maatjes en hulpvragers belangrijk. Voor deze reden gaan wij zorgvuldig om met persoonsgegevens en leven wij de bepalingen van de Algemene Verordening Gegevensbescherming (AVG) na.
## Website
Wanneer bezoekers opwegdenhaag.nl raadplegen dan wordt enkel de bezoeker, <NAME> 's-Gravenhage en de bouwer en beheerder van de website -- [Opinionated](https://opinionated.nl "De website van de websitebouwer") -- betrokken. Andere derde partijen worden op geen enkele manier op de hoogte gebracht. Alle bestanden worden, tenzij anders aangegeven, op de server van de websitebouwer gehost.
## Gebruikersanalyze
T.b.v. het verbeteren van de gebruikerservaring wordt er stelselmatig gegevens verzameld over hoe gebruikers de website gebruiken. Denk hierbij aan gegevens over welke webpagina's het meest worden bezocht, met wat voor apparaat en browser men de website bezoekt of hoe gebruikers op de website terecht komen.
Hiervoor wordt de software Matomo gebruikt. Matomo is een [open source](https://nl.wikipedia.org/wiki/Opensourcesoftware "De betekenis van open source") platform om gebruikersgegevens te meten, analyzeren en rapporteren. Als je wilt weten hoe Matomo eruit ziet dan kan je een voorbeeld raadplegen op [https://demo.matomo.cloud](https://demo.matomo.cloud.).<file_sep>/content/pages/maatje-worden.md
---
title: Maatje worden
date: 2021-01-19T00:00:00.000+01:00
---
Op Weg is op zoek naar enthousiaste vrijwilligers die het leuk vinden om samen met mensen, die een psychose hebben doorgemaakt, activiteiten te ondernemen!
_Wat doet een vrijwilliger?_
Als vrijwilliger (maatje) spreek je een keer per week of om de week af met je cliënt om een activiteit te ondernemen en te werken aan doelen. Denk hierbij aan een kopje koffie drinken, maar ook actief op zoek naar gaan dingen die de hulpvrager wilt bereiken. Daarnaast bied je een luisterend oor aan jouw maatje en zoek je samen naar meer mogelijkheden om andere mensen te ontmoeten.
_Wat wordt er van jou verwacht?_
\- Warm, hartelijk en nieuwsgierig aan de ander
\- Gemotiveerd, enthousiast en open
\- In staat om kritiek of feedback te ontvangen
\- Kan luisteren en is communicatief vaardig
\- Heeft geduld en komt niet gelijk met oplossingen
\- Kan grenzen stellen, ze bewaken en zich inleven
\- Eventuele kennis van psychoses, maar dit is geen vereiste
\- 18 jaar of ouder
\- Een dagdeel per week beschikbaar voor tenminste een jaar
\- Bereid om scholing en intervisie te volgen
Cursus
Op Weg biedt, naast de basistraining voor vrijwilligers een korte cursus aan van een dagdeel voor nieuwe vrijwilligers. De cursus is bedoeld om meer inzicht te krijgen in wat een psychose nou precies is, hoe je in moeilijke situaties kan handelen en hoe je meer inzicht krijgt in jouw eigen mogelijkheden.
_Intervisie_
Vrijwilligers doen nogal wat indrukken op tijdens hun vrijwilligerswerk. Soms zijn er vragen hoe met bepaalde situaties om te gaan. Tijdens terugkomavonden kunnen vrijwilligers ervaringen delen en elkaar vragen stellen en adviezen geven hoe iets aan te pakken. Dit gebeurt onder begeleiding met gebruik van een intervisiemethode
_Evaluatiemomenten_
Tijdens de contactperiode van een jaar zijn er evaluatiemomenten met de projectleider, het maatje en de vrijwilliger. Hierbij worden de ervaringen besproken en afspraken gemaakt over de voortgang van het contact.
_Wat biedt dit project voor jou?_
\- Zinvol vrijwilligerswerk dat veel voldoening geeft
\- Uitwisseling van ervaringen met collega-vrijwilligers
\- Ondersteuning en begeleiding
\- Leerzame ontwikkeling en CV-builder
Ben je geïnteresseerd geraakt in het vrijwilligerswerk? Of heb je vragen?
Neem dan contact met ons op, we zien graag je aanmelding tegemoet!
Contact:
<NAME>, projectleider Op Weg
06-13489319
[<EMAIL>](mailto:<EMAIL>)<file_sep>/content/pages/ik-wil-hulp.md
---
title: Ik wil hulp
date: 2021-01-19T00:00:00.000+01:00
---
Ben jij op zoek naar een Maatje en ben je in behandeling bij het Centrum Eerste Psychose van de Parnassia Groep dan kun jij je aanmelden. <file_sep>/content/pages/over-ons.md
---
title: Over ons
date: 2020-12-16T19:32:09.251+00:00
---
De maatjes van Op Weg begeleiden Hagenaars die een psychose hebben gehad
Eenzaamheid kent allerlei vormen en maten, zo ook bij jongvolwassenen die een eerste psychose hebben doorgemaakt. Bij een psychose is iemand de grip op zijn of haar realiteit kwijt. Een ontzettende enge en onzekere ervaring, wat soms tot onbegrip bij anderen kan leiden. De omgeving vindt het misschien lastig om met deze mensen om te gaan, aangezien psychoses onvoorspelbaar zijn. Dit kan leiden tot weinig sociale contacten en uiteindelijk eenzaamheid. Deze eenzaamheid maakt het lastig voor jongvolwassenen om na hun psychose terug te keren in de maatschappij. Om dit mogelijk te maken, is het maatjesproject Op Weg in het leven geroepen.
Maak kennis met ons werk, het begeleiden van deze Hagenaars door onze vrijwilligers! Aan de hand van het buddysysteem gaan onze vrijwilligers met de mensen op pad om aan hun doelen te gaan werken. Dit kan zijn van het starten met een opleiding tot het opzetten van een sociale kring. Het gaat zeker niet alleen om serieuze dingen, er wordt genoeg afgelachen en ontspannen. De hulpvragers, zoals wij ze noemen, zijn onder behandeling bij het Centrum Eerste Psychose (CEP), waar ze worden begeleid en inzichten verkrijgen in de psychose. De kans op een nieuwe psychose wordt hiermee verkleind en eerder herkend door zowel de hulpvrager als zijn of haar behandelaar. Een ontzettende uitdagende groep, met veel diversiteit en waar veel voldoening uit kan worden gehaald.
Kom ons team versterken!<file_sep>/content/posts/test-3.md
---
title: Vrijwilligers onmisbaar bij Op Weg
date: 2021-03-17T00:00:00+01:00
---
De vrijwilligers van maatjesproject Op Weg doen heel waardevol werk in de steun aan onze cliënten, ook in deze tijd waarin we contacten moeten beperken gaan ze door met het ondersteunen. Dit doen ze geheel belangeloos, waarvoor hulde!!

Volg het voorbeeld van deze helden en word ook vrijwilliger bij Op Weg!<file_sep>/src/main.js
// This is the main.js file. Import global CSS and scripts here.
// The Client API can be used here. Learn more: gridsome.org/docs/client-api
import Vuelidate from 'vuelidate'
import 'typeface-lato'
import 'typeface-karla'
import '~/assets/css/reset.css'
import '~/assets/scss/index.scss'
import DefaultLayout from '~/layouts/Default.vue'
export default function (Vue, { router, head, isClient }) {
// Set default layout as a global component
Vue.component('Layout', DefaultLayout)
Vue.use(Vuelidate)
router.beforeEach((to, _from, next) => {
head.meta.push({
key: 'og:url',
name: 'og:url',
content: 'https://www.opwegdenhaag.nl' + to.fullPath,
})
next()
})
head.meta.push({
key: 'og:description',
name: 'og:description',
content: "De website van maatjesproject Op Weg van stichting Ozanam 's-Gravenhage",
})
head.meta.push({
key: 'twitter:description',
name: 'twitter:description',
content: "De website van maatjesproject Op Weg van stichting Ozanam 's-Gravenhage",
})
}
<file_sep>/content/pages/disclaimer.md
---
title: Disclaimer
date: 2021-01-19T00:00:00.000+01:00
---
#### Auteursrecht
Niets van deze website mag zonder voorafgaande schriftelijke toestemming van de eigenaar openbaar worden gemaakt of verveelvoudigd, waaronder begrepen het reproduceren door middel van druk, offset, fotokopie of microfilm of in enige digitale, elektronische, optische of andere vorm of (en dit geldt zo nodig in aanvulling op het auteursrecht) het reproduceren (i) ten behoeve van een onderneming, organisatie of instelling of (ii) voor eigen oefening, studie of gebruik welk(e) niet strikt privé van aard is of (iii) voor het overnemen in enig dag-, nieuws- of weekblad of tijdschrift (al of niet in digitale vorm of online) of in een RTV-uitzending.
### Uw bijdrage
Op iedere inzending van een bijdrage of informatie aan Stichting Ozanam en/of Maatjesproject Op Weg zijn de standaard publicatievoorwaarden van toepassing. Inzending van een bijdrage impliceert steeds toestemming aan de eigenaar om de bijdrage geheel of gedeeltelijk verder te exploiteren door opname en/of publicatie in enige databank, informatiedrager (al of niet elektronisch) of middels online beschikbaarstelling in enig netwerk.
### Vertrouwelijk
Alle gegevens die door Stichting Ozanam en/of Maatjesproject Op Weg worden verzameld, zullen strikt vertrouwelijk bewaard worden en zullen niet worden uitgeleend, verhuurd of verkocht, noch op een of andere manier worden openbaar gemaakt. De informatie die u aan Stichting Ozanam en/of Maatjesproject Op Weg geeft, zal met de grootst mogelijke zorg worden behandeld.
### Links
Onze sites bevatten links naar andere sites die niet tot het eigendom van Stichting Ozanam en/of Maatjesproject Op Weg. Wij zijn niet aansprakelijk voor de privacy praktijken noch de inhoud van zulke sites.<file_sep>/content/pages/steun-ons.md
---
title: Steun ons
date: 2021-01-19T00:00:00.000+01:00
---
Doneren aan Op Weg ...steun ons bijzonder maatschappelijk werk!
Onze vrijwilligers zijn actief om ieder mens te laten meetellen. Voor elk bedrag dat u kunt missen heeft u de mogelijkheid ons werk te ondersteunen.
**Structureel doneren
**Maatjesproject Op Weg krijgt voor het grootste deel geld via subsidies en fondsen. We proberen de financiële basis van ons project te versterken door het aantrekken van donateurs die bereid zijn ons werk voor langere tijd te ondersteunen, met een kleine bijdrage van bijvoorbeeld 10 euro per maand.
**Doneren via overmaking**
U kunt een bijdrage overmaken via IBAN-nummer:
* NL47INGB0005801423 t.n.v. Ozanam <NAME> te Den Haag o.v.v. Donatie aan Maatjesproject Op Weg.
**Doneren via iDEAL**
Met iDEAL kunt u direct uw donatie overmaken via uw bank aan Maatjesproject Op Weg.
* Het minimum bedrag per donatie bedraagt € 1,00.
* Het eerste invulveld is voor hele eurobedragen en het tweede invulveld voor eurocenten.
Alvast hartelijk dank voor uw bijdrage!<file_sep>/content/pages/cursus.md
---
title: Cursus
date: 2021-03-12T00:00:00+01:00
---
##### Cursus
Op Weg biedt, naast de basistraining voor vrijwilligers een korte cursus aan van een dagdeel voor nieuwe vrijwilligers. De cursus is bedoeld om meer inzicht te krijgen in wat een psychose nou precies is, hoe je in moeilijke situaties kan handelen en hoe je meer inzicht krijgt in jouw eigen mogelijkheden.
Deze cursus is verplicht, gezien wij waarden hechten aan goede scholing van onze vrijwilligers. Na het afronden van deze cursus kan je aan de slag als vrijwilliger. | f57412bc405e4783734456b4548ea1e2ea81290b | [
"Markdown",
"JavaScript"
] | 11 | Markdown | pandu-supriyono/opwegdenhaag.nl | 8872048daa832402a87d2c4c8d7b2de8923408ea | 1fccd2ce316b049782fdb9c50d26cd1f1e82a320 |
refs/heads/master | <file_sep>
def correction(name):
print('***************do something')
print('correction : ' + name)
print('**************')<file_sep>from django import forms
class CorrectionForm(forms.Form):
something1 = forms.CharField(label='something_lable', max_length=100)
something2 = forms.ChoiceField(label='something2_lable', choices=['c1', 'c2', 'c3'])
class AnotherForm(forms.Form):
name = forms.CharField(max_length=30)
email = forms.EmailField()
<file_sep>creat webTools by command line :
check the python version :
python - python3 - 3.7.4
pip - pip3 - pip in python 3.7
easy_install-3.7
>mkdir webTools
>cd webTools
>pip3 install virtualenv
>virtualenv —version
16.7.7
>virtualenv transactionCorrection
Now, activate the virtual environment by typing the following command. Please Make sure you are in the virtual environment directory.
//todo activate virtualenv
>cd trainsactionCorrection
>source bin/activate
So, our virtual environment has been started. Now, this is the time to install the Django Framework.
We recommend using the latest version of Python 3. The last version to support Python 2.7 is Django 1.11 LTS.
The latest official version is 2.2.7 (LTS).
pip3 install Django==2.2.7
Creat project :
Interpreter :
Path : ${PROJECT/venv/bin/python
Version : 3.7
>django-admin startproject correction
>cd correction
>python manage.py runserver
This will run a serveur to response http://localhost:8000
Creat app:
a project can include one or more apps. We could creat app with command line :
>python manage.py startapp correctionApp<file_sep>from django.shortcuts import render
# Create your views here.
from .scripts.toto import correction
from .forms import xinForm
def hello(request):
if request.method == 'POST':
# submit form
print(request)
form = xinForm(request.POST)
name = form.data['name']
print(name)
correction(name)
else:
form = xinForm()
return render(request, 'xinApp/hello-world.html', {'form':form})
<file_sep>from django.urls import path
from . import views
urlpatterns = [
path('hello/', views.hello_world),
path('thanks/', views.thanks),
path('another/', views.another),
]
<file_sep>#!/bin/sh
source transactionCorrection/bin/activate
cd example
python manage.py runserver
<file_sep>from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .scripts.correction import do_correction
from .forms import CorrectionForm, AnotherForm
def thanks(request):
print(request)
return HttpResponse('<h1>Thanks for using</h1>')
def another(request):
if request.method == 'POST':
form = AnotherForm(request.POST)
print(form)
if form.is_valid():
return HttpResponseRedirect('/thanks/')
else:
form = AnotherForm()
return render(request, 'correctionApp/anotherForm.html', {'form': form})
# Create your views here.
def hello_world(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = CorrectionForm(request.POST)
value = form.data['something1']
print(value)
do_correction(value)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = CorrectionForm()
return render(request, 'correctionApp/correctionForm.html', {'form': form})
<file_sep>
def do_correction(something):
print('*****************************')
print(something)
print('do some corrections')
print('*****************************')
<file_sep>from django import forms
class xinForm(forms.Form):
name = forms.CharField(label='What\'s your name')
line2 = forms.CharField(label='line 2', required=False)
line3 = forms.CharField(label='line 3')
| 665581b93c18f745f472c99acd89cea547ad1f7f | [
"Markdown",
"Python",
"Shell"
] | 9 | Python | disappearwang/webTools | d49c634f0e83adcdc1a77d72f01f08e37fb02648 | 986b26763ddefac54f936d1afa2c33d6d45acfd4 |
refs/heads/master | <file_sep>/*jslint plusplus: false, bitwise: true, eqeq: true, unparam: true, white: false, browser: true, onevar: false */
/*global console: true, window: true, chrome: true, $: true, require: true, exports: true, process: true, module: true*/
(function(module){
function AssertionCheckerEngine(executionIndex) {
if (!(this instanceof AssertionCheckerEngine)) {
return new AssertionCheckerEngine(executionIndex);
}
// Jalangi style argument passing.
// A map of system independent assertions about different source locations
// Use `export JALANGI_ACE_PLUGIN=/home/drx/foo/bar/assertions/xyz.js`
var pluginFile = process.env.JALANGI_ACE_PLUGIN;
var plugin = require(pluginFile);
var getIIDInfo = require('./../../utils/IIDInfo');
function getLocation(iid){
var info = getIIDInfo(iid);
var location = info.replace(/^\((.*)\)$/, "$1");
return location;
}
var callLocations = [];
this.Fe = function(iid, val, dis, args){
plugin.functionEntry(getLocation(iid), dis, args, callLocations);
};
this.invokeFunPre = function(iid, f, base, args, isConstructor){
callLocations.push(""); // start call
};
this.invokeFun = function(iid, f, base, args, val, isConstructor){
callLocations.pop(); // end call
return val;
};
this.endExecution = function(){
plugin.endExecution();
};
return undefined; // already initialized..
}
module.exports = AssertionCheckerEngine;
}(module));
<file_sep>/*jslint plusplus: false, bitwise: true, eqeq: true, unparam: true, white: false, browser: true, onevar: false */
/*global console: true, window: true, chrome: true, $: true, require: true, exports: true, process: true, module: true*/
(function(module){
function CallInspectionEngine(executionIndex) {
if (!(this instanceof CallInspectionEngine)) {
return new CallInspectionEngine(executionIndex);
}
var getIIDInfo = require('./../../utils/IIDInfo');
this.Fe = function(iid, val, dis, args){
console.log("<Fe> %s<%s>@%s(%s)", getIIDInfo(iid), val.name, dis, Array.prototype.slice.call(args, 0));
};
return undefined; // already initialized..
}
module.exports = CallInspectionEngine;
}(module));
<file_sep>/*jslint plusplus: false, bitwise: true, eqeq: true, unparam: true, white: false, browser: true, onevar: false */
/*global console: true, window: true, chrome: true, $: true, require: true, exports: true, process: true, module: true*/
(function(module){
function StringHistoryTrackingEngine(executionIndex) {
if (!(this instanceof StringHistoryTrackingEngine)) {
return new StringHistoryTrackingEngine(executionIndex);
}
var ConcolicValue = require('./../../ConcolicValue');
var getIIDInfo = require('./../../utils/IIDInfo');
var getConcrete = this.getConcrete = ConcolicValue.getConcrete;
var getSymbolic = this.getSymbolic = ConcolicValue.getSymbolic;
var accesses = [];
function ACCESS(type, iid, value){
this.type = type;
this.iid = iid;
this.value = value;
}
ACCESS.prototype.toString = function(){
var str;
var sym = getSymbolic(this.value);
if(sym){
str = sym.toString();
}else{
str = "OTHER(" + this.value + ")";
}
return this.type + "(" + str + ")@" + getIIDInfo(this.iid);
};
function VAL(type, iid, value){
this.type = type;
this.iid = iid;
this.value = value;
}
VAL.prototype.toString = function(){
return this.type + "(" + this.value + ")";
};
function makeLiteral(iid, value){
return new VAL("LIT", iid, value);
}
function renderSymbolic(v){
var symbolic = getSymbolic(v);
return symbolic? symbolic: "?(" + v + ")";
}
function renderSymbolicArrayEntries(a){
var renderedArrayEntries = [];
for(var i = 0; i < a.length; i++){
renderedArrayEntries.push(renderSymbolic(a[i]));
}
return renderedArrayEntries + "";
}
function makeFunctionCall(iid, stringFunction, base, args, value){
var str;
if(stringFunction === undefined){
str = "? ," + renderSymbolic(value);
}else{
str = renderSymbolic(base) + "." + stringFunction + "(" + renderSymbolicArrayEntries(args) + "), " + value;
}
return new VAL("FUN", iid, str);
}
function makeConcat(iid, left, right, value){
return new VAL("+", iid, renderSymbolic(left) + ", " + renderSymbolic(right) + ", " + value);
}
function registerAccess(type, iid, value){
if(value instanceof ConcolicValue){
accesses.push(new ACCESS(type, iid, value));
}
}
this.literal = function(iid, val) {
if (typeof val === "string") {
return new ConcolicValue(val, makeLiteral(iid, val));
}
return val;
};
this.binary = function(iid, op, left, right, result_c){
if(op === "+"){
if(typeof result_c === "string"){
return new ConcolicValue(result_c, makeConcat(iid, left, right, result_c));
}
}
return result_c;
};
this.invokeFun = function(iid, f, base, args, val, isConstructor){
if(typeof val === "string" || val instanceof ConcolicValue){
var stringFunction;
if(f === String.prototype.indexOf){
stringFunction = "indexOf"; // returns DPA-uninteresting integer ...
}else if(f === String.prototype.substring){
stringFunction = "substring";
}else{
stringFunction = undefined;
}
return new ConcolicValue(val, makeFunctionCall(iid, stringFunction, base, args, val));
}
return val;
};
this.getFieldPre = function(iid, base, offset) {
registerAccess("READ", iid, offset);
};
this.putFieldPre = function(iid, base, offset, val) {
registerAccess("WRITE", iid, offset);
};
this.endExecution = function(){
console.log("PROPERTY ACCESSES:");
for(var access in accesses){
if(accesses.hasOwnProperty(access)){
console.log(accesses[access].toString());
}
}
};
return undefined; // already initialized..
}
module.exports = StringHistoryTrackingEngine;
}(module));
<file_sep>
# Copyright 2013 Samsung Information Systems America, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Author: <NAME>
import os
import subprocess
import sys
import shutil
from tempfile import NamedTemporaryFile
def get_analysis(a):
ka = {"concolic" : "analyses/concolic/SymbolicEngine",
"coverage" : "analyses/coverage/CoverageEngine",
"empty" : "analyses/empty/EmptyEngine",
"likelytype" : "analyses/likelytype/LikelyTypeInferEngine",
"nop" : "analyses/nop/NOPEngine",
"objectalloc" : "analyses/objectalloc/ObjectAllocationTrackerEngine",
"simpletaint" : "analyses/simpletaint/TaintEngine",
"trackundefinednull" : "analyses/trackundefinednull/UndefinedNullTrackingEngine",
"wrapping" : "analyses/wrapping/WrappingEngine"}
if a in ka.keys():
return ka[a]
return None
class JalangiInstall:
def instrumentation_script(self):
return self.get_home() + "/src/js/instrument/esnstrument.js"
def replay_script(self):
return self.get_home() + "/src/js/commands/replay.js"
def analyses(self):
return os.listdir(self.get_home() + "/src/js/analyses")
def get_home(self):
if hasattr(self,"home"):
return self.home
else:
return os.path.abspath(os.path.join(os.path.dirname(__file__),os.pardir,os.pardir))
def self_or_env(self,local,env):
if hasattr(self,local):
return self.getattr(local)
else:
return os.environ[env] if env in os.environ else False
def coverage(self):
return self.self_or_env("use_coverage", "USE_COVERAGE")
def timed(self):
return self.self_or_env("use_time", "USE_TIME")
DEFAULT_INSTALL = JalangiInstall()
class JalangiException(Exception):
"""Any error that happens during the Jalangi
analysis process
Attributes:
install -- the JalangiInstall being used
msg -- User understandable message of what went wrong
trigger -- Exception that caused this error (if any)
"""
def __init__(self, install, message, trigger=None):
self.install = install
self.message = message
self.trigger = trigger
def run_node_script(script, *args, **kwargs):
"""Execute script and returns output string"""
jal = kwargs['jalangi']
if jal.timed():
cmd = ["time"]
else:
cmd = []
if jal.coverage():
cmd = cmd + ["cover", "run"]
cmd = cmd + ([find_node()] if not jal.coverage() else [])
with NamedTemporaryFile() as f:
try:
subprocess.check_call(cmd + [script] + [x for x in args],stdout=f, stderr=open(os.devnull, 'wb'),bufsize=1000)
f.seek(0)
return f.read()
except subprocess.CalledProcessError as e:
return ""
def is_node_exe(path):
try:
subprocess.check_output([path,"-e","42"])
return True
except: return False
def find_node():
try:
return find_node.mem
except: pass
LOCATIONS = [os.environ.get("NODE_EXECUTABLE"),
"node",
"/usr/bin/node",
"/usr/local/bin/node",
"C:/Program Files/nodejs/node.exe",
"C:/Program Files (x86)/nodejs/node.exe"]
l = filter(is_node_exe, LOCATIONS)
if len(l) == 0:
print "Could not find the node.js executable. node.js is required for Jalangi"
print "If you have installed node.js in a non-standard location you can set environment variable NODE_EXECUTABLE to the full path of the node executable."
exit(1)
find_node.mem = l[0]
return l[0]
def mkempty(f):
"""
Create f as an empty file
"""
open(f, 'w').close()
def head(f,n):
"""Returns either the first n of lines of f or f if fewer lines
"""
from itertools import islice
with open(f) as ff:
head=list(islice(ff,n))
return head
def count_lines(f):
with open(f) as fin:
ines = sum(1 for line in fin)
return ines
def move_coverage(jalangi):
if jalangi.coverage():
shutil.move(".coverage_data", "..")
| e666222e4d54e3aec99132e956cadbf9b0ea0a1d | [
"JavaScript",
"Python"
] | 4 | JavaScript | esbena/jalangi | 2b9a633ef8aab90d46058e9b1ac32909b2a6961a | 66a37d62b05a674845b32b0156f20284c9540ed1 |
refs/heads/master | <file_sep>#ifndef CLIENT_HPP
#define CLIENT_HPP
#include "everything.hpp"
using boost::asio::ip::tcp;
class client
{
public:
client(boost::asio::io_service& io_service);
void connect(const std::string &host, const std::string &address);
void write(const std::string& msg);
void close();
private:
virtual void client_connected() {}
virtual void client_error(boost::system::error_code& ec) {}
virtual void client_received(std::string &s) {}
void do_connect(tcp::resolver::iterator endpoint_iterator);
void do_read_line();
void do_write();
private:
boost::asio::io_service& io_service_;
tcp::socket socket_;
boost::asio::streambuf readbuf_;
std::deque<std::string> write_msgs_;
};
#endif
<file_sep>#ifndef EVERYTHING_HPP
#define EVERYTHING_HPP
#include <string>
#include <boost/asio.hpp>
#include <vector>
#include <algorithm>
#include <deque>
#include <iostream>
#include "aux.hpp"
#endif
<file_sep>#include "client.hpp"
client::client(boost::asio::io_service& io_service) : io_service_(io_service), socket_(io_service) {}
void client::connect(const std::string &host, const std::string &address)
{
tcp::resolver resolver(io_service_);
auto endpoint_iterator = resolver.resolve({ host, address});
do_connect(endpoint_iterator);
}
void client::write(const std::string& msg)
{
io_service_.post(
[this, msg]()
{
bool write_in_progress = !write_msgs_.empty();
write_msgs_.push_back(msg);
if (!write_in_progress)
{
do_write();
}
});
}
void client::close()
{
io_service_.post([this]() { socket_.close(); });
}
void client::do_connect(tcp::resolver::iterator endpoint_iterator)
{
boost::asio::async_connect(socket_, endpoint_iterator,
[this](boost::system::error_code ec, tcp::resolver::iterator)
{
if (!ec)
{
client_connected();
do_read_line();
}
else
{
client_error(ec);
}
});
}
void client::do_read_line()
{
boost::asio::async_read_until(socket_,
readbuf_,
'\n',
[this](boost::system::error_code ec, std::size_t /*length*/)
{
if (!ec)
{
std::istream is(&readbuf_);
std::string line;
std::getline(is,line);
client_received(line);
do_read_line();
}
else
{
socket_.close();
client_error(ec);
}
});
}
void client::do_write()
{
boost::asio::async_write(socket_,
boost::asio::buffer(write_msgs_.front().data(),
write_msgs_.front().length()),
[this](boost::system::error_code ec, std::size_t /*length*/)
{
if (!ec)
{
write_msgs_.pop_front();
if (!write_msgs_.empty())
{
do_write();
}
}
else
{
socket_.close();
}
});
}
<file_sep>#ifndef IRC_CLIENT_HPP
#define IRC_CLIENT_HPP
#include "everything.hpp"
#include "client.hpp"
using namespace std;
class irc_client : public client
{
public:
irc_client(boost::asio::io_service& io_service);
void writeln(const std::string &line);
private:
void client_received(string &line);
void on_ping(const string& ping_id);
virtual void on_error(boost::system::error_code& ec) {}
virtual void irc_connected() {}
virtual void irc_disconnected() {}
void client_connected() {irc_connected();}
};
#endif
<file_sep>#include "aux.hpp"
std::vector<std::string> split(const std::string& str, const std::string& delimiter)
{
size_t pos = 0, lpos=0;
std::string token;
std::vector<std::string> ret;
if((pos = str.find(delimiter,lpos))!=std::string::npos)
{
do
{
ret.push_back(str.substr(lpos,pos-lpos));
lpos=pos+delimiter.length();
}
while ((pos = str.find(delimiter,lpos)) != std::string::npos );
}
ret.push_back(str.substr(lpos,str.length()-lpos));
return ret;
}
std::string lcase(const std::string &s)
{
std::string ret=s;
std::transform(ret.begin(), ret.end(), ret.begin(), ::tolower);
return ret;
}
<file_sep>#ifndef AUX_HPP
#define AUX_HPP
#include "everything.hpp"
std::vector<std::string> split(const std::string& str, const std::string& delimiter);
std::string lcase(const std::string &s);
#endif
<file_sep>#include "irc_bot.hpp"
irc_bot::irc_bot(boost::asio::io_service& io_service) : irc_client(io_service) {};
void irc_bot::on_error(boost::system::error_code& ec)
{
on_disconnect();
}
void irc_bot::irc_connected()
{
writeln("NICK previsoes");
writeln("USER previsoes previsoes irc.rizon.net :previsoes");
writeln("JOIN #safe-space");
};
void irc_bot::on_disconnect() {}
void irc_bot::on_channel_message(const std::string& from, const std::string& message) {}
void irc_bot::on_private_message(const std::string& from, const std::string& message) {}
<file_sep>#ifndef IRC_BOT_HPP
#define IRC_BOT_HPP
#include "everything.hpp"
#include "irc_client.hpp"
class irc_bot : public irc_client
{
public:
irc_bot(boost::asio::io_service& io_service);
void on_error(boost::system::error_code& ec);
void irc_connected();
void on_disconnect();
void on_channel_message(const std::string& from, const std::string& message);
void on_private_message(const std::string& from, const std::string& message);
};
#endif
<file_sep>#include "irc_client.hpp"
irc_client::irc_client(boost::asio::io_service& io_service) : client(io_service) {}
void irc_client::writeln(const std::string &line)
{
write(line + '\n');
std::cout << ">>>>>" << line << std::endl;
}
void irc_client::client_received(std::string &line)
{
auto v=split(line," ");
if(v.size()==0) return;
if(v.size()>=2)
{
}
auto cmd=lcase(v[0]);
if(cmd=="ping" && v.size()==2)
on_ping(v[1]);
std::cout << line << std::endl;
}
void irc_client::on_ping(const std::string& ping_id)
{
writeln("PONG " + ping_id);
}
<file_sep>//
// chat_client.cpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2013 <NAME> (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <cstdlib>
#include <deque>
#include <thread>
#include <vector>
#include <boost/asio.hpp>
#include <algorithm>
#include "irc_bot.hpp"
using boost::asio::ip::tcp;
int main(int argc, char* argv[])
{
try
{
if (argc != 3)
{
std::cerr << "Usage: chat_client <host> <port>\n";
return 1;
}
boost::asio::io_service io_service;
irc_bot irc(io_service);
irc.connect(argv[1],argv[2]);
std::thread t([&io_service](){ io_service.run(); });
std::string line;
while (std::getline(std::cin,line))
{
irc.write(line + "\n");
}
irc.close();
t.join();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
| ef2fd5c89853060affefb03f727aa922175f5259 | [
"C++"
] | 10 | C++ | decltypo/irc_previsoes | 5fa7ccf9a65b9a3f5e846bc6ff57cb2895da9817 | 836e8db71a923ead530b367ff135d422c70cfcfc |
refs/heads/master | <repo_name>phystem/bdd-test-framework<file_sep>/src/test/java/com/test/madhan/stepdefs/AutomationPracticeSteps.java
package com.test.madhan.stepdefs;
import com.codeborne.selenide.Configuration;
import com.test.madhan.model.OrderData;
import com.test.madhan.pages.*;
import com.test.madhan.pages.shoppingcart.OrderConfirmationPage;
import com.test.madhan.pages.shoppingcart.SummaryPage;
import io.cucumber.java8.En;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Assert;
public class AutomationPracticeSteps implements En {
OrderData orderData;
HomePage homePage;
String currentPassword;
MyAccountPage myAccountPage;
CategoryPage categoryPage;
SummaryPage summaryPage;
OrderConfirmationPage orderConfirmationPage;
String orderReferenceNumber;
OrderHistoryPage orderHistoryPage;
PersonalInformationPage personalInformationPage;
String firstNameToBeUpdated;
public AutomationPracticeSteps() {
Before(() -> {
Configuration.baseUrl = "http://automationpractice.com/index.php";
});
initSteps();
}
private void initSteps() {
Given("I login to the application with {string} and {string}", (String userName, String password) -> {
homePage = new HomePage();
this.currentPassword = <PASSWORD>;
myAccountPage = homePage.openApp()
.goToLogin()
.login(userName, password);
});
And("^I navigate to \"([^\"]*)\" category$", (String categoryName) -> {
categoryPage = myAccountPage.selectCategory(categoryName);
});
And("^I add the T-shirt to the cart$", () -> {
categoryPage.addProductToCart();
});
And("^I continue to checkout$", () -> {
summaryPage = categoryPage.proceedToCheckout();
});
And("^I increase the product qty$", () -> {
summaryPage.incrementProductQuantity();
});
Then("^I store the order details$", () -> {
orderData = summaryPage.getOrderData();
});
And("^I complete placing the order$", () -> {
orderConfirmationPage = summaryPage.proceedToCheckout()
.proceedToCheckout()
.proceedToCheckout()
.payByBankWire().confirmOrder();
orderReferenceNumber = orderConfirmationPage.getOrderReferenceNumber();
});
When("^I view the order details in order history$", () -> {
orderHistoryPage = orderConfirmationPage.backToOrders();
orderHistoryPage.selectOrder(orderReferenceNumber);
});
Then("^the order details should match the stored order$", () -> {
orderHistoryPage.verifyOrder(orderData);
});
And("^I navigate to personal information$", () -> {
personalInformationPage = myAccountPage.openPersonalInformation();
});
When("^I update my firstname$", () -> {
firstNameToBeUpdated = RandomStringUtils.randomAlphabetic(5).toLowerCase();
personalInformationPage.setFirstName(firstNameToBeUpdated);
personalInformationPage.saveDetails(currentPassword);
});
Then("^the firstname should be updated$", () -> {
String accountName = myAccountPage.getAccountName();
String currentFirstName = accountName.split(" ")[0].toLowerCase();
Assert.assertEquals(firstNameToBeUpdated, currentFirstName);
});
And("^I logout from the application$", () -> {
homePage.logout();
});
}
}
<file_sep>/src/test/java/com/test/madhan/pages/shoppingcart/SummaryPage.java
package com.test.madhan.pages.shoppingcart;
import com.codeborne.selenide.SelenideElement;
import com.test.madhan.model.OrderData;
import static com.codeborne.selenide.Condition.text;
import static com.codeborne.selenide.Condition.visible;
import static com.codeborne.selenide.Selenide.$;
public class SummaryPage {
private final SelenideElement pageHeading = $(".page-heading");
private final SelenideElement addQuantityButton = $(".cart_quantity_button [title='Add']");
private final SelenideElement productQuantitySummary = $("#summary_products_quantity");
private final SelenideElement productNameLabel = $(".cart_description .product-name");
private final SelenideElement productQuantity = $(".cart_quantity_input");
private final SelenideElement orderTotalText = $("#total_price_container");
private final SelenideElement proceedToCheckout = $("a.standard-checkout[title='Proceed to checkout']");
public SummaryPage() {
pageHeading.shouldHave(text("Shopping-cart summary"));
}
public SummaryPage incrementProductQuantity() {
addQuantityButton.click();
productQuantitySummary.shouldHave(text("2 Products"));
return this;
}
public OrderData getOrderData() {
String productName = productNameLabel.text();
String productQuantity = this.productQuantity.val();
String orderTotal = orderTotalText.text();
return OrderData.builder()
.productName(productName)
.productQuantity(productQuantity)
.orderTotal(orderTotal)
.build();
}
public AddressPage proceedToCheckout() {
proceedToCheckout.should(visible).click();
return new AddressPage();
}
}
<file_sep>/README.md
# BDD Automation framework using Selenide and Cucumber
## How to run
It's a gradle based project. You should have `Java8` or greater installed and `chrome browser` installed in your machine
Run the tests using the below command
`gradlew clean cucumber`
## Execution report

<file_sep>/src/test/java/com/test/madhan/pages/LoginPage.java
package com.test.madhan.pages;
import com.codeborne.selenide.SelenideElement;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Selenide.title;
import static org.junit.Assert.assertEquals;
public class LoginPage {
private final SelenideElement emailTextBox = $("#email");
private final SelenideElement passwordTextBox = $("#<PASSWORD>");
private final SelenideElement submitButton = $("#SubmitLogin");
public LoginPage() {
assertEquals("Verifying page tile", "Login - My Store", title());
}
public MyAccountPage login(String email, String password) {
$(emailTextBox).val(email);
$(passwordTextBox).val(password);
$(submitButton).click();
return new MyAccountPage();
}
}
<file_sep>/src/test/java/com/test/madhan/pages/shoppingcart/ShippingPage.java
package com.test.madhan.pages.shoppingcart;
import com.codeborne.selenide.SelenideElement;
import static com.codeborne.selenide.Condition.visible;
import static com.codeborne.selenide.Selenide.$;
public class ShippingPage {
private final SelenideElement agreeToTerms = $("#uniform-cgv");
private final SelenideElement proceedToCheckout = $("button[name='processCarrier']");
public PaymentMethodPage proceedToCheckout() {
agreeToTerms.shouldBe(visible).click();
proceedToCheckout.click();
return new PaymentMethodPage();
}
}
<file_sep>/gradle.properties
cucumberVersion=6.10.1
selenideVersion=5.19.0<file_sep>/src/test/java/com/test/madhan/pages/shoppingcart/PaymentSummaryPage.java
package com.test.madhan.pages.shoppingcart;
import com.codeborne.selenide.SelenideElement;
import static com.codeborne.selenide.Selenide.$x;
public class PaymentSummaryPage {
private final SelenideElement confirmOrderButton = $x("//button[./span[text()='I confirm my order']]");
public OrderConfirmationPage confirmOrder() {
confirmOrderButton.click();
return new OrderConfirmationPage();
}
}
<file_sep>/src/test/java/com/test/madhan/pages/CategoryPage.java
package com.test.madhan.pages;
import com.codeborne.selenide.SelenideElement;
import com.test.madhan.pages.shoppingcart.SummaryPage;
import static com.codeborne.selenide.Condition.visible;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Selenide.title;
import static org.junit.Assert.assertEquals;
public class CategoryPage {
private final SelenideElement productContainer = $(".product_list .product-container");
private final SelenideElement addToCartButton = $("a[title='Add to cart']");
private final SelenideElement proceedToCheckout = $("a.btn[title='Proceed to checkout']");
public CategoryPage(String categoryName) {
assertEquals("Verifying page tile", categoryName + " - My Store", title());
}
public CategoryPage addProductToCart() {
productContainer.shouldBe(visible).hover();
addToCartButton.should(visible).click();
return this;
}
public SummaryPage proceedToCheckout() {
proceedToCheckout.should(visible).click();
return new SummaryPage();
}
}
<file_sep>/src/test/java/com/test/madhan/pages/OrderHistoryPage.java
package com.test.madhan.pages;
import com.codeborne.selenide.SelenideElement;
import com.test.madhan.model.OrderData;
import static com.codeborne.selenide.CollectionCondition.sizeGreaterThanOrEqual;
import static com.codeborne.selenide.Condition.text;
import static com.codeborne.selenide.Condition.visible;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Selenide.$$;
public class OrderHistoryPage {
private final SelenideElement orderDetailBlock = $("#block-order-detail");
private final SelenideElement orderDetailTable = $("#order-detail-content");
private final String productNameLabel = "tbody .item .bold";
private final String productQtyLabel = "tbody .item .return_quantity";
private final String orderTotalLabel = ".totalprice .price";
public OrderHistoryPage selectOrder(String orderReference) {
$$("#order-list td.history_link>a")
.shouldHave(sizeGreaterThanOrEqual(1))
.filter(text(orderReference))
.first().click();
return this;
}
public void verifyOrder(OrderData orderData) {
orderDetailBlock.should(visible);
SelenideElement orderDetailTableElement = orderDetailTable.scrollIntoView(true);
orderDetailTableElement.$(productNameLabel).shouldHave(text(orderData.getProductName()));
orderDetailTableElement.$(productQtyLabel).shouldHave(text(orderData.getProductQuantity()));
orderDetailTableElement.$(orderTotalLabel).shouldHave(text(orderData.getOrderTotal()));
}
}
<file_sep>/src/test/java/com/test/madhan/pages/shoppingcart/AddressPage.java
package com.test.madhan.pages.shoppingcart;
import com.codeborne.selenide.SelenideElement;
import static com.codeborne.selenide.Condition.visible;
import static com.codeborne.selenide.Selenide.$;
public class AddressPage {
private final SelenideElement proceedToCheckout = $("button[name='processAddress']");
public ShippingPage proceedToCheckout() {
proceedToCheckout.should(visible).click();
return new ShippingPage();
}
}
<file_sep>/src/test/java/com/test/madhan/pages/shoppingcart/PaymentMethodPage.java
package com.test.madhan.pages.shoppingcart;
import com.codeborne.selenide.SelenideElement;
import static com.codeborne.selenide.Condition.visible;
import static com.codeborne.selenide.Selenide.$;
public class PaymentMethodPage {
private final SelenideElement bankWireButton = $(".bankwire");
public PaymentSummaryPage payByBankWire() {
bankWireButton.shouldBe(visible).click();
return new PaymentSummaryPage();
}
}
<file_sep>/build.gradle
plugins {
id 'java'
id "se.thinkcode.cucumber-runner" version "0.0.8"
id "io.freefair.lombok" version "5.3.0"
}
group 'com.test.madhan'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
testImplementation "io.cucumber:cucumber-java8:${cucumberVersion}"
testImplementation "io.cucumber:cucumber-junit:${cucumberVersion}"
testImplementation "io.cucumber:cucumber-picocontainer:${cucumberVersion}"
testImplementation "com.codeborne:selenide:${selenideVersion}"
}
cucumber {
glue = 'classpath:com.test.madhan'
strict = 'true'
plugin = ['pretty', 'html:build/result.html']
featurePath = 'src/test/resources'
main = 'io.cucumber.core.cli.Main'
} | 35f7ba535264e9d5fd5e8db9f08130ab67242032 | [
"Markdown",
"Java",
"INI",
"Gradle"
] | 12 | Java | phystem/bdd-test-framework | f3768b0c60ccfd0dab595beff4fb4eb2a42f9654 | 33d19cad4fc30c079732c2be43966fbb6ed82915 |
refs/heads/master | <repo_name>dangquocdung/xprobus<file_sep>/public/doc/index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
<title>Xpro Bussiness - Corporate, Agency Business HTML5 Template</title>
<link href="favicon.ico" rel="shortcut icon" type="image/x-icon">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<div id="layout">
<aside id="menu">
<div class="logo">
<a href="#">Xpro Bussiness</a>
</div>
<div class="menu-links">
<ul>
<li>
<a href="#getting-started">Getting Started</a>
<ul>
<li><a href="#requirements">Requirements</a>
<li><a href="#installation">Installation</a>
</ul>
</li>
<li><a href="#preloader">Preloader</a></li>
<li><a href="#favicon">Favicon</a></li>
<li><a href="#themes">Themes</a></li>
<li>
<a href="#grid-system">Modular Grid</a>
<ul>
<li><a href="#twboot">Twitter Bootstrap</a>
<li><a href="#grid-padding">Paddings and Margins</a>
</ul>
</li>
</li>
<!--
<li>
<a href="#page-header">Header</a>
</li>
<li>
<a href="#patterns">Patterns</a>
</li>
<li>
<a href="#boxed">Boxed Layout</a>
</li>
-->
<li>
<a href="#sliders">Sliders</a>
</li>
<li><a href="#gmaps">Google Maps</a></li>
<li><a href="#errorpage">Error Pages</a></li>
<li><a href="#forms">Forms</a>
</li>
<li><a href="#font-settings">Fonts settngs</a></li>
</ul>
</div>
</aside>
<!-- /#menu -->
<section id="main">
<nav class="slideshow-bar">
<a id="menu-link" href="#menu"></a>
<a id="scrolltop" href="#"></a>
</nav>
<!-- /.slideshow-bar -->
<header class="header content">
<div>
<h1>Xpro Bussiness - Documentation</h1>
<small class="version">Version 1.0</small>
<h4>Cross Browser, High Quality and Responsive Multipurpose HTML Template.</h4>
<p>Thank you very much for purchasing our template. It is built with the latest HTML5 and CSS3 technologies, but at the same time it is also made compatible with older browser versions. If you have any questions that aren’t covered in this article, please feel free to email us on our user page, you can find the contact form <a href="">here</a>.</p>
<p>Don’t forget to rate this template, it helps us improve our products. <img src="images/rate.png" alt=""></p>
<h4>Thanks so much!</h4>
</div>
</header>
<!-- /.header -->
<section id="getting-started" class="content slide">
<div>
<h2>Getting Started</h2>
<h4 id="requirements">Requirements</h4>
<p>For installing this template you need to make sure that you have the following extensions on your webserver. You will need to contact your webhost if the following requirements are missing.</p>
<ul>
<li>PHP 5.2+;</li>
<li>PHP Mail support;</li>
<li>Enabling JavaScript in the web browser.</li>
</ul>
<h4 id="installation">Installation</h4>
<p>Unzip the downloaded files to the local disk on your computer. Inside the extracted folder there will be contents and folder with documentation. Copy all contents, except from folder with documentation, to your server via FTP client.</p>
</div>
</section>
<!-- #getting-started -->
<section id="preloader" class="content slide">
<div>
<h2>Preloader</h2>
<p>Before the main contents of the website are loaded, there is an opportunity to show the preloader of the site. It can be any image, a gif-animated icon. You can change the path to the image.</p>
<p>If you don’t need the preloader, you can delete div with id <strong>preloader</strong> and comment/remove some lines in custom.js file.</p>
<pre class="snippet" data-language="html">
<!-- Preloader -->
<div id="preloader">
 <div class="sk-circle">
  <div class="sk-circle1 sk-child"></div>
   <div class="sk-circle2 sk-child"></div>
   <div class="sk-circle3 sk-child"></div>
  <div class="sk-circle4 sk-child"></div>
   <div class="sk-circle5 sk-child"></div>
   <div class="sk-circle6 sk-child"></div>
   <div class="sk-circle7 sk-child"></div>
  <div class="sk-circle8 sk-child"></div>
  <div class="sk-circle9 sk-child"></div>
   <div class="sk-circle10 sk-child"></div>
  <div class="sk-circle11 sk-child"></div>
  <div class="sk-circle12 sk-child"></div>
 </div>
</div>
</pre>
<pre class="snippet" data-language="html">
$(window).load(function() {
 $("#preloader").fadeOut();
 })
</pre>
</div>
</section>
<!-- #preloader -->
<section id="favicon" class="content slide">
<div>
<h2>Favicon</h2>
<p>To change the favicon of your site, you need to load a new image in a site root or to point out a new address of the image.</p>
<pre class="snippet" data-language="js">
<link href="favicon.ico" rel="shortcut icon" type="image/x-icon">
</pre>
</div>
</section>
<!-- /#favicon -->
<section id="themes" class="content slide">
<div>
<h2>Color themes</h2>
<p>There have already been created a few special <code>CSS</code> file for the theme, which stylize a color scheme.</p>
<ul>
<li><strong>amethyst.css</strong> - a VioletDark color</li>
<li><strong>asphalt.css</strong> - a DarkSlateGray color;</li>
<li><strong>steelblue</strong> - an steelblue color;</li>
<li><strong>emerland </strong> - a emerland color;</li>
<li><strong>green </strong> - a green color;</li>
<li><strong>lightorange </strong> - a lightorange color;</li>
<li><strong>peterriver </strong> - a peterriver color;</li>
<li><strong>pink </strong> - a pink color;</li>
<li><strong>pomegranate </strong> - a pomegranate color;</li>
<li><strong>pumpkin </strong> - a pumpkin color;</li>
<li><strong>purple </strong> - a purple color;</li>
<li><strong>red </strong> - a red color;</li>
<li><strong>yellow </strong> - a yellow color;</li>
<li><strong>sunflower </strong> - a sunflower color;</li>
</ul>
<pre class="snippet" data-language="html">
<link href="assets/css/theme-color/default.css" rel="stylesheet" id="theme-color" type="text/css">
</pre>
<p class="warning">The file <strong>theme.css</strong> it set by default. Also you have to change <code>css/theme-color/theme.css</code> file into the <code>head</code> tag.</p>
<p>Also you have to change <strong>theme.scss</strong> file into online compiler
<a href="http://www.sassmeister.com/" target="_blank">Here</a> to "unlimited colors" </p>
<pre class="snippet" data-language="html">
$theme-color: #19b5fe;// Change here your theme color
</pre>
</div>
</section>
<!-- /#themes -->
<section id="grid-system" class="content slide">
<div>
<h2>Modular grid</h2>
<p>The Template is built on the system by using a 12-column markup. With the help of the given system you can create almost any modular grid and insert a necessary content in created modules.</p>
<h3 id="grid-padding">Paddings and Margins</h3>
<p>If it’s necessary to add a padding on the top or bottom or both, it’s enough to add one of the classes that will set up padding:</p>
<pre class="snippet" data-language="js">
.no-padding {
padding: 0 !important;
}
.padding-30 {
padding: 30px !important;
}
.padding-40 {
padding: 40px !important;
}
.plr-0 {
padding-left: 0 !important;
padding-right: 0 !important;
}
.pl-0 {
padding-left: 0;
}
.pr-0 {
padding-right: 0;
}
.ptb-0 {
padding-top: 0px !important;
padding-bottom: 0px !important;
}
.pt-0 {
padding-top: 0px !important;
}
.pb-0 {
padding-bottom: 0px !important;
}
.pt-30 {
padding-top: 30px !important;
}
.ptb {
padding-top:60px;
padding-bottom: 60px;
}
.pt {
padding-top: 110px;
}
.pb {
padding-bottom: 110px;
}
.ptb-15 {
padding-top: 15px;
padding-bottom: 15px;
}
.pt-15 {
padding-top: 15px;
}
.pb-15 {
padding-bottom: 15px;
}
.ptb-60 {
padding-top: 80px;
padding-bottom: 80px;
}
.pt-60 {
padding-top: 60px;
}
.pb-60 {
padding-bottom: 60px;
}
.ptb-80 {
padding-top: 80px;
padding-bottom: 80px;
}
.pt-80 {
padding-top: 80px;
}
.pb-80 {
padding-bottom: 80px;
}
.mtb-0 {
margin-top: 0px;
margin-bottom: 0px;
}
.mlr-0 {
margin-left: 0px;
margin-right: 0px;
}
.mt-0 {
margin-top: 0px !important;
}
.mb-0 {
margin-bottom: 0px !important;
}
.ml-0 {
margin-left: 0px !important;
}
.mr-0 {
margin-right: 0px !important;
}
.mtb-80 {
margin-top: 80px;
margin-bottom: 80px;
}
.mt-80 {
margin-top: 80px;
}
.mb-80 {
margin-bottom: 80px;
}
.mtb-60 {
margin-top: 60px;
margin-bottom: 60px;
}
.mt-60 {
margin-top: 60px;
}
.mb-60 {
margin-bottom: 60px;
}
.mtb-45 {
margin-top: 45px;
margin-bottom: 45px;
}
.mt-45 {
margin-top: 45px;
}
.mb-45 {
margin-bottom: 45px;
}
.mtb-30 {
margin-top: 30px;
margin-bottom: 30px;
}
.mt-30 {
margin-top: 30px;
}
.mb-30 {
margin-bottom: 30px;
}
.ml-30 {
margin-left: 30px;
}
.mr-30 {
margin-right: 30px;
}
.mtb-25 {
margin-top: 25px;
margin-bottom: 25px;
}
.mt-25 {
margin-top: 25px;
}
.mb-25 {
margin-bottom: 25px;
}
.mtb-15 {
margin-top: 15px;
margin-bottom: 15px;
}
.mt-15 {
margin-top: 15px;
}
.mb-15 {
margin-bottom: 15px;
}
</pre>
</ul>
<pre class="snippet" data-language="js">
<div class="container pt">
 <div class="row text-center">
  <div class="col-md-3 col-sm-6 margin-top-big">
   …
  </div>
 </div>
</div>
</pre>
<p>You can change the size of paddings in the css/style.css file or you can add a new class in which you set up user’s paddings.</p>
<!-- /#ecommerce -->
<section id="gmaps" class="content slide">
<div>
<h2>Google Maps</h2>
<pre class="snippet" data-language="js">
<!-- CONTACT-map -->
<div class="map">
<div id="map"></div>
</div>
</pre>
<p>In <strong>HTML</strong> file you should write only single line, with unique <code>id</code> attribute.</p>
<p>To set Google map you need to edit the <code>custom.js</code> file. To get the longitude and latitude you can use the <a href="http://itouchmap.com/latlong.html" target="_blank">following service</a>. Click a map and replace a marker into the place you need after switching to a link. Then insert the received coordinates into the <code>custom.js</code> file.</p>
<p class="path" >custom.js</p>
<pre class="snippet" data-language="js">
var myCenter = new google.maps.LatLng(51.528308, -0.3817765); Set Your Location Hare
</pre>
</div>
</section>
<!-- /#gmaps -->
<!-- /#gmaps -->
<section id="errorpage" class="content slide">
<div>
<h2>Error Pages</h2>
<p>For special pages, like 404 or 505 or under Xpro Bussiness use a few another markup. At first, you should add class <code>page404</code> for HTML tag. This pages do not contain header and footer like in another pages. For more details information look at <strong>404.html</strong>. By analogy of this pages you may create suitable and needed for your purposes pages.</p>
</div>
</section>
<!-- #errorpage -->
<section id="forms" class="content slide">
<div>
<h2>Forms</h2>
<p>All the areas must be in the <code>form</code> tag. add Id <strong>contact-form</strong> in form tag. The tag must have obligatory attributes:</p>
<pre class="snippet" data-language="js">
<form id="contact-form" class="contact-form">
<ul class="col-xs-12 col-sm-6">
<li>
<input id="name" class="name" type="text" name="name" placeholder="Name*">
</li>
<li>
<input id="email" class="email" type="email" name="email" placeholder="E-Mail*">
</li>
<li>
<input id="sub" class="sub" type="text" name="sub" placeholder="subject*">
</li>
</ul>
<ul class="col-xs-12 col-sm-6">
<li>
<textarea id="message" class="message" name="message" placeholder="Message:"></textarea>
</li>
</ul>
<div class="col-xs-12">
<input id="submit" class="send-btn" type="button" name="send-btn" value="Send">
</div>
</form>
</pre>
<p>Change here the Success msg content</p>
<pre class="snippet" data-language="js">
<div id="success">
<div class="alert alert-success">
<strong>Thanks</strong> for using our template. Your message has been sent.
</div>
</div>
</pre>
<p class="question">In the <code>mail.php</code> file you can change the address of message receiving, a message topic, also the whole text that will deliver to the administrator of the site.</p>
<pre class="snippet" data-language="js">
// Global Configuration start: From here you can change the email-id of receiver, cc, from email-id & subject;
$to = "<EMAIL>";
$cc = "<EMAIL>";
$from = "<EMAIL>";
$subject = "Email Submission";
// Global configuration end
</pre>
</div>
</section>
<!-- #forms -->
<section id="font-settings" class="content slide last">
<div>
<h2>Font Settings</h2>
<p>To change the font-family you will have to edit the file <code>css/style.css</code>. If the font is a standard one, built the system by default, you can just write it here.</p>
<pre class="snippet" data-language="js">
body { font-family: 'Open Sans', Arial, Helvetica, sans-serif; } // or whatever you want (e.g. "lato")
</pre>
<p class="warning">Also you can use <a href="http://www.google.com/fonts" target="_blank" title="Google Font">Google Font</a> and connect it to your website.</p>
<ol>
<li>Go to <a href="http://www.google.com/fonts" target="_blank">http://www.google.com/fonts</a>.</li>
<li>Choose the appropriate font.</li>
<li>Click the <strong>Quick-use</strong> button (<img src="images/quick_use_static.png" alt="">).</li>
<li>Choose the styles that you want;</li>
<li>Choose the character sets that you want.</li>
<li>Below that click on the @import tab and copy this line.</li>
<li>Paste this line to that <code>css/style.css</code> file on 3d line instead of the default (e.g.):
<pre class="snippet" data-language="css">
@import url(http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700,800%7COswald:300,400,700);
</pre>
</li>
<li>At last, copy font-family name from Google Fonts website and paste on <code>css/style.css</code>:
<pre class="snippet" data-language="js">
body { font-family: 'Open Sans', Arial, Helvetica, sans-serif; }
</pre>
</li>
</ol>
</div>
</section>
<!-- /#font-settings -->
<footer id="footer">
Thank You, Xpro Bussiness
</footer>
<!-- /#footer -->
</section>
<!-- /#main -->
</div>
<script src="js/jquery-2.1.1.min.js"></script>
<script src="js/jquery.plugins.js"></script>
<script src="js/custom.js"></script>
</body>
</html><file_sep>/app/TypeLps.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class TypeLps extends Model
{
public function lps()
{
return $this->hasMany('App\Lps', 'type_id');
}
}
<file_sep>/public/cache/get-cache.php
<?php
/*
* Caches API calls to a local file which is updated in a
* given time interval.
*/
$update_interval = $_REQUEST['interval'] * 60; // 10 minutes
$cache_file = $_REQUEST['cacheFile'];
/*
* Checks the cache file and if the last modified time is lesser than
* update interval then returns cache contents else returns a "expired" status
*/
if ( !file_exists($cache_file) || (time() - filemtime($cache_file) > $update_interval) ) {
header('Content-Type: application/json; charset=UTF-8');
echo '{"expired": true}';
}
else {
header('Content-Type: application/json; charset=UTF-8');
echo file_get_contents($cache_file);
}
<file_sep>/app/Http/Controllers/LpsController.php
<?php
namespace App\Http\Controllers;
use App\Lps;
use App\TypeLps;
use App\Http\Requests;
use App\WebmasterLps;
use App\WebmasterSection;
use Auth;
use File;
use Helper;
use Illuminate\Config;
use Illuminate\Http\Request;
use Redirect;
use Carbon\Carbon;
class LpsController extends Controller
{
// Define Default Variables
public function __construct()
{
$this->middleware('auth');
// Check Permissions
if (!@Auth::user()->permissionsGroup->lps_status) {
return Redirect::to(route('NoPermission'))->send();
}
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
// General for all pages
$GeneralWebmasterSections = WebmasterSection::where('status', '=', '1')->orderby('row_no', 'asc')->get();
// General END
//List of Lps Sections
$WebmasterLps = WebmasterLps::where('status', '=', '1')->orderby('row_no', 'asc')->get();
$Lps = Lps::where('status', '=', '1')->orderby('ngay_ps','desc')->orderby('gio_ps','desc')->orderby('section_id', 'asc')->paginate(env('BACKEND_PAGINATION'));
return view("backEnd.lps", compact("Lps", "GeneralWebmasterSections", "WebmasterLps"));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create($sectionId)
{
// Check Permissions
if (!@Auth::user()->permissionsGroup->add_status) {
return Redirect::to(route('NoPermission'))->send();
}
//
// General for all pages
$GeneralWebmasterSections = WebmasterSection::where('status', '=', '1')->orderby('row_no', 'asc')->get();
// General END
//Lps Sections Details
$WebmasterLps = WebmasterLps::find($sectionId);
//Type Banner
$TypeLps = TypeLps::all();
return view("backEnd.lps.create", compact("GeneralWebmasterSections", "WebmasterLps","TypeLps"));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// Check Permissions
if (!@Auth::user()->permissionsGroup->add_status) {
return Redirect::to(route('NoPermission'))->send();
}
$Lps = new Lps;
$Lps->section_id = $request->section_id;
$Lps->date = Carbon::parse($request->date)->format('Y-m-d H:i:s');
$Lps->time = Carbon::parse($request->date)->format('H:i:s');
$Lps->type_id = $request->type_id;
$Lps->title = $request->title;
$Lps->link_url = $request->link_url;
$Lps->status = 1;
$Lps->created_by = Auth::user()->id;
$Lps->save();
return redirect()->action('LpsController@index')->with('doneMessage', trans('backLang.addDone'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
// Check Permissions
if (!@Auth::user()->permissionsGroup->edit_status) {
return Redirect::to(route('NoPermission'))->send();
}
//
// General for all pages
$GeneralWebmasterSections = WebmasterSection::where('status', '=', '1')->orderby('row_no', 'asc')->get();
// General END
//Type Banner
$TypeLps = TypeLps::all();
if (@Auth::user()->permissionsGroup->view_status) {
$Lps = Lps::where('created_by', '=', Auth::user()->id)->find($id);
} else {
$Lps = Lps::find($id);
}
if (count($Lps) > 0) {
//Lps Sections Details
$WebmasterLps = WebmasterLps::find($Lps->section_id);
return view("backEnd.Lps.edit", compact("Lps", "GeneralWebmasterSections", "WebmasterLps", "TypeLps"));
} else {
return redirect()->action('LpsController@index');
}
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
// Check Permissions
if (!@Auth::user()->permissionsGroup->add_status) {
return Redirect::to(route('NoPermission'))->send();
}
//
$Lps = Lps::find($id);
if (count($Lps) > 0) {
$Lps->date = Carbon::parse($request->date)->format('Y-m-d H:i:s');
$Lps->time = Carbon::parse($request->date)->format('H:i:s');
$Lps->type_id = $request->type_id;
$Lps->title = $request->title;
$Lps->link_url = $request->link_url;
$Lps->status = $request->status;
$Lps->updated_by = Auth::user()->id;
$Lps->save();
return redirect()->action('LpsController@edit', $id)->with('doneMessage', trans('backLang.saveDone'));
} else {
return redirect()->action('LpsController@index');
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
// Check Permissions
if (!@Auth::user()->permissionsGroup->delete_status) {
return Redirect::to(route('NoPermission'))->send();
}
//
if (@Auth::user()->permissionsGroup->view_status) {
$Lps = Lps::where('created_by', '=', Auth::user()->id)->find($id);
} else {
$Lps = Lps::find($id);
}
if (count($Lps) > 0) {
$Lps->delete();
return redirect()->action('LpsController@index')->with('doneMessage', trans('backLang.deleteDone'));
} else {
return redirect()->action('LpsController@index');
}
}
/**
* Update all selected resources in storage.
*
* @param \Illuminate\Http\Request $request
* @param buttonNames , array $ids[]
* @return \Illuminate\Http\Response
*/
public function updateAll(Request $request)
{
//
if ($request->action == "order") {
foreach ($request->row_ids as $rowId) {
$Lps = Lps::find($rowId);
if (count($Lps) > 0) {
$row_no_val = "row_no_" . $rowId;
$Lps->row_no = $request->$row_no_val;
$Lps->save();
}
}
} elseif ($request->action == "activate") {
Lps::wherein('id', $request->ids)
->update(['status' => 1]);
} elseif ($request->action == "block") {
Lps::wherein('id', $request->ids)
->update(['status' => 0]);
} elseif ($request->action == "delete") {
// Check Permissions
if (!@Auth::user()->permissionsGroup->delete_status) {
return Redirect::to(route('NoPermission'))->send();
}
// Delete Lps files
$Lps = Lps::wherein('id', $request->ids)->get();
foreach ($Lps as $Lps) {
if ($Lps->file_vi != "") {
File::delete($this->getUploadPath() . $Lps->file_vi);
}
if ($Lps->file_en != "") {
File::delete($this->getUploadPath() . $Lps->file_en);
}
}
Lps::wherein('id', $request->ids)
->delete();
}
return redirect()->action('LpsController@index')->with('doneMessage', trans('backLang.saveDone'));
}
}
<file_sep>/resources/lang/vi/backLang.php
<?php
return array (
'direction' => 'ltr',
'code' => 'vi',
'lang' => 'VI',
'left' => 'left',
'right' => 'right',
'arabicBox' => '<small>[ Tiếng Việt ]</small>',
'englishBox' => '<small>[ English ]</small>',
'rtl' => 'ltr',
'ltr' => 'ltr',
'boxCode' => 'vi',
'boxCodeOther' => 'en',
'translations' => 'Chuyển ngữ',
'calendarLanguage' => 'vi',
'backup' => 'Sao lưu',
'media' => 'Nghe nhìn',
'topicIntro' => 'Giới thiệu',
'topicInvest' => 'Đầu tư',
'topicOperations' => 'Chỉ Đạo - Điều Hành',
'siteMap' => 'Sơ đồ cổng',
'typeBanner' => 'Loại',
'update' => 'Cập nhật',
'hotTopic' => 'Tin nổi bật',
'marqueeTopic' => 'Tin thông báo',
'topicTCBC' => 'Thông cáo báo chí',
'topicEnvironmental' => 'Thông Tin Quan Trắc Môi Trường',
'topicConversation' => 'Đối thoại trực tuyến',
'topicGYVB' => 'Góp ý văn bản QPPL',
'home' => 'Trang chủ',
'main' => 'Trang chính',
'siteData' => 'Dữ liệu',
'settings' => 'Cài đặt',
'dashboard' => 'Quản trị',
'visitorsAnalytics' => 'Phân tích',
'visitorsAnalyticsBydate' => 'Theo ngày',
'visitorsAnalyticsByCity' => 'Thành phố',
'visitorsAnalyticsByRegion' => 'Khu vực',
'visitorsAnalyticsByAddress' => 'Địa chỉ',
'visitorsAnalyticsByCountry' => 'Quốc gia',
'visitorsAnalyticsByOperatingSystem' => 'Hệ điều hành',
'visitorsAnalyticsByBrowser' => 'Trình duyệt',
'visitorsAnalyticsByScreenResolution' => 'Độ phân giải màn hình',
'visitorsAnalyticsByReachWay' => 'Cách tiếp cận',
'visitorsAnalyticsByHostName' => 'Tên máy chủ',
'visitorsAnalyticsByOrganization' => 'Tổ chức',
'visitorsAnalyticsVisitorsHistory' => 'Lịch sử truy cập',
'visitorsAnalyticsIPInquiry' => 'Truy vấn IP',
'visitorsAnalyticsLastVisit' => 'Chuyến thăm Lần cuối',
'members' => 'Thành viên',
'adsBanners' => 'Băng rôn, Quảng cáo',
'siteInbox' => 'Hộp thư đến',
'newsletter' => 'Liên hệ',
'calendar' => 'Lịch',
'generalSiteSettings' => 'Cài đặt',
'webmasterTools' => 'Webmaster',
'generalSettings' => 'Cài đặt chung',
'siteSectionsSettings' => 'Site Sections',
'adsBannersSettings' => 'Cài đặt Banners',
'languageSettings' => 'Cài đặt ngôn ngữ',
'siteMenus' => 'Trang web Menus',
'usersPermissions' => 'Người dùng & Quyền',
'shoppingCart' => 'Giỏ hàng',
'orders' => 'Đơn đặt hàng',
'logout' => 'Đăng xuất',
'checkAll' => 'Chọn tất cả',
'profile' => 'Hồ sơ',
'search' => 'Tìm kiếm',
'new' => 'Mới',
'add' => 'Thêm',
'cập nhật' => 'Cập nhật',
'save' => 'Lưu',
'saveOrder' => 'Lưu',
'edit' => 'Chỉnh sửa',
'delete' => 'Xóa',
'undoDelete' => 'Hoàn tác Xóa',
'cancel' => 'Hủy',
'apply' => 'Áp dụng',
'active' => 'Hoạt động',
'notActive' => 'Không hoạt động',
'status' => 'Trạng thái',
'visits' => 'Visits',
'contents' => 'Nội dung',
'options' => 'Tùy chọn',
'showing' => 'Hiển thị',
'bulkAction' => 'Thao tác',
'activeSelected' => 'Kích hoạt',
'blockSelected' => 'Chặn',
'deleteSelected' => 'Xoá',
'of' => 'của',
'records' => 'tin, bài',
'confirmation' => 'Xác nhận',
'yes' => 'Có',
'no' => 'Không',
'confirmationDeleteMsg' => 'Bạn có chắc chắn muốn xóa?',
'sectionsOf' => 'Danh mục của',
'comments' => 'Bình luận',
'videoTypes' => 'Phần mở rộng: .mp4, .ogv, .webm',
'imagesTypes' => 'Phần mở rộng: .png, .jpg, .jpeg, .gif',
'audioTypes' => 'Phần mở rộng: .mp3, .wav',
'attachTypes' => 'Tiện ích mở rộng: (* ALL)',
'addDone' => 'Tin, bài mới đã được thêm thành công',
'saveDone' => 'Sửa đổi bạn đã lưu thành công',
'deleteDone' => 'Dữ liệu đã bị xóa thành công',
'erorr' => 'Có lỗi, hãy thử lại',
'noData' => 'Không có dữ liệu cho đến bây giờ',
'appsSettings' => 'Ứng dụng đang hoạt động',
'fieldsSettings' => 'Fields Settings',
'frontSettings' => 'Cài đặt Giao diện Người dùng',
'arabicLanguageFields' => 'Các trường ngôn ngữ tiếng Việt',
'englishLanguageFields' => 'Trường ngôn ngữ tiếng Anh',
'seoTab' => 'Tab SEO',
'seoTabTitle' => 'Cài đặt SEO',
'defaultCurrency' => 'Tiền tệ mặc định',
'commentsStatus' => 'Trạng thái nhận xét',
'automaticPublish' => 'Xuất bản tự động',
'manualByAdmin' => 'Manual By Admin',
'headerMenu' => 'Tiêu đề trình đơn',
'footerMenu' => 'Footer Menu',
'homeSlideBanners' => 'Trang chủ Trình chiếu Biểu ngữ',
'homeTextBanners' => 'Biểu ngữ Văn bản Trang chủ',
'sideBanners' => 'Biểu ngữ cột phải',
'none' => 'Không có',
'newsletterGroup' => 'Nhóm tin email bản tin (trong danh bạ)',
'homeRow1' => 'Trang chủ Nội dung ROW 1',
'homeRow2' => 'Trang chủ Nội dung ROW 2',
'homeRow3' => 'Chủ đề mới nhất (trong footer)',
'contactPageId' => 'Liên hệ Trang (Chi tiết & Bản đồ)',
'activeLanguages' => 'Ngôn ngữ hoạt động',
'activeLanguages1' => 'Một ngôn ngữ (Mặc định trong .env)',
'activeLanguages2' => 'Tất cả ngôn ngữ',
'homeBanners' => 'Slide Banners',
'textBanners' => 'Biểu ngữ kèm văn bản',
'blockBanners' => 'Banner dạng khối',
'sectionName' => 'Tiêu đề mục',
'sectionType' => 'Loại mục',
'sectionNew' => 'Phần mới',
'sectionEdit' => 'Chỉnh sửa phần',
'sectionIcon' => 'Biểu tượng',
'sectionFather' => '<NAME>',
'sectionNoFather' => 'Cha Mục',
'size' => 'Kích thước',
'width' => 'Width',
'height' => 'Chiều cao',
'descriptionBox' => 'Hộp để mô tả',
'linkBox' => 'Hộp cho URL',
'sectionTypeCode' => 'Mã / Văn bản',
'sectionTypePhoto' => 'Ảnh',
'sectionTypeVideo' => 'Video',
'langVar' => 'Variable',
'sitePages' => 'Trang web',
'photos' => 'Ảnh',
'blog' => 'Blog',
'dịch vụ' => 'Dịch vụ',
'news' => 'Tin tức',
'videos' => 'Video',
'sounds' => 'Âm thanh',
'products' => 'Sản phẩm',
'typeTextPages' => 'Chung',
'typePhotos' => 'Photos',
'typeVideos' => 'Video',
'typeSounds' => 'Audio',
'hasCategories' => 'Danh mục',
'reviewsAvailable' => 'Nhận xét Có sẵn',
'dateField' => 'Trường ngày tháng',
'longTextField' => 'Long Text Field',
'allowEditor' => 'Cho phép biên tập',
'attachFileField' => 'Gắn File Field',
'additionalImages' => 'Hình ảnh bổ sung',
'attachGoogleMaps' => 'Đính kèm Google Maps',
'attachOrderForm' => 'Đính kèm đơn đặt hàng',
'withoutCategories' => 'Không có Loại',
'mainCategoriesOnly' => 'Chỉ các loại chính',
'mainAndSubCategories' => 'Danh mục chính và phụ',
'sectionIconPicker' => 'Phần Icon (Bộ lọc)',
'topicsIconPicker' => 'Chủ đề Biểu tượng (Trình chọn)',
'iconPicker' => 'Biểu tượng (Bộ chọn)',
'siteInfoSettings' => 'Website Info',
'siteStatusSettings' => 'Trạng thái Trang web',
'siteSocialSettings' => 'Liên kết xã hội',
'siteContactsSettings' => 'Thông tin liên hệ',
'websiteTitle' => 'Tiêu đề Website',
'metaDescription' => 'Mô tả Meta',
'metaKeywords' => 'Từ khoá Meta',
'websiteUrl' => 'Website URL',
'websiteNotificationEmail' => 'Email thông báo của trang web',
'websiteNotificationEmail1' => 'Gửi cho tôi một email về Tin nhắn liên lạc mới',
'websiteNotificationEmail2' => 'Gửi cho tôi một email về Bình luận mới',
'websiteNotificationEmail3' => 'Gửi cho tôi một email về Đơn đặt hàng Mới',
'emailNotifications' => 'Thông báo bằng email',
'contactAddress' => 'Địa chỉ',
'contactPhone' => 'Điện thoại',
'contactFax' => 'Fax',
'contactMobile' => 'Mobile',
'contactEmail' => 'Email',
'worksTime' => 'Thời gian làm việc',
'siteStatusSettingsPublished' => 'Đã xuất bản',
'siteStatusSettingsClosed' => 'Đã đóng',
'siteStatusSettingsMsg' => 'Đóng Tin nhắn',
'facebook' => 'Facebook',
'twitter' => 'Twitter',
'google' => 'Google+',
'linkedin' => 'Linkedin',
'youtube' => 'Youtube',
'instagram' => 'Instagram',
'pinterest' => 'Pinterest',
'tumblr' => 'Tumblr',
'flickr' => 'Flickr',
'whatapp' => 'Whatsapp',
'styleSettings' => 'Cài đặt kiểu',
'siteLogo' => 'Site Logo',
'favicon' => 'Favicon',
'appleIcon' => 'Apple Icon',
'styleColor1' => 'Kiểu màu 1',
'styleColor2' => 'Style Color 2',
'restoreDefault' => 'Phục hồi Mặc định',
'layoutMode' => 'Giao diện Chế độ',
'wide' => 'rộng',
'boxed' => 'đóng hộp',
'backgroundStyle' => 'Phong cách nền',
'colorBackground' => 'Màu nền',
'patternsBackground' => 'Pattern Background',
'imageBackground' => 'Hình nền',
'newsletterSubscribe' => 'Đăng ký nhận bản tin',
'footerStyle' => 'Footer Style',
'footerStyleBg' => 'Phần chân trang',
'preLoad' => 'Trình tải trước',
'bannerAdd' => 'Thêm mới Banner',
'bannerEdit' => 'Chỉnh sửa Bảng quảng cáo',
'bannerTitle' => 'Tiêu đề Quảng cáo',
'bannerSection' => 'Mục',
'bannerPhoto' => 'Ảnh',
'bannerDetails' => 'Chi tiết',
'bannerVideoType' => 'Loại Video',
'bannerVideoType1' => 'Video trực tiếp',
'bannerVideoType2' => 'Youtube',
'bannerVideoType3' => 'Vimeo',
'bannerVideoFile' => 'Video File',
'bannerVideoUrl' => 'URL của Youtube video',
'bannerVideoUrl2' => 'Video URL Vimeo',
'bannerCode' => 'Banner Code',
'topicNew' => 'Mới',
'topicEdit' => 'Chỉnh sửa',
'topicName' => 'Tiêu đề',
'topicPhoto' => 'Ảnh',
'topicSection' => 'Mục',
'topicSelectSection' => 'Chọn mục',
'topicDate' => 'Ngày',
'topicAudio' => 'File âm thanh',
'topicVideo' => 'Video File',
'topicAttach' => 'Đính kèm tệp',
'topicDeletedSection' => 'Chưa phân loại',
'topicTabSection' => 'Chi tiết về mặt hàng',
'topicTabDetails' => 'Chi tiết chủ đề',
'topicSEOTitle' => 'Trang tiêu đề',
'topicSEODesc' => 'Mô tả Meta',
'topicSEOKeywords' => 'Từ khoá Meta',
'topicAdditionalPhotos' => 'Ảnh',
'topicGoogleMaps' => 'Google Maps',
'topicDropFiles' => 'Thả ảnh vào đây hoặc nhấn để tải lên',
'topicDropFiles2' => 'Bạn có thể tải lên nhiều bức ảnh cùng một lúc',
'topicCommentName' => 'Tên',
'topicCommentEmail' => 'Email',
'topicComment' => 'Bình luận',
'topicNewComment' => 'Bình luận mới',
'topicNewMap' => 'Bản đồ mới',
'topicMapTitle' => 'Bản đồ Tiêu đề',
'topicMapDetails' => 'Chi tiết',
'topicMapLocation' => 'Vị trí',
'topicMapIcon' => 'Biểu tượng',
'topicMapClick' => 'Kích vào vị trí để thêm New Marker',
'topicMapORClick' => 'Hoặc bấm vào đây để thêm Thủ công',
'allContacts' => 'Tất cả Địa chỉ liên hệ',
'WaitActivation' => 'Chờ kích hoạt',
'blockedContacts' => 'Blocked Contacts',
'newGroup' => 'Nhóm mới',
'newContacts' => 'Liên hệ mới',
'editContacts' => 'Chỉnh sửa Liên hệ',
'deleteContacts' => 'Xóa địa chỉ liên hệ',
'searchAllContacts' => 'Tìm kiếm tất cả các địa chỉ liên hệ',
'firstName' => 'Tên',
'lastName' => 'Họ',
'companyName' => '<NAME>',
'city' => 'Thành phố',
'country' => 'quốc gia',
'notes' => 'Ghi chú',
'nhóm' => 'Nhóm',
'sendEmail' => 'Gửi Email',
'callNow' => 'Gọi ngay bây giờ',
'selectFile' => 'Chọn tập tin',
'labels' => 'Labels',
'inbox' => 'Hộp thư đến',
'sent' => 'Gửi',
'draft' => 'Dự thảo',
'compose' => 'Soạn thư',
'makeAsRead' => 'Làm như đã đọc',
'makeAsUnread' => 'Tạo thành chưa đọc',
'moveTo' => 'Chuyển đến',
'replay' => 'Replay',
'forward' => 'Chuyển tiếp',
'sendTo' => 'Tới',
'sendFrom' => 'Từ',
'sendCc' => 'Cc',
'sendBcc' => 'Bcc',
'sendTitle' => 'Tiêu đề',
'SaveToDraft' => 'Lưu nháp',
'send' => 'Gửi',
'print' => 'In',
'AttachFiles' => 'Đính kèm tệp',
'newEvent' => 'Sự kiện mới / Lưu ý',
'eventTotal' => 'Tổng số',
'eventTitle' => 'Tiêu đề',
'eventStart' => 'Sự kiện bắt đầu',
'eventEnd' => 'Sự kiện kết thúc',
'eventStart2' => 'Bắt đầu',
'eventEnd2' => 'Kết thúc',
'eventDetails' => 'Chi tiết',
'eventNote' => 'Lưu ý',
'eventMeeting' => 'Hội nghị',
'eventEvent' => 'Sự kiện',
'eventTask' => 'Nhiệm vụ',
'eventType' => 'Loại',
'eventAt' => 'Tại',
'eventToday' => 'Hôm nay',
'eventDay' => 'Ngày',
'eventWeek' => 'Tuần',
'eventMonth' => 'Tháng',
'eventDelete' => 'Xóa ghi chú này / Sự kiện?',
'eventClear' => 'Xóa tất cả ghi chú và sự kiện?',
'diagram' => 'Sơ đồ',
'barDiagram' => 'Hiển thị dữ liệu dưới dạng biểu đồ thanh',
'visitors' => 'Lượt truy cập',
'ip' => 'IP',
'pageViews' => 'Lượt xem trang',
'today' => 'Hôm nay',
'Yesterday' => 'Hôm qua',
'last7Days' => '7 ngày trước',
'last30Days' => '30 ngày vừa qua',
'thisMonth' => 'Tháng này',
'lastMonth' => 'Tháng trước',
'applyFrom' => 'Từ',
'applyTo' => 'Tới',
'customRange' => 'Phạm vi tùy chỉnh',
'weekDays' => '"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"',
'monthsNames' => '"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"',
'activity' => 'Hoạt động',
'activityHistory' => 'Lịch sử Hoạt động',
'newUser' => 'Người dùng mới',
'editUser' => 'Chỉnh sửa Người dùng',
'fullName' => '<NAME>',
'Permission' => 'Quyền',
'Permission1' => 'Webmaster',
'Permission2' => 'Quản lý trang web (Tính năng đầy đủ)',
'Permission3' => 'Người dùng giới hạn (không xóa)',
'Permission4' => 'Xem lại Người dùng (Xem Chỉ)',
'personalPhoto' => 'Ảnh cá nhân',
'loginEmail' => 'Đăng nhập Email',
'loginPassword' => '<PASSWORD>',
'users' => 'Người dùng',
'permissions' => 'Quyền',
'newPermissions' => 'Quyền mới',
'title' => 'Tiêu đề',
'dataManager' => 'Quản lý dữ liệu',
'dataManager1' => 'Chỉ riêng dữ liệu riêng của mình (đối với tài khoản cá nhân)',
'dataManager2' => 'Tất cả người dùng dữ liệu (đối với Tài khoản Quản trị Chung)',
'activeApps' => 'Ứng dụng đang hoạt động',
'activeSiteSections' => 'Các trang hoạt động',
'addPermission' => 'Thêm giấy phép',
'editPermission' => 'EDIT Permission',
'deletePermission' => 'DELETE Cho phép',
'viewOnly' => 'VIEW ONLY',
'editPermissions' => 'Chỉnh sửa Quyền',
'perAdd' => 'ADD',
'perEdit' => 'EDIT',
'perDelete' => 'DELETE',
'selectPermissionsType' => 'Chọn loại quyền',
'newLink' => 'Liên kết mới',
'newMenu' => 'Trình đơn Mới',
'menuTitle' => 'Tiêu đề Menu',
'editSection' => 'Chỉnh sửa liên kết',
'linkType' => 'Loại liên kết',
'linkType1' => 'Tiêu đề Chính',
'linkType2' => 'Liên kết trực tiếp',
'linkType3' => 'Mục chính',
'linkType4' => 'Thả danh sách',
'linkURL' => 'Liên kết URL',
'linkSection' => 'Mục liên kết',
'sectionTitle' => 'Liên kết / Tiêu đề Mục',
'fatherSection' => 'Cha Mục',
'latestMessages' => 'Tin nhắn',
'notesEvents' => 'Ghi chú & Sự kiện',
'latestContacts' => 'Danh bạ Mới',
'more' => 'Khác',
'viewMore' => 'View More',
'addNew' => 'Thêm mới',
'reports' => 'Báo cáo',
'reportsDetails' => 'Bạn có thể xem nhiều báo cáo hơn',
'hi' => 'Chào',
'welcomeBack' => 'Welcome back',
'lastFor7Days' => 'Khách truy cập trong 7 ngày qua',
'todayByCountry' => 'Hôm nay theo quốc gia',
'browsers' => 'Trình duyệt',
'browsersCalculated' => 'Tính trong 7 ngày qua',
'visitorsRate' => 'Tỷ lệ khách truy cập',
'visitorsRateToday' => 'Tỷ lệ khách truy cập trong ngày hiện tại',
'pages' => 'Trang',
'sections' => 'Phần',
'resultsFoundFor' => 'Đã tìm thấy kết quả cho',
'connectEmailToConnect' => 'Kết nối với tài khoản webmail',
'connectEmail' => 'Email',
'connectPassword' => '<PASSWORD>',
'openWebmail' => 'Mở Webmail',
'themeSwitcher' => 'Thay đổi giao diện',
'foldedAside' => 'Thu gọn menu',
'boxedLayout' => 'Giao diện đóng hộp',
'themes' => 'Chủ đề',
'themes1' => 'LIGHT',
'themes2' => 'GREY',
'themes3' => 'Dark',
'themes4' => 'Đen',
'language' => 'Ngôn ngữ',
'change' => 'Thay đổi',
'sitePreview' => 'trang web',
'oops' => 'OOPS',
'noPermission' => 'Xin lỗi! Bạn không có quyền xem trang này',
'notFound' => 'Trang bạn đang tìm kiếm không thể tìm thấy',
'forgotPassword' => '<PASSWORD>?',
'signIn' => 'Đăng nhập',
'keepMeSignedIn' => 'Giữ cho tôi đăng nhập',
'signedInToControl' => 'Đăng nhập vào Quản trị',
'control' => 'Vùng quản trị',
'resetPassword' => '<PASSWORD>',
'confirmPassword' => '<PASSWORD>',
'newPassword' => '<PASSWORD>',
'yourEmail' => 'Email của bạn',
'sendPasswordResetLink' => 'Gửi mật khẩu Reset Link',
'returnTo' => 'Trở lại',
'enterYourEmail' => 'Nhập địa chỉ email của bạn bên dưới và chúng tôi sẽ gửi cho bạn các hướng dẫn về cách thay đổi mật khẩu của bạn.',
'expireDateField' => 'Trường ngày hết hạn',
'expireDate' => 'Ngày hết hạn',
'hết hạn' => 'Đã hết hạn',
'additionalFiles' => 'Tập tin bổ sung',
'relatedTopics' => 'Chủ đề liên quan',
'relatedTopicsAdd' => 'Thêm các chủ đề liên quan',
'relatedTopicsSelect' => 'Chọn mục trang Để tải Chủ đề',
'customFields' => 'Các trường bổ sung',
'customFieldsTitle' => 'Tiêu đề trường',
'customFieldsType' => 'Loại trường',
'customFieldsStatus' => 'Trạng thái Trường',
'customFieldsNewField' => 'Thêm trường Mới',
'customFieldsEditField' => 'Hiệu chỉnh trường',
'customFieldsRequired' => 'Bắt buộc',
'customFieldsOptional' => 'Tùy chọn',
'customFieldsDefault' => 'Giá trị mặc định',
'customFieldsOptions' => 'Tùy chọn',
'customFieldsOptionsHelp' => 'Gõ mọi tuỳ chọn vào dòng riêng',
'customFieldsForAllLang' => 'Dành cho mọi ngôn ngữ',
'customFieldsType0' => 'Hộp văn bản',
'customFieldsType1' => 'Văn bản Diện tích',
'customFieldsType2' => 'Số',
'customFieldsType3' => 'Địa chỉ Email',
'customFieldsType4' => 'Ngày',
'customFieldsType5' => 'Ngày & Giờ',
'customFieldsType6' => 'Chọn',
'customFieldsType7' => 'Kiểm tra nhiều lần',
'customFieldsType8' => 'Photo File',
'customFieldsType9' => 'Đính kèm tệp',
'customFieldsType10' => 'Video File',
'customFieldsType11' => 'Youtube Video Link',
'customFieldsType12' => 'Vimeo Video Link',
'optionalFields' => 'Trường tùy chọn',
'additionalTabs' => 'Tab bổ sung',
'active_disable' => 'Hoạt động / Vô hiệu hoá',
'friendlyURL' => 'URL thân thiện',
'seoTabSettings' => 'Quản lý tiêu đề trang, mô tả meta, từ khoá và URL thân thiện. Điều này giúp bạn quản lý chủ đề này hiển thị trên các công cụ tìm kiếm như thế nào. ',
'friendlyURLinks' => 'Loại URL Giao diện Người dùng',
'friendlyURLinks1' => 'URL mặc định',
'friendlyURLinks2' => 'Công cụ tìm kiếm URL thân thiện',
'registrationSettings' => 'Cài đặt Đăng ký',
'allowRegister' => 'Cho phép đăng ký cho Backend',
'permissionForNewUsers' => 'Nhóm quyền cho đăng ký mới',
'createNewAccount' => 'Tạo tài khoản mới',
'APIStatus' => 'RESTful API status',
'APIKey' => 'Khóa API',
'APIKeyGenerate' => 'Tạo ra một khóa API mới',
'APIKeyConfirm' => 'Bạn có chắc chắn muốn tạo một khóa API mới?',
'homeRow_3' => 'Trang chủ Nội dung ROW 3',
'partners' => 'Liên kết',
'draftDoc' => 'Góp ý Dự thảo VB',
'dataManagements' => 'Quản lý dữ liệu',
'dataManagements1' => 'Chỉ riêng dữ liệu riêng của mình (đối với tài khoản cá nhân)',
'dataManagements2' => 'Tất cả người dùng dữ liệu (đối với Tài khoản Quản trị Chung)',
'activitiesHistory' => 'Lịch sử Hoạt động',
'usersBackup' => 'Sao lưu & Khôi phục',
'curlBHT' => 'Báo Hà Tĩnh',
'bannerLinkUrl' => 'Đường dẫn banner',
'request' => 'Phản ảnh, kiến nghị',
'q&a' => 'Trao đổi, Hỏi đáp',
'co-op' => 'Thông tin doanh nghiệp',
'de-tai-khoa-hoc' => 'Đề tài khoa học',
'tuyen-truyen' => 'Tuyên truyền',
'Header-Banner' => 'Banner Chính',
'curlBCP' => 'Báo Chính phủ',
'quy-hoach' => 'Quy hoạch',
'lien-he' => 'Liên hệ',
'gop-y' => 'Góp ý',
'phone' => 'Điện thoại',
'address' => 'Địa chỉ',
'passport' => 'Số CMND/Hộ chiếu',
'nguoi-phat-ngon' => 'Người phát ngôn',
'dau-thau-mua-sam-cong' => 'Đấu thầu, mua sắm công',
'phong-vien-thuong-tru' => 'Phóng viên thường trú',
'nga3dongloc' => 'Ngã ba Đồng Lộc',
'bando' => 'Bản đồ',
'sumTopic' => 'Tóm tắt',
'dvyte' => 'Dịch vụ y tế',
'ythatinh' => 'Y tế Hà Tĩnh',
'thoi-su' => 'Thời sự',
'gioi-thieu' => 'Giới thiệu',
'tin-trong-tinh' => 'Tin trong tỉnh',
'tin-trong-nuoc' => 'Tin trong nước',
'the-thao-giai-tri' => 'Thể thao giải trí',
'the-gioi' => 'Thế giới',
'su-kien' => 'Sự kiện',
'khoa-hoc-cong-nghe' => 'Khoa học & Công nghệ',
'doi-song' => 'Đời sống',
'hinh-anh' => 'Hình ảnh',
'chuyen-muc' => 'Chuyên mục',
'chuyen-de' => 'Chuyên đề',
'ps-ks-ptl-td' => 'Phóng sự, Kí sự, Phim TL, Tọa đàm',
'van-nghe' => 'Văn nghệ',
'truyen-hinh' => 'Truyền hình',
'tap-chi' => 'Tạp chí',
'group' => 'Nhóm',
'lich-phat-thanh' => 'Lịch phát thanh',
'lich-truyen-hinh' => 'Lịch truyền hình',
'adsLps' => 'Thêm lịch phát sóng',
'Lpsection' => 'Loại',
'ytlist' => 'Youtube Playlist',
'sapoField' => 'Sapo',
);
<file_sep>/app/Topic.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Spatie\Feed\Feedable;
use Spatie\Feed\FeedItem;
class Topic extends Model implements Feedable
{
//Relation to webmasterSections
public function webmasterSection()
{
return $this->belongsTo('App\WebmasterSection', 'webmaster_id');
}
// Relation to Sections
public function section()
{
return $this->belongsTo('App\Section', 'section_id');
}
//Relation to TopicCategory
public function categories()
{
return $this->hasMany('App\TopicCategory','topic_id');
}
//Relation to Users
public function user()
{
return $this->belongsTo('App\User', 'created_by');
}
//Relation to Users
public function edituser()
{
return $this->belongsTo('App\User', 'updated_by');
}
//Relation to Photos
public function photos()
{
return $this->hasMany('App\Photo', 'topic_id')->orderby('row_no', 'asc');
}
//Relation to Attach Files
public function attachFiles()
{
return $this->hasMany('App\AttachFile', 'topic_id')->orderby('row_no', 'asc');
}
//Relation to Related Topics
public function relatedTopics()
{
return $this->hasMany('App\RelatedTopic', 'topic_id')->orderby('row_no', 'asc');
}
//Relation to Maps
public function maps()
{
return $this->hasMany('App\Map', 'topic_id')->orderby('row_no', 'asc');
}
//Relation to Comments
public function comments()
{
return $this->hasMany('App\Comment', 'topic_id')->orderby('row_no', 'asc');
}
//Relation to New Comments
public function newComments()
{
return $this->hasMany('App\Comment', 'topic_id')->where('status', '=', 0)->orderby('row_no', 'asc');
}
//Relation to approved Comments
public function approvedComments()
{
return $this->hasMany('App\Comment', 'topic_id')->where('status', '=', 1)->orderby('row_no', 'asc');
}
//Relation to Additional Fields
public function fields()
{
return $this->hasMany('App\TopicField', 'topic_id')->orderby('id', 'asc');
}
public function toFeedItem()
{
return FeedItem::create()
->id($this->id)
->title($this->title_vi)
->summary($this->title_vi)
->updated($this->updated_at)
->link($this->seo_url_slug_vi)
->author($this->user->name);
}
public static function getFeedItems()
{
return Topic::where('status','1')->orderby('id','desc')->take(20)->get();
}
}
<file_sep>/app/Http/Controllers/AjaxController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Lps;
use App\TypeLps;
class AjaxController extends Controller
{
public function LichTruyenHinh(Request $request)
{
$date = Carbon::parse($request->ngay)->format('Y-m-d');
$date= date('Y-m-d', strtotime($date. ' + 1 days'));
$Lps = Lps::where('section_id',1)->where('ngay_ps','LIKE',$date.'%')->orderby('gio_ps','asc')->get();
// $Lpss = Lps::all();
// echo Carbon::parse($request->ngay)->add(1, 'day')->format('Y-m-d');
//echo $date;
foreach ($Lps as $lps){
$time = Carbon::parse($lps->gio_ps)->format('H:i');
echo "<div class=\"item\">
<div class=\"calendar-item\">
<div class=\"time\">$time</div>
<div class=\"name\">
<strong>
$lps->chuong_trinh
</strong>
<br>
$lps->noi_dung
</div>
</div>
</div>";
// echo "123";
}
}
public function LichPhatThanh(Request $request)
{
$date = Carbon::parse($request->ngay)->format('Y-m-d');
$date= date('Y-m-d', strtotime($date. ' + 1 days'));
$Lps = Lps::where('section_id',2)->where('date','LIKE',$date.'%')->orderby('time','asc')->get();
foreach ($Lps as $lps){
$time = Carbon::parse($lps->time)->format('h:i');
$type = TypeLps::find($lps->type_id);
echo "<div class=\"item\">
<div class=\"calendar-item\">
<div class=\"time\">$time</div>
<div class=\"name\">
<strong>
$type->title
</strong>
<br>
$lps->title
</div>
</div>
</div>";
}
}
}
<file_sep>/public/cache/update-cache.php
<?php
/*
* Caches API calls to a local file which is updated on a
* given time interval.
*/
$cache_file = $_REQUEST['cacheFile'];
if( get_magic_quotes_gpc() ) {
$playlist = stripcslashes( $_REQUEST['playlist'] );
}
else {
$playlist = $_REQUEST['playlist'];
}
// $playlist = json_encode($playlist);
// update the cache if past interval time
$fp = fopen($cache_file, 'w+'); // open or create cache
if ($fp) {
if (flock($fp, LOCK_EX)) {
fwrite($fp, $playlist);
flock($fp, LOCK_UN);
}
fclose($fp);
}<file_sep>/app/WebmasterLps.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class WebmasterLps extends Model
{
//
public function lps()
{
return $this->hasMany('App\Lps', 'section_id');
}
}
<file_sep>/resources/assets/js/light.js
$(document).ready(function(){
$("#shadow").css("height", $(document).height()).hide();
$(".lightSwitcher").click(function(){
$("#shadow").toggle();
if ($("#shadow").is(":hidden")){
$(this).html("Tắt Đèn").removeClass("turnedOff");
}else{
$(this).html("Bật Đèn").addClass("turnedOff");
}
});
});
<file_sep>/resources/lang/vi/frontLang.php
<?php
return array (
'dashboard' => 'Quản trị',
'toTop' => 'Lên đầu trang',
'AllRightsReserved' => 'Tất cả các Quyền',
'moreDetails' => 'Chi tiết khác',
'viewMore' => 'Xem nhiều hơn',
'readMore' => 'Đọc thêm',
'downloadAttach' => 'Tải xuống tệp đính kèm',
'contactDetails' => 'Thông tin liên lạc',
'callUs' => 'Gọi cho chúng tôi',
'callFax' => 'Fax',
'callMobile' => 'Điện thoại di động',
'callPhone' => 'Điện thoại',
'callTimes' => 'Thời gian làm việc',
'address' => 'Địa chỉ',
'name' => 'Tên',
'email' => 'Email',
'phone' => 'Điện thoại',
'latestNews' => 'Tin mới nhất',
'ourGallery' => 'Thư viện của chúng tôi',
'subscribeToOurNewsletter' => 'Đăng ký nhận bản tin của chúng tôi',
'subscribeToOurNewsletterDone' => 'Bạn đã Đăng ký',
'subscribeToOurNewsletterError' => 'Bạn Đã Đăng ký',
'newsletter' => 'Bản tin của chúng tôi',
'subscribe' => 'Đăng ký',
'yourEmail' => 'Email của bạn',
'yourName' => 'Tên bạn',
'enterYourName' => '<NAME>',
'enterYourEmail' => 'Hãy nhập địa chỉ email của bạn',
'enterYourPhone' => 'Hãy nhập số điện thoại của bạn',
'enterYourSubject' => 'Vui lòng nhập chủ đề cho tin nhắn của bạn',
'enterYourMessage' => 'Hãy nhập thông điệp của bạn',
'youMessageSent' => 'Thư của bạn đã được gửi thành công, chúng tôi sẽ liên lạc với bạn càng sớm càng tốt. Cảm ơn bạn!',
'youMessageNotSent' => 'Lỗi: Vui lòng thử lại',
'subject' => 'Tiêu đề',
'message' => 'Tin nhắn',
'sendMessage' => 'Gửi tin nhắn',
'workingHours' => 'Giờ làm việc',
'categories' => 'Danh mục',
'noData' => 'Không có dữ liệu cho đến bây giờ',
'most Viewed' => 'Được xem nhiều nhất',
'share' => 'Chia sẻ',
'locationMap' => 'Bản Đồ Địa Điểm',
'comments' => 'Bình luận',
'comment' => 'Bình luận',
'enterYourComment' => 'Hãy nhập bình luận của bạn',
'sendComment' => 'Gửi nhận xét',
'youCommentSent' => 'Bình luận của bạn đã được gửi thành công. Cảm ơn bạn!',
'newComment' => 'Thêm nhận xét mới',
'refresh' => 'Làm mới',
'getInTouch' => 'Hãy liên lạc với chúng tôi bằng cách điền vào mẫu dưới đây',
'homeContents1Title' => 'Các bài báo mới nhất',
'homeContents1desc' => 'Các bài báo mới nhất từ blog của chúng tôi, bạn có thể duyệt nhiều hơn',
'homeContents2Title' => 'Tác phẩm gần đây',
'homeContents2desc' => 'Một số tác phẩm mới nhất của chúng tôi, bạn có thể duyệt nhiều hơn',
'search' => 'Tìm kiếm ...',
'visits' => 'Visits',
'orderForm' => 'Đặt hàng mẫu',
'quantity' => 'Số lượng',
'yourQuantity' => 'Hãy nhập số',
'notes' => 'Ghi chú',
'sendOrder' => 'Gửi đơn hàng',
'youOrderSent' => 'Đơn đặt hàng của bạn đã được gửi thành công. Chúng tôi sẽ liên hệ với bạn ngay khi có thể.',
'đối tác' => 'Đối tác của chúng tôi',
'partnersMsg' => 'Hợp tác lâu dài với các công ty hàng đầu trong nước và quốc tế',
'hotNews' => 'Tin Nổi bật',
'mostViewed' => 'Tin đọc nhiều',
'partners' => 'Liên kết',
'map' => 'Bản đồ địa giới',
'events' => 'Sự kiện',
'sponsers' => 'Do<NAME>ệp',
'sumTopic' => 'Tóm tắt',
'thoi-su' => 'Thời sự',
);
<file_sep>/app/Lps.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Lps extends Model
{
//Relation to Users
public function user()
{
return $this->belongsTo('App\User', 'created_by');
}
//Relation to Users
public function edituser()
{
return $this->belongsTo('App\User', 'updated_by');
}
//
public function webmasterLps()
{
return $this->belongsTo('App\WebmasterLps', 'section_id');
}
public function typeLps()
{
return $this->belongsTo('App\TypeLps', 'type_id');
}
}
<file_sep>/resources/views/httv/includes/phat-thanh.blade.2.php
<style>html,body{margin:0;}</style>
<style> .video-js {width: 100%; height: 100%;} #videojs {width: 100%; height: 100%;}</style>
<meta name="referrer" content="no-referrer">
<!-- jQuery JS -->
<script src="{{ URL::asset('httv/js/vendor/jquery-1.12.0.min.js') }}"></script>
<link href="/httv/css/video-js.min.css" rel="stylesheet">
<script src="/httv/js/videojs-ie8.min.js"></script>
<script src="/httv/js/video.min.js"></script>
<script src="/httv/js/videojs-contrib-hls.min.js"></script>
<script src="/httv/js/vjs-hls.min.js"></script>
<style>
@import url(https://fonts.googleapis.com/css?family=Oswald:300);
* { box-sizing: border-box; }
html { width: 100%; height: 100%; overflow: hidden; background: #1f323e; background: radial-gradient(80% 0%, ellipse cover, rgba(66,97,104,1) 0%,rgba(49,67,74,.1) 100%), radial-gradient(20% 100%, ellipse cover, rgba(8,13,17,1) 0%,rgba(36,58,67,1) 100%); }
body {
font-family: 'Oswald', sans-serif;
}
video { border-radius: 6px; }
/* video container */
.videoContainer{
width:380px;
height:163px;
position:relative;
overflow:hidden;
background:#000;
color:#ccc;
border-radius: 6px;
border: 1px solid rgba(0,0,0,0.8);
box-shadow: 0 0 5px rgba(0,0,0,0.5);
margin: 50px auto 0;
}
.videoContainer:before {
content: '';
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
box-shadow: inset 0 1px 2px rgba(255,255,255,0.3);
z-index: 6;
border-radius: 6px;
pointer-events: none;
}
/* video caption css */
.caption{
display:none;
position:absolute;
top:0;
left:0;
width:100%;
padding: 5px 10px;
color:#ddd;
font-size:14px;
font-weight:300;
text-align: center;
background: rgba(0,0,0,0.4);
text-transform: uppercase;
border-radius: 6px 6px 0 0;
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
-ms-backface-visibility: hidden;
}
/*** VIDEO CONTROLS CSS ***/
/* control holder */
.control{
color:#ccc;
position:absolute;
bottom:10px;
left:10px;
width:360px;
z-index:5;
display:none;
}
/* control bottom part */
.btmControl{
clear:both;
}
.control .btnPlay {
float:left;
width:34px;
height:30px;
padding:5px;
background: rgba(0,0,0,0.5);
cursor:pointer;
border-radius: 6px 0 0 6px;
border: 1px solid rgba(0,0,0,0.7);
box-shadow: inset 0 0 1px rgba(255,255,255,0.5);
}
.control .icon-play{
background:url(https://s.cdpn.io/6035/vp_sprite.png) no-repeat -11px 0;
width: 6px;
height: 9px;
display: block;
margin: 4px 0 0 8px;
}
.control .icon-pause{
background:url(https://s.cdpn.io/6035/vp_sprite.png) no-repeat -34px -1px;
width: 8px;
height: 9px;
display: block;
margin: 4px 0 0 8px;
}
.control .selected{
font-size:15px;
color:#ccc;
}
.control .sound{
width: 30px;
height: 30px;
float:left;
background: rgba(0,0,0,0.5);
border: 1px solid rgba(0,0,0,0.7);
border-left: none;
box-shadow: inset 0 0 1px rgba(255,255,255,0.5);
cursor: pointer;
}
.control .icon-sound {
background:url(https://s.cdpn.io/6035/vp_sprite.png) no-repeat -19px 0;
width: 13px;
height: 10px;
display: block;
margin: 8px 0 0 8px;
}
.control .muted .icon-sound{
width: 7px !important;
}
.control .btnFS{
width: 30px;
height: 30px;
border-radius: 0 6px 6px 0;
float:left;
background: rgba(0,0,0,0.5);
border: 1px solid rgba(0,0,0,0.7);
border-left: none;
box-shadow: inset 0 0 1px rgba(255,255,255,0.5);
}
.control .icon-fullscreen {
background:url(https://s.cdpn.io/6035/vp_sprite.png) no-repeat 0 0;
width: 10px;
height: 10px;
display: block;
margin: 8px 0 0 9px;
}
/* PROGRESS BAR CSS */
/* Progress bar */
.progress-bar {
height: 30px;
padding: 10px;
background: rgba(0,0,0,0.6);
border: 1px solid rgba(0,0,0,0.7);
border-left: none;
box-shadow: inset 0 0 1px rgba(255,255,255,0.5);
float:left;
}
.progress {
width:240px;
height:7px;
position:relative;
cursor:pointer;
background: rgba(0,0,0,0.4); /* fallback */
box-shadow: 0 1px 0 rgba(255,255,255,0.1), inset 0 1px 1px rgba(0,0,0,1);
border-radius:10px;
}
.progress span {
height:100%;
position:absolute;
top:0;
left:0;
display:block;
border-radius:10px;
}
.timeBar{
z-index:10;
width:0;
background: -webkit-linear-gradient(top, rgba(107,204,226,1) 0%,rgba(29,163,208,1) 100%);
box-shadow: 0 0 7px rgba(107,204,226,.5);
}
.bufferBar{
z-index:5;
width:0;
background: rgba(255,255,255,0.2);
}
/* VOLUME BAR CSS */
/* volume bar */
.volume{
position:relative;
cursor:pointer;
width:70px;
height:10px;
float:right;
margin-top:10px;
margin-right:10px;
}
.volumeBar{
display:block;
height:100%;
position:absolute;
top:0;
left:0;
background-color:#eee;
z-index:10;
}
</style>
<body onLoad="init()">
<section id="wrapper">
<div class="videoContainer">
<video id="myVideo" controls preload="auto" poster="https://s.cdpn.io/6035/vp_poster.jpg" width="380" >
<p>Your browser does not support the video tag.</p>
</video>
<div class="caption">Prometheus</div>
<div class="control">
<div class="btmControl">
<div class="btnPlay btn" title="Play/Pause video"><span class="icon-play"></span></div>
<div class="progress-bar">
<div class="progress">
<span class="bufferBar"></span>
<span class="timeBar"></span>
</div>
</div>
<!--<div class="volume" title="Set volume">
<span class="volumeBar"></span>
</div>-->
<div class="sound btn muted" title="Mute/Unmute sound"><span class="icon-sound"></span></div>
<div class="btnFS btn" title="Switch to full screen"><span class="icon-fullscreen"></span></div>
</div>
</div>
</div>
</section>
<script>
function play(link){
if(link.indexOf('.php')!=-1){
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET",link,!1);
xmlhttp.send();
src=xmlhttp.responseText;
}else
src=link;
player=videojs("myVideo");
player.ready(function(){
player.src({src:src,type:"application/x-mpegURL"})
});
player.play()
}
function reload(i){
if(player.paused()&&player.error_!=null){
if(i<link.length){
play(link[i])
}
}
}
function init(){
var i=0;
link=[
'http://113.160.178.167/phatthanh/m3u8/audio.m3u8'
];
play(link[i]);
interval=setInterval(function(){
i++;reload(i)
},2000)
}
$(document).ready(function(){
//INITIALIZE
var video = $('#myVideo');
//remove default control when JS loaded
video[0].removeAttribute("controls");
$('.control').fadeIn(500);
$('.caption').fadeIn(500);
//before everything get started
video.on('loadedmetadata', function() {
//set video properties
$('.current').text(timeFormat(0));
$('.duration').text(timeFormat(video[0].duration));
updateVolume(0, 0.7);
//start to get video buffering data
setTimeout(startBuffer, 150);
//bind video events
$('.videoContainer')
.hover(function() {
$('.control').stop().fadeIn();
$('.caption').stop().fadeIn();
}, function() {
if(!volumeDrag && !timeDrag){
$('.control').stop().fadeOut();
$('.caption').stop().fadeOut();
}
})
.on('click', function() {
$('.btnPlay').find('.icon-play').addClass('icon-pause').removeClass('icon-play');
$(this).unbind('click');
video[0].play();
});
});
//display video buffering bar
var startBuffer = function() {
var currentBuffer = video[0].buffered.end(0);
var maxduration = video[0].duration;
var perc = 100 * currentBuffer / maxduration;
$('.bufferBar').css('width',perc+'%');
if(currentBuffer < maxduration) {
setTimeout(startBuffer, 500);
}
};
//display current video play time
video.on('timeupdate', function() {
var currentPos = video[0].currentTime;
var maxduration = video[0].duration;
var perc = 100 * currentPos / maxduration;
$('.timeBar').css('width',perc+'%');
$('.current').text(timeFormat(currentPos));
});
//CONTROLS EVENTS
//video screen and play button clicked
video.on('click', function() { playpause(); } );
$('.btnPlay').on('click', function() { playpause(); } );
var playpause = function() {
if(video[0].paused || video[0].ended) {
$('.btnPlay').addClass('paused');
$('.btnPlay').find('.icon-play').addClass('icon-pause').removeClass('icon-play');
video[0].play();
}
else {
$('.btnPlay').removeClass('paused');
$('.btnPlay').find('.icon-pause').removeClass('icon-pause').addClass('icon-play');
video[0].pause();
}
};
//fullscreen button clicked
$('.btnFS').on('click', function() {
if($.isFunction(video[0].webkitEnterFullscreen)) {
video[0].webkitEnterFullscreen();
}
else if ($.isFunction(video[0].mozRequestFullScreen)) {
video[0].mozRequestFullScreen();
}
else {
alert('Your browsers doesn\'t support fullscreen');
}
});
//sound button clicked
$('.sound').click(function() {
video[0].muted = !video[0].muted;
$(this).toggleClass('muted');
if(video[0].muted) {
$('.volumeBar').css('width',0);
}
else{
$('.volumeBar').css('width', video[0].volume*100+'%');
}
});
//VIDEO EVENTS
//video canplay event
video.on('canplay', function() {
$('.loading').fadeOut(100);
});
//video canplaythrough event
//solve Chrome cache issue
var completeloaded = false;
video.on('canplaythrough', function() {
completeloaded = true;
});
//video ended event
video.on('ended', function() {
$('.btnPlay').removeClass('paused');
video[0].pause();
});
//video seeking event
video.on('seeking', function() {
//if video fully loaded, ignore loading screen
if(!completeloaded) {
$('.loading').fadeIn(200);
}
});
//video seeked event
video.on('seeked', function() { });
//video waiting for more data event
video.on('waiting', function() {
$('.loading').fadeIn(200);
});
//VIDEO PROGRESS BAR
//when video timebar clicked
var timeDrag = false; /* check for drag event */
$('.progress').on('mousedown', function(e) {
timeDrag = true;
updatebar(e.pageX);
});
$(document).on('mouseup', function(e) {
if(timeDrag) {
timeDrag = false;
updatebar(e.pageX);
}
});
$(document).on('mousemove', function(e) {
if(timeDrag) {
updatebar(e.pageX);
}
});
var updatebar = function(x) {
var progress = $('.progress');
//calculate drag position
//and update video currenttime
//as well as progress bar
var maxduration = video[0].duration;
var position = x - progress.offset().left;
var percentage = 100 * position / progress.width();
if(percentage > 100) {
percentage = 100;
}
if(percentage < 0) {
percentage = 0;
}
$('.timeBar').css('width',percentage+'%');
video[0].currentTime = maxduration * percentage / 100;
};
//VOLUME BAR
//volume bar event
var volumeDrag = false;
$('.volume').on('mousedown', function(e) {
volumeDrag = true;
video[0].muted = false;
$('.sound').removeClass('muted');
updateVolume(e.pageX);
});
$(document).on('mouseup', function(e) {
if(volumeDrag) {
volumeDrag = false;
updateVolume(e.pageX);
}
});
$(document).on('mousemove', function(e) {
if(volumeDrag) {
updateVolume(e.pageX);
}
});
var updateVolume = function(x, vol) {
var volume = $('.volume');
var percentage;
//if only volume have specificed
//then direct update volume
if(vol) {
percentage = vol * 100;
}
else {
var position = x - volume.offset().left;
percentage = 100 * position / volume.width();
}
if(percentage > 100) {
percentage = 100;
}
if(percentage < 0) {
percentage = 0;
}
//update volume bar and video volume
$('.volumeBar').css('width',percentage+'%');
video[0].volume = percentage / 100;
//change sound icon based on volume
if(video[0].volume == 0){
$('.sound').removeClass('sound2').addClass('muted');
}
else if(video[0].volume > 0.5){
$('.sound').removeClass('muted').addClass('sound2');
}
else{
$('.sound').removeClass('muted').removeClass('sound2');
}
};
//Time format converter - 00:00
var timeFormat = function(seconds){
var m = Math.floor(seconds/60)<10 ? "0"+Math.floor(seconds/60) : Math.floor(seconds/60);
var s = Math.floor(seconds-(m*60))<10 ? "0"+Math.floor(seconds-(m*60)) : Math.floor(seconds-(m*60));
return m+":"+s;
};
});
</script>
</body>
| cb01cbf8797dd91dee0967eedecb64f102b9bbe3 | [
"JavaScript",
"HTML",
"PHP"
] | 13 | HTML | dangquocdung/xprobus | ea7cbc7e794ff75aa30d72888cfd8d0a0cd526cc | 2965c84c6893937ceba3913a2245f2e752ea273a |
refs/heads/master | <file_sep>
public class myVariables {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// String Variable;
String name = "<NAME>";
name = "My Favorite Singer: " + name;
System.out.println(name);
// Integers and its Math.
int price = 38;
int tax = 2;
int total = price + tax;
System.out.println(total);
}
}
<file_sep># Java-Basics
A basic explanation of the Java Programming Language
| 59f16a4919e4b19b355c273f459285180be5d880 | [
"Markdown",
"Java"
] | 2 | Java | Edxael/Java-Basics | d545c948874d08bfde4adc707f7471c7e41fe4c0 | 7643e304f7a7836ac04789f306c63b771a92adcb |
refs/heads/master | <repo_name>bondarukoleh/react_web_app<file_sep>/server/routes/routes.paths.js
module.exports = {
authGoogle: '/auth/google',
apiLogout: '/api/logout',
apiCurrentUser: '/api/current_user',
apiTestUser: '/api/test_user',
surveys: '/api/surveys',
apiPayment: '/api/payment',
};
<file_sep>/client/src/components/UI/Modal/Modal.js
import React, {PureComponent} from 'react';
import style from './Modal.module.scss';
import Shade from '../Shade/Shade';
import PropTypes from 'prop-types';
class Modal extends PureComponent {
render() {
return (
<React.Fragment>
<Shade onClick={this.props.shadeClick} show={this.props.show}/>
<div
className={style.Modal}
style={{
transform: this.props.show ? 'translateY(0)' : 'translateY(-200vh)',
opacity: this.props.show ? '1' : '0'
}}
>
{this.props.children}
</div>
</React.Fragment>
);
}
}
Modal.propTypes = {
shadeClick: PropTypes.func.isRequired,
show: PropTypes.bool.isRequired,
};
export default Modal;
<file_sep>/client/src/components/Landing/Steps/Steps.js
import React from 'react';
import Step from "./Step/Step";
import styles from './Steps.module.scss'
import step1Icon from '../../../assets/steps/step1.svg'
import step2Icon from '../../../assets/steps/step2.svg'
import step3Icon from '../../../assets/steps/step3.svg'
import step4Icon from '../../../assets/steps/step4.svg'
const Steps = () => {
const renderSteps = () => {
const steps = [
{left: true, circleColor: 'circle_red', icon: step1Icon, stepDescription: 'Login with Google account', stepNum: 1},
{left: false, circleColor: 'circle_yellow', icon: step2Icon, stepDescription: 'Add credit', stepNum: 2},
{left: true, circleColor: 'circle_green', icon: step3Icon, stepDescription: 'Create quiz', stepNum: 3},
{left: false, circleColor: 'circle_blue', icon: step4Icon, stepDescription: 'Collect the result', stepNum: 4},
];
return steps.map(step => <Step key={step.stepNum} {...step}/>);
}
return (
<section className={styles.Steps}>
<h3 className={styles.StepExplanation}>For start you need do 4 easy steps:</h3>
{renderSteps()}
</section>
);
};
export default Steps;<file_sep>/client/src/components/App.js
import React, {Component} from 'react';
import {BrowserRouter as Router, Route, Switch} from "react-router-dom";
import Header from './Header/Header';
import Landing from './Landing/Landing';
import Footer from "./Footer/Footer";
import NewSurvey from "./Surveys/NewSurvey/NewSurvey";
import {fetchCurrentUserActionCreator} from '../actions/auth.actions';
import {connect} from 'react-redux';
import '../sass/_reset.scss'
import '../sass/_config.scss'
import Popup from "./UI/Popup/Popup";
import Surveys from "./Surveys/Surveys";
class App extends Component {
componentDidMount() {
this.props.getCurrentUser();
}
render() {
return (
<Router>
<Popup/>
<Header/>
<Switch>
{/*same as exact={true}*/}
<Route exact path="/">
<Landing/>
</Route>
<Route exact path="/surveys">
<Surveys/>
</Route>
<Route exact path="/surveys/new">
<NewSurvey/>
</Route>
</Switch>
<Footer/>
</Router>
);
}
}
const mapStateToProps = store => {
return {
user: store.auth.user
};
};
const mapDispatchToProps = dispatch => {
return {
getCurrentUser: () => dispatch(fetchCurrentUserActionCreator())
};
};
export default connect(mapStateToProps, mapDispatchToProps)(App);<file_sep>/server/db/models/recipient.js
const mongoose = require('mongoose');
const {Schema} = mongoose;
const RecipientScheme = new Schema({
email: {type: String, required: true, minlength: 5, maxlength: 50},
responded: {type: Boolean, default: false},
});
module.exports = {RecipientScheme};
<file_sep>/README.md
# Email surveys application. :mailbox:
This application helps you to create email surveys for your employees, friends, or any kind of people you want to know
opinion from.
You can easily create a survey, add recipients list, and send them emails with simple quise.
**Check out the [application][1]**:email:.
---
### For devs
To start the server in dev mode you need to check `server/config/dev.dist` [file][2].
### About app
You can find some tech information about the application [here][3].
[1]: https://olehbondaruk-emaily-server.herokuapp.com/
[2]: server/config/dev.dist
[3]: info/different.stuff.md<file_sep>/client/src/components/Surveys/SurveyField.js
import React from "react";
import styles from "./SurveyForm/SurveyForm.module.scss";
/* props here has "input" object with onBlur, onChange, onFocus etc. event handlers added by redux-form
* so we will extract those handlers to our input element we returning.
* */
const SurveyField = ({input, label, meta: {error, touched}}) => {
return (
<div className={styles.InputGroup}>
<label>{label}</label>
<input style={{marginBottom: '5px'}} {...input}/>
<div className={styles.RedText}>
{touched && error}
</div>
</div>);
};
export default SurveyField;<file_sep>/client/src/reducers/index.js
import {combineReducers} from 'redux';
import {authReducer} from './auth.reducer';
import {paymentReducer} from './payment.reducer';
import {surveyReducer} from './survey.reducer';
import {reducer as surveyFormReducer} from "redux-form";
export const rootReducer = combineReducers({
form: surveyFormReducer, // name should be "form", all forms of redux-form - will be connected to this property
auth: authReducer,
payment: paymentReducer,
survey: surveyReducer,
});<file_sep>/server/helpers/emails/index.js
const {Mailer} = require('./Mailer');
const templates = require('./templates');
module.exports = {Mailer, templates};<file_sep>/server/routes/test.user.js
const express = require('express');
const router = express.Router();
const paths = require('./routes.paths');
const passport = require('passport'), LocalStrategy = require('passport-local').Strategy;
router.post('/',
passport.authenticate('local', {failureRedirect: '/login'}), (req, res) => {return res.send(200);}
);
module.exports = {handler: router, path: paths.apiTestUser};
<file_sep>/client/src/components/Landing/Landing.js
import React, {Component} from "react";
import {connect} from 'react-redux';
import {Link} from "react-router-dom";
import styles from './Landing.module.scss'
import greetingImage from '../../assets/greeting.png'
import Steps from "./Steps/Steps";
class Landing extends Component {
render() {
const {user} = this.props;
return (
<main id='main' className={styles.Content}>
<section className={styles.Greeting}>
<h1>Create your quiz with fast response</h1>
<img src={greetingImage} alt="Greeting_picture"/>
{user
? <Link to='/surveys' className={styles.btn_red}>Got to your surveys.</Link>
: <a href="/auth/google" className={styles.btn_red}>Login with Google</a>
}
</section>
<Steps/>
</main>
)
}
}
const mapStateToProps = store => {
return {
user: store.auth.user
};
};
export default connect(mapStateToProps)(Landing);
<file_sep>/server/config/production.js
const {
GOOGLE_CLIENT_ID,
GOOGLE_CLIENT_SECRET,
DB_USER,
DB_PASS,
DB_NAME,
DB_HOST,
COOKIE_KEY,
STRIPE_PUB_KEY,
STRIPE_SEC_KEY,
MAIL_SERVER_KEY,
HOST,
} = process.env;
module.exports = {
GOOGLE_CLIENT_ID,
GOOGLE_CLIENT_SECRET,
DB_USER,
DB_PASS,
DB_NAME,
DB_HOST,
COOKIE_KEY,
STRIPE_PUB_KEY,
STRIPE_SEC_KEY,
MAIL_SERVER_KEY,
HOST,
};<file_sep>/client/src/components/Payment/Payments.js
import React, {Component} from "react";
import {connect} from 'react-redux';
import StripeCheckout from "react-stripe-checkout";
import {sendUserPaymentToken} from '../../actions/payment.actions';
import styles from './Payment.module.scss'
const {REACT_APP_STRIPE_PUB_KEY} = process.env;
class Payments extends Component {
stripePaymentCallback = (tokenObj) => {
console.log(`Your token id ${tokenObj.id}, email - ${tokenObj.email}`);
const {sendPaymentToken} = this.props;
sendPaymentToken(tokenObj);
};
render() {
return (
<StripeCheckout
amount={500} // amount cents to pay
token={this.stripePaymentCallback} // callback after authorization with card details in stripe vendor is done
stripeKey={REACT_APP_STRIPE_PUB_KEY}
name="Quick Quiz"
description="5$ for 5 email credits"
>
<button className={styles.btn_red}>Add credits</button>
</StripeCheckout>
);
}
}
const mapStateToProps = store => {
return {
user: store.auth.user
};
};
const mapDispatchToProps = dispatch => {
return {
sendPaymentToken: (token) => dispatch(sendUserPaymentToken(token))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Payments);<file_sep>/server/db/mongoose.client.js
const mongooseClient = require('mongoose');
const {DB_USER: user, DB_PASS: <PASSWORD>, DB_NAME: name, DB_HOST: host} = require('../config');
const defaultOption = {retryWrites: true, w: 'majority', useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false};
const getDbUrl = () => `mongodb+srv://${user}:${password}@${host}`;
class Mongoose {
constructor({dbUrl = getDbUrl(), options = defaultOption} = {}) {
this.mongoose = mongooseClient;
this.dbUrl = dbUrl;
this.options = options;
this.connection = null;
this.connectionUrl = null;
}
async connect(database = name) {
try {
this.connectionUrl = `${this.dbUrl}/${database}`;
console.log(`Connecting to: ${this.connectionUrl}, with options: %j`, this.options);
this.connection = await this.mongoose.connect(this.connectionUrl, this.options);
console.log(`DB connected: ${this.dbUrl}`);
} catch (e) {
console.log(`Fail to connect to DB: ${e.message}`);
throw new Error(`Error while connecting to DB: "${e.message}"`);
}
return this.connection;
}
async disconnect() {
try {
console.log(`Disconnecting from: ${this.dbUrl}, with options: %j`, this.options);
await this.connection.connection.close();
console.log(`BD disconnected: ${this.dbUrl}`);
} catch (e) {
console.log(`Fail to disconnect to DB: ${e.message}`);
throw new Error(`Error while connecting to DB: "${e.message}"`);
}
}
}
module.exports = Mongoose;
<file_sep>/server/helpers/emails/Mailer.js
const sendGrid = require('@sendgrid/mail');
const {MAIL_SERVER_KEY} = require('../../config');
sendGrid.setApiKey(MAIL_SERVER_KEY);
class Mailer {
constructor({fromEmail, subject, content, recipients}) {
this.subject = subject;
this.content = content;
this.recipients = recipients;
this.from_email = fromEmail;
}
async sendSurvey() {
const request = {
to: this.recipients,
subject: this.subject,
html: this.content,
from: this.from_email,
trackingSettings: {
clickTracking: {
enable: true
},
},
};
return sendGrid.sendMultiple(request);
}
}
module.exports = {Mailer};<file_sep>/client/src/components/Footer/Footer.js
import React from 'react';
import styles from './Footer.module.scss'
import {withRouter} from "react-router-dom";
const Footer = (props) => {
const classes = [styles.Footer];
props.location.pathname !== '/' && classes.push(styles.FixedFooter);
return (<footer id='footer' className={classes.join(' ')}>
<p>Copyright © 2020. All Rights Reserved</p>
</footer>);
};
export default withRouter(Footer);<file_sep>/server/db/models/index.js
const dbModels = {
user: require('./user.model'),
survey: require('./survey'),
};
module.exports = dbModels;
<file_sep>/client/src/components/Header/Header.js
import React, {Component} from "react";
import {connect} from 'react-redux';
import {Link} from 'react-router-dom';
import logo from '../../assets/logo.svg';
import styles from './Header.module.scss'
import HamburgerMenu from "./HamburgerMenu/HamburgerMenu";
import NavItems from "./NavItems/NavItems";
class Header extends Component {
state = {
showSurveyError: false,
showSurveySuccess: false,
showSideMenu: false
};
componentDidMount() {
const {showSurveyError, showSurveySuccess, error} = this.state;
if (showSurveyError) {
setTimeout(() => {
this.setState({showSurveyError: false});
}, 5000);
return <h5 className="red-text">{`Survey was not send, something went wrong, sorry ${error && error}`}</h5>;
}
if (showSurveySuccess) {
setTimeout(() => {
this.setState({showSurveySuccess: false});
}, 5000);
return <h5 className="green-text">Survey was send successfully!</h5>;
}
}
changeShowState = () => this.setState(({showSideMenu}) => ({showSideMenu: !showSideMenu}))
render() {
return (
<header id='header' className={styles.Header}>
<HamburgerMenu clicked={this.changeShowState} sideMenuShown={this.state.showSideMenu}/>
<nav className={styles.Navbar}>
<div>
<Link className={styles.Logo} to={'/'}>
<img src={logo} alt="Logo"/>
</Link>
</div>
<NavItems sideMenuShown={false}/>
</nav>
</header>
);
}
}
const mapStateToProps = store => {
return {
user: store.auth.user,
};
};
export default connect(mapStateToProps)(Header);<file_sep>/server/services/index.js
const {useGoogleAuth, useLocalStrategy} = require('./passport');
const pluginRoutes = require('./routes');
const serveProdBuild = require('./production');
module.exports = {
useGoogleAuth,
useLocalStrategy,
pluginRoutes,
serveProdBuild,
};
<file_sep>/server/routes/surveys.js
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const {URL} = require('url');
const {Path} = require('path-parser');
const paths = require('./routes.paths');
const {isLoggedIn, hasCredits} = require('../middleware/authorization');
const {templates, Mailer} = require('../helpers/emails');
const Survey = mongoose.model('survey');
const isClickEvent = (eventObj) => eventObj.event === 'click' && eventObj.url;
const extractSurveyIdAndAnswer = ({url, email}) => {
const urlObject = new URL(url);
const parsedPath = new Path('/api/surveys/:surveyID/:answer').test(urlObject.pathname);
if (parsedPath) {
return {email, surveyID: parsedPath.surveyID, answer: parsedPath.answer};
}
};
const updateDBSurvey = ({email, surveyID, answer}) => {
// instead of finding survey by id, find a recipient by email, change him, then change it, and return whole
// list or Surveys back - we will sent only one query, that will cover all the actions
Survey.updateOne({_id: surveyID, recipients: {$elemMatch: {email, responded: false}}},
{$inc: {[answer]: 1}, $set: {'recipients.$.responded': true}, lastResponded: Date.now()}
).exec()
.catch(console.log);
};
router.post('/', [isLoggedIn, hasCredits], async (req, res) => {
let {title, subject, body, recipients} = req.body;
recipients = recipients.split(',').map(email => ({email: email.trim().toLowerCase()}));
const survey = new Survey({
title,
subject,
body,
recipients,
_user: req.user.id,
dateSent: Date.now(),
});
/* sendgrid - will add an uniq id to every link from the email we send thru him, so when user click it - we know
* which distinguish user has done it. We could also add the id (connected to particular user) to url query and
* figure out who clicked it. Links that inform application that something just happened called webhooks, or web
* callbacks or reverse API */
const mailerConfig = {
fromEmail: '<EMAIL>',
subject,
recipients: recipients.map(({email}) => email),
content: templates.surveyTemplate(survey)
};
const mailer = new Mailer(mailerConfig);
try {
await mailer.sendSurvey();
await survey.save();
req.user.credit -= 1;
const user = await req.user.save();
return res.send(user);
} catch (error) {
// Log friendly error
console.error(error);
if (error.response) {
// Extract error msg
const {message, code, response} = error;
const {headers, body} = response;
console.error(body);
}
return res.status(422).send({error: `Couldn't send the survey! ${error.message}`});
}
});
// this url is added as webhook to sendgrid mail settings
router.post('/webhook', async (req, res) => {
let clickEvents = [];
if (req.body.length) {
clickEvents = req.body.filter(isClickEvent);
}
if (clickEvents.length) {
clickEvents = clickEvents.map(extractSurveyIdAndAnswer).filter(v => v && v); // filter undefined
}
if (clickEvents.length) {
try {
clickEvents.map(updateDBSurvey);
} catch (e) {
return res.status(500).send({message: e});
}
return res.send({message: 'Thanks, got the hook data.'});
}
console.log('we got some unneeded data');
res.send({message: 'no needed hook data received'});
});
// TODO: move to the client side
router.get('/:surveyID/:answer', (req, res) => {
res.send(`
<html lang="en">
<body style="background-color: #cad8f8;">
<div style="display: flex; justify-content: center; align-items: center; font-family: Arial, serif;">
<h1>Thank you for your participation!</h1>
</div>
</body>
</html>
`);
});
router.get('/', isLoggedIn, async (req, res) => {
let surveys = [];
try {
surveys = await Survey.find({_user: req.user.id}).select({recipients: false});
surveys = surveys.map(survey => ({
body: survey.body,
dateSent: survey.dateSent,
lastResponded: survey.lastResponded,
no: survey.no,
subject: survey.subject,
title: survey.title,
yes: survey.yes,
id: survey._id
}));
} catch (e) {
res.status(500).send({error: `Couldn't get the surveys`});
}
res.send(surveys);
});
router.delete('/:id', isLoggedIn, async (req, res) => {
const survey = await Survey.findByIdAndRemove({_id: req.params.id});
if(!survey) return res.status(404).send({error: `Survey with id: "${req.params.id}" is not found.`});
return res.send({id: survey._id});
});
module.exports = {handler: router, path: paths.surveys};
<file_sep>/server/db/models/survey.js
const mongoose = require('mongoose');
const {Schema} = mongoose;
const {RecipientScheme} = require('./recipient');
const surveyScheme = new Schema({
title: {type: String, required: true},
subject: {type: String, required: true},
body: {type: String, required: true},
recipients: {type: [RecipientScheme], required: true},
yes: {type: Number, default: 0},
no: {type: Number, default: 0},
_user: {type: Schema.Types.ObjectID, ref: 'user'},
dateSent: Date,
lastResponded: Date,
});
const Model = mongoose.model('survey', surveyScheme);
module.exports = {Model};
<file_sep>/client/src/components/Header/NavItems/NavItems.js
import React, {Fragment} from 'react';
import styles from "./NavItems.module.scss";
import userIcon from "../../../assets/user_icon.svg";
import Payments from "../../Payment/Payments";
import {connect} from "react-redux";
import PropTypes from "prop-types";
import axios from "axios";
function NavItems(props) {
const showHeaderContent = () => {
const {user} = props;
if (user === null) {
return <li>Fetching user data...</li>
} else if (user === false) {
return <Fragment>
<li><a href="/auth/google" className={styles.btn_red}>Login with Google</a></li>
<li><a onClick={() => axios.post('/api/test_user', {
username: 'Test User', password: <PASSWORD>
}).then(_ => {
/* I don't know why, but it's not working in the way it works with 'google' auth. Need to investigate */
window.location.reload();
})} className={styles.btn_red}>Test User</a></li>
</Fragment>
} else {
return <React.Fragment>
<li><span>{`Hi ${user.name}!`}</span><span className={styles.Space}> </span>
<span>{` You have credits: ${user.credit ? user.credit : 0}`}</span><img src={userIcon} alt="user_icon"/></li>
<li id="add_credits"><Payments/></li>
<li><a href="/api/logout" className={props.sideMenuShown ? styles.btn_grey : styles.btn_dark}>Logout</a></li>
{/*We will sent full request to backend with browser refresh,
but we also could handle this click via creating action "USER_LOGOUT", make inner ajax request to backend,
without refresh, clear store etc.*/}
</React.Fragment>;
}
};
const classes = [styles.NavItems];
props.sideMenuShown && classes.push(styles.InSideMenu)
return <ul className={classes.join(' ')}>
{showHeaderContent()}
</ul>;
}
const mapStateToProps = store => {
return {
user: store.auth.user,
};
};
NavItems.propTypes = {
sideMenuShown: PropTypes.bool.isRequired
}
export default connect(mapStateToProps)(NavItems);
<file_sep>/client/src/reducers/survey.reducer.js
import {SurveyActions} from '../actions/survey.actions';
const initialState = {
surveySend: null,
fetchSurveys: null,
deleteSurvey: null
};
export function surveyReducer(state = initialState, action) {
switch (action.type) {
case SurveyActions.surveySendFail:
return {...state, surveySend: action.payload};
case SurveyActions.surveySendSuccess:
return {...state, surveySend: action.payload};
case SurveyActions.fetchSurveysSuccess:
return {...state, fetchSurveys: action.payload};
case SurveyActions.fetchSurveysFail:
return {...state, fetchSurveys: action.payload};
case SurveyActions.deleteSurveySuccess:
return {...state, deleteSurvey: action.payload};
case SurveyActions.deleteSurveyFail:
return {...state, deleteSurvey: action.payload};
default:
return state;
}
}<file_sep>/client/src/actions/payment.actions.js
import axios from 'axios';
import {AuthActions} from "./auth.actions";
export const BillingActions = {
billingFail: 'BILLING_FAIL'
};
export const sendUserPaymentToken = (token) => async (dispatch) => {
try {
const {data} = await axios.post('/api/payment/token', token);
if (data && data.error) {
return dispatch({
type: BillingActions.billingFail,
payload: data
});
}
dispatch({
type: AuthActions.currentUser,
payload: data
});
} catch (e) {
console.log(`Couldn't bill credit user \n`, e);
return dispatch({
type: BillingActions.billingFail,
payload: false
});
}
};<file_sep>/client/src/components/UI/Popup/Popup.js
import React, {useEffect, useState} from 'react';
import styles from './Popup.module.scss';
import {connect} from 'react-redux';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faSmileBeam, faSadTear} from '@fortawesome/free-solid-svg-icons';
function Popup(props) {
const [state, setState] = useState({showSuccess: props.sentSurvey});
const successMessage = <p><span>Survey sent successfully!</span><FontAwesomeIcon icon={faSmileBeam} size={"lg"}/></p>;
const errorMessage = <p><span>Something went wrong, sorry</span><FontAwesomeIcon icon={faSadTear} size={"lg"}/></p>;
useEffect(() => {
if (props.sentSurvey) {
setState({showError: false, showSuccess: true})
setTimeout(() => setState({showSuccess: false}), 5000);
}
}, [props.sentSurvey]);
if (state.showSuccess) {
return <div className={styles.Success}>
{successMessage}
</div>;
}
if (state.showError) {
return <div className={styles.Error}>{errorMessage}</div>;
}
return null;
}
const mapStateToProps = store => {
return {
sentSurvey: store.survey.surveySend,
error: store.error,
};
};
export default connect(mapStateToProps)(Popup);<file_sep>/info/different.stuff.md
### About everything and nothing
Every app starts from idea, and from planning what app should do and how it should be used.
We need to white a few diagrams, and pictures what the main flows.
#### Survey application flow:
1. User signs up via Google OAuth (sign with 'google' account) -> (Express, MongoDB, PassportJS)
2. User pays for email credits via a stripe -> (Stripe + MongoDB)
3. User creates a new "survey" -> (React + Redux)
4. User enters a list of emails to send question survey to -> (React + Redux + Redux Form)
5. App sends emails to list -> (Email Provider)
6. User clicks on a link in email to provide feedback -> (Express, MongoDB, Email Provider)
7. App tabulate feedback -> (Express, MongoDB)
8. Survey user can see report of all survey responses. (React + Redux + MongoDB)
App parts: \
React App <-> Express API Server <-> MongoDB. Client doesn't talk to DB directly.
`OAuth login`
1. App shows user - "Login with google". User clicks.;
2. Redirecting user to google (with our app ID) where google asks user "Do you grant permission for this app (ID)
to get info about yourself?" -> User clicks yes;
3. Google gives our app "user code" means User has granted permission;
4. App asks google to exchange "user code" on information about the User;
5. Google returns to the app User profile;
6. App creates a User record in DB, and gives User cookies (e.g. JWT). Further User requests to App User makes with cookies.
All things that related to `google auth` - is [passportJS][1] library responsibilities. \
In google [console.developers](https://console.developers.google.com/) we can add a `appID`. \
#### Setup your application
* Enable Google+ API to get OAuth2.0.
* Create a ClientID - which brings you to set up consent screen
* consent screen - one that Google shows to User, so he can grant app the permission to get his data.
* ClientID - Public token (key) of the App in google developers console. ClientSecret - is a private token (key), don't
share it.
Also, to avoid a redirect *redirect_uri_mismatch* error - you need to provide a valid redirect links in you Google dev
console that you set up to redirect to. Those links Google with match with it's "hackers base", if everything is ok -
than google will send `user access code` to your app, with this access code you can ask google to get info about the
user or some more stuff. So access code is like a permission to access user info from your app, but it expires with time,
that's why google sends you the `refresh token`, with this token you can get new `access token`.
If google complaining about the redirect mismatch - that's the heroku proxy fault.
In passport JS we can ask for `scope of information` user should give access to e.g. we can ask for photos from google
drive, contact list, calendar, a lot of stuff.
When you get the User profile, you can generate a token based on this profile and ask passport.js to stick this token
to the user cookie. This can be done with implementation of **serialize** function in passport.js, which gets a `User model
as an argument` and serialize it to `token`. \
When User will return to our app with his token - another function that we need to implement is **deserialize**, that `gets
token` as an argument and `returns the User model`.
#### cookieSession and passport
`cookieSession` when request comes in, `extracts all cookie data` from request and adds it to `req.session` property, so
passport don't have to worry about a cookie, it has to grab data from *req.session* property and deserialize it to *req.user*. \
So req.session - it's a cookieSession's work, req.user - passport's work. When we send the request cookieSession grabs
data from req.session (?) and assign it to response cookie.
Express says that we can also use `express-session` package instead of cookie-session. Difference is between storing
cookie data inside the app. `Cookie-session stores` the encrypted user id, and all `user object data to cookie`, so only
thing we need to do is decrypt it (which) done by cookie-session and cookie data in our needs. \
`Express-session stores in cookie only session id`, it has its session id storage where it can find a `match of session id
and user data` that this session id is belong to. \
So `cookie-session stores data inside cookie`, `express-session - stores user data in storage Map`. The nice thing in
*express-session - it can store a lot of data for particular session*, because we `don't need to pass all the stuff via
network` to client, but the *bad thing is we make our session not stateless* on the server side. + we need to set up
external session storage, which makes our server on one dependency more.
---
#### Some theory about login.
HTTP is stateless, about next request. So to login, server got to give you something (like JWT, cookie), that would give
you ability to say that you've been here lately, and you have rights to get this info you're asking.
If we are talking about `cookie-based authentication`, server should add header `"Set-Cookie": "aldskfluh"` with some token to
response, `browser will see this specific header`, and `store it in his memory`, and automatically will `append this header to
each further request` (if you are writing test with REST lib, you need to add it by yourself of course).
Simple login flow is different from OAuth flow. \
`Simple login`: User sign up with login/pass, server stores them, User login with login/pass - server search the match and
know who's logged in. \
`OAuth flow`: User sign up with Google, server stores his profile data gotten from Google, User login - server once again
goes to google to get profile data and search for match among created Users, then it understands who's logged in.
This a third-party (Google in this case) relation, but we make an assumption that data of the profile (e.g. UserID)
won't change with time, and User can always login to our app and sees his data.
When User logs out - server invalidate, unset, or expire "Set-Cookie" header, which makes user session invalid.
---
#### Mongo & mongoose
Mongo - it's about collections, and rows in these collections. It's pretty basics. \
Mongoose - it's a js library above the Mongo, there are schemes, Models. \
Model class - works with single collection, with addition features like inserting a record, find records, filter, so on.
Model class also gives us access to instance(s) of rows. It returns record, or records - depend on what have you asked.
---
#### React app
React has his own server, that is responsible for the UI, for JS. \
Express server - responsible for the backend and for generating and providing JSON data. \
`TIP`: `express by default DOESN'T PARSE POST request body`, so use `app.use(express.json())` or "body-parser" package.
#### Dev mode
There will be two separate servers *react* dev server and *express*. That's why we need `react-proxy set up`, to
`not hardcoded all the links` when we want user to be redirected to express, but keep the relative style. React server
gives us live-reload and linting mostly, so there not much magic in it. \
In prod mode, we build react prod build "npm run build", and there will be only one server that will return production
html and bundle from "build" directory, where create-react-app stored it after we ask him to make us a prod build.
So *when we keep **relative** links in our code* - we *don't need hard code or prod-checks in code*, everything will
work in prod and in dev. \
So there will be only our express server, but what about routes that we've defined in React app like "/surveys"?
express server if gets request to some url it doesn't know - will return index html file to the client, that's the
only thing he can do, in client [html][2] file there is a link to script that index want to get from express -
client\build\static\js\main.4f595ecb.chunk.js which is going to load the React library, and React library with react
Router inside will se that "/surveys" request and understood that he needs to return the right component. \
So we need to explain express server that if he gets something he doesn't know - return the index.html and if he gets
the GET main.js script request - return actual script or any other asset (like css file or else). See schemes for more
info.
Thing with proxying request in dev mode from one server to another have a few strengths:
1. Cookies included automatically only to request from client to domain source html comes from, so when we request
something from the client side with same domain - cookies will be included, and then on backend we'll redirect req to
another server, if we'll request something directly from API and UI comes from another domain (in dev), cookie will be
lost.
2. CORS, cross origin resource sharing request would be captured, and browser needs you to provide special permission
for that stuff if we'll request different domain or different port from first source, and we don't want thins headache.
React proxy is greedy, it takes all request that starts with '/auth/google', means it will take '/auth/google/whatever'
We'll try to keep all data/redux layer/logic in src/index.js, and all render/react layer/logic in App.js
`React-redux` provides a layer of connection between redux state and react components. \
Note about where we should keep state. *If there no effect on application state from component*, then *keep state on
component level*. If you realize that *change this component state affects, or needed somewhere else in the app*, or some
other component will use it - then *create action creator, action, reducer*, and add this logic in redux level.
`React-router` is a basic library with routing, React-router-dom for all apps that somehow working with dom,
React-router-native is for the react-native apps.
```jsx
import {
BrowserRouter, // tells how to behave, looks for current url - and decide what page it should draw.
Route, // rule that decide between certain route that user can visit, and components that will be visible on the screen
Switch, // looks through its children <Route>s and renders the first one that matches the current URL.
} from "react-router-dom";
// exact - means only for this path it will be visible. If not - it will be visible everywhere.
<Route exact path={'/myPath'} render={() => <MyComponent />}/> // one way
<Route exact path={'/myPath'}><MyComponent/></Route> // another way
<Route exact path={'/myPath'} component={MyComponent}/> // one more way
```
Route adds special methods and properties to Component it wraps. But be aware if you mess with properties somehow, you
cannot get the *history, location, match, etc.* from props that Route provide, since you re write it.
```jsx
<Route exact path={'/myPath'} render={() => <MyComponent/>}/> // You cannot get them
<Route exact path={'/myPath'}><MyComponent/></Route> // You cannot get them
<Route exact path={'/myPath'} component={MyComponent}/> // This way you CAN get them.
<Route exact path={'/myPath'} component={(props) => <MyComponent {...props}/>}/> // This way you CAN get them.
<Route exact path={'/myPath'} render={(props) => <MyComponent {...props}/>}/> // This way you CAN get them.
```
Any children don't get those props of course, you need to pass them with hands. Or there is a better way `withRouter`.
```jsx
import {withRouter} from 'react-router-dom';
class MyComponent(){};
export default withRouter(MyComponent); // Now, ANY way you would wrap this Component - it alwas will have Route props.s
```
[Materializecss][3] - library to get predefined css styles for elements. \
There is one more popular library for React - MaterialUI, but this library is javascript based styles, this means that
css styles is added by javascript, not plain old css, witch is harder to override and customise, that's why we
picked up "materialize css" \
`Webpack` that comes with create-react-app package, and beside it compiles all js modules and files in one, it can also
include other extensions like css, called loaders, so when we are adding css import in our js files webpack will add
them as well.
`a vs Link (from React Router)` \
We *use anchor*, *when* we want *User to be redirected to completely different html document*, in different domain, like login
via google.
We *use Link* (React Router) when we want *to navigate User to some other route hosted by React Router inside our
application*. There nice features of [Link][5]
```jsx
<Link to="/news">News</Link>
<Link to={{pathname: "/news", search: "?sort=name", hash: "#the-hash",}}>News</Link>
```
#### About payment
Don't store raw credit card numbers, or store them in your DB, or process payment on your side. Always use outside
payment service (vendor) that will handle all these stuff on it's side. We will use billing system mock, but for prod -
we could use "stripe". Js plugin - `react-stripe-checkout`.
[Custom env variables][4] in React app. \
Basically same as regular, but we need to add REACT_APP_ before variables in React app.
We can add one time vars set "REACT_APP_NOT_SECRET_CODE=abcdef" && npm start / REACT_APP_NOT_SECRET_CODE=abcdef npm start
or via .env file
```js
// little fetch example
fetch('/api/surveys', {method: "POST", body: JSON.stringify({title: '', subject: ''}),
headers: { "Content-Type": "application/json" }}).then(console.log, console.log)
```
`Redux Form` - helping to add complicated logic form to app, it has its own reducer, so we don't need to add a lot of
logic in redux store.
`Localtunnel` - package that gives your local PC to be reachable from outside network. But it doesn't work) :disappointed: \
`ngrok` - nice, but they wanted money :broken_heart: for static proxy url + you need to install stuff \
I've picked up **ssh.localhost.run** :boom:
Improvements: \
Must have:
1. Delete survey message.
Nice to have: render optimization, Error handling, code linter, pre commit hook, readme.
[1]: http://www.passportjs.org
[2]: client/build/index.html
[3]: https://materializecss.com/
[4]: https://create-react-app.dev/docs/adding-custom-environment-variables/
[5]: https://reactrouter.com/web/api/Link<file_sep>/client/src/components/Surveys/survey.data.js
export const FIELD_PROPS = [
{label: 'Email subject', name: 'subject'},
{label: 'Quiz title', name: 'title'},
{label: 'Question you want to ask', name: 'body'},
{label: 'Recipient list', name: 'recipients'}
];<file_sep>/client/src/components/Landing/Steps/Step/Step.js
import React from 'react';
import styles from './Step.module.scss'
import PropTypes from 'prop-types'
const Step = (props) => {
return (
<div className={props.left ? styles.StepLeftAside : styles.StepRightAside}>
<div className={styles[props.circleColor]}/>
<img src={props.icon} alt="step"/>
<div className={styles.StepDesc}>
<div>
<h3>{`Step ${props.stepNum}`}</h3>
<div className={styles.line}/>
</div>
<span>{props.stepDescription}</span>
</div>
</div>
);
};
Step.propTypes = {
left: PropTypes.bool.isRequired,
circleColor: PropTypes.string.isRequired,
icon: PropTypes.string.isRequired,
stepDescription: PropTypes.string.isRequired,
stepNum: PropTypes.number.isRequired
}
export default Step;<file_sep>/client/src/components/Header/HamburgerMenu/HamburgerMenu.js
import React from 'react';
import PropTypes from 'prop-types';
import styles from './HamburgerMenu.module.scss'
import NavItems from "../NavItems/NavItems";
import Shade from "../../UI/Shade/Shade";
function HamburgerMenu(props) {
return (
<React.Fragment>
<Shade onClick={props.clicked} show={props.sideMenuShown}/>
<div className={props.sideMenuShown ? styles.CrossBtn : styles.MenuBtn}>
<input type="checkbox" id="menuToggle" onClick={props.clicked}/>
<label htmlFor="menuToggle">
<span></span>
</label>
</div>
<div className={[styles.SideDrawer, props.sideMenuShown ? styles.Open : styles.Closed].join(' ')}>
<NavItems sideMenuShown={props.sideMenuShown}/>
</div>
</React.Fragment>
);
}
HamburgerMenu.propTypes = {
sideMenuShown: PropTypes.bool.isRequired,
clicked: PropTypes.func.isRequired
};
export default HamburgerMenu;<file_sep>/start.tunnel.sh
# Don't forget to make it executable.
# APP WON'T WORK ON YOUR LOCAL MACHINE PROPERLY, if you want to try something out here in dev mode unfortunately - no.
# Proxy "url" generated with ssh.localhost.run on my local machine, and added as a webhook to sendgrid account that I use
# So to make application work properly on your local machine you need to check where I'm using my integration with
# sendgrid and change it to your keys and urls. Yeah, I'm also sad about it, but proxying your localhost to world web
# for free - never was a simple task.
echo Starting tunnel service...
ssh -R 80:localhost:8080 ssh.localhost.run
<file_sep>/server/routes/payment.js
const express = require('express');
const router = express.Router();
const paths = require('./routes.paths');
const {isLoggedIn} = require('../middleware/authorization');
const {STRIPE_SEC_KEY} = require('../config');
router.post('/token', isLoggedIn, async (req, res) => {
const stripe = require('stripe')(STRIPE_SEC_KEY);
const {id} = req.body;
const chargeRequest = {
amount: 500,
currency: 'usd',
source: id,
description: `Charging user "${req.user.name}" with 5$`,
};
// creating charge for user
let chargeObj = null;
try {
chargeObj = await stripe.charges.create(chargeRequest);
} catch (e) {
return res.status(500).send({error: `Couldn't charge the money, please try again later.`});
}
// updating user credits after success charge
try {
// since we are using mongo and passport, we can access user model via req.user and all methods like .save()
req.user.credit += chargeObj.amount * 0.01;
const user = await req.user.save(); // by convention - we use updated latest version of the model, not just req.user
return res.send(user);
} catch (e) {
return res.status(500).send({error: `Couldn't update User credit, we will return you the money!`});
}
});
module.exports = {handler: router, path: paths.apiPayment};
<file_sep>/server/services/routes.js
const {auth, payment, logout, currentUser, surveys, testUser} = require('../routes');
module.exports = function (app) {
app.use(auth.path, auth.handler);
app.use(payment.path, payment.handler);
app.use(logout.path, logout.handler);
app.use(currentUser.path, currentUser.handler);
app.use(surveys.path, surveys.handler);
app.use(testUser.path, testUser.handler);
};
<file_sep>/server/config/index.js
const {onProd} = require('../helpers/common');
function checkEnvVars(config) {
if (!config.GOOGLE_CLIENT_ID || !config.GOOGLE_CLIENT_SECRET) {
throw new Error(`CLIENT ID AND SECRET SHOULD BE SET!`);
}
}
const getConfig = () => {
try {
return onProd() ? require('./production') : require('./dev');
} catch (e) {
if(e.message.includes('Cannot find module')){
throw Error(`Please create dev.js file, for DEV mode server config;`)
}
throw e;
}
}
checkEnvVars(getConfig());
module.exports = getConfig();<file_sep>/client/src/components/Surveys/SortingDropdown/SortingDropdown.js
import React, {useState} from 'react';
import PropTypes from 'prop-types';
import styles from './SortingDropdown.module.scss';
const SortingDropdown = (props) => {
const [state, setState] = useState({sortingShown: false});
const showSorting = () => {
setState(({sortingShown}) => ({sortingShown: !sortingShown}));
};
return (
<div className={styles.Dropdown}>
<input id={"sortingToggle"} type={'checkbox'} checked={state.sortingShown} onChange={showSorting}/>
<label htmlFor="sortingToggle">
<span></span>
</label>
<ul className={state.sortingShown ? styles.Shown : styles.Hide}>
<li><button
onClick={() => {
props.ascSorting();
showSorting();
}}>New on top</button></li>
<li><button onClick={() => {
props.descSorting();
showSorting();
}}>Old on top</button></li>
</ul>
</div>
);
};
SortingDropdown.propTyes = {
ascSorting: PropTypes.func.isRequired,
descSorting: PropTypes.func.isRequired
};
export default SortingDropdown;
| a4dc0998c2705215026d2ebf1401e9213fd130f4 | [
"JavaScript",
"Markdown",
"Shell"
] | 34 | JavaScript | bondarukoleh/react_web_app | 3ba8be76d25f41655d3d4fc5a93458804a3f880c | cc63d6d589352fd97df9cd286d482f2be4139b42 |
refs/heads/master | <file_sep>import com.github.pysrc.sheet.AbstractSheet;
import com.github.pysrc.sheet.IRead;
import com.github.pysrc.sheet.IWrite;
import com.github.pysrc.sheet.impl.SheetRead;
import com.github.pysrc.sheet.impl.SheetWrite;
import com.github.pysrc.sheet.report.Report2;
import bean.Item;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class TestFilter {
static void out() throws Exception {
List<Item> items = new ArrayList<>();
items.add(new Item("字符测试", "456.9", 70.34, 43.1, "项目2", "2019/12/04", new Date(), new Date(), "Hello"));
items.add(new Item("字符测试2", "46", 8.4, 78.45, "项目1", "2019/10/04", new Date(), new Date(), "Hi"));
OutputStream os = new FileOutputStream("E:/xxx.xlsx");
Workbook wb = new XSSFWorkbook();
AbstractSheet<Item> write = new SheetWrite<>(wb, Item.class);
write.setFilter("test");
IWrite i = new Report2(write, "报表标题测试", "制表人:杨三");
i.write(items);
wb.write(os);
wb.close();
os.close();
}
public static void in() throws Exception {
InputStream is = new FileInputStream("E:/xxx.xlsx");
Workbook wb = new XSSFWorkbook(is);
AbstractSheet<Item> abs = new SheetRead<Item>(wb, Item.class)
.setFilter("test");
IRead<Item> read = (IRead) abs;
List<Item> items = read.read();
wb.close();
is.close();
for (Item i : items) {
System.out.println(i);
}
}
public static void main(String[] args) throws Exception {
out();
in();
}
}
<file_sep>package com.github.pysrc.sheet.style;
import com.github.pysrc.sheet.AbstractSheet;
import com.github.pysrc.sheet.Column;
import com.github.pysrc.sheet.ICellStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Workbook;
// 左对齐
public class StyleBlockFont implements ICellStyle {
@Override
public void style(AbstractSheet base, Column column, CellStyle cellStyle) {
Workbook workbook = base.getWorkbook();
Font font = workbook.createFont();
font.setBold(true);
cellStyle.setFont(font);
}
}
<file_sep>package com.github.pysrc.sheet;
import com.github.pysrc.sheet.enums.EType;
/**
* Sheet页的列信息
*/
public class Column implements Comparable<Column> {
public int rank = Integer.MIN_VALUE;
public String field;
public String title;
public int width = 256 * 10; // 10个字符宽度
public EType etype = EType.STR;
public String format = "";
public String[] valueList = {};
public String filter = "";
public Column() {
}
public Column(String field) {
this.field = field;
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public String[] getValueList() {
return valueList;
}
public void setValueList(String[] valueList) {
this.valueList = valueList;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public EType getEtype() {
return etype;
}
public void setEtype(EType etype) {
this.etype = etype;
}
public String getFilter() {
return filter;
}
public void setFilter(String filter) {
this.filter = filter;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
@Override
public int compareTo(Column o) {
return this.rank - o.getRank();
}
}
<file_sep>package com.github.pysrc.sheet.report;
import com.github.pysrc.sheet.AbstractSheet;
import com.github.pysrc.sheet.ISchema;
import com.github.pysrc.sheet.style.*;
import com.github.pysrc.sheet.style.*;
/**
* 通用报表导出风格
*
*/
public class Report1<T> extends AbstractReport<T> {
public Report1(AbstractSheet<T> base) {
super(base);
}
@Override
public void before() {
base.addTitleStyle(new StyleGray())
.addTitleStyle(new StyleCenter())
.addTitleStyle(new StyleBlockFont())
.addTitleStyle(new StyleFrame())
.addRowStyle(new StyleFrame())
.addRowStyle(new StyleLeft());
}
@Override
public void after() {
}
@Override
public void updateSchema(ISchema schema) {
}
}
<file_sep>package com.github.pysrc.sheet.exception;
import com.github.pysrc.sheet.lang.Lang;
public class NullDataClassException extends Exception {
public NullDataClassException(){
super(Lang.get("exc.null.class"));
}
}
<file_sep>package bean;
import com.github.pysrc.sheet.annotation.ColRole;
import com.github.pysrc.sheet.annotation.SheetSchema;
import com.github.pysrc.sheet.enums.EType;
import java.util.Date;
@SheetSchema(
sheetName = "Sheet1",
titleEnable = true,
startCol = 1,
startRow = 4
)
public class Item {
// 以下代表 Java类型->Excel类型 导入时类型则相反
@ColRole(title = "字符->字符")
private String sts;
@ColRole(title = "字符->数字", etype = EType.NUM, format = "0.00") // 保留两位小数
private String stn;
@ColRole(title = "数字->字符")
private Double nts;
@ColRole(title = "数字->数字", etype = EType.NUM, format = "00.00$", rank = 100)
private Double ntn;
@ColRole(title = "下拉框", valueList = {"项目1", "项目2", "项目3", "项目4"}, filter = "test")
private String drp;
@ColRole(title = "字符->日期", width = 256 * 20, etype = EType.DAT, format = "yyyy/MM/dd")
private String std;
@ColRole(title = "日期->字符", width = 256 * 20, format = "yyyy/MM/dd")
private Date dts;
@ColRole(title = "日期->日期", width = 256 * 30, etype = EType.DAT, format = "yyyy/MM/dd HH:mm:ss")
private Date dtd;
@ColRole(title = "其他测试", width = 256 * 20, filter = "test")
private String slf;
public Item() {
}
public Item(String sts, String stn, Double nts, Double ntn, String drp, String std, Date dts, Date dtd, String slf) {
this.sts = sts;
this.stn = stn;
this.nts = nts;
this.ntn = ntn;
this.drp = drp;
this.std = std;
this.dts = dts;
this.dtd = dtd;
this.slf = slf;
}
// getter/setter
public String getSts() {
return sts;
}
public void setSts(String sts) {
this.sts = sts;
}
public String getStn() {
return stn;
}
public void setStn(String stn) {
this.stn = stn;
}
public Double getNts() {
return nts;
}
public void setNts(Double nts) {
this.nts = nts;
}
public Double getNtn() {
return ntn;
}
public void setNtn(Double ntn) {
this.ntn = ntn;
}
public String getDrp() {
return drp;
}
public void setDrp(String drp) {
this.drp = drp;
}
public String getStd() {
return std;
}
public void setStd(String std) {
this.std = std;
}
public Date getDts() {
return dts;
}
public void setDts(Date dts) {
this.dts = dts;
}
public Date getDtd() {
return dtd;
}
public void setDtd(Date dtd) {
this.dtd = dtd;
}
public String getSlf() {
return slf;
}
public void setSlf(String slf) {
this.slf = slf;
}
@Override
public String toString() {
return String.format("%-15s | %-15s | %-15s | %-15s | %-15s | %-15s | %-15s | %-15s | %-15s", sts, stn, nts, ntn, drp, std, dts, dtd, slf);
}
}
<file_sep>package com.github.pysrc.sheet.impl;
import com.github.pysrc.sheet.*;
import com.github.pysrc.sheet.exception.NullDataClassException;
import com.github.pysrc.sheet.exception.NullSheetException;
import com.github.pysrc.sheet.exception.NullWorkbookException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
public class SheetRead<T> extends AbstractSheet<T> {
public SheetRead(Workbook workbook, Class<T> dataClass) throws NullDataClassException, NullWorkbookException {
super(workbook, dataClass);
this.scan = new ScanReadDefault<T>();
}
@Override
public List<T> read() throws IllegalAccessException, InstantiationException, NoSuchFieldException, ParseException {
if (!isDone) {
done();
}
if (this.sheet == null) {
new NullSheetException();
}
List<T> res = new ArrayList<>();
if (titleEnable) {
startRow++;
}
for (int i = startRow; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
// 数据至此断
if (row == null) {
break;
}
boolean isend = true;
int curCol = startCol;
for (Column c : columns) {
if (row.getCell(curCol++) != null) {
isend = false;
break;
}
}
if (isend) {
break;
}
T d = dataClass.newInstance();
curCol = startCol;
boolean vali = true;
for (Column c : columns) {
Cell cell = row.getCell(curCol++);
if (this.validator.pass(i, c, cell)) {
scan.scan(this, c, d, fieldMap.get(c.getField()), cell);
} else {
vali = false;
}
}
if (vali) {
res.add(d);
}
}
return res;
}
@Override
public void write(List<T> datas) throws IllegalAccessException, NoSuchFieldException, ParseException {
}
}
<file_sep>package com.github.pysrc.sheet.report;
import com.github.pysrc.sheet.AbstractSheet;
import com.github.pysrc.sheet.IWrite;
import java.text.ParseException;
import java.util.List;
/**
* 代理模式,嵌入导出样式
*/
public abstract class AbstractReport<T> implements IWrite<T> {
protected AbstractSheet<T> base;
public AbstractReport(AbstractSheet<T> base) {
this.base = base;
}
@Override
public void write(List<T> datas) throws IllegalAccessException, NoSuchFieldException, ParseException {
if(!base.isDone()){
base.done();
}
before();
base.write(datas);
after();
}
public abstract void before();
public abstract void after();
}
<file_sep>package com.github.pysrc.sheet;
import org.apache.poi.ss.usermodel.Cell;
/**
* 导入校验器
*/
public interface IReadValidator {
/**
* 校验/修改导入的数据
* @param row 数据的行标
* @param column 数据列的Schema
* @param cell Excel的Cell
* @return 是否通过校验,通过校验的数据才会写入导入Bean
*/
boolean pass(int row, Column column, Cell cell);
}
<file_sep>### Excel导入/出工具类
类似的东西挺多的,这个仓库仅仅根据实际使用总结出来的工具类
### Maven
```xml
<dependency>
<groupId>com.github.pysrc</groupId>
<artifactId>sheet-io</artifactId>
<version>1.0.2</version>
</dependency>
```
### Example
#### Bean类
```java
package bean;
import com.github.pysrc.sheet.annotation.ColRole;
import com.github.pysrc.sheet.annotation.SheetSchema;
import com.github.pysrc.sheet.enums.EType;
import java.util.Date;
@SheetSchema(
sheetName = "Sheet1",
titleEnable = true,
startCol = 1,
startRow = 4
)
public class Item {
// 以下代表 Java类型->Excel类型 导入时类型则相反
@ColRole(title = "字符->字符")
private String sts;
@ColRole(title = "字符->数字", etype = EType.NUM, format = "0.00") // 保留两位小数
private String stn;
@ColRole(title = "数字->字符")
private Double nts;
@ColRole(title = "数字->数字", etype = EType.NUM, format = "00.00$", rank = 100)
private Double ntn;
@ColRole(title = "下拉框", valueList = {"项目1", "项目2", "项目3", "项目4"}, filter = "test")
private String drp;
@ColRole(title = "字符->日期", width = 256 * 20, etype = EType.DAT, format = "yyyy/MM/dd")
private String std;
@ColRole(title = "日期->字符", width = 256 * 20, format = "yyyy/MM/dd")
private Date dts;
@ColRole(title = "日期->日期", width = 256 * 30, etype = EType.DAT, format = "yyyy/MM/dd HH:mm:ss")
private Date dtd;
@ColRole(title = "其他测试", width = 256 * 20, filter = "test")
private String slf;
public Item() {
}
public Item(String sts, String stn, Double nts, Double ntn, String drp, String std, Date dts, Date dtd, String slf) {
this.sts = sts;
this.stn = stn;
this.nts = nts;
this.ntn = ntn;
this.drp = drp;
this.std = std;
this.dts = dts;
this.dtd = dtd;
this.slf = slf;
}
// getter/setter 省略
@Override
public String toString() {
return String.format("%-15s | %-15s | %-15s | %-15s | %-15s | %-15s | %-15s | %-15s | %-15s", sts, stn, nts, ntn, drp, std, dts, dtd, slf);
}
}
```
#### 基本导入/出测试
```java
import com.github.pysrc.sheet.impl.SheetRead;
import com.github.pysrc.sheet.impl.SheetWrite;
import bean.Item;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class TestBase {
static void out() throws Exception {
List<Item> items = new ArrayList<>();
items.add(new Item("字符测试", "456.9", 70.34, 43.1, "项目2", "2019/12/04", new Date(), new Date(), "Hello"));
items.add(new Item("字符测试2", "46", 8.4, 78.45, "项目1", "2019/10/04", new Date(), new Date(), "Hi"));
OutputStream os = new FileOutputStream("E:/xxx.xlsx");
Workbook wb = new XSSFWorkbook();
new SheetWrite<>(wb, Item.class)
.write(items);
wb.write(os);
wb.close();
os.close();
}
public static void in() throws Exception {
InputStream is = new FileInputStream("E:/xxx.xlsx");
Workbook wb = new XSSFWorkbook(is);
List<Item> read = new SheetRead<Item>(wb, Item.class)
.read();
wb.close();
is.close();
for (Item i : read) {
System.out.println(i);
}
}
public static void main(String[] args) throws Exception {
out();
in();
}
}
```
**更多测试见:[示例](https://github.com/pysrc/sheet-io/tree/master/src/test/java)**
<file_sep>package com.github.pysrc.sheet.style;
import com.github.pysrc.sheet.AbstractSheet;
import com.github.pysrc.sheet.Column;
import com.github.pysrc.sheet.ICellStyle;
import org.apache.poi.ss.usermodel.*;
// 灰色背景
public class StyleGray implements ICellStyle {
@Override
public void style(AbstractSheet base, Column column, CellStyle cellStyle) {
cellStyle.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
}
}
<file_sep>package com.github.pysrc.sheet.lang;
import java.util.HashMap;
import java.util.Map;
public class Lang {
public static Env env = Env.EN;
public static Map<Env, Map<String, String>> langs = new HashMap<>();
static {
langs.put(Env.EN, new HashMap<String, String>() {{
put("exc.cell.type", "Cell type is error");
put("exc.null.class", "Dataclass is null");
put("exc.null.sheet", "Sheet is null");
put("exc.null.wb", "Workbook is null");
}});
langs.put(Env.CN, new HashMap<String, String>() {{
put("exc.cell.type", "当前Cell类型错误");
put("exc.null.class", "数据类型类为空");
put("exc.null.sheet", "Sheet 页为空");
put("exc.null.wb", "Workbook 为空");
}});
}
public static String get(String id) {
return langs.get(env).get(id);
}
}
<file_sep>package com.github.pysrc.sheet.report;
import com.github.pysrc.sheet.AbstractSheet;
import com.github.pysrc.sheet.ISchema;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
public class Report3<T> extends AbstractReport {
private String header;
private String param;
private String tail;
public Report3(AbstractSheet base, String header, String param, String tail) {
super(base);
this.header = header;
this.param = param;
this.tail = tail;
}
@Override
public void before() {
new Report2<T>(base, header, param).before();
}
@Override
public void after() {
Sheet sheet = base.getSheet();
int maxrow = sheet.getLastRowNum();
// 合并单元格
Row row = sheet.createRow(maxrow + 1);
CellRangeAddress region = new CellRangeAddress(maxrow + 1, maxrow + 1, this.base.getStartCol(), this.base.getStartCol() + this.base.getColumns().size() - 1);
sheet.addMergedRegion(region);
CellStyle cellStyle = base.getWorkbook().createCellStyle();
cellStyle.setBorderLeft(BorderStyle.THIN);
cellStyle.setBorderTop(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);
cellStyle.setBorderBottom(BorderStyle.THIN);
for (int i = 0; i < base.getColumns().size(); i++) {
row.createCell(base.getStartCol()+i).setCellStyle(cellStyle);
}
row.getCell(base.getStartCol()).setCellValue(tail);
}
@Override
public void updateSchema(ISchema schema) {
}
}
| 24702b940534bc8ec63bdf88b78c7243ed66a487 | [
"Markdown",
"Java"
] | 13 | Java | pysrc/sheet-io | d67be57aebf3153c1e0a0b9c8cf7e0490e1b179f | c30527fd4cc607f8d088d7b46e44c9130c68c74c |
refs/heads/master | <file_sep>package com.jasonllinux.app.se;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.apache.lucene.search.highlight.Formatter;
import org.apache.lucene.search.highlight.Fragmenter;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.Scorer;
import org.apache.lucene.search.highlight.SimpleFragmenter;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.queryParser.ParseException;
import com.jasonllinux.app.entity.Book;
public class IndexFiles {
//分词器
private Analyzer analyzer;
//索引存放目录
private Directory directory;
public IndexFiles() {
try {
before();
testCreateIndex();
testSearchBook();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//准备工作
public void before() throws IOException {
//建立一个标准分词器
//Version.LUCENE_36 表示匹配Lucene3.6版本
analyzer = new StandardAnalyzer(Version.LUCENE_36);
//在当前路径下建立一个目录叫indexDir
File indexDir = new File("./indexDir");
//创建索引目录
directory = FSDirectory.open(indexDir);
}
//生成索引
public void testCreateIndex() throws IOException {
//建立一个IndexWriter配置,指定匹配的版本,以及分词器
IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_36,analyzer);
//创建IndexWriter,它负责索引的创建和维护
IndexWriter indexWriter = new IndexWriter(directory,indexWriterConfig);
//获取图书信息
Book book1 = new Book();
book1.setId(1);
book1.setTitle("Java编程思想");
book1.setAuthor("<NAME>");
book1.setContent("Thinking in Java should be read cover to cover by every Java programmer, then kept close at hand for frequent reference.");
Book book2 = new Book();
book2.setId(2);
book2.setTitle("建筑的永恒之道");
book2.setAuthor("亚历山大");
book2.setContent("《建筑的永恒之道》提出了一个关于建筑设计、建筑和规划的新的理论、思想,该理论的核心是社会成员按照他们自己的存在状态设定他们生活的世界秩序,这一古老方式从根本上构成了新的后工业时代建筑的基础,这些建筑由人们创造。");
//建立Document
Document doc1 = new Document();
//Store指定Field是否需要存储,Index指定Field是否需要分词索引
doc1.add(new Field("id",book1.getId().toString(),Store.YES,Index.NOT_ANALYZED));
doc1.add(new Field("title",book1.getTitle(),Store.YES,Index.ANALYZED));
doc1.add(new Field("author",book1.getAuthor(),Store.YES,Index.ANALYZED));
doc1.add(new Field("content",book1.getContent(),Store.YES,Index.ANALYZED));
//建立Document
Document doc2 = new Document();
//Store指定Field是否需要存储,Index指定Field是否需要分词索引
doc2.add(new Field("id",book2.getId().toString(),Store.YES,Index.NOT_ANALYZED));
doc2.add(new Field("title",book2.getTitle(),Store.YES,Index.ANALYZED));
doc2.add(new Field("author",book2.getAuthor(),Store.YES,Index.ANALYZED));
doc2.add(new Field("content",book2.getContent(),Store.YES,Index.ANALYZED));
//把Document加入到索引中
indexWriter.addDocument(doc1);
indexWriter.addDocument(doc2);
//提交改变到索引,然后关闭
indexWriter.close();
}
public void testSearchBook() throws ParseException, CorruptIndexException, IOException, InvalidTokenOffsetsException {
//搜索的关键词
String queryKeyWord = "思想";
//创建查询分析器,把查询关键词转化为查询对象Query(单个Field中搜索)
//QueryParser queryParser = new QueryParser(Version.LUCENE_36,"author",analyzer);//在作者的索引中搜索
String[] fields = {"title","content"};
//(在多个Filed中搜索)
QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_36,fields,analyzer);
Query query = queryParser.parse(queryKeyWord);
//获取访问索引的接口,进行搜索
IndexReader indexReader = IndexReader.open(directory);
IndexSearcher indexSearcher = new IndexSearcher(indexReader);
//TopDocs 搜索返回的结果
TopDocs topDocs = indexSearcher.search(query, 100);//只返回前100条记录
int totalCount = topDocs.totalHits; // 搜索结果总数量
System.out.println("搜索到的结果总数量为:" + totalCount);
ScoreDoc[] scoreDocs = topDocs.scoreDocs; // 搜索的结果列表
//创建高亮器,使搜索的关键词突出显示
Formatter formatter = new SimpleHTMLFormatter("<font color='red'>","</font>");
Scorer fragmentScore = new QueryScorer(query);
Highlighter highlighter = new Highlighter(formatter,fragmentScore);
Fragmenter fragmenter = new SimpleFragmenter(100);
highlighter.setTextFragmenter(fragmenter);
List<Book> books = new ArrayList<Book>();
//把搜索结果取出放入到集合中
for(ScoreDoc scoreDoc : scoreDocs) {
int docID = scoreDoc.doc;//当前结果的文档编号
float score = scoreDoc.score;//当前结果的相关度得分
System.out.println("score is : "+score);
Document document = indexSearcher.doc(docID);
Book book = new Book();
book.setId(Integer.parseInt(document.get("id")));
//高亮显示title
String title = document.get("title");
String highlighterTitle = highlighter.getBestFragment(analyzer, "title", title);
//如果title中没有找到关键词
if(highlighterTitle == null) {
highlighterTitle = title;
}
book.setTitle(highlighterTitle);
book.setAuthor(document.get("author"));
//高亮显示content
String content = document.get("content");
String highlighterContent = highlighter.getBestFragment(analyzer, "content", content);
//如果content中没有找到关键词
if(highlighterContent == null) {
highlighterContent = content;
}
book.setContent(highlighterContent);
books.add(book);
}
//关闭
indexReader.close();
indexSearcher.close();
for(Book book : books) {
System.out.println("book'id is : "+book.getId());
System.out.println("book'title is : "+book.getTitle());
System.out.println("book'author is : "+book.getAuthor());
System.out.println("book'content is : "+book.getContent());
}
}
}
| aa13708f2506ffccae7b708aa85991b2c80d66c5 | [
"Java"
] | 1 | Java | jpollo/search_engine | 55e309ffa499cf2c7a6f9a6e745d47f0b2369af8 | 5f8e426a1a837288ea322402e059dbb4fcc9db22 |
refs/heads/main | <repo_name>BUAA-zxb/Kaggle-learning<file_sep>/main.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from time import time
from sklearn.decomposition import PCA
from sklearn import metrics
from sklearn.model_selection import GridSearchCV
# 训练集和测试集数据路径
train_path = 'E:/AAAdesktop/Kaggle/digit-recognizer/train.csv'
test_path = 'E:/AAAdesktop/Kaggle/digit-recognizer/test.csv'
# 导入训练集和测试集数据
train = pd.read_csv(train_path)
test = pd.read_csv(test_path)
# 查看训练集和测试集数据信息
# train.info()
# test.info()
# 查看训练集是否有缺失值,结果是不存在缺失值
# train.isnull().any().describe()
# test.isnull().any().describe()
# 从训练集中找出数据和标签
X_train = train.drop(labels={"label"}, axis=1)
Y_train = train["label"]
# 正则化
X_train = X_train / 255
test = test / 255
print(X_train.shape)
# 显示训练集前几个数据 如果显示就不能训练
# X_train = np.array(X_train).reshape(-1, 28, 28, 1)
# plt.imshow(X_train[1][:, :, 0], interpolation="none", cmap="Greys")
# plt.show()
# 训练集和测试集数据分开
x_train, x_test, y_train, y_test = train_test_split(X_train, Y_train, test_size=0.1, random_state=1)
# # 主成分分析函数
# def get_accuracy_score(n, X_train, X_test, y_train, y_test):
# t0 = time()
# pca = PCA(n_components=n)
# pca.fit(X_train)
# x_train_pca = pca.transform(X_train)
# x_test_pca = pca.transform(X_test)
# # 使用支持向量机分类器
# clf = SVC()
# clf.fit(x_train_pca, y_train)
# y_predict = clf.predict(x_test_pca)
# # 计算准确度
# accuracy = metrics.accuracy_score(y_test, y_predict, normalize=True)
# t1 = time()
# print('n_components:{:.2f} , accuracy:{:.4f} , time:{:.2f}s'.format(n, accuracy, t1 - t0))
# print(metrics.f1_score(y_test, y_predict, average='macro'),
# metrics.f1_score(y_test, y_predict, average='micro'),
# metrics.f1_score(y_test, y_predict, average='weighted'))
# print(metrics.precision_score(y_test, y_predict, average='macro'),
# metrics.precision_score(y_test, y_predict, average='micro'),
# metrics.precision_score(y_test, y_predict, average='weighted'))
# print(metrics.recall_score(y_test, y_predict, average='macro'),
# metrics.recall_score(y_test, y_predict, average='micro'),
# metrics.recall_score(y_test, y_predict, average='weighted'))
# return accuracy
#
#
# # 定义得分矩阵
# all_scores = []
# # 生成n_components的取值列表 0.5~1,分成500个数
# n_components = np.linspace(0.5, 1, num=500, endpoint=False)
# for n in n_components:
# score = get_accuracy_score(n, x_train, x_test, y_train, y_test)
# # 最终发现0.75是效果最好
# all_scores.append(score)
# # 找出识别有误的数据
# pca = PCA(n_components=0.75)
# pca.fit(x_train)
# X_train_pca = pca.transform(x_train)
# X_test_pca = pca.transform(x_test)
# clf = SVC()
# clf.fit(X_train_pca, y_train)
# y_pred = clf.predict(X_test_pca)
# errors = (y_pred != y_test)
# y_pred_errors = y_pred[errors]
# y_test_errors = y_test[errors].values
# X_test_errors = x_test[errors]
# print(y_pred_errors[:5])
# print(y_test_errors[:5])
# print(X_test_errors[:5])
# X_test_errors = np.array(X_test_errors).reshape(-1, 28, 28, 1)
# n = 0
# rows = 2
# cols = 5
# for row in range(rows):
# for col in range(cols):
# plt.imshow(X_test_errors[n][:, :, 0], interpolation="none", cmap="Greys")
# n += 1
# plt.show()
# n_components为0.75时, 模型的准确率最高
# 对训练集和测试集进行PCA降低维度处理, 主成分个数为33
pca = PCA(n_components=0.75)
pca.fit(x_train)
# 打印主成分个数
# print(pca.n_components_)
# 对训练集和测试集进行主成分转换
x_train_pca = pca.transform(x_train)
x_test_pca = pca.transform(x_test)
test_pca = pca.transform(test)
# # 使用支持向量机预测,使用网格搜索进行调参
# # 调参结果发现C=5,kernel=rbf,效果最好
# clf_svc = GridSearchCV(estimator=SVC(), param_grid={'C': [5], 'gamma': [0.03], 'kernel': ['rbf']}, cv=5, verbose=2)
# clf_svc.fit(x_train_pca, y_train)
# # 显示使模型准确率最高的参数
# print(clf_svc.best_params_)
# 使用最好参数训练算法
clf_svc = SVC(C=5, gamma=0.03, kernel='rbf')
clf_svc.fit(x_train_pca, y_train)
# 使用现有数据预测模型
y_predict = clf_svc.predict(x_test_pca)
print('准确率:', metrics.accuracy_score(y_test, y_predict, normalize=True))
print('宏平均查准率:', metrics.precision_score(y_test, y_predict, average='macro'))
print('微平均查准率:', metrics.precision_score(y_test, y_predict, average='micro'))
print('加权平均查准率:', metrics.precision_score(y_test, y_predict, average='weighted'))
print('宏平均查全率:', metrics.recall_score(y_test, y_predict, average='macro'))
print('微平均查全率:', metrics.recall_score(y_test, y_predict, average='micro'))
print('加权平均查全率:', metrics.recall_score(y_test, y_predict, average='weighted'))
print('宏平均f1-score:', metrics.f1_score(y_test, y_predict, average='macro'))
print('微平均f1-score:', metrics.f1_score(y_test, y_predict, average='micro'))
print('加权平均f1-score:', metrics.f1_score(y_test, y_predict, average='weighted'))
# 生成最终预测结果
pred = clf_svc.predict(test_pca)
image_id = pd.Series(range(1, len(pred)+1))
result_2 = pd.DataFrame({'ImageID': image_id, 'Label': pred})
# 保存为CSV文件
result_2.to_csv('result2_svc.csv', index=False)
print('Done')
<file_sep>/README.md
# Kaggle-learning
The storage inventory storage code when I learn, I learn knowledge is very shallow, if lucky to be anyone to search, welcome to guide, I will be open-minded to ask, thank you
This is my machine learning, in order to deepen the impression of learning, in kaggle to find the project for practical engineering projects. The data used in this project is a very common digital recognizer data set, which is known as the Hello world in machine learning. I use machine learning SVM algorithm, the accuracy is 98.282, the accuracy is very low. This item is only my collection for commemorative use, welcome professional guidance, I am very grateful.
| b27798b0400bae3b9b4c5caba02521acc029fc92 | [
"Markdown",
"Python"
] | 2 | Python | BUAA-zxb/Kaggle-learning | 6d12b540219616ae3d494d438913a42013f6f1f2 | 9aa48d316d866fd09dd0f68a967828d2f4de1328 |
refs/heads/master | <file_sep>/**
* ProtectedrouteController
*
* @description :: Server-side logic for managing protectedroutes
* @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/
module.exports = {
getRequestHandler: function getRequestHandler(req,res) {
console.log("entered");
res.ok("PROTECTED ROUTE ACCESSIBLE");
}
};
<file_sep>/**
* PublicrouteController
*
* @description :: Server-side logic for managing publicroutes
* @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/
module.exports = {
getRequestHandler: function getRequestHandler(req,res) {
res.ok("PUBLIC ROUTE");
}
};
<file_sep># sails-auth-example
Example sails authentication API
| 26b7635d5c8a1e60824077e4bb3819871e102bc0 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | Neera-Dixit/sailsjs-jwt-authentication | 2e01e9fbc4a8d8b2549f7b7c464fcc2289c4cd71 | 72a0cd099ecd728ece4d172ca24f412cb4ce81cf |
refs/heads/main | <file_sep># neuroscience-project
Project for Introduction to Computational Neuroscience
<file_sep>import json
from io import StringIO
from html.parser import HTMLParser
from nltk.tokenize.treebank import TreebankWordDetokenizer
import nltk
from timeit import default_timer as timer
import random
class MLStripper(HTMLParser):
def __init__(self):
super().__init__()
self.reset()
self.strict = False
self.convert_charrefs= True
self.text = StringIO()
def handle_data(self, d):
self.text.write(d)
def get_data(self):
return self.text.getvalue()
def strip_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()
def update_timer(last_update_time, counter, max_counter=None, start_time=None, runtime=None):
now = timer()
# If last update was less than {float}s ago, dont update
if now-last_update_time < 0.25:
return last_update_time
if start_time and max_counter:
seconds_left = ((now - start_time)/counter)*(max_counter-counter)
hours = int(seconds_left / 3600)
minutes = int((seconds_left/60) % 60)
seconds = int(seconds_left%60)
print(f'Done: {counter:,}/{max_counter:,} iterations, finishing in: {hours:02d}:{minutes:02d}:{seconds:02d}.', end="\r")
elif start_time and runtime:
seconds_left = max(runtime - (now - start_time), 0)
hours = int(seconds_left / 3600)
minutes = int((seconds_left/60) % 60)
seconds = int(seconds_left%60)
print(f'Done: {counter:,} iterations, finishing in: {hours:02d}:{minutes:02d}:{seconds:02d}.', end='\r')
else:
print(f'Done: {counter:,}/{max_counter:,} iterations')
return now
def clean_text(text):
# Remove html tags
text_without_tags = strip_tags(text)
# Tokenize (the text still has spaces in wrong places e.G " didn ' t ")
tokenized = nltk.word_tokenize(text_without_tags)
# Detokenize
detokenized = TreebankWordDetokenizer().detokenize(tokenized)
return detokenized
def extract_from_json(obj):
question = obj["question_text"]
text = obj["document_text"]
# Long answer
# Annotator chosen answer exists
if obj["annotations"][0]["long_answer"]["candidate_index"] != -1:
long_start_token = obj["annotations"][0]["long_answer"]["start_token"]
long_end_token = obj["annotations"][0]["long_answer"]["end_token"]
# Annotator has marked that question has no answer: choose random paragraph
else:
top_level_candidates = [o for o in obj["long_answer_candidates"] if o["top_level"]]
# Top level answers are preferred (ones that are not contained in other answers)
if len(top_level_candidates) > 0:
canditate = random.choice(top_level_candidates)
else:
canditate = random.choice(obj["long_answer_candidates"])
long_start_token = canditate["start_token"]
long_end_token = canditate["end_token"]
long_answer = " ".join(text.split(" ")[long_start_token:long_end_token])
long_answer = clean_text(long_answer)
# Short answer
short_answers = obj["annotations"][0]["short_answers"]
short_answer = ""
if len(short_answers) > 0:
short_start_token = short_answers[0]["start_token"]
short_end_token = short_answers[0]["end_token"]
short_answer = " ".join(text.split(" ")[short_start_token:short_end_token])
short_answer = clean_text(short_answer)
# Yes_no_answer
yes_no_answer = obj["annotations"][0]["yes_no_answer"]
new_obj = {
"question": question,
"long_answer": long_answer,
"short_answer": short_answer,
"yes_no_answer": yes_no_answer
}
return new_obj
filename = "data/simplified-nq-train.jsonl"
results = []
counter = 0
print("Hakkan avama")
with open(filename, "r", encoding="utf-8") as f:
print("Avamine õnnestus")
start_time = timer()
last_update_time = timer()
for line in f:
obj = json.loads(line)
new_obj = extract_from_json(obj)
results.append(new_obj)
last_update_time = update_timer(last_update_time, counter, max_counter=307373, start_time=start_time)
counter += 1
print()
with open('data/google_qa_cleaned.json','w') as f:
json.dump(results,f)
print("Lõpetasin")
<file_sep>import json
def clean(source_fn, destination_fn):
with open(source_fn) as f:
data = json.load(f)
seen_ids = set()
duplicates = 0
removed = 0
cleaned_posts = []
for post in data:
# Post is duplicate based on id.
if post["id"] in cleaned_posts:
duplicates += 1
else:
seen_ids.add(post["id"])
# Title or body has been deleted (usually for TOS violation)
if post["title"] in ["[removed]", "[deleted]"] or post["body"] in ["[removed]", "[deleted]"]:
removed += 1
# Post fits all criteria to be saved.
# TODO Can add more post filtering rules here if necessary
else:
keys = ["body", "id", "score", "title"]
clean_post = { key: post[key] for key in keys }
cleaned_posts.append(clean_post)
print(f'Total cleaned posts: {len(cleaned_posts)}')
print(f'Duplicates: {duplicates}')
print(f'Removed/deleted: {removed}')
with open(destination_fn, 'w') as f:
json.dump(cleaned_posts, f, indent=4)
print(f'Saved cleaned posts to: {destination_fn}')
# clean(source_fn="data/r_cleanjokes_uncleaned.json", destination_fn="data/reddit_cleanjokes.json")
# clean(source_fn="data/r_DirtyJokes_uncleaned.json", destination_fn="data/reddit_DirtyJokes.json")
clean(source_fn="data/r_jokes_2021_uncleaned.json", destination_fn="data/reddit_jokes.json")<file_sep>argon2-cffi==20.1.0
async-generator==1.10
attrs==20.3.0
backcall==0.2.0
bleach==3.2.1
cffi==1.14.4
click==7.1.2
cloudpickle==1.6.0
colorama==0.4.4
cycler==0.10.0
dafsa==1.0
decorator==4.4.2
defusedxml==0.6.0
entrypoints==0.3
future==0.18.2
graphframes==0.6
gym==0.18.0
ipykernel==5.4.3
ipython==7.19.0
ipython-genutils==0.2.0
ipywidgets==7.6.3
jedi==0.17.2
Jinja2==2.11.2
joblib==1.0.0
jsonschema==3.2.0
jupyter==1.0.0
jupyter-client==6.1.11
jupyter-console==6.2.0
jupyter-core==4.7.0
jupyter-http-over-ws==0.0.8
jupyterlab-pygments==0.1.2
jupyterlab-widgets==1.0.0
jupyterthemes==0.20.0
kiwisolver==1.3.1
lesscpy==0.14.0
llvmlite==0.35.0
MarkupSafe==1.1.1
matplotlib==3.3.3
mistune==0.8.4
nbclient==0.5.1
nbconvert==6.0.7
nbformat==5.1.2
nest-asyncio==1.4.3
networkx==2.5
nose==1.3.7
notebook==6.2.0
numba==0.52.0
numpy==1.19.4
opencv-python==4.4.0.46
packaging==20.8
pandas==1.2.0
pandocfilters==1.4.3
parso==0.7.1
pickleshare==0.7.5
Pillow==7.2.0
ply==3.11
prometheus-client==0.9.0
prompt-toolkit==3.0.10
pycparser==2.20
pyglet==1.5.0
Pygments==2.7.4
pyparsing==2.4.7
pyrsistent==0.17.3
python-dateutil==2.8.1
pytz==2020.5
pywin32==300
pywinpty==0.5.7
pyzmq==21.0.1
qtconsole==5.0.1
QtPy==1.9.0
regex==2020.11.13
scipy==1.6.0
Send2Trash==1.5.0
six==1.15.0
terminado==0.9.2
testpath==0.4.4
torch==1.7.1
torchvision==0.2.2.post3
tornado==6.1
tqdm==4.56.0
traitlets==5.0.5
typing-extensions==3.7.4.3
wcwidth==0.2.5
webencodings==0.5.1
widgetsnbextension==3.5.1
<file_sep># Data gathering
Since the raw files are close to 10GB, I will not include them here.
## r/Jokes
Data was gathered with the script "pushshiftio_scraper.py"
Importand parts extracted in notebook "preprocessing_Siim.ipynb"
Cleaned in notebook "preprocessing_Siim.ipynb".
## Google NQ
Data from: https://ai.google.com/research/NaturalQuestions/dataset
Important parts extracted to a separate file with "cleaning_raw_google_qa.py"
Cleaned in notebook "preprocessing_Siim.ipynb".
## News
Data from: https://components.one/datasets/all-the-news-2-news-articles-dataset/
Importand parts extracted in notebook "preprocessing_Siim.ipynb"
Cleaned in notebook "preprocessing_Siim.ipynb".
<file_sep>import requests
from datetime import datetime
import traceback
import time
import json
url = "https://api.pushshift.io/reddit/{}/search?subreddit={}&limit=500&fields={}&sort=desc&before="
start_time = datetime.utcnow()
def downloadFromUrl(filename, subreddit):
object_type = "submission"
print(f"Saving {object_type}s to {filename}")
count = 0
handle = open(filename, 'a')
previous_epoch = int(start_time.timestamp())
while True:
# new_url = url.format(object_type, username)+str(previous_epoch)
fields = "title,selftext,created_utc,score,id,author,subreddit"
new_url = url.format(object_type, subreddit, fields)+str(previous_epoch)
json_response = requests.get(new_url)
time.sleep(1) # pushshift has a rate limit, if we send requests too fast it will start returning error messages
try:
json_data = json_response.json()
except json.decoder.JSONDecodeError as err:
print(f'Got corrupt json at epoch {previous_epoch}. Trying again.')
continue
if 'data' not in json_data:
print('No data on json response.')
break
objects = json_data['data']
if len(objects) == 0:
break
for object in objects:
previous_epoch = object['created_utc'] - 1
count += 1
if 'selftext' not in object:
continue
try:
importantFields = ["title", "selftext", "created_utc", "score", "id", "author", "subreddit"]
smallJSON = {key:object[key] for key in importantFields}
smallJSON["body"] = smallJSON.pop("selftext")
json.dump(smallJSON,handle, indent=4)
except Exception as err:
print(f"Couldn't print post: {object['url']}")
print(traceback.format_exc())
print("Saved {} {}s through {}".format(count, object_type, datetime.fromtimestamp(previous_epoch).strftime("%Y-%m-%d")))
print(f"Saved {count} {object_type}s")
handle.close()
downloadFromUrl(filename="r_jokes_2021_uncleaned.json", subreddit="jokes") | 0eb2ed946a23405cfb8016ceb21459625a3f8960 | [
"Markdown",
"Python",
"Text"
] | 6 | Markdown | hendriksuvalov/detecting-jokes | 00c92cfffe5e4f0ce6c693787ca646a67450fdab | c54ab917f76132a8f33ec8f0d2e82cb7a7604467 |
refs/heads/master | <file_sep>#! /usr/bin/env python
import os
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy as np
incdirs = [os.getcwd(), np.get_include()]
ext_modules = [
Extension("memleak.extra_types", ["memleak/extra_types.pyx"],
include_dirs=incdirs, language="c++"),
Extension("memleak.stlcontainers", ["memleak/stlcontainers.pyx"],
include_dirs=incdirs, language="c++"),
Extension("memleak.hollow", ['hollow.cpp', "memleak/hollow.pyx", ],
include_dirs=incdirs, language="c++"),
]
setup(
name = 'memleak',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules,
packages = ['memleak']
)
<file_sep>#! /usr/bin/env python
from __future__ import print_function
import sys
import glob
import gc
import resource
N = 10**4
freq = N/100
buildlib = glob.glob('build/lib.*')
sys.path.insert(0, buildlib[0])
from memleak.hollow import Hollow
for n in xrange(N):
#gc.collect()
h = Hollow()
del h
if n%freq == 0:
print(n/freq, resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
sys.stdout.flush()
print()
<file_sep>memory leak tests
=================
This tries a bunch of potential causes of a memory leak in gidden/cyclopts.
A plotting script is provided that can plot the results for any of the following
tests. For example, one can plot the results ``pttest.py`` by ::
$ ./pttest.py > out
$ ./plt.py out
$ eog fig.png
An arbitrary number of files can be plotted against each other, e.g. ::
$ ./pttest.py > out.pt
$ ./pttest-np.py > out.np
$ ./plt.py out.pt out.np
$ eog fig.png
Test 1: xdress
--------------
This is not the cause. To replicate run::
$ xdress --debug
$ ./setup.py build
$ ./memtest.py
Play around with the ``N`` value in memtest and un/comment the gc.collect() call
inside of the loop. If you are running h/top you'll see that the memory
resources are cleaned up correctly.
Test 2: pytables row
--------------------
This test definitely mem leaks. This uses the table row object and the
memory leak seems to be fairly fast. Run this test with::
$ ./pttest.py
Test 3: pytables append
------------------------
This test uses the table append() method rather than the row object.
It also directly appends numpy arrays. This may have a minor memory
leak but it is much slower. Run this test with::
$ pttest-np.py
Conclusion
----------
The row attr should probably be avoided, not just because it is slow!
<file_sep>#! /usr/bin/env python
import sys
import io
from matplotlib import pyplot as plt
def readf(fname):
with io.open(fname) as f:
lines = f.readlines()
lines = [x.strip() for x in lines]
n = [int(x.split()[0]) for x in lines if len(x) > 0]
mem = [float(x.split()[1]) / 1e3 for x in lines if len(x) > 0] # kb to mb
return n, mem
def main():
fnames = sys.argv[1:]
plt.rc('lines', linewidth=2)
plt.rc('axes', color_cycle=['r', 'g', 'b', 'y'])
fig, ax = plt.subplots()
for fname in fnames:
n, mem = readf(fname)
ax.plot(n, mem)
ax.set_xlabel('divisions')
ax.set_ylabel('memory (mb)')
ax.legend(fnames)
plt.savefig('fig.png')
if __name__ == '__main__':
main()
<file_sep>#! /usr/bin/env python
from __future__ import print_function
import os
import gc
import sys
import resource
import numpy as np
import tables as tb
N = 10**4
freq = N/100
_N_CAPS_MAX = 10
exarc = np.dtype([
("instid", ('str', 16)), # 16 bytes for uuid
("id", np.int64),
("uid", np.int64),
("ucaps", (np.float64, _N_CAPS_MAX),), # array of size N_CAPS_MAX
("vid", np.int64),
("vcaps", (np.float64, _N_CAPS_MAX),), # array of size N_CAPS_MAX
("pref", np.float64),
])
data = np.empty(N, dtype=exarc)
with tb.open_file('x.h5', 'w') as f:
tab = f.create_table('/', 'tab', exarc, chunkshape=(N/1000,))
row = tab.row
for n, dat in enumerate(data):
gc.collect()
for name in exarc.names:
row[name] = dat[name]
row.append()
tab.flush()
if n%freq == 0:
print(n/freq, resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
sys.stdout.flush()
print()
<file_sep>#ifndef HOLLOW_H
#define HOLLOW_H
#include <vector>
class Hollow {
public:
Hollow();
std::vector<int> x;
};
#endif // hollow<file_sep>#include "hollow.h"
Hollow::Hollow() {
x.resize(1, 42);
};<file_sep>from xdress.utils import apiname
package = 'memleak' # top-level python package name
extra_types = 'extra_types'
stlcontainers = [
('vector', 'int'),
]
classes = [
apiname('Hollow', 'hollow.*', incfiles='hollow.h'),
]
| 9da25d9b9eaf88ba53fb4eb02469c73fa1cc1d87 | [
"Python",
"C++",
"reStructuredText"
] | 8 | Python | gidden/memleak | 397460213f03ed3f0302722e92feb8c3e1f0a676 | 7ca7d2d0638b82d009e0f364f916f2d032cdd9d4 |
refs/heads/master | <repo_name>ddevault/srht-android<file_sep>/README.md
# sr.ht Android
### Android application for file sharing through [sr.ht](https://sr.ht)
Adds a share feature that uploads the file and shows the link to the uploaded file
## Requires
- Android > 4.0.3
(currently not working)
<file_sep>/app/src/main/java/io/github/wiiam/srhtapp/Share.java
package io.github.wiiam.srhtapp;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.provider.MediaStore;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collection;
import com.loopj.android.http.*;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;
import io.github.wiiam.srhtapp.config.Config;
/**
* Created by william on 9/07/15.
*/
public class Share extends Activity {
private final int maxBufferSize = 104857600;
private static final String DEBUG_TAG = "SHARE-DEBUG";
private static final String tag = "SHARE-DEBUG";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String action = intent.getAction();
if (Intent.ACTION_SEND.equals(action)) {
if (extras.containsKey(Intent.EXTRA_STREAM)) {
// Get resource path
Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
if (uri != null) {
if(Config.getApiKey() == "" || Config.getApiKey() == null){
Toast.makeText(getApplicationContext(),"API key not set",Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(getApplicationContext(),"Uploading file...",Toast.LENGTH_SHORT).show();
String path = parseUriToFilename(uri);
try {
upload(path, intent.getType());
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Upload failed", Toast.LENGTH_SHORT).show();
}
}
}
}
}
private String parseUriToFilename(Uri uri) {
String selectedImagePath = null;
String filemanagerPath = uri.getPath();
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
selectedImagePath = cursor.getString(column_index);
}
if (selectedImagePath != null) {
return selectedImagePath;
}
else if (filemanagerPath != null) {
return filemanagerPath;
}
return null;
}
private void upload(String filepath, String mimetype) throws FileNotFoundException, IOException {
String filename = filepath.split("/")[filepath.split("/").length-1];
RequestParams params = new RequestParams();
params.put("key", Config.getApiKey());
String url = Config.getUrl();
String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimetype);
if (extension != null) {
extension = "." + extension;
} else {
extension = "";
if (mimetype.equals("image/*")) {
extension = ".png"; // stupid guess, browsers can probably handle it anyway
}
}
InputStream stream = new FileInputStream(new File(filepath));
params.put("file", stream, filename + extension);
AsyncHttpClient client = new AsyncHttpClient(true, 80, 443);
client.post("https://" + url + "/api/upload", params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
Uri result = Uri.parse(response.getString("url"));
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("sr.ht URL", result.toString());
clipboard.setPrimaryClip(clip);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, result);
startActivity(launchBrowser);
Toast.makeText(getApplicationContext(), "File uploaded, URL copied to clipboard.", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Upload failed", Toast.LENGTH_SHORT).show();
}
}
});
}
} | d7a97d5823da2ef08be992629394bfefef35d903 | [
"Markdown",
"Java"
] | 2 | Markdown | ddevault/srht-android | ae3493d871f1510c6b0bcbb513bd6522b4e88cf7 | d194c42bd4604175d030eb48a38a176c8eea1e01 |
refs/heads/main | <repo_name>Michaelwong0820/reactRN<file_sep>/demo/navigation-param.js
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { createAppContainer } from 'react-navigation'
import { createStackNavigator } from 'react-navigation-stack';
class HomeScreen extends React.Component {
static navigationOptions = {
title: 'Home'
};
render() {
const params = { id: 1, value: 'this is NewValue' }
return (
<View style={styles.container}>
<Text>Hello, Navigation!</Text>
<View style={{ backgroundColor: 'blue', height: 60, width: 200, alignItems: 'center', justifyContent: 'center', borderRadius: 5 }}>
<Button
title="go to Details"
color="#fff"
onPress={() => {
this.props.navigation.navigate('Detail', params)
}} />
</View>
</View>
)
}
componentDidMount() {
console.log('home - componentDidMount');
}
componentWillUnmount() {
console.log('hmoe - componentWillUnmount');
}
}
class DetailScreen extends React.Component {
static navigationOptions = {
title: 'Detail'
};
render() {
const navigate = this.props.navigation
// console.log(navigate.getParam('id'));
return (
<View style={styles.container}> 】
<Text>Detail!</Text>
<Text>id: {navigate.getParam('id')}</Text>
<Text>value: {navigate.getParam('value')}</Text>
<View style={{ backgroundColor: 'blue', height: 60, width: 200, alignItems: 'center', justifyContent: 'center', borderRadius: 5 }}>
<Button
title="go to Detail"
color="#fff"
onPress={() => {
navigate.push('Detail',{
id: Math.floor(Math.random()*100),
value: 'this is OldValue'
})
}} />
</View>
</View>)
}
componentDidMount() {
console.log('Detail - componentDidMount');
}
componentWillUnmount() {
console.log('Detail - componentWillUnmount');
}
}
const SimpleApp = createStackNavigator({
Home: { screen: HomeScreen },
Detail: { screen: DetailScreen }
}, {
initialRouteName: 'Home'
});
export default createAppContainer(SimpleApp)
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: "space-around"
}
});<file_sep>/src/pages/main/bookScreen/BookList.js
import React from 'react'
import { View, FlatList, Text, StyleSheet, Image } from 'react-native'
import { initialWindowMetrics } from 'react-native-safe-area-context'
import { connect } from 'react-redux'
import actionCreator from '../../../store/action/actionCreator'
class BookList extends React.PureComponent {
constructor(props) {
super(props)
const initBookList = this.props.bookList
}
componentDidMount() {
const { route, getBookList } = this.props
getBookList(route.params.categoryId)
}
_renderItem = ({ item }) => {
console.log(item);
return (
<View style={styles.content}>
<Image source={{ uri: item.img }} style={styles.itemImage} />
<View>
<Text>{item.title}</Text>
<Text style={{overflow:'hidden',width:200,flexWrap:'nowrap'}}>{item.tags}</Text>
</View>
</View>
)
}
render() {
const { bookList } = this.props
console.log(bookList.result.data);
if (bookList) {
return (
<View style={styles.container}>
<FlatList
data={bookList && bookList.result.data}
keyExtractor={(item, index) => {
return index
}}
renderItem={this._renderItem}
/>
</View>
)
} else {
return (
<View style={styles.container}>
<Text>Loading.....</Text>
</View>
)
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
content: {
height: 200,
marginBottom: 10,
backgroundColor: '#fff',
alignItems: "center",
// justifyContent: "center",
width: 350,
flexDirection:'row'
},
itemGroup1: {
flex: 1,
fontWeight: '600'
},
itemGroup2: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-around',
color: '#eee'
},
itemGroup3: {
flex: 2,
flexDirection: 'row'
},
itemImage: {
width: 80,
height: 80,
marginRight: 10
}
})
const mapStateToProps = (state) => {
return {
bookList: state.bookReducer.bookList
}
}
const mapDispatchToProps = (dispatch) => {
return {
getBookList(data) {
dispatch(actionCreator.actionBookListNet(data))
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(BookList)<file_sep>/src/store/reducer/index.js
// 拆分reducer
import {combineReducers} from 'redux'
import newsReducers from './news'
import weatherReducer from './weather'
import bookReducer from './book'
const reducerRouter = combineReducers({
newsReducers,
weatherReducer,
bookReducer
})
export default reducerRouter<file_sep>/README.md
### 组件间传值
父组件传值 : 直接通过属性参数传值
子组件接收值: 通过this.props 获取属性参数
### StyleSheet 使用方式
引入StyleSheet
import { StyleSheet } from 'react-native'
语法 :
```js
// StyleSheet 可以同时定义多个属性值,方便管理,类似于vue的style标签
// 注意: 当一个dom有多个属性值控制时, 使用数组管理 , 具有优先级 , 后面的样式属性会覆盖前面的样式属性
const styles = StyleSheet.create({
red: {
color:'red'
},
blue: {
color:"blue"
},
bigRed: {
color: 'red',
fontWeight : '600',
fontSize: 30
},
bigBlue: {
color: 'blue',
fontWeight: '600',
fontSize : 30
}
})
```
### 标题栏样式
1. 通过静态属性 navigationOptions 配置一个对象 或 返回一个对象属性
2. 根据不同的对象属性进行样式的调整
3. 可自定义标题的显示方式(可图片加文字组合)
4. 跨页面共享标题默认属性,可在根组件的createStackNavigator 中配置默认样式属性
```
title:标题,如果设置了这个导航栏和标签栏的title就会变成一样的,不推荐使用
header:可以设置一些导航的属性,如果隐藏顶部导航栏只要将这个属性设置为``null
headerTitle:设置导航栏标题,推荐
headerBackTitle:设置跳转页面左侧返回箭头后面的文字,默认是上一个页面的标题。可以自定义,也可以设置为``null
headerTruncatedBackTitle:设置当上个页面标题不符合返回箭头后的文字时,默认改成``"返回"
headerRight:设置导航条右侧。可以是按钮或者其他视图控件
headerLeft:设置导航条左侧。可以是按钮或者其他视图控件
headerStyle:设置导航条的样式。背景色,宽高等
headerTitleStyle:设置导航栏文字样式
headerBackTitleStyle:设置导航栏‘返回’文字样式
headerTintColor:设置导航栏颜色
headerPressColorAndroid:安卓独有的设置颜色纹理,需要安卓版本大于5.0
gesturesEnabled:是否支持滑动返回手势,iOS默认支持,安卓默认关闭
screen:对应界面名称,需要填入import之后的页面
mode:定义跳转风格
card:使用iOS和安卓默认的风格
modal:iOS独有的使屏幕从底部画出。类似iOS的present效果
headerMode:返回上级页面时动画效果
float:iOS默认的效果
screen:滑动过程中,整个页面都会返回
none:无动画
cardStyle:自定义设置跳转效果
transitionConfig: 自定义设置滑动返回的配置
onTransitionStart:当转换动画即将开始时被调用的功能
onTransitionEnd:当转换动画完成,将被调用的功能
path:路由中设置的路径的覆盖映射配置
initialRouteName:设置默认的页面组件,必须是上面已注册的页面组件
initialRouteParams:初始路由参数
```
语法:
```js
// 单个组件的标题栏样式
static navigationOptions = {
// header:null,
headerBackTitle:'返回',
headerTitle: 'DetailScreen',
headerStyle: {
backgroundColor:"pink"
},
headerTitleStyle : {
color:'skyblue',
fontSize: 16
}
};
// 根组件定义默认样式
const SimpleApp = createStackNavigator({
Home: { screen: HomeScreen },
Detail: { screen: DetailScreen }
}, {
initialRouteName: 'Home',
defaultNavigationOptions: {
headerTitle: 'Home',
headerStyle: {
backgroundColor:"#2A60E4"
},
headerTitleStyle : {
color:'#fff',
fontSize: 18,
fontWeight: 'bold'
}
}
});
// 自定义标题内容
static navigationOptions = {
headerTitle:()=> <LogoTitle />
}
class LogoTitle extends React.Component {
render() {
return (
<Image
source={{uri:'https://...'}} // source={require('./...')}
style={{ width: 30, height: 30 }}
/>
)
}
}
```
### react-navigation (路由的配置)
https://reactnavigation.org/docs/getting-started
1. 安装核心包 yarn add @react-navigation/native
2. 安装依赖 yarn add
react-native-reanimated
react-native-gesture-handler
react-native-screens
react-native-safe-area-context
@react-native-community/masked-view
3. 使用createStackNavigator 配置 基础导航器
yarn add @react-navigation/stack
4. iOS 端需要 pod install 重新安装依赖
5. 基础步骤
1. 引入 import { createStackNavigator } from '@react-navigation/stack';
2. 配置路由信息 createStackNavigator({路由项},{基础路由配置})
3. 使用 NavigationContairner / createStackNavigator 生成组件进行包裹 ,导出组件作为根组件
4. onPress 事件 调用 navigation.navigate({ routeName: Path }) 方法
#### 路由API
https://reactnavigation.org/docs/navigation-prop
1. 应用中的每个页面组件都会自动提供 this.props.navigation
this.props.navigation可以获取的一些方法:
- **`navigate`** - 转到另一个页面, 计算出需要执行的操作 (常用)
- **`goBack`** - 关闭活动屏幕并在堆栈中向后移动 (常用)
- `addListener` - 订阅导航生命周期的更新
- `isFocused` - 函数返回 `true` 如果屏幕焦点和 `false` 否则。
- **`state`** - 当前状态/路由 (常用)
- **`setParams`** - 对路由的参数进行更改 (常用)
- **`getParam`** - 获取具有回退的特定参数 (常用)
- **`dispatch`** - 向路由发送 action (常用)
- `dangerouslyGetParent` - 返回父级 navigator 的函数
注意: this.props.navigation并不是在所有页面(组件)中都可以使用,而是必须在StackNavigator、DrawerNavigator中声明的screen组件,才可以使用this.props.navigation
也就是说,screen组件会自动获得这个props
**`this.props.navigation` 上还有一些方法取决于当前 navigator 的附加函数(StackNavigator 和 DrawerNavigator)**
2. 如果是StackNavigator,除了以上方法,this.props.navigation还提供如下的一些方法:
- **`push`** - 推一个新的路由到堆栈 (常用)
- **`pop`** - 返回堆栈中的上一个页面 (常用)
- **`popToTop`** - 跳转到堆栈中最顶层的页面 (常用)
- `replace` - 用新路由替换当前路由
- **reset**- 操作会擦除整个导航状态,并将其替换为多个操作的结果。 (常用)
- `dismiss` - 关闭当前堆栈
3. 如果是DrawerNavigator,除了以上方法,this.props.navigation还提供如下的一些方法:
- `openDrawer` - 打开
- `closeDrawer` - 关闭
- `toggleDrawer` - 切换,如果是打开则关闭,反之亦然
#### 路由传参
navigation.navigate(routeName, {
key1 : 值1,
key2 : 值2,
......
}) // 路由传参
navigation.getParam(key,默认值) // 获取路由中的参数,此方法是4.x版本
5.x版本接收路由参数
const {route} = this.props
路由的参数都存放在route.params中
#### 路由配置
createAppContainer 路由容器,包裹路由配置在根组件
```
import { createAppContainer } from 'react-navigation'
// ...///
export default createAppContainer('')
```
createStackNavigator 路由配置,创建页面,配置路由跳转的属性,可自定义标题栏的样式属性
```js
import { createStackNavigator } from 'react-navigation-stack';
class HomeScreen extends React.Component {
static navigationOptions: {
// 配置单组件的路由标题栏样式
}
...//
}
class PageScreen extends React.Component {
...//
}
const AppStack = createStackNavigator(
{
Home: {
screen: HomeScreen
},
Page: {
screen:PageScreen
}
}, {
// 默认标题栏配置项
initialRouteName: 'Home',
defaultNavigationOptions: {
headerTitle: null,
headerStyle: {
backgroundColor: "#2A60E4"
},
headerTitleStyle: {
color: '#fff',
fontSize: 18,
fontWeight: 'bold'
}
}
)
```
createSwitchNavigator 主页面的跳转,适用于登录页面或者注册页面跳转到主页面
```js
import { createSwitchNavigator} from 'react-navigation'
const App = createStackNavigator({
Home: {
screen: HomeScreen
},
Page: {
screen:Page1Screen
},
Login: {
screen:LoginScreen
}
}, {
initialRouteName: 'Home',
defaultNavigationOptions: {
headerTitle: null,
headerStyle: {
backgroundColor: "#2A60E4"
},
headerTitleStyle: {
color: '#fff',
fontSize: 18,
fontWeight: 'bold'
}
}
})
const Auth = createStackNavigator({
Login:{
screen:LoginScreen
}
},{
initialRouteName:'Login'
})
const switchNavigator = createSwitchNavigator({
App:{
screen:App
},
Auth:{
screen:Auth
}
},{
initialRouteName:'Auth'
})
// 在路由容器中导出
export default createAppContainer(switchNavigator)
```
注意 :使用createSwitchNavigator配置的页面不能使用navigation.goBack()返回到上一级
#### 路由工具
新建文件NavigationUtil.js
```js
class NavigationUtil {
static goPage(page,params) {
const navigation = NavigationUtil.navigation
if(!navigation) {
alert('navigation can not be null !')
return
}
navigation.navigate(page,params)
}
static goBack(navigation) {
navigation.goBack()
}
static goHome(params) {
const navigation = params
navigation.navigate('home')
}
}
export default NavigationUtil
```
#### 5.x版本的路由配置
```js
import React from 'react'
import { View, Text, Button, SectionList, SafeAreaView, StyleSheet } from 'react-native'
import { NavigationContainer } from '@react-navigation/native'
import { createStackNavigator } from '@react-navigation/stack'
class HomeScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home</Text>
<Button
title="goToPage"
color="#f00"
onPress={() => {
this.props.navigation.navigate('Section',{id:1,name:'john'})
}}
/>
</View>
)
}
}
class SectionScreen extends React.Component {
render() {
return (
<View>
....
</View>
)
}
}
const Stack = createStackNavigator()
const MyStack = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Section" component={SectionScreen} />
</Stack.Navigator>
</NavigationContainer>
)
}
export default MyStack
```
### RN原生组件
https://reactnative.cn/docs/components-and-apis
#### DrawerNavigation 抽屉式导航
安装依赖 yarn add @react-navigation/drawer
引包 : import { createDrawerNavigator } from '@react-navigation/drawer'
语法:
```js
const Drawer = createDrawerNavigator()
const MyDrawer = () => {
return (
<NavigationContainer> //路由容器
<Drawer.Navigator initialRouteName="Page1"> //导航容器
<Drawer.Screen //路由组件
name="Page1"
component={Page1Screen}
options={{
drawerLabel:'Page1',
drawerIcon:({tiniColor,focused})=> (
<MaterialIcon
style={tiniColor}
size={24}
name={'360'}
/>
)
}}
/>
</Drawer.Navigator>
</NavigationContainer>
```
### Hooks
在无状态组件中使用Hooks,实现在组件中可使用有状态组件同样数据操作
#### useState
语法 : const [count,setCount] = useState(0) // useState本质是一个数组,初始值可传Number,String,Object,Array
特殊用法:
useState除了可传上述值,还可通过函数返回一个值
useState(()=>{
....
return 值
})
#### useEffect
作用:在render之后处理行为,可传递函数,使无状态组件可以有效访问state变量和props
语法:useEffect(()=>{
执行的js代码
})
运行于首次render和每次update的时候
当需采取事件监听时:
useEffect(参1,参2)
参1:执行监听的方法,必须在事件结束后清除监听,否则会产生内存泄漏
参2:监听的值,默认传空数组‘[]’(变量),如果传空数组,事件只会执行一次,不传则每次update都会执行一次,并且当有多个useEffect的事件在同时执行时,没有设置就会发送冲突
```js
const [reWidth,setReWidth] = useState(document.body.clientWidth)
const resetWidth = () =>{
setReWidth(document.body.clientWidth)
}
useEffect(()=>{
console.log('====================================');
console.log('width');
console.log('====================================');
window.addEventListener('resize',resetWidth,false)
return(()=>{
window.removeEventListener('resize',resetWidth,false)
})
},[])
useEffect(()=>{
console.log('====================================');
console.log('name');
console.log('====================================');
document.title = `my name is ${name.name}`
},[name])
```
#### useContext
组件间传值,没有层级的限制,子孙组件都可以拿到父组件传的值
语法:const {Provider,Consumer} = React.createContext(默认值)
Provider:以标签的格式包裹着组件,value属性传递所需的值
Consumer:以标签的格式包裹组件,必须是js返回的组件内容,注意:不能直接对dom数据进行操作
**多个Context传值:**
当有多个context传值时,可使用context.Provider ,组件接受值也是根据对应的context.Consumer获取
```js
// const { Provider, Consumer } = React.createContext("default");
// 多个context传值
const momeyContext = React.createContext(0);
const houseContext = React.createContext("default");
class Father extends React.Component {
constructor(props) {
super(props);
this.state = {
momey: 100,
house: "复式别墅",
};
}
render() {
const momey = 100;
return (
<momeyContext.Provider value={this.state.momey}>
<houseContext.Provider value={this.state.house}>
<div
style={{
border: "1px solid #000",
width: "40%",
margin: "50px auto",
}}
>
<p>father momey:{this.state.momey}</p>
<p>father house:{this.state.house}</p>
<Son />
</div>
</houseContext.Provider>
</momeyContext.Provider>
);
}
}
function Son(props) {
return (
<momeyContext.Consumer
>
{(momey) => (
<div style={{ border: "1px solid #000", width: "40%", margin: 10 }}>
<p>father give {momey}</p>
<GrandSon name="儿子" />
</div>
)}
</momeyContext.Consumer>
);
}
function GrandSon(props) {
return (
<momeyContext.Consumer>
{(momey) => (
<houseContext.Consumer>
{(house) => (
<div style={{ border: "1px solid #000", width: "40%", margin: 10 }}>
<p>son give {momey}</p>
<p>house:{house}</p>
</div>
)}
</houseContext.Consumer>
)}
</momeyContext.Consumer>
);
}
```
拓展点:
**contextType:**
当有多个context嵌套时,使用contextType可以解决嵌套问题,必须作用于类组件中,只支持一个
```js
class Son extends React.Component{
static contextType = momeyContext //固定格式
render() {
const momey = this.context
return(
<div>
<p>son{momey}</p>
</div>
)
}
}
```
当父组件的值发生改变时,子组件的值同时发生改变
**useContext**:
使用useContext 可以支持多个context.Provider传过来的值
```js
function Childs() {
const momey = useContext(momeyContext);
const house = useContext(houseContext);
return (
<div>
<p>momey:{momey}</p>
<p>house:{house}</p>
</div>
);
}
```
#### useMemo
根据依赖项变化而执行的hooks,类似于computed,不能针对副作用处理
会在组件第一次渲染的时候执行,之后会在其依赖的变量发生改变时再次执行,返回的是缓存的变量
必须在第二个参数绑定依赖项,否则只会在第一渲染的时候执行,不会根据依赖项改变
优点:优化性能
```js
const [count, setCount] = useState(0);
const add = useMemo(() => {
return count + 1;
}, [count]);
```
#### useCallback
useCallback是useMemo的语法糖,能够使用useCallback的必定能使用useMemo
区别:useCallback返回的是缓存的函数,useMemo返回的是缓存的变量
依赖变化会重新执行,生成一个新的函数
```js
const addCount = useCallback(() => {
setCount(count + 1);
}, [count]);
```
useCallback与React.memo 同时使用,性能优化效果更佳
#### useReducer
在function组件中使用类Redux功能
*const* [state, dispatch] = useReducer(reducer, *initCount*,init);
参数定义:
1. reducer:store的配置
2. *initCount*:初始数据
3. init:惰性初始化,对初始数据进行处理再返回
```js
import React, { useReducer } from "react";
function init (initCount) {
initCount = initCount +5
return {count:initCount}
}
function reducer(state, action) {
switch (action.type) {
case "increate":
return {count:state.count + 1};
case "decreate":
return {count:state.count - 1};
default:
return state;
}
}
// var initCount = {count:0}
function Counter({initCount}) {
const [state, dispatch] = useReducer(reducer, initCount,init);
return (
<>
<div>count:{state.count}</div>
<div>
<button onClick={()=>dispatch({type:'increate'})}>++</button>
</div>
<div>
<button onClick={()=>dispatch({type:'decreate'})}>--</button>
</div>
</>
);
}
const App = ()=><Counter initCount={10} />
export default App
```
#### useRef
function 组件使用hooks 绑定dom组件,即可绑定dom结构,也可绑定子组件获取子组件的数据
运用场景:当需要改变唯一值时可以使用,使输入的唯一值在发生改变时可以直接体现
意义:可以替代class组件的唯一值修改变化,同步到使用的方法内
```js
const inputRef = useRef()
const handleChange = (e) => {
inputRef.current.value = e.target.value
}
const handleClick = () => {
setTimeout(()=>{
alert(inputRef.current.value)
},3000)
}
return (
<>
<div>
<input type="text" ref={inputRef} name="" id="" onChange={handleChange}/>
<button onClick={handleClick}>click me</button>
</div>
</>
)
```
#### useImperativeHandle
作用:父组件需要调用子组件属性方式时,暴露给父组件的实例值,`useImperativeHandle` 应当与 [`forwardRef`](https://react.docschina.org/docs/react-api.html#reactforwardref) 一起使用
```js
function FancyInput(props, ref) {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} ... />;
}
FancyInput = forwardRef(FancyInput);
```
渲染 `<FancyInput ref={inputRef} />` 的父组件可以调用 `inputRef.current.focus()`
### AsyncStorage
缓存数据信息
与localStorage作用一致
方法:
1、AsyncStorage.setItem(key,value,callback)
2、AsyncStorage.getItem(key,callback)
3、AsyncStorage.removeItem(key)
4、AsyncStorage.merge(key,value,callback) // 合并缓存
5、AsyncStorage.clear() // 清除所有缓存
即可使用then接受缓存值
### React-native-storage
https://github.com/sunnylqm/react-native-storage/blob/HEAD/README.zh-CN.md
这是一个本地持久存储的封装,可以同时支持 react-native(AsyncStorage)和浏览器(localStorage)
安装依赖
```
yarn add react-native-storage
yarn add @react-native-community/async-storage
```
封装storageUtils插件
```js
// storageUtils.js
import Storage from 'react-native-storage';
import AsyncStorage from '@react-native-community/async-storage';
const storage = new Storage({
// 最大容量,默认值1000条数据循环存储
size: 1000,
// 存储引擎:对于RN使用AsyncStorage,对于web使用window.localStorage
// 如果不指定则数据只会保存在内存中,重启后即丢失
storageBackend: AsyncStorage,
// 数据过期时间,默认一整天(1000 * 3600 * 24 毫秒),设为null则永不过期
defaultExpires: 1000 * 3600 * 24,
// 读写时在内存中缓存数据。默认启用。
enableCache: true,
// 你可以在构造函数这里就写好sync的方法
// 或是在任何时候,直接对storage.sync进行赋值修改
// 或是写到另一个文件里,这里require引入
// 如果storage中没有相应数据,或数据已过期,
// 则会调用相应的sync方法,无缝返回最新数据。
// sync方法的具体说明会在后文提到
sync: require('你可以另外写一个文件专门处理sync'),
});
export default storage;
```
### 性能优化
浅度优化:使用生命周期shouldComponentUpdate 监听是否有变化,重新渲染dom
深度优化:class 组件:使用PureComponent 可实现直接监听子组件的dom是否发生改变,判断是否需要重新渲染
function组件:使用memo
<file_sep>/demo/5.xnavigation-stack.js
import React from 'react'
import { View, Text, Button, SectionList, SafeAreaView, StyleSheet, Image } from 'react-native'
import { NavigationContainer } from '@react-navigation/native'
import { createStackNavigator } from '@react-navigation/stack'
class HomeScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home</Text>
<Button
title="goToPage"
color="#f00"
onPress={() => {
this.props.navigation.navigate('Section', { id: 1, name: 'john' })
}}
/>
</View>
)
}
}
class LogoTitle extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<Image
source={{ uri: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603967495082&di=7380af7856300c5cfd6617c7e136845c&imgtype=0&src=http%3A%2F%2Fku.90sjimg.com%2Felement_origin_min_pic%2F17%2F03%2F26%2Fcafc6ea253bc2ebc78918dc44c8671c7.jpg' }}
style={{ width: 30, height: 30 }}
/>
)
}
}
const DATA_CITY = [
{
title: "Main dishes",
data: ["Pizza", "Burger", "Risotto"]
},
{
title: "Sides",
data: ["French Fries", "Onion Rings", "Fried Shrimps"]
},
{
title: "Drinks",
data: ["Water", "Coke", "Beer"]
},
{
title: "Desserts",
data: ["Cheese Cake", "Ice Cream"]
}
];
class SectionScreen extends React.Component {
constructor(props) {
super(props)
this.state = {
data: DATA_CITY
}
}
_renderItems = (item) => {
return (
<View style={styles.item}>
<Text style={styles.title}>{item}</Text>
</View>
)
}
_sectionHeader = ({ section: { title } }) => {
return (
<Text style={styles.header}>{title}</Text>
)
}
render() {
console.log(this.props);
const { params } = this.props.route
return (
<SafeAreaView style={styles.container}>
<SectionList
sections={this.state.data}
keyExtractor={(item, index) => item + index}
renderItem={({ item }) => this._renderItems(item)}
renderSectionHeader={(item) => this._sectionHeader(item)}
/>
</SafeAreaView>
)
}
}
const Stack = createStackNavigator()
const MyStack = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home" screenOptions={{
headerTitleStyle: {
fontSize: 20,
fontWeight: '600',
},
headerTintColor: "#fff",
headerStyle: {
backgroundColor: "#ff0034"
}
}}>
<Stack.Screen name="Home" component={HomeScreen}
options={{
title: 'My Home',
headerTitleStyle: {
fontSize: 20,
fontWeight: '600',
},
headerTintColor: "#fff",
headerStyle: {
backgroundColor: "#ff0034"
},
headerTitle: (props) => <LogoTitle {...props}/>
}} />
<Stack.Screen name="Section" component={SectionScreen}
options={({ route }) => {
return {
title: route.params.name
}
}} />
</Stack.Navigator>
</NavigationContainer>
)
}
export default MyStack
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 20,
marginHorizontal: 16
},
item: {
backgroundColor: "#f9c2ff",
padding: 20,
marginVertical: 8
},
header: {
fontSize: 32,
backgroundColor: "#fff"
},
title: {
fontSize: 24
}
});
<file_sep>/src/store/action/news/index.js
import TYPE from '../types'
export function actionNetNews (data,category) {
return {
type: TYPE.TYPE_NEWS_NET,
data,
category
}
}
export function actionNewsFresh (data,category) {
return {
type: TYPE.TYPE_NEWS_FRESH,
data,
category
}
}
export function actionNewsData (category) {
console.log('---',category);
return (dispatch)=> {
const url = `http://v.juhe.cn/toutiao/index?type=${category}&key=25c017e18f559ef538308b1c2a891f23`
fetch(url)
.then(response=>{
if(response.ok) {
return response.json()
}
throw new Error('network in error')
})
.then(res=>{
const action = actionNetNews(res,category)
dispatch(action)
})
.catch(e=>{
console.log(e);
})
}
}<file_sep>/src/pages/main/Mode.js
import React from 'react'
import {Text,View,Button} from 'react-native'
import NavigationUtil from '../../utils/navigationUtil'
class ModeScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Mode</Text>
<Button
title="goToDetails"
onPress={()=>{
NavigationUtil.goPage('details')
}}
/>
<Button
title="goBack"
onPress={()=>{
NavigationUtil.goHome(this.props.navigation)
}}
/>
</View>
)
}
}
export default ModeScreen<file_sep>/src/pages/Navigation/BottomNavigation.js
import React from 'react'
import { createMaterialBottomTabNavigator } from '@react-navigation/material-bottom-tabs'
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import Bottom1 from '../main/Bottom1'
import Bottom2 from '../main/Bottom2'
import Bottom3 from '../main/Bottom3'
import Bottom4 from '../main/Bottom4'
import Book from '../main/bookScreen/Main1'
const Bottom = createMaterialBottomTabNavigator()
const HomeScreen = () => {
return (
<Bottom.Navigator
activeColor="#f0edf6"
inactiveColor="#3e2465"
barStyle={{ backgroundColor: '#694fad', height: 80, padding: 10 }}>
<Bottom.Screen name="Page1" component={Bottom1} options={{
tabBarLabel: '新闻',
tabBarIcon: ({ color }) => (
<MaterialCommunityIcons name="home" color={color} size={26} />
),
}} />
<Bottom.Screen name="Page2" component={Bottom2} options={{
tabBarLabel: '天气',
tabBarIcon: ({ color }) => (
<MaterialCommunityIcons name="bell" color={color} size={26} />
),
}} />
<Bottom.Screen name="Page3" component={Book} options={{
tabBarLabel: '图书',
tabBarIcon: ({ color }) => (
<MaterialCommunityIcons name="car" color={color} size={26} />
),
}} />
<Bottom.Screen name="Page4" component={Bottom4} options={{
tabBarLabel: '用户',
tabBarIcon: ({ color }) => (
<MaterialCommunityIcons name="account" color={color} size={26} />
),
}} />
</Bottom.Navigator>
)
}
export default HomeScreen<file_sep>/src/store/action/book/index.js
import TYPE from '../types'
export function actionBookNet (data) {
return {
type:TYPE.TYPE_DATA_BOOK,
data
}
}
export function actionBookFresh (data) {
return {
type: TYPE.TYPE_BOOK_FRESH,
data,
category
}
}
export function actionBookAsync (data) {
return (dispatch)=> {
const url = `http://apis.juhe.cn/goodbook/catalog?dtype${data}=&key=74ffe3d155ebe5e77a692dfa6b0c6e9a`
fetch(url)
.then(response=>{
if(response.ok) {
return response.json()
}
throw new Error('network is error')
})
.then(res=>{
const action = actionBookNet(res)
dispatch(action)
})
.catch(e=>{
console.log(e);
})
}
}
export function actionBookList(data) {
return {
data,
type:TYPE.TYPT_BOOK_NET
}
}
export function actionBookListNet(data) {
return (dispatch) => {
const url = `http://apis.juhe.cn/goodbook/query?catalog_id=${data}&pn=1&rn=10&dtype=json&key=74ffe3d155ebe5e77a692dfa6b0c6e9a`
fetch(url)
.then(response=>{
if(response.ok) {
return response.json()
}
throw new Error('network is error')
})
.then(res=>{
// console.log('net',res.result);
const action = actionBookList(res)
dispatch(action)
})
.catch(e=>{
console.log(e);
})
}
}<file_sep>/src/pages/main/Bottom2.js
import React from 'react'
import { Text, View, FlatList, StyleSheet, ActivityIndicator } from 'react-native'
import { connect } from 'react-redux'
import actionCreators from '../../store/action/actionCreator'
// const PROVINCE_CITY = [{ city: '广东', id: 1001 }, { city: '上海', id: 1002 }, { city: '重庆', id: 1003 }, { city: '北京', id: 1004 }, { city: '湖南', id: 1005 }]
class Page2Screen extends React.Component {
constructor(props) {
super(props)
this.state = {
initCity: '哈尔滨',
// data: PROVINCE_CITY,
isLoading: false
}
}
_renderItem = (item) => {
return (
<View style={styles.container}>
<Text style={styles.city}>{item.weather}</Text>
</View>
)
}
renderData = () => {
const { getWeatherData,getWeatherFresh } = this.props
getWeatherFresh(true)
getWeatherData('上海')
// this.setState({
// isLoading: true
// })
}
loadComponent = () => {
return (
<View style={styles.loadComponents}>
<ActivityIndicator style={styles.indicator} size="large" color="#0000ff" animating={true} />
</View>
)
}
endData = () => {
console.log(1);
setTimeout(() => {
const newData = [{ city: '东莞', id: 1011 }, { city: '广州', id: 1012 }, { city: '深圳', id: 1013 }, { city: '中山', id: 1014 }, { city: '惠州', id: 1015 }]
this.setState({
data: [...this.state.data, ...newData]
})
}, 2000)
}
componentDidMount() {
this.props.getWeatherData(this.state.initCity)
}
render() {
const { weatherData,isFreshing } = this.props
// console.log(this.props);
// if(!weatherData) {
// return (<>
// </>)
// }
if (weatherData) {
return (
<View>
<View style={[styles.container, { backgroundColor: 'green' }]}>
<Text style={styles.city}>
{/* update:msg */}
{weatherData&&weatherData.result.city}
</Text>
</View>
<FlatList
data={weatherData && weatherData.result.future}
keyExtractor={(item) => {
return item.date
}}
renderItem={({ item }) => this._renderItem(item)}
refreshing={isFreshing}
onRefresh={() => {
this.renderData()
}}
// ListFooterComponent={
// this.loadComponent()
// }
// onEndReached={()=>{
// this.endData()
// }}
// onEndReachedThreshold={0.1}
/>
</View>
)
} else {
return (
<View style={styles.load}>
<ActivityIndicator
size="large" color="#0000ff" animating={true}
/>
</View>
)
}
}
}
function mapStateToProps(state) {
return {
weatherData: state.weatherReducer.weather,
isFreshing:state.weatherReducer.isFresh
}
}
function mapDispatchToProps(dispatch) {
return {
getWeatherData: (city) => {
let action = actionCreators.actionWeatherData(city)
dispatch(action)
},
getWeatherFresh: (flag) => {
dispatch(actionCreators.actionWeatherFresh(flag))
}
}
}
const newScreen = connect(
mapStateToProps,
mapDispatchToProps
)(Page2Screen)
export default newScreen
const styles = StyleSheet.create({
load: {
flex: 1,
alignItems: "center",
justifyContent: "center"
},
container: {
height: 200,
marginBottom: 10,
backgroundColor: '#fff',
alignItems: "center",
justifyContent: "center"
},
city: {
fontSize: 16,
fontWeight: '600',
color: "skyblue"
},
loadComponents: {
alignSelf: 'center',
},
indicator: {
margin: 10
}
})<file_sep>/demo/navigation-bottom.js
import React from 'react';
import { StyleSheet, Text, View, Button, Image } from 'react-native';
import { createAppContainer } from 'react-navigation'
import { createStackNavigator } from 'react-navigation-stack';
import { createMaterialTopTabNavigator, createBottomTabNavigator } from 'react-navigation-tabs';
import Icon from 'react-native-vector-icons/AntDesign'
class TopScreen extends React.Component {
static navigationOptions = {
headerTitle: 'page1'
}
render() {
return (
<View>
<Text>Page1Screen</Text>
</View>
)
}
}
const topBar = createMaterialTopTabNavigator({
page1: {
screen: TopScreen,
navigationOptions: {
tabBarLabel: 'all'
}
},
page2: {
screen: TopScreen,
navigationOptions: {
tabBarLabel: 'vue'
}
},
page3: {
screen: TopScreen,
navigationOptions: {
tabBarLabel: 'react'
}
},
page4: {
screen: TopScreen,
navigationOptions: {
tabBarLabel: 'angular'
}
}
}, {
tabBarOptions: {
style: {
backgroundColor: '#443200'
},
labelStyle: {
fontSize: 12
},
// tabStyle: {
// width:120
// },
// upperCaseLabel:false,
// scrollEnabled:true
}
})
class Page1Screen extends React.Component {
render() {
return (
<View>
<Text>Page1Screen</Text>
</View>
)
}
}
class Page2Screen extends React.Component {
render() {
return (
<View>
<Text>Page2Screen</Text>
</View>
)
}
}
class Page3Screen extends React.Component {
render() {
return (
<View>
<Text>Page3Screen</Text>
</View>
)
}
}
class Page4Screen extends React.Component {
render() {
return (
<View>
<Text>Page4Screen</Text>
</View>
)
}
}
const bottomBar = createBottomTabNavigator({
Tab1: {
screen: Page1Screen,
navigationOptions: {
tabBarLabel: 'Home',
tabBarIcon: ({ tintColor, focused }) => (<Icon name="home" size={30} color={tintColor} />)
}
},
Tab2: {
screen: Page2Screen,
navigationOptions: {
tabBarLabel: 'Line',
tabBarIcon: ({ tintColor, focused }) => (<Icon name="logout" size={30} color={tintColor} />)
}
},
Tab3: {
screen: Page3Screen,
navigationOptions: {
tabBarLabel: 'Comstour',
tabBarIcon: ({ tintColor, focused }) => (<Icon name="form" size={30} color={tintColor} />)
}
},
Tab4: {
screen: Page4Screen,
navigationOptions: {
tabBarLabel: 'User',
tabBarIcon: ({ tintColor, focused }) => (<Icon name="wechat" size={30} color={tintColor} />)
}
},
}, {
tabBarOptions: {
style: {
backgroundColor: 'green',
height:30,
paddingTop:6,
paddingBottom:6
},
labelStyle: {
fontSize: 12,
// color:'#fff'
},
activeTintColor: 'red',
inactiveTintColor: '#fff'
// tabStyle: {
// width:120
// },
// upperCaseLabel:false,
// scrollEnabled:true
}
})
class HomeScreen extends React.Component {
static navigationOptions = {
headerTitle:'Home'
}
render() {
const { navigation } = this.props
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>HomeScreen</Text>
<Icon name="home" size={30} color="#900" />
<Button
title="top"
color="#f00"
onPress={() => { navigation.navigate('topBar') }}
/>
<Button
title="bottom"
color="#f0f"
onPress={() => { navigation.navigate('bottomBar') }}
/>
</View>
)
}
}
const stack = createStackNavigator({
Home: {
screen: HomeScreen
},
topBar: {
screen: topBar
},
bottomBar: {
screen: bottomBar
}
}, {
initialRouteName: 'Home',
defaultNavigationOptions: {
headerTitle: null,
headerStyle: {
backgroundColor: "#2A60E4"
},
headerTitleStyle: {
color: '#fff',
fontSize: 18,
fontWeight: 'bold'
}
}
})
export default createAppContainer(stack)<file_sep>/demo/WidthHeight.js
import React from 'react'
import { View, Text , StyleSheet } from 'react-native'
// react-native 宽高设置不需要设置单位 === 代表独立像素
// android 设备 宽高自动解析成 dp 单位 , 字体大小自动解析成 sp 单位
// ios 设备 宽高自动解析成 pt 单位
const styles = StyleSheet.create({
pickOne: {
backgroundColor: 'skyblue',
width: 60,
height: 60
},
pickTwo: {
backgroundColor: 'pink',
width: 80,
height :80
}
})
class InfoStyle extends React.Component {
render() {
return (
<View style={{marginTop:50}}>
<View style={styles.pickOne}></View>
<View style={styles.pickTwo}></View>
</View>
)
}
}
export default InfoStyle<file_sep>/src/pages/main/Bottom4.js
import React from 'react'
import { Text, View, Button } from 'react-native'
class Page4Screen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Page4</Text>
<Button
title="goRedux"
onPress={()=>{
this.props.navigation.navigate('redux')
}}
/>
<Button
title="goReactRedux"
onPress={()=>{
this.props.navigation.navigate('reactRedux')
}}
/>
<Button
title="goTouchable"
onPress={()=>{
this.props.navigation.navigate('touchable')
}}
/>
</View>
)
}
}
export default Page4Screen<file_sep>/src/utils/storageUtil.js
import Storage from 'react-native-storage'
import AsyncStorage from '@react-native-community/async-storage'
let storage = null
let size = 1000
let defaultExpires = 24 * 3600 * 1000
// 本地数据持久化
const createStorage = () => {
storage = new Storage({
size: size, //数量数
// 存储引擎 不指定,存储在内存中,重启失效
storageBackend: AsyncStorage,
// 过期时间,传null 永不过期
defaultExpires: defaultExpires,
// 读写缓存
enableCache: true
})
}
// 单列模式
const initStorage = () => {
if (!storage) {
createStorage()
}
}
// 进行二次封装
const _storage = {
save(key, value) {
initStorage()
storage.save({
key: key,
data: value,
expires: defaultExpires, //过期时间
})
},
get(key, callback) {
initStorage()
storage.load({
key: key,
autoSync: true,
syncInBackground: true,
syncPrams: {
extraFetchOptions: {
},
someFlag: true
}
}).then(res => {
callback && callback(res)
return res
}).catch(err => {
console.log(err.message);
})
},
getAllDataForId(key, callback) {
initStorage()
storage.getAllDataForId(key).then(res => {
callback && callback(res)
})
},
clearMapForKey(key) {
initStorage()
storage.clearMapForKey(key)
},
remove(key) {
initStorage()
storage.remove({ key })
},
clear() {
initStorage()
storage.clear()
}
}
export { _storage as storageUtils } <file_sep>/src/utils/navigationUtil.js
class NavigationUtil {
static goPage(page,params) {
const navigation = NavigationUtil.navigation
if(!navigation) {
alert('navigation can not be null !')
return
}
navigation.navigate(page,params)
}
static goBack(navigation) {
navigation.goBack()
}
static goHome(params) {
const navigation = params
navigation.navigate('home')
}
}
export default NavigationUtil<file_sep>/demo/5.xBottomTab.js
import React from 'react'
import { View, Text, Button } from 'react-native'
import { NavigationContainer } from '@react-navigation/native'
import { createMaterialBottomTabNavigator } from '@react-navigation/material-bottom-tabs'
import { createStackNavigator } from '@react-navigation/stack'
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
class HomeScreen extends React.Component {
render() {
return (
<View>
<Button
title="goToPage"
onPress={() => {
this.props.navigation.navigate('Bottom')
}}
/>
</View>
)
}
}
class Page1Screen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Page1</Text>
</View>
)
}
}
class Page2Screen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Page2</Text>
</View>
)
}
}
class Page3Screen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Page3</Text>
</View>
)
}
}
class Page4Screen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Page4</Text>
</View>
)
}
}
class Page5Screen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Page5</Text>
</View>
)
}
} class Page6Screen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Page6</Text>
</View>
)
}
}
const Bottom = createMaterialBottomTabNavigator()
const TopScreen = () => {
return (
<Bottom.Navigator
activeColor="#f0edf6"
inactiveColor="#3e2465"
barStyle={{ backgroundColor: '#694fad',height:80,padding:10}}>
<Bottom.Screen name="Page1" component={Page1Screen} options={{
tabBarLabel: '首页',
tabBarIcon: ({ color }) => (
<MaterialCommunityIcons name="home" color={color} size={26} />
),
}} />
<Bottom.Screen name="Page2" component={Page2Screen} options={{
tabBarLabel: '信息',
tabBarIcon: ({ color }) => (
<MaterialCommunityIcons name="bell" color={color} size={26} />
),
}} />
<Bottom.Screen name="Page3" component={Page3Screen} options={{
tabBarLabel: '导航',
tabBarIcon: ({ color }) => (
<MaterialCommunityIcons name="car" color={color} size={26} />
),
}} />
<Bottom.Screen name="Page4" component={Page4Screen} options={{
tabBarLabel: '用户',
tabBarIcon: ({ color }) => (
<MaterialCommunityIcons name="account" color={color} size={26} />
),
}} />
</Bottom.Navigator>
)
}
const Stack = createStackNavigator()
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Bottom" component={TopScreen} />
</Stack.Navigator>
</NavigationContainer>
)
}
export default App<file_sep>/demo/flatList-load.js
import React from 'react';
import { StyleSheet, Text, View, Button, FlatList, RefreshControl, ActivityIndicator } from 'react-native';
import { createAppContainer } from 'react-navigation'
import { createStackNavigator } from 'react-navigation-stack';
class HomeScreen extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<View style={styles.contairner}>
<Text>Home</Text>
<ActivityIndicator size="small" color="#00ff00" />
<Button
title="goPage"
color='red'
onPress={() => {
this.props.navigation.navigate('Page')
}}
/>
</View>
)
}
}
const PROVINCE_CITY = [{ city: '广东', id: 1001 }, { city: '上海', id: 1002 }, { city: '重庆', id: 1003 }, { city: '北京', id: 1004 }, { city: '湖南', id: 1005 }]
class PageScreen extends React.Component {
constructor(props) {
super(props)
this.state = {
isRef: false,
data: PROVINCE_CITY
}
}
pageItem = (item) => {
return (
<View style={styles.city}>
<Text style={styles.cityText}>{item.city}</Text>
</View>
)
}
loadPage = () => {
this.setState({
isRef: true
})
setTimeout(() => {
const dataNew = [{ city: '江苏', id: 1007 }, { city: '新疆', id: 1008 }, { city: '东北', id: 1009 }]
const dataOld = this.state.data
const data = [...dataNew, ...dataOld]
this.setState({
data: data,
isRef: false
})
}, 1000)
}
loadComponent = () => {
return (
<View style={styles.loadComponents}>
<ActivityIndicator style={styles.indicator} size="large" color="#0000ff" animating={true} />
</View>
)
}
loadDate = () => {
this.setState({
isRef: true
})
setTimeout(() => {
const dataNew = [{ city: '广西', id: 1011 }, { city: '云南', id: 1012 }, { city: '四川', id: 1013 }]
const dataOld = this.state.data
const data = [...dataOld, ...dataNew]
this.setState({
data: data,
isRef: false
})
}, 2000)
}
render() {
return (
<View style={styles.pageContairner}>
<FlatList
data={this.state.data}
keyExtractor={item => item.id}
renderItem={({ item }) => this.pageItem(item)}
// refreshing={this.state.isRef}
// onRefresh={()=>{
// this.loadPage()
// }}
refreshControl={
<RefreshControl
tintColor="#f00"
title="正在加载..."
colors={['#ee3ff2', '#h4322g', '#a22334']}
tintColor='#ee3ff2'
refreshing={this.state.isRef}
onRefresh={() => {
this.loadPage()
}}
/>
}
listFooterComponent={this.loadComponent}
onEndReachedThreshold='0.3'
onEndReached={() => {
this.loadDate()
}}
/>
</View>
)
}
}
const App = createStackNavigator({
Home: {
screen: HomeScreen
},
Page: {
screen: PageScreen,
navigationOptions: {
title: 'Page'
}
}
}, {
initialRouteName: 'Home',
defaultNavigationOptions: {
headerTintColor: '#f0f',
headerTitleStyle: {
fontSize: 18,
fontWeight: '900'
}
}
})
const styles = StyleSheet.create({
contairner: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
pageContairner: {
flex: 1,
justifyContent: 'center'
},
city: {
height: 200,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#fff',
marginBottom: 20
},
cityText: {
fontSize: 16,
},
loadComponents: {
alignSelf: 'center',
},
indicator: {
margin: 10
}
})
export default createAppContainer(App)<file_sep>/src/store/reducer/news/index.js
import TYPE from '../../action/types'
const defaultState = {
top: {
newsData: null,
isFresh: false
},
shehui: {
newsData: null,
isFresh: false
},
guonei: {
newsData: null,
isFresh: false
},
guoji: {
newsData: null,
isFresh: false
}
}
const newsReducers = (state = defaultState, action) => {
const newState = JSON.parse(JSON.stringify(state))
switch (action.type) {
case TYPE.TYPE_NEWS_NET:
var category = action.category
newState[category].newsData = action.data
newState[category].isFresh = false
return newState
case TYPE.TYPE_NEWS_FRESH:
var category = action.category
newState[category].isFresh = action.data
return newState
default:
return state;
}
}
export default newsReducers<file_sep>/src/store/reducer/weather/index.js
import TYPE from '../../action/types'
const defaultState = {
weather: '',
isFresh:false
}
const weatherReducer = (state = defaultState, action) => {
const newState = JSON.parse(JSON.stringify(state))
const data = action.data
switch (action.type) {
case TYPE.NET_WEATHER:
newState.weather = data
newState.isFresh = false
return newState
// return {
// // ...state,
// // weather: data,
// // isFresh:false
// }
case TYPE.TYPE_EATHER_FRESH:
// return {
// ...state,
// isFresh: data
// }
newState.isFresh = data
default:
return state
}
}
export default weatherReducer<file_sep>/src/utils/storage.js
import AsyncStorage from "@react-native-community/async-storage"
class Storage {
static save =async (key,value) => {
// AsyncStorage.setItem(key,value,(err)=>{
// err&&console.log(err);
// })
// AsyncStorage.setItem(key,value)
// .catch(err=>{
// err&&console.log(err);
// })
try {
await AsyncStorage.setItem(key,JSON.stringify(value))
} catch (err) {
err&&console.log(err);
}
}
static get = (key) => {
// AsyncStorage.getItem(key,(err,res)=>{
// err&&console.log(err);
// return JSON.parse(res)
// })
AsyncStorage.getItem(key)
.catch(err => {
err && console.log(err);
})
.then(value => {
return JSON.parse(value)
})
}
static update = async(key,value) => {
try{
await AsyncStorage.removeItem(key)
await AsyncStorage.setItem(key,JSON.stringify(value))
}catch(err) {
err&&console.log(err);
}
}
static delete = (key) => {
AsyncStorage.removeItem(key,(err)=>{
err&&console.log(err);
})
}
static merge = (key,value) => {
AsyncStorage.mergeItem(key,JSON.stringify(value),(err)=>{
err&&console.log(err);
})
}
static clear = () => {
AsyncStorage.clear()
}
}
export default Storage<file_sep>/src/store/reducer/book/index.js
import TYPE from '../../action/types'
const defaultState = {
bookData: {},
isFresh: false,
bookList:{}
}
const bookReducers = (state = defaultState, action) => {
const newState = JSON.parse(JSON.stringify(state))
switch (action.type) {
case TYPE.TYPE_DATA_BOOK:
newState.bookData = action.data
return newState
case TYPE.TYPE_BOOK_FRESH:
newState.isFresh = action.data
return newState
case TYPE.TYPT_BOOK_NET:
newState.bookList = action.data
return newState
default:
return state
}
}
export default bookReducers<file_sep>/demo/5.xTopTab.js
import React from 'react'
import { View, Text, Button } from 'react-native'
import { NavigationContainer } from '@react-navigation/native'
import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs'
import { createStackNavigator } from '@react-navigation/stack'
class HomeScreen extends React.Component {
render() {
return (
<View>
<Button
title="goToPage"
onPress={() => {
this.props.navigation.navigate('Top')
}}
/>
</View>
)
}
}
class Page1Screen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Page1</Text>
</View>
)
}
}
class Page2Screen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Page2</Text>
</View>
)
}
}
class Page3Screen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Page3</Text>
</View>
)
}
}
class Page4Screen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Page4</Text>
</View>
)
}
}
class Page5Screen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Page5</Text>
</View>
)
}
}class Page6Screen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Page6</Text>
</View>
)
}
}
const Top = createMaterialTopTabNavigator()
const TopScreen = () => {
return (
<Top.Navigator tabBarOptions={{
labelStyle: { fontSize: 12 },
tabStyle: { width: 100 },
style: { backgroundColor: 'blue' },
activeTintColor:'#fff',
inactiveTintColor:'#ccc',
indicatorStyle:{
backgroundColor:"#fff",
height:4
},
scrollEnabled:true,
tabStyle: {
width:80
}
}}>
<Top.Screen name="Page1" component={Page1Screen} />
<Top.Screen name="Page2" component={Page2Screen} />
<Top.Screen name="Page3" component={Page3Screen} />
<Top.Screen name="Page4" component={Page4Screen} />
<Top.Screen name="Page5" component={Page5Screen} />
<Top.Screen name="Page6" component={Page6Screen} />
</Top.Navigator>
)
}
const Stack = createStackNavigator()
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Top" component={TopScreen} />
</Stack.Navigator>
</NavigationContainer>
)
}
export default App<file_sep>/src/pages/main/AsyncStorage.js
import AsyncStorage from '@react-native-community/async-storage'
import React, { Component } from 'react'
import { Text, View, Button, TextInput, StyleSheet } from 'react-native'
class AsyncStorageScreen extends Component {
constructor(props) {
super(props)
this.state = {
data: '',
value: ''
}
}
/**
* {
method:'get',
headers:{
'Accept':'application/json'
}
}
*/
loadSearch = () => {
// console.log(this.searchText);
this.searchText = encodeURI(this.searchText)
const url = `http://apis.juhe.cn/simpleWeather/query?city=${this.searchText}&key=a91cee95b92875ee341e57fc54ac09b1`
fetch(url)
.then(res => res.json())
.then(res => {
console.log(res);
this.setState({
data: res
})
})
}
loadSearch2 = async () => {
this.searchText = encodeURI(this.searchText)
const url = `http://apis.juhe.cn/simpleWeather/query?city=${this.searchText}&key=a91cee95b92875ee341e57fc54ac09b1`
const responents = await fetch(url)
const res = await responents.json() // 只要有Promise 数据返回就能用await
console.log(res);
this.setState({
data: res
})
}
saveData = () => {
AsyncStorage.setItem('DATA', JSON.stringify(this.state.data)).catch(err => {
err && console.log(err);
})
}
removeData = () => {
AsyncStorage.removeItem('DATA')
.catch(err=>{
err&&console.log(err);
})
}
getData = () => {
// AsyncStorage.getItem('DATA',(err,value)=>{
// err&&console.log(err);
// console.log(value);
// const data = JSON.parse(value)
// console.log(data);
// this.setState({
// value:data.result.city
// })
// })
AsyncStorage.getItem('DATA')
.catch(err => {
err && console.log(err);
})
.then(value => {
const data = JSON.parse(value)
console.log(data);
this.setState({
value: data&&JSON.stringify(data.result) || 'no message'
})
})
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Fetch</Text>
<TextInput style={styles.input} onChangeText={text => {
this.searchText = text === 'shanghai' ? '上海' : ''
}} />
<Button
title="get Data"
onPress={() => {
this.loadSearch()
}}
/>
<Button
title="save Data"
onPress={() => {
this.saveData()
}}
/>
<Button
title="get Data"
onPress={() => {
this.getData()
}}
/>
<Button
title="remove Data"
onPress={() => {
this.removeData()
}}
/>
<Text>{this.state.data && this.state.data.result.city}</Text>
<Text>{this.state.value}</Text>
</View>
)
}
}
const styles = StyleSheet.create({
input: {
width: 300,
height: 40,
borderColor: '#000',
borderWidth: 1,
borderRadius: 0.5
}
})
export default AsyncStorageScreen<file_sep>/src/pages/main/Touchable.js
import React from 'react'
import { View, Text, StyleSheet,Alert, TouchableOpacity,TouchableHighlight,TouchableWithoutFeedback,Platform, TouchableNativeFeedback } from 'react-native'
class Touchable extends React.Component {
_onPress = () => {
// Alert('message')
// console.log(1);
Alert.alert('message')
}
_onLongPress = () => {
Alert.alert('long message')
}
render() {
return (
<View style={styles.container}>
<Text>page</Text>
<TouchableOpacity onPress={()=>{
this._onPress()
}}>
<View style={styles.button}>
<Text style={{color:'#fff'}}>TouchableOpacity</Text>
</View>
</TouchableOpacity>
<TouchableNativeFeedback onPress={()=>{
this._onPress()
}} backgroundColor={Platform.OS==='android'?TouchableNativeFeedback.SelectableBackground:""}>
<View style={styles.button}>
<Text style={{color:'#fff'}}>TouchableNativeFeedback</Text>
</View>
</TouchableNativeFeedback>
<TouchableWithoutFeedback onPress={()=>{
this._onPress()
}}
backgroundColor={Platform.OS==='android'?TouchableNativeFeedback.SelectableBackground:""}
>
<View style={styles.button}>
<Text style={{color:'#fff'}}>TouchableWithoutFeedback</Text>
</View>
</TouchableWithoutFeedback>
<TouchableHighlight onPress={()=>{
this._onPress()
}}
onLongPress={()=>{
this._onLongPress()
}}
underlayColor="#f00">
<View style={styles.button}>
<Text style={{color:'#fff'}}>TouchableHighlight</Text>
</View>
</TouchableHighlight>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 60,
alignItems: 'center'
},
button: {
width:200,
height:30,
backgroundColor:'#2e7272',
alignItems:'center',
justifyContent:"center",
marginBottom:20
}
})
export default Touchable<file_sep>/demo/State.js
import React from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
Image,
StatusBar,
} from 'react-native';
class Blink extends React.Component {
state = {
isShow: true
}
componentDidMount() {
this.inter = setInterval(() => {
this.setState((perStatus) => ({
isShow: !perStatus.isShow
}))
}, 2000)
}
componentWillUnmount() {
clearInterval(this.inter)
}
render() {
if (!this.state.isShow) {
return null
}
return (
<View>
<Text>{this.props.text}</Text>
</View>
)
}
}
export default class App extends React.Component {
render() {
return (
<View style={{ flex: 1, justifyContent: 'center' }}>
{/* <Blink text="小米" />
<Blink text="华为" /> */}
</View>
)
}
}
<file_sep>/demo/navigation.js
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { createAppContainer } from 'react-navigation'
import { createStackNavigator } from 'react-navigation-stack';
class HomeScreen extends React.Component {
static navigationOptions = {
title: 'Home'
};
render() {
return (
<View style={styles.container}>
<Text>Hello, Navigation!</Text>
<View style={{ backgroundColor: 'blue', height: 60, width: 200, alignItems: 'center', justifyContent: 'center' ,borderRadius:5}}>
<Button
title="go to Details"
color="#fff"
onPress={() => {
this.props.navigation.navigate({ routeName: 'Detail' })
}} />
</View>
</View>
)
}
}
class DetailScreen extends React.Component {
static navigationOptions = {
title: 'Detail'
};
render() {
return <Text>Detail!</Text>;
}
}
const SimpleApp = createStackNavigator({
Home: { screen: HomeScreen },
Detail: { screen: DetailScreen }
}, {
initialRouteName: 'Home'
});
export default createAppContainer(SimpleApp)
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
}
});<file_sep>/demo/StyleSheet.js
import React from 'react'
import { View, Text , StyleSheet } from 'react-native'
const styles = StyleSheet.create({
red: {
color:'red'
},
blue: {
color:"blue"
},
bigRed: {
color: 'red',
fontWeight : '600',
fontSize: 30
},
bigBlue: {
color: 'blue',
fontWeight: '600',
fontSize : 30
}
})
class InfoStyle extends React.Component {
render() {
return (
<View style={{marginTop:50}}>
<Text style={styles.red}>Just red</Text>
<Text style={styles.blue}>Just blue</Text>
<Text style={[styles.bigBlue,styles.red]}>BigBlue and red</Text>
<Text style={[styles.bigRed, styles.blue]}>BigRed and blue</Text>
</View>
)
}
}
export default InfoStyle<file_sep>/src/store/action/types.js
export default {
TYPE_DATA_WEATHER:'TYPE_DATA_WEATHER',
NET_WEATHER:'NET_WEATHER',
TYPE_EATHER_FRESH:'TYPE_EATHER_FRESH',
TYPE_NEWS_NET:'TYPE_NEWS_NET',
TYPE_NEWS_FRESH:'TYPE_NEWS_FRESH',
TYPE_DATA_BOOK:'TYPE_DATA_BOOK',
TYPE_BOOK_FRESH:'TYPE_BOOK_FRESH',
TYPT_BOOK_NET:'TYPT_BOOK_NET'
}<file_sep>/src/pages/main/FetchMemo.js
import React from 'react'
import {Text,View,Button,TextInput,StyleSheet} from 'react-native'
class FetchScreen extends React.Component {
constructor(props) {
super(props)
this.state = {
data:''
}
}
/**
* {
method:'get',
headers:{
'Accept':'application/json'
}
}
*/
loadSearch = () => {
// console.log(this.searchText);
this.searchText = encodeURI(this.searchText)
const url = `http://apis.juhe.cn/simpleWeather/query?city=${this.searchText}&key=a91cee95b92875ee341e57fc54ac09b1`
fetch(url)
.then(res=>res.json())
.then(res=>{
console.log(res);
this.setState({
data:res
})
})
}
loadSearch2 = async() => {
this.searchText = encodeURI(this.searchText)
const url = `http://apis.juhe.cn/simpleWeather/query?city=${this.searchText}&key=a91cee95b92875ee341e57fc54ac09b1`
const responents = await fetch(url)
const res = await responents.json() // 只要有Promise 数据返回就能用await
console.log(res);
this.setState({
data:res
})
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Fetch</Text>
<TextInput style={styles.input} onChangeText={text=>{
this.searchText = text==='shanghai'?'上海':''
}}/>
<Button
title="get Data"
onPress={()=>{
this.loadSearch()
}}
/>
</View>
)
}
}
const styles = StyleSheet.create({
input:{
width:300,
height:40,
borderColor:'#000',
borderWidth:1,
borderRadius:0.5
}
})
export default FetchScreen<file_sep>/src/pages/main/Bottom1.js
import React from 'react'
import TopNavigation from '../Navigation/TopNavigation'
import NavigationUtil from '../../utils/navigationUtil'
class Page1Screen extends React.Component {
constructor(props) {
super(props)
}
render() {
NavigationUtil.navigation = this.props.navigation
return <TopNavigation />
}
}
export default Page1Screen<file_sep>/demo/navigation-button.js
import React from 'react';
import { StyleSheet, Text, View, Button, Image } from 'react-native';
import { createAppContainer } from 'react-navigation'
import { createStackNavigator } from 'react-navigation-stack';
class HomeScreen extends React.Component {
// static navigationOptions = {
// headerTitle: 'HomeScreen',
// headerStyle: {
// backgroundColor:"steelblue"
// },
// headerTitleStyle : {
// color:'#fff',
// fontSize: 18,
// fontWeight: 'bold'
// }
// };
constructor(props) {
super(props)
this.state = {
count: 0
}
}
static navigationOptions = ({ navigation }) => {
return {
headerTitle: () => <LogoTitle />,
headerRight: () => <Button
title='click'
color='#fff'
onPress={
// console.log(1);
navigation.getParam('createCount')
}
/>
}
}
_createCount = () => {
this.setState({
count: ++this.state.count
})
}
render() {
const params = { id: 1, value: 'this is NewValue' }
return (
<View style={styles.container}>
<Text>Hello, Navigation!</Text>
<Text>count:{this.state.count}</Text>
<View style={{ backgroundColor: 'blue', height: 60, width: 200, alignItems: 'center', justifyContent: 'center', borderRadius: 5 }}>
<Button
title="go to Details"
color="#fff"
onPress={() => {
this.props.navigation.navigate('Detail', params)
}} />
</View>
</View>
)
}
componentDidMount() {
console.log('home - componentDidMount');
this.props.navigation.setParams({ createCount: this._createCount })
}
componentWillUnmount() {
console.log('hmoe - componentWillUnmount');
}
}
class LogoTitle extends React.Component {
render() {
return (
<Image
source={{ uri: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603967495082&di=7380af7856300c5cfd6617c7e136845c&imgtype=0&src=http%3A%2F%2Fku.90sjimg.com%2Felement_origin_min_pic%2F17%2F03%2F26%2Fcafc6ea253bc2ebc78918dc44c8671c7.jpg' }}
style={{ width: 30, height: 30 }}
/>
)
}
}
class DetailScreen extends React.Component {
static navigationOptions = {
// header:null,
headerBackTitle: '返回',
headerTitle: 'DetailScreen',
headerStyle: {
backgroundColor: "pink"
},
headerTitleStyle: {
color: 'skyblue',
fontSize: 16
}
};
render() {
const navigate = this.props.navigation
// console.log(navigate.getParam('id'));
return (
<View style={styles.container}>
<Text>Detail!</Text>
<Text>id: {navigate.getParam('id')}</Text>
<Text>value: {navigate.getParam('value')}</Text>
<View style={{ backgroundColor: 'blue', height: 60, width: 200, alignItems: 'center', justifyContent: 'center', borderRadius: 5 }}>
<Button
title="go to Detail"
color="#fff"
onPress={() => {
navigate.push('Detail', {
id: Math.floor(Math.random() * 100),
value: 'this is OldValue'
})
}} />
</View>
</View>)
}
componentDidMount() {
console.log('Detail - componentDidMount');
}
componentWillUnmount() {
console.log('Detail - componentWillUnmount');
}
}
const SimpleApp = createStackNavigator({
Home: { screen: HomeScreen },
Detail: { screen: DetailScreen }
}, {
initialRouteName: 'Home',
defaultNavigationOptions: {
headerTitle: 'Home',
headerStyle: {
backgroundColor: "#2A60E4"
},
headerTitleStyle: {
color: '#fff',
fontSize: 18,
fontWeight: 'bold'
}
}
});
export default createAppContainer(SimpleApp)
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: "space-around"
}
}); | 2fb672df8666e936437641c88a65d72ff06a21e5 | [
"JavaScript",
"Markdown"
] | 31 | JavaScript | Michaelwong0820/reactRN | 6b3fedf13ce1594e7daefb82ddcc11ac94966384 | 9ac46a0e64c8f61be013318113c6d2b4130c0239 |
refs/heads/master | <file_sep># Zoo Application
Zoo application that model several types of animals and expose REST apis to query them.
You can refer to [class diagram](src/main/resources/docs/class_diagram.png) to visually see class modeling.
## Installation
Java Version - 15
```
java -jar target/zoo-1.0-SNAPSHOT.jar
```
Fetch All Animals
```bash
curl localhost:8080/api/animal
```
Fetch Walking Animals
```bash
curl localhost:8080/api/animal?type=walking
```
Fetch Swimming Animals
```bash
curl localhost:8080/api/animal?type=swimming
```
## Assumptions
1. Caterpillar to Butterfly transformation.
Insect can be in either in caterpillar status of butterfly status. Butterfly can fly but not caterpillar.
The caller who has reference to an insect object is supposed to use canFly() before calling fly().
## Enhancements
1. Write [contract tests](https://spring.io/projects/spring-cloud-contract) for REST API.
<file_sep>package com.udara.zoo.model;
import static com.udara.zoo.model.Colour.GREY;
import static com.udara.zoo.model.Size.LARGE;
public class Shark extends Fish {
public Shark(String name) {
super(LARGE, GREY, name);
}
public Shark() {
super(LARGE, GREY);
}
public void eat(Fish fish){
System.out.println("What a yummy meal");
}
}
<file_sep>package com.udara.zoo.model;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static com.udara.zoo.model.Colour.ORANGE;
import static com.udara.zoo.model.Size.SMALL;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringContains.containsString;
import static org.junit.Assert.assertEquals;
public class ClownFishTest {
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
@Before
public void init() {
System.setOut(new PrintStream(outContent));
}
@Test
public void clownFishShouldBeSmall() {
assertEquals(SMALL, new ClownFish().getSize());
}
@Test
public void clownFishShouldBeColourFull() {
assertEquals(ORANGE, new ClownFish().getColour());
}
@Test
public void clownFishShouldBeAbleToMakeJokes() {
new ClownFish().makeJoke();
assertThat(outContent.toString(), containsString("Where do fish sleep, on water bed!"));
}
@Test
public void clownFishShouldBeAbleToMakeSwim() {
new ClownFish().swim();
assertThat(outContent.toString(), containsString("default swim method for Fish"));
}
}<file_sep>package com.udara.zoo.model.behavior;
public interface Jumpable {
void jump();
}
<file_sep>package com.udara.zoo.model;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringContains.containsString;
public class CatTest {
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
@Before
public void init() {
System.setOut(new PrintStream(outContent));
}
@Test
public void catShouldBeAbleToWalk() {
new Cat().walk();
assertThat(outContent.toString(), containsString("I am walking"));
}
@Test
public void catShouldBeAbleToShout() {
new Cat().speak();
assertThat(outContent.toString(), containsString("Me ow"));
}
@Test
public void catShouldBeAbleToSwim() {
new Cat().swim();
assertThat(outContent.toString(), containsString("Swimming quietly keeping head on top"));
}
}<file_sep>package com.udara.zoo.model;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringContains.containsString;
public class FrogTest {
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
@Before
public void init() {
System.setOut(new PrintStream(outContent));
}
@Test
public void frogShouldBeAbleToWalk() {
new Frog().walk();
assertThat(outContent.toString(), containsString("I am walking"));
}
@Test
public void frogShouldBeAbleToShout() {
new Frog().speak();
assertThat(outContent.toString(), containsString("Baka Baka"));
}
@Test
public void frogShouldBeAbleToSwim() {
new Frog().swim();
assertThat(outContent.toString(), containsString("Swimming on surface of water"));
}
@Test
public void frogShouldBeAbleToJump() {
new Frog().jump();
assertThat(outContent.toString(), containsString("I am jumping"));
}
}<file_sep>package com.udara.zoo.model;
import java.util.Locale;
import java.util.Map;
public class ChickenSpeakingBehavior {
private Map<Locale, String> languageVoiceMap;
ChickenSpeakingBehavior(Map<Locale, String> languageVoiceMap) {
this.languageVoiceMap = languageVoiceMap;
}
public void speak(){
speak(Locale.getDefault());
}
public void speak(Locale locale){
String speech = locale == null ? languageVoiceMap.get(Locale.getDefault()) : languageVoiceMap.get(locale);
System.out.println(speech);
}
}
<file_sep>package com.udara.zoo.api.animal;
import com.udara.zoo.model.Animal;
import java.util.List;
public interface AnimalRepository {
List<Animal> fetchAll();
}
<file_sep>package com.udara.zoo.model;
import org.junit.Test;
import static org.junit.Assert.*;
public class ParrotLivingWithDogSpeakingBehaviorTest {
@Test
public void parrotLivingWithDogShouldShoutAsDog() {
assertEquals("Woof, woof", new ParrotLivingWithDogSpeakingBehavior().getSpeech());
}
}<file_sep>package com.udara.zoo.model;
public class ParrotLivingWithDogSpeakingBehavior extends SpeakingBehavior {
@Override
public String getSpeech() {
return "Woof, woof";
}
}
<file_sep>package com.udara.zoo.model.behavior;
public interface Speakable {
void speak();
}
<file_sep>package com.udara.zoo.model;
import static com.udara.zoo.model.Colour.ORANGE;
import static com.udara.zoo.model.Size.SMALL;
public class ClownFish extends Fish {
public ClownFish() {
super(SMALL, ORANGE);
}
public ClownFish(String name) {
super(SMALL, ORANGE, name);
}
public void makeJoke(){
System.out.println("Where do fish sleep, on water bed!");
}
}
<file_sep>package com.udara.zoo.model;
import com.udara.zoo.model.behavior.Jumpable;
import com.udara.zoo.model.behavior.Speakable;
import com.udara.zoo.model.behavior.Swimable;
import com.udara.zoo.model.behavior.Walkable;
import lombok.NoArgsConstructor;
@NoArgsConstructor
public class Frog extends Animal implements Walkable, Speakable, Swimable, Jumpable {
public Frog(String name) {
super(name);
}
@Override
public void jump() {
System.out.println("I am jumping");
}
@Override
public void speak() {
System.out.println("Baka Baka");
}
@Override
public void swim() {
System.out.println("Swimming on surface of water");
}
}
<file_sep>package com.udara.zoo.model;
import com.udara.zoo.model.behavior.Speakable;
import com.udara.zoo.model.behavior.Swimable;
import com.udara.zoo.model.behavior.Walkable;
import lombok.NoArgsConstructor;
@NoArgsConstructor
public class Dog extends Animal implements Speakable, Walkable, Swimable {
public Dog(String name) {
super(name);
}
@Override
public void speak() {
System.out.println("Bab Baw");
}
@Override
public void swim() {
System.out.println("Swiming keeping head out of water");
}
}
<file_sep>package com.udara.zoo.model;
public class Butterfly extends Animal implements Insect {
private boolean alreadyTransformed = false;
private Insect metamorphosisStatus;
public Butterfly() {
// starting as a Caterpillar
metamorphosisStatus = new CaterpillarState();
}
public Butterfly(String name) {
super(name);
}
@Override
public void fly() {
metamorphosisStatus.fly();
}
@Override
public void walk() {
metamorphosisStatus.walk();
}
public void transform(){
if (alreadyTransformed){
return;
}
System.out.println("I am becoming a beautiful butterfly now");
this.metamorphosisStatus = new ButterflyState();
alreadyTransformed = true;
}
@Override
public boolean canFly() {
return metamorphosisStatus.canFly();
}
}
<file_sep>package com.udara.zoo.model;
import com.udara.zoo.model.behavior.Swimable;
public abstract class Fish extends Animal implements Swimable {
private Size size;
private Colour colour;
public Fish(Size size, Colour colour, String name) {
super(name);
this.size = size;
this.colour = colour;
}
public Fish(Size size, Colour colour) {
this.size = size;
this.colour = colour;
}
public Size getSize() {
return size;
}
public Colour getColour() {
return colour;
}
}
<file_sep>package com.udara.zoo.model;
public class ParrotWithIphoneSpeakingBehavior extends SpeakingBehavior {
@Override
public String getSpeech() {
//this is Iphone ringing sound
return "Ton kota tan tan ton ton";
}
}
| 784104bc965c0585b7679a497c651e4ff910f4b3 | [
"Markdown",
"Java"
] | 17 | Markdown | udaraliyanage/zoo | 57f2db77a470717e699ac6123336eb355503345a | 00795ea54178af035bb81bb1b4f5d7ffc8202561 |
refs/heads/master | <file_sep>import React from 'react';
import axios from 'axios';
import Button from '../components/Button';
class Old extends React.Component {
constructor(props) {
super(props);
this.state = {
users: [],
firstname: ''
};
}
componentDidMount() {
axios.get('http://localhost:3001/api/users').then(({data}) => {
this.setState({users: data});
});
}
addUser = () => {
this.setState({firstname: ''});
axios
.post('http://localhost:3001/api/users', {
firstname: this.state.firstname
})
.then(({data}) => {
this.setState(state => ({
users: state.users.concat(data)
}));
});
};
render() {
return (
<div>
<input
value={this.state.firstname}
onChange={e => this.setState({firstname: e.target.value})}
/>
<Button onClick={this.addUser}>Add user {this.state.firstname}</Button>
{this.state.users.map(user => {
return <div>{user.firstname}</div>;
})}
</div>
);
}
}
export default Old;
<file_sep>const Koa = require('koa');
const axios = require('axios');
const koaBody = require('koa-body');
const Router = require('@koa/router');
const cors = require('@koa/cors');
const app = new Koa();
app.use(koaBody());
app.use(cors());
const router = new Router({
prefix: '/api'
});
const users = [];
router.post('/users', async ctx => {
const {firstname} = ctx.request.body;
const user = {
id: Date.now(),
firstname
};
users.push(user);
return (ctx.body = user);
});
router.get('/users', async ctx => {
ctx.body = users;
});
app.use(router.routes()).use(router.allowedMethods());
app.listen(3001);
| 38b84f7a906b4c90611a49fd9499686d50da3416 | [
"JavaScript"
] | 2 | JavaScript | DavoCg/laloco | a427333a5b4c6b087071fc673f82a76de60bc09a | 12d70237a47a3673a88e2bb963e035e7963031d2 |
refs/heads/master | <file_sep>[SuiteResult context=PrivacyTest][SuiteResult context=LoginTest]<file_sep>package Resources;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class BaseSalesforces {
public static WebDriver driver;
public static Properties prop;
public static WebDriver initializeDriver() throws IOException {
prop = new Properties();
String path = "D:\\Selenium Test Cases\\Salesforce\\src\\main\\java\\Resources\\base.properties";
FileInputStream fis = new FileInputStream(path);
prop.load(fis);
String browserName = prop.getProperty("browser");
System.out.println(prop.getProperty("browser"));
if(browserName.contains("chrome")) {
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver_v93\\chromedriver.exe");
ChromeOptions option = new ChromeOptions();
if(browserName.contains("headless")) {
option.addArguments("headless");
}
driver = new ChromeDriver(option);
}
driver.get(prop.getProperty("url"));
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
return driver;
}
public String getScreenshot(String testMethodName, WebDriver driver) throws IOException {
File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
String desfile = System.getProperty("user.dir")+"\\reports\\"+testMethodName+".jpg";
FileUtils.copyFile(src, new File(desfile));
return desfile;
}
}
<file_sep>package Automation.Salesforce;
import java.io.IOException;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import PageObject.Homepage;
import Resources.BaseSalesforces;
public class LoginTest extends BaseSalesforces{
public Homepage hp;
@BeforeTest
public void openBrowser() throws IOException {
initializeDriver();
}
@Test(priority=1)
public void loginTest() {
hp = new Homepage(driver);
hp.getUsername().sendKeys("abcd");
hp.getPassword().sendKeys("<PASSWORD>");
hp.getLogin().click();
System.out.println("Logged in successfully??");
System.out.println("Not there is a credential error, credential mismatch");
System.out.println("Ok, I have resolved. Please check...!");
System.out.println("Ok now its working");
}
@Test(priority=2)
public void getTextStatus() {
String text = hp.getCust().getText();
Assert.assertEquals(text, "a customer");
}
//@AfterTest
public void closeBrowser() {
driver.close();
}
}
<file_sep>package PageObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import Resources.BaseSalesforces;
public class Homepage extends BaseSalesforces {
public Homepage(WebDriver driver) {
// TODO Auto-generated constructor stub
this.driver=driver;
}
WebDriver driver;
By username = By.id("username");
By password = By.id("<PASSWORD>");
By login = By.xpath("//*[@id='Login']");
//By cust = By.cssSelector("[class*='mr16']");
By cust = By.xpath("//*[@id='signup']/p");
By privacy = By.id("privacy-link");
By number = By.cssSelector(".hidden-xs");
public WebElement getNumber() {
return driver.findElement(number);
}
public WebElement viewPrivacy() {
return driver.findElement(privacy);
}
public WebElement getLogin() {
return driver.findElement(login);
}
public WebElement getUsername() {
return driver.findElement(username);
}
public WebElement getPassword() {
return driver.findElement(password);
}
public WebElement getCust() {
return driver.findElement(cust);
}
}
<file_sep>package stepDefinitions;
import org.testng.Assert;
import PageObject.Homepage;
import Resources.BaseSalesforces;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class stepDefinition extends BaseSalesforces{
public Homepage hp;
@Given("^initialize the driver with chrome and navigate to https://login\\.salesforce\\.com/\\?locale=eu$")
public void initialize_the_driver_with_chrome_and_navigate_to_https_login_salesforce_com_locale_eu() throws Throwable {
initializeDriver();
}
@When("^user input username test(\\d+)@gmail\\.com and password(\\d+)$")
public void user_input_username_test_gmail_com_and_password(String arg1, String arg2) throws Throwable {
hp = new Homepage(driver);
hp.getUsername().sendKeys("abcd");
hp.getPassword().sendKeys("<PASSWORD>");
}
@When("^click on Login button$")
public void click_on_Login_button() throws Throwable {
hp.getLogin().click();
}
@Then("^Error message shown$")
public void error_message_shown() throws Throwable {
String text = hp.getCust().getText();
Assert.assertEquals(text, "a customer");
}
@Then("^close the browser$")
public void close_the_browser() throws Throwable {
driver.close();
}
}
<file_sep>browser=chrome
url=https://login.salesforce.com/?locale=in<file_sep>package Automation.Salesforce;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import Resources.BaseSalesforces;
import Resources.ExtentReportTestNG;
public class ListenerTest extends BaseSalesforces implements ITestListener {
public ExtentTest test;
ExtentReports extent = ExtentReportTestNG.getExtentReport();
ThreadLocal<ExtentTest> extentTest = new ThreadLocal<ExtentTest>();
public void onTestStart(ITestResult result) {
// TODO Auto-generated method stub
test = extent.createTest(result.getMethod().getMethodName());
extentTest.set(test);
}
public void onTestSuccess(ITestResult result) {
// TODO Auto-generated method stub
extentTest.get().log(Status.PASS, "Test Passed");
}
public void onTestFailure(ITestResult result) {
// TODO Auto-generated method stub
extentTest.get().fail(result.getThrowable());
String testMethodName = result.getMethod().getMethodName();
try {
driver = (WebDriver)result.getTestClass().getRealClass().getDeclaredField("driver").get(result.getInstance()); //this allows you to take screenshot of failed method of any class
} catch(Exception e)
{
}
try {
test.addScreenCaptureFromPath(getScreenshot(testMethodName, driver), testMethodName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onFinish(ITestContext context) {
// TODO Auto-generated method stub
extent.flush();
}
}
<file_sep>[SuiteResult context=LoginTest][SuiteResult context=PrivacyTest] | 9824b5b637937bcf3ad3c25e85bd13bbbf0360e2 | [
"Java",
"INI"
] | 8 | INI | rohitkumarr995/SalesDemo | 330cbca7053f9b7e6813a9ecab99bf6a5fdbbcdf | 280fbcf94d234c39aa6fd77cdd4ded42a17ea82f |
refs/heads/master | <file_sep>Unleash the scripting power with HomeyScript. Automate everything you every dreamed of, even when Flows are not enough for you!
HomeyScript is a JavaScript-based scripting language that interacts with the Homey Web API and various Homey Apps SDK functions.
Among many things, you can:
— Control & Monitor your Homey's devices.
— Start a HomeyScript from a Flow, even with Tags.
— Make a Flow only continue when your HomeyScript says 'True!'
— Create & Manage Flow Tags from a HomeyScript.
— Access any website's API from within a HomeyScript.
— Let Homey say dynamic text.
— And much, much more...
After installation, visit https://homeyscript.homey.app on your Mac or PC to start scripting.<file_sep>function Sidebar( api, editor ) {
this._scripts = [];
this._activeFileEl = undefined;
this._ctxmenuEl = undefined;
this._api = api;
this._app = null;
this._editor = editor;
this._api.registerAppListener( this._onApp.bind(this) );
this._sidebarEl = document.querySelector('.hs-sidebar');
this._filesEl = this._sidebarEl.querySelector('.hs-files');
this._actionsEl = this._sidebarEl.querySelector('.hs-actions');
this._buttonCreateEl = this._sidebarEl.querySelector('.hs-actions .button.create');
this._buttonCreateEl.addEventListener('click', this.createScript.bind(this));
}
Sidebar.prototype.init = function(){
this.render();
}
Sidebar.prototype.render = function(){
this._filesEl.innerHTML = '';
this._scripts.forEach(function(scriptId){
var fileEl = document.createElement('div');
fileEl.classList.add('hs-file', 'hs-transition');
fileEl.addEventListener('click', function(e){
this._editor.open( scriptId );
if( this._activeFileEl )
this._activeFileEl.classList.remove('hs-active');
this._activeFileEl = fileEl;
this._activeFileEl.classList.add('hs-active');
}.bind(this));
fileEl.addEventListener('contextmenu', function(e){
e.preventDefault();
this._destroyCtxmenu();
var rect = this._filesEl.getBoundingClientRect();
window.addEventListener('click', this._destroyCtxmenu.bind(this));
this._ctxmenuEl = document.createElement('div');
this._ctxmenuEl.classList.add('ctxmenu');
this._ctxmenuEl.style.top = ( e.clientY - rect.top ) + 'px';
this._ctxmenuEl.style.left = ( e.clientX - rect.left ) + 'px';
this._ctxmenuEl.addEventListener('click', function(e){
e.stopPropagation();
});
this._filesEl.appendChild(this._ctxmenuEl);
var deleteFileEl = document.createElement('div');
deleteFileEl.classList.add('item');
deleteFileEl.textContent = 'Delete';
deleteFileEl.addEventListener('click', function(e){
this.deleteScript( scriptId );
this._destroyCtxmenu();
}.bind(this));
this._ctxmenuEl.appendChild(deleteFileEl);
}.bind(this));
var fileIconEl = document.createElement('i');
fileIconEl.classList.add('fa', 'fa-file-o');
fileEl.appendChild(fileIconEl);
var fileNameEl = document.createElement('span');
fileNameEl.textContent = scriptId;
fileEl.appendChild(fileNameEl);
this._filesEl.appendChild(fileEl);
}.bind(this));
}
Sidebar.prototype._destroyCtxmenu = function() {
if( this._ctxmenuEl ) {
this._filesEl.removeChild(this._ctxmenuEl);
this._ctxmenuEl = null;
}
}
Sidebar.prototype._onApp = function( app ) {
this._app = app;
this._refreshScripts();
if( this._app ) {
this._actionsEl.style.visibility = 'visible';
} else {
this._actionsEl.style.visibility = 'hidden';
}
}
Sidebar.prototype._refreshScripts = function(){
if( this._app ) {
this._app.apiGet('script')
.then(function(scripts){
this._scripts = scripts;
this.render();
}.bind(this))
.catch(function(err){
console.error(err);
alert(err);
})
} else {
this._scripts = [];
this.render();
}
}
Sidebar.prototype.deleteScript = function( scriptId ) {
this._app.apiDelete('script/' + scriptId)
.then(function(scripts){
this._refreshScripts();
}.bind(this))
}
Sidebar.prototype.createScript = function() {
var scriptId = prompt("Please enter your script name.", 'myNewScript');
if( scriptId === null | scriptId.length < 1 ) return;
if( this._scripts.indexOf(scriptId) > -1 ) return alert("That name already exists. Please choose a unique name.");
this._app.apiPut('script/' + scriptId, { code: '// my script' })
.then(function(scripts){
this._refreshScripts();
this._editor.open( scriptId );
}.bind(this))
}
<file_sep># HomeyScript
> "The best thing since sliced bread!"
Unleash the scripting power with HomeyScript. Automate everything you every dreamed of, even when Flows are not enough for you!
HomeyScript is a JavaScript-based scripting language that interacts with the Homey Web API and various Homey Apps SDK functions.
## Usage
1. Install HomeyScript from [https://homey.app/a/com.athom.homeyscript](https://homey.app/a/com.athom.homeyscript)
2. Visit [https://homeyscript.homey.app](https://homeyscript.homey.app)
3. Script as you please!
## Example
```javascript
// Get all devices
const devices = await Homey.devices.getDevices();
// Loop over all devices
for (const device of Object.values(devices)) {
// If this device is a light (class)
// Or this is a 'What's plugged in?'-light (virtualClass)
if (device.class === 'light' || device.virtualClass === 'light') {
log(`\nTurning '${device.name}' on...`);
// Turn the light on by setting the capability `onoff` to `true`
await device.setCapabilityValue('onoff', true)
.then(() => log('OK'))
.catch(error => log(`Error:`, error));
}
}
```
For more examples, see `/examples` in the source code.
## Documentation
In your HomeyScript, the following properties are directly accessible.
### Global Properties
The following properties are accessible anywhere.
#### `log(Mixed obj1 [, Mixed obj, ..., Mixed objN])` -> `undefined`
Log a value to the console.
#### `say(String text)` -> `Promise`
Make Homey say something.
```javascript
await say('Hello world!');
```
#### `tag(String id, String|Number|Boolean value)` -> `Promise`
Creates or updates a Flow Token. These are persistent across reboots.
Delete a Flow Token by providing `null` as value.
Resolves after `milliseconds` milliseconds.
```javascript
await tag('My Tag', 1337); // Create
await tag('My Tag', 1338); // Update
await tag('My Tag', null); // Delete
```
#### `wait(Number milliseconds)` -> `Promise`
Resolves after `milliseconds` milliseconds.
```javascript
log('Foo');
await wait(1000);
log('Bar');
```
#### `Homey` -> `HomeyAPI`
This is a [HomeyAPI](https://api.developer.athom.com/HomeyAPI.html) instance with permissions on behalf of the app (`homey:manager:api`).
```javascript
const devices = await Homey.devices.getDevices();
```
#### `fetch`
Shortcut to [node-fetch](https://github.com/node-fetch/node-fetch).
#### `_`
Shortcut to [lodash](https://github.com/lodash/lodash).
#### `global.get(String key)` -> `Mixed`
Get a global value that's accessible between HomeyScripts.
#### `global.set(String key, Mixed value)` -> `undefined`
Set a global value that's accessible between HomeyScripts.
#### `global.keys()` -> `Array`
Gets all keys of global values.
#### `args` -> `Array`
The `args` array contains arguments as provided by a Flow or the Web API.
### Web API
From any other location where you can use the Web API, you can call:
```javascript
const scriptId = 'myScript';
const args = [ 'foo' ];
const HomeyScript = await HomeyAPI.apps.getApp({ id: 'com.athom.homeyscript' });
await HomeyScript.apiPost(`script/${scriptId}/run`, args);
```
### Disclaimer
This app has been created during one of Athom's Hacky Fridays.
This means that we cannot give official support on it, but we welcome high quality issue reports.<file_sep>'use strict';
module.exports = {
async getScripts({ homey, ...args }) {
const scripts = await homey.app.getScripts({ ...args });
return Object.keys(scripts);
},
async getScript({ homey, params }) {
const { id } = params;
return homey.app.getScript({ id });
},
async runScript({ homey, params, body = [] }) {
const { id } = params;
const {
code,
args
} = body;
try {
return {
success: true,
returns: await homey.app.runScript({
id,
code,
args,
}),
};
} catch (err) {
return {
success: false,
returns: {
message: err.message,
stack: err.stack,
},
}
}
},
async updateScript({ homey, params, body }) {
const { id } = params;
const { code } = body;
return homey.app.updateScript({ id, code });
},
async deleteScript({ homey, params }) {
const { id } = params;
return homey.app.deleteScript({ id });
},
}<file_sep>function Topbar(api, editor) {
this._api = api;
this._editor = editor;
this._api.registerHomeyListener(this._onApiHomey.bind(this));
this._api.registerUserListener(this._onApiUser.bind(this));
this._el = document.querySelector('.hs-header');
this._buttonSaveEl = this._el.querySelector('.button.save');
this._buttonSaveEl.addEventListener('click', this._onButtonSave.bind(this));
this._buttonRunEl = this._el.querySelector('.button.run');
this._buttonRunEl.addEventListener('click', this._onButtonRun.bind(this));
this._userEl = this._el.querySelector('.user');
this._userEl.addEventListener('click', this._onUserClick.bind(this));
this._userNameEl = this._userEl.querySelector('.name');
this._userAvatarEl = this._userEl.querySelector('.avatar');
this._userHomeyEl = this._userEl.querySelector('.homey');
}
Topbar.prototype.init = function (api) {
}
Topbar.prototype._onApiHomey = function (homey) {
this._userHomeyEl.textContent = homey.name;
this._userHomeyEl.title = 'v' + homey.softwareVersion;
}
Topbar.prototype._onApiUser = function (user) {
this._userNameEl.textContent = user.fullname;
this._userAvatarEl.src = user.avatar.small;
}
Topbar.prototype._onButtonSave = function (e) {
this._editor.save();
}
Topbar.prototype._onButtonRun = function (e) {
this._editor.run();
}
Topbar.prototype._onUserClick = function (e) {
this._api.logout();
} | 403e8e31db16c26ecd9e400a599975ca38789e16 | [
"JavaScript",
"Text",
"Markdown"
] | 5 | Text | maksim-sushkevich/com.athom.homeyscript | 5c99edd06bf5cd8303db02ab8e8f0ddefd311f13 | 5658858bbb2b6fdd5a8dbb2d2344f1d8d1901813 |
refs/heads/main | <repo_name>prraoo/particle-collision<file_sep>/src/particles/GLParticlePipeline.cpp
#include <GL/error.h>
#include "GLParticlePipeline.h"
extern const char particle_vs[];
extern const char particle_gs[];
extern const char particle_fs[];
GLParticlePipeline::GLParticlePipeline()
{
{
auto vs = GL::compileVertexShader(particle_vs);
auto gs = GL::compileGeometryShader(particle_gs);
auto fs = GL::compileFragmentShader(particle_fs);
glAttachShader(particle_prog, vs);
glAttachShader(particle_prog, gs);
glAttachShader(particle_prog, fs);
GL::linkProgram(particle_prog);
}
GL::throw_error();
}
void GLParticlePipeline::draw(GLsizei offset, GLsizei num_particles, GLuint vao) const
{
glDisable(GL_BLEND);
glBindVertexArray(vao);
glUseProgram(particle_prog);
glDrawArrays(GL_POINTS, offset, num_particles);
GL::throw_error();
}
<file_sep>/src/hdr_pipeline/GLRenderer.cpp
#include <cstdint>
#include <memory>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <GL/error.h>
#include <cuda_gl_interop.h>
#include <utils/CUDA/error.h>
#include <utils/CUDA/graphics_gl_interop.h>
#include "GLScene.h"
#include "GLRenderer.h"
#include "HDRPipeline.h"
using namespace std::literals;
#ifdef WIN32
extern "C" __declspec(dllexport) DWORD NvOptimusEnablement = 1U;
#endif
extern const char fullscreen_triangle_vs[];
extern const char fullscreen_triangle_fs[];
namespace
{
#ifdef WIN32
void APIENTRY debug_output_callback(GLenum /*source*/, GLenum /*type*/, GLuint /*id*/, GLenum /*severity*/, GLsizei /*length*/, const GLchar* message, const void* /*userParam*/)
{
OutputDebugStringA(message);
OutputDebugStringA("\n");
}
#else
void debug_output_callback(GLenum /*source*/, GLenum /*type*/, GLuint /*id*/, GLenum /*severity*/, GLsizei /*length*/, const GLchar* message, const void* /*userParam*/)
{
std::cerr << message << '\n';
}
#endif
}
GLRenderer::GLRenderer(std::string title, int width, int height, float exposure, float brightpass_threshold)
: window(title.c_str(), 1024, 1024 * height / width),
context(window.createContext(4, 3, true)),
ctx(context, window),
exposure(exposure),
brightpass_threshold(brightpass_threshold),
title(std::move(title))
{
std::cout << "\nOpenGL on " << glGetString(GL_RENDERER) << '\n' << std::flush;
glDebugMessageCallback(debug_output_callback, nullptr);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE);
glEnable(GL_FRAMEBUFFER_SRGB);
{
auto vs = GL::compileVertexShader(fullscreen_triangle_vs);
auto fs = GL::compileFragmentShader(fullscreen_triangle_fs);
glAttachShader(fullscreen_prog, vs);
glAttachShader(fullscreen_prog, fs);
GL::linkProgram(fullscreen_prog);
}
window.attach(this);
ctx.setSwapInterval(0);
GL::throw_error();
}
void GLRenderer::resize(int width, int height, GL::platform::Window*)
{
framebuffer_width = width;
framebuffer_height = height;
hdr_buffer_resource.reset();
ldr_buffer_resource.reset();
hdr_buffer = GL::createTexture2D(framebuffer_width, framebuffer_height, 1, GL_RGBA32F);
ldr_buffer = GL::createTexture2D(framebuffer_width, framebuffer_height, 1, GL_SRGB8_ALPHA8);
depth_buffer = GL::createRenderbuffer(framebuffer_width, height, GL_DEPTH_COMPONENT32);
hdr_buffer_resource = CUDA::graphics::register_GL_image(hdr_buffer, GL_TEXTURE_2D, cudaGraphicsRegisterFlagsReadOnly);
ldr_buffer_resource = CUDA::graphics::register_GL_image(ldr_buffer, GL_TEXTURE_2D, 0U);
pipeline.emplace(framebuffer_width, framebuffer_height);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, hdr_buffer, 0);
glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depth_buffer);
}
void GLRenderer::render()
{
if (framebuffer_width <= 0 || framebuffer_height <= 0)
return;
glViewport(0, 0, framebuffer_width, framebuffer_height);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
if (scene)
scene->draw(framebuffer_width, framebuffer_height);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
{
auto mapped_resources = CUDA::graphics::map_resources(hdr_buffer_resource.get(), ldr_buffer_resource.get());
cudaArray_t hdr_buffer_array = CUDA::graphics::get_mapped_array(hdr_buffer_resource.get());
cudaArray_t ldr_buffer_array = CUDA::graphics::get_mapped_array(ldr_buffer_resource.get());
if (pipeline)
{
throw_error(cudaEventRecord(pipeline_begin.get()));
pipeline->process(ldr_buffer_array, hdr_buffer_array, exposure, brightpass_threshold);
throw_error(cudaEventRecord(pipeline_end.get()));
throw_error(cudaEventSynchronize(pipeline_end.get()));
pipeline_time += CUDA::elapsed_time(pipeline_begin.get(), pipeline_end.get());
++frame_count;
if (auto now = std::chrono::steady_clock::now(); next_fps_tick <= now)
{
auto dt = std::chrono::duration<float>(now - next_fps_tick + 1s).count();
std::ostringstream str;
str << title << " @ t = " << std::setprecision(2) << std::fixed << pipeline_time / frame_count << " ms";
window.title(str.str().c_str());
next_fps_tick = now + 1s;
frame_count = 0;
pipeline_time = 0.0f;
}
}
}
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBindVertexArray(vao);
glUseProgram(fullscreen_prog);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, ldr_buffer);
glBindSampler(0, sampler);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 3);
GL::throw_error();
ctx.swapBuffers();
}
image2D<std::uint32_t> GLRenderer::screenshot() const
{
image2D<std::uint32_t> buffer(framebuffer_width, framebuffer_height);
glReadBuffer(GL_FRONT);
glReadPixels(0, 0, framebuffer_width, framebuffer_height, GL_RGBA, GL_UNSIGNED_BYTE, data(buffer));
GL::throw_error();
using std::swap;
for (int y = 0; y < height(buffer) / 2; ++y)
for (int x = 0; x < width(buffer); ++x)
std::swap(buffer(x, y), buffer(x, height(buffer) - y - 1));
return buffer;
}
void GLRenderer::attach(GL::platform::MouseInputHandler* mouse_input)
{
window.attach(mouse_input);
}
void GLRenderer::attach(GL::platform::KeyboardInputHandler* keyboard_input)
{
window.attach(keyboard_input);
}
void GLRenderer::attach(const GLScene* scene)
{
this->scene = scene;
}
<file_sep>/src/particles/GLParticleReplay.cpp
#include <algorithm>
#include <GL/error.h>
#include "GLParticleReplay.h"
namespace
{
std::vector<float> init_position(std::size_t num_particles, const float* position)
{
std::vector<float> position_data;
position_data.reserve(4 * num_particles);
for (std::size_t i = 0; i < num_particles; ++i)
{
position_data.push_back(position[0 * num_particles + i]);
position_data.push_back(position[1 * num_particles + i]);
position_data.push_back(position[2 * num_particles + i]);
position_data.push_back(position[3 * num_particles + i]);
}
return position_data;
}
}
void GLParticleReplayBuilder::add_frame(std::chrono::nanoseconds dt, const float* position, const std::uint32_t* color)
{
t.push_back(t.back() + dt);
position_data.insert(std::end(position_data), position, position + 4 * num_particles);
color_data.insert(std::end(color_data), color, color + num_particles);
}
GLParticleReplayBuilder::GLParticleReplayBuilder(std::size_t num_particles, const float* position, const std::uint32_t* color, const ParticleSystemParameters& params)
: num_particles(num_particles),
t { std::chrono::nanoseconds(0) },
position_data(init_position(num_particles, position)),
color_data { color, color + num_particles },
bb_min(params.bb_min[0], params.bb_min[1], params.bb_min[2]),
bb_max(params.bb_max[0], params.bb_max[1], params.bb_max[2])
{
}
std::tuple<std::unique_ptr<GLScene>, math::float3, math::float3> GLParticleReplayBuilder::finish()
{
return {
std::make_unique<GLParticleReplay>(num_particles, std::move(t), &position_data[0], &color_data[0], bb_min, bb_max),
bb_min,
bb_max
};
}
GLParticleReplay::GLParticleReplay(std::size_t num_particles, std::vector<std::chrono::nanoseconds> frame_times, const float* position, const std::uint32_t* color, const math::float3& bb_min, const math::float3& bb_max)
: num_particles(static_cast<GLsizei>(num_particles)),
bounding_box(bb_min, bb_max),
frame_times(std::move(frame_times))
{
glBindBuffer(GL_ARRAY_BUFFER, particle_position_buffer);
glBufferStorage(GL_ARRAY_BUFFER, num_particles * size(this->frame_times) * 16U, position, 0U);
glBindBuffer(GL_ARRAY_BUFFER, particle_color_buffer);
glBufferStorage(GL_ARRAY_BUFFER, num_particles * size(this->frame_times) * 4U, color, 0U);
GL::throw_error();
glBindVertexArray(particles_vao);
glBindVertexBuffer(0U, particle_position_buffer, 0U, 16U);
glEnableVertexAttribArray(0U);
glVertexAttribBinding(0U, 0U);
glVertexAttribFormat(0U, 4, GL_FLOAT, GL_FALSE, 0U);
glBindVertexBuffer(1U, particle_color_buffer, 0U, 4U);
glEnableVertexAttribArray(1U);
glVertexAttribBinding(1U, 1U);
glVertexAttribFormat(1U, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0U);
GL::throw_error();
}
void GLParticleReplay::reset()
{
time = std::chrono::nanoseconds(0);
frame = 0;
}
float GLParticleReplay::update(int steps, float dt)
{
time += steps * std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::duration<float>(dt));
auto found = std::upper_bound(begin(frame_times) + frame, end(frame_times), time);
if (found != end(frame_times))
frame = found - begin(frame_times) - 1;
return 0.0f;
}
void GLParticleReplay::draw(bool draw_bounding_box) const
{
pipeline.draw(frame * num_particles, num_particles, particles_vao);
if (draw_bounding_box)
bounding_box.draw();
}
<file_sep>/src/particles/GLRenderer.cpp
#include <cstdint>
#include <memory>
#include <string_view>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <GL/error.h>
#include "GLRenderer.h"
using namespace std::literals;
#ifdef WIN32
extern "C" __declspec(dllexport) DWORD NvOptimusEnablement = 1U;
#endif
namespace
{
#ifdef WIN32
void APIENTRY debug_output_callback(GLenum /*source*/, GLenum /*type*/, GLuint /*id*/, GLenum /*severity*/, GLsizei /*length*/, const GLchar* message, const void* /*userParam*/)
{
OutputDebugStringA(message);
OutputDebugStringA("\n");
}
#else
void debug_output_callback(GLenum /*source*/, GLenum /*type*/, GLuint /*id*/, GLenum /*severity*/, GLsizei /*length*/, const GLchar* message, const void* /*userParam*/)
{
std::cerr << message << '\n';
}
#endif
}
GLRenderer::GLRenderer(int max_frames, float dt, bool frozen)
: window("particles", 1024, 768, 24),
context(window.createContext(4, 3, true)),
ctx(context, window),
max_frames(max_frames),
frozen(frozen),
timestep(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::duration<float>(dt)))
{
std::cout << "\nOpenGL on " << glGetString(GL_RENDERER) << '\n' << std::flush;
glDebugMessageCallback(debug_output_callback, nullptr);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE);
glEnable(GL_FRAMEBUFFER_SRGB);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glClearColor(0.6f, 0.7f, 1.0f, 1.0f);
glClearDepth(1.0f);
ctx.setSwapInterval(0);
window.attach(this);
GL::throw_error();
}
void GLRenderer::resize(int width, int height, GL::platform::Window*)
{
framebuffer_width = width;
framebuffer_height = height;
}
void GLRenderer::render()
{
if (framebuffer_width <= 0 || framebuffer_height <= 0)
return;
glViewport(0, 0, framebuffer_width, framebuffer_height);
auto now = std::chrono::steady_clock::now();
if (scene && !frozen)
{
std::chrono::nanoseconds dt = now - last_update;
if (dt > timestep)
{
step(dt / timestep);
last_update = now;
}
}
glDepthMask(GL_TRUE);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (scene)
{
scene->draw(framebuffer_width, framebuffer_height);
}
++frame_count;
if (next_fps_tick <= now)
{
constexpr auto fps_update_timestep = 100ms;
auto dt = std::chrono::duration<float>(now - next_fps_tick + fps_update_timestep).count();
update_window_title(dt);
next_fps_tick = now + fps_update_timestep;
frame_count = 0;
}
GL::throw_error();
ctx.swapBuffers();
}
void GLRenderer::update_window_title(float dt)
{
std::ostringstream str;
str << "particles @ t_avg = "sv
<< std::setprecision(3) << std::fixed << update_time / step_count << " ms "sv
<< std::setw(static_cast<int>(std::log10(max_frames)) + 1) << step_count << " simulation steps * "sv
<< std::defaultfloat << std::chrono::duration<double>(timestep).count() << " s = "sv
<< std::fixed << std::setw(static_cast<int>(std::log10(std::chrono::duration<double>(max_frames * timestep).count())) + 4) << std::chrono::duration<double>(simulation_time).count() << " s";
if (show_fps)
str << " "sv << std::setprecision(1) << std::fixed << dt * 1000.0f / frame_count << " mspf = "sv << frame_count / dt << " fps"sv;
window.title(str.str().c_str());
}
void GLRenderer::step(int steps)
{
steps = std::min(step_count + steps, max_frames) - step_count;
update_time += scene->update(steps, std::chrono::duration<float>(timestep).count());
step_count += steps;
simulation_time += steps * timestep;
if (step_count >= max_frames)
reset();
}
void GLRenderer::reset()
{
scene->reset();
scene->update(1, 0.0f);
last_update = std::chrono::steady_clock::now();
simulation_time = std::chrono::nanoseconds(0);
step_count = 0;
update_time = 0.0f;
}
bool GLRenderer::toggle_freeze()
{
frozen = !frozen;
if (!frozen)
last_update = std::chrono::steady_clock::now();
return frozen;
}
bool GLRenderer::toggle_fps()
{
return show_fps = !show_fps;
}
void GLRenderer::attach(GL::platform::MouseInputHandler* mouse_input)
{
window.attach(mouse_input);
}
void GLRenderer::attach(GL::platform::KeyboardInputHandler* keyboard_input)
{
window.attach(keyboard_input);
}
void GLRenderer::attach(GLScene* scene)
{
this->scene = scene;
reset();
}
image2D<std::uint32_t> GLRenderer::screenshot() const
{
image2D<std::uint32_t> buffer(framebuffer_width, framebuffer_height);
glReadBuffer(GL_FRONT);
glReadPixels(0, 0, framebuffer_width, framebuffer_height, GL_RGBA, GL_UNSIGNED_BYTE, data(buffer));
GL::throw_error();
using std::swap;
for (int y = 0; y < height(buffer) / 2; ++y)
for (int x = 0; x < width(buffer); ++x)
std::swap(buffer(x, y), buffer(x, height(buffer) - y - 1));
return buffer;
}
<file_sep>/src/particles/GLNoCUDAParticleDemo.cpp
#include <utility>
#include <stdexcept>
#include <optional>
#include <vector>
#include <iostream>
#include "particle_system_state.h"
#include "ParticleSystemLoader.h"
#include "GLParticleReplay.h"
#include "GLParticleDemo.h"
std::tuple<std::unique_ptr<GLScene>, math::float3, math::float3> load_scene(const std::filesystem::path& path, int cuda_device)
{
class SceneBuilder : private virtual ParticleSystemBuilder
{
std::optional<GLParticleReplayBuilder> builder;
void add_particle_simulation(std::size_t num_particles, std::unique_ptr<float[]> position, std::unique_ptr<std::uint32_t[]> color, const ParticleSystemParameters& params) override
{
throw std::runtime_error("cannot run particle system without CUDA");
}
ParticleReplayBuilder& add_particle_replay(std::size_t num_particles, const float* position, const std::uint32_t* color, const ParticleSystemParameters& params) override
{
return builder.emplace(num_particles, position, color, params);
}
public:
std::tuple<std::unique_ptr<GLScene>, math::float3, math::float3> load(const std::filesystem::path& path)
{
load_particles(*this, path);
return builder->finish();
}
};
SceneBuilder scene_builder;
return scene_builder.load(path);
}
<file_sep>/src/particles/particle_system_module.cpp
#include "ParticleSystem.h"
#ifdef _WIN32
#define EXPORT __declspec(dllexport)
#else
#define EXPORT __attribute__((visibility("default")))
#endif
extern "C"
{
EXPORT ParticleSystem* create_particles(std::size_t num_particles, const float* x, const float* y, const float* z, const float* r, const std::uint32_t* color, const ParticleSystemParameters& params)
{
return new ParticleSystem(num_particles, x, y, z, r, color, params);
}
EXPORT void reset_particles(ParticleSystem* particles, const float* x, const float* y, const float* z, const float* r, const std::uint32_t* color)
{
particles->reset(x, y, z, r, color);
}
EXPORT void update_particles(ParticleSystem* particles, float* position, std::uint32_t* color, float dt)
{
particles->update(position, color, dt);
}
EXPORT void destroy_particles(ParticleSystem* particles)
{
delete particles;
}
}
<file_sep>/src/hdr_pipeline/run_interactive.cpp
#include <cstdint>
#include <iostream>
#include <GL/platform/Application.h>
#include <utils/PerspectiveCamera.h>
#include <utils/OrbitalNavigator.h>
#include <utils/image.h>
#include "envmap.h"
#include "InputHandler.h"
#include "GLRenderer.h"
#include "GLScene.h"
#include "HDRDemo.h"
void HDRDemo::run(const std::filesystem::path& output_file, const std::filesystem::path& envmap_path, float exposure, float brightpass_threshold, int test_runs)
{
if (test_runs != 1)
std::cerr << "\nWARNING: test-runs parameter ignored in interactive mode\n";
auto envmap = load_envmap(envmap_path, true);
PerspectiveCamera camera(60.0f * math::pi<float> / 180.0f, 0.1f, length(bb_max - bb_min) * 10.0f);
OrbitalNavigator navigator(-math::pi<float> / 2, 0.0f, length(bb_max - bb_min) * 1.5f, (bb_min + bb_max) * 0.5f);
camera.attach(&navigator);
GLRenderer renderer(envmap_path.string(), static_cast<int>(width(envmap)), static_cast<int>(height(envmap)), exposure, brightpass_threshold);
InputHandler input_handler(navigator, renderer);
GLScene scene(camera, envmap, data(vertices), static_cast<GLsizei>(size(vertices) / 6), data(indices), static_cast<GLsizei>(size(indices)));
renderer.attach(static_cast<GL::platform::MouseInputHandler*>(&input_handler));
renderer.attach(static_cast<GL::platform::KeyboardInputHandler*>(&input_handler));
renderer.attach(&scene);
GL::platform::run(renderer);
}
<file_sep>/src/particles/ParticleSystemLoader.h
#ifndef INCLUDED_PARTICLE_SYSTEM_LOADER
#define INCLUDED_PARTICLE_SYSTEM_LOADER
#pragma once
#include <memory>
#include <utils/dynamic_library.h>
#include "particle_system_module.h"
struct particle_system_deleter
{
destroy_particles_func* destroy;
void operator ()(ParticleSystem* particles) const
{
destroy(particles);
}
};
using unique_particle_system = std::unique_ptr<ParticleSystem, particle_system_deleter>;
class particle_system_instance
{
update_particles_func* update_func;
reset_particles_func* reset_func;
unique_particle_system particles;
public:
particle_system_instance(update_particles_func* update_func, reset_particles_func* reset_func, unique_particle_system particles)
: update_func(update_func), reset_func(reset_func), particles(std::move(particles))
{
}
void reset(const float* x, const float* y, const float* z, const float* r, const std::uint32_t* color)
{
reset_func(particles.get(), x, y, z, r, color);
}
void update(float* position, std::uint32_t* color, float dt)
{
update_func(particles.get(), position, color, dt);
}
};
class particle_system_module
{
unique_library module;
create_particles_func* create_particles;
reset_particles_func* reset_particles;
update_particles_func* update_particles;
destroy_particles_func* destroy_particles;
public:
particle_system_module(const std::filesystem::path& path)
: module(load_library(path)),
create_particles(lookup_symbol<create_particles_func>(module.get(), "create_particles")),
reset_particles(lookup_symbol<reset_particles_func>(module.get(), "reset_particles")),
update_particles(lookup_symbol<update_particles_func>(module.get(), "update_particles")),
destroy_particles(lookup_symbol<destroy_particles_func>(module.get(), "destroy_particles"))
{
}
auto create_instance(std::size_t num_particles, const float* x, const float* y, const float* z, const float* r, const std::uint32_t* color, const ParticleSystemParameters& params)
{
return particle_system_instance(update_particles, reset_particles, unique_particle_system(create_particles(num_particles, x, y, z, r, color, params), { destroy_particles }));
}
};
#endif // INCLUDED_PARTICLE_SYSTEM_LOADER
<file_sep>/src/particles/GLCUDAParticles.cpp
#include <utility>
#include <GL/error.h>
#include <cuda_gl_interop.h>
#include <utils/CUDA/error.h>
#include <utils/CUDA/device.h>
#include <utils/CUDA/graphics_gl_interop.h>
#include "GLCUDAParticles.h"
GLCUDAParticles::GLCUDAParticles(particle_system_instance particles, std::size_t num_particles, std::unique_ptr<float[]> position, std::unique_ptr<std::uint32_t[]> color, const math::float3& bb_min, const math::float3& bb_max)
: particles(std::move(particles)),
bounding_box(bb_min, bb_max),
num_particles(static_cast<GLsizei>(num_particles)),
particles_begin(CUDA::create_event()),
particles_end(CUDA::create_event()),
initial_position(std::move(position)),
initial_color(std::move(color))
{
glBindBuffer(GL_ARRAY_BUFFER, particle_position_buffer);
glBufferStorage(GL_ARRAY_BUFFER, num_particles * 16U, nullptr, 0U);
particle_position_buffer_resource = CUDA::graphics::register_GL_buffer(particle_position_buffer, cudaGraphicsMapFlagsReadOnly);
glBindBuffer(GL_ARRAY_BUFFER, particle_color_buffer);
glBufferStorage(GL_ARRAY_BUFFER, num_particles * 4U, nullptr, 0U);
particle_color_buffer_resource = CUDA::graphics::register_GL_buffer(particle_color_buffer, cudaGraphicsMapFlagsReadOnly);
GL::throw_error();
glBindVertexArray(particles_vao);
glBindVertexBuffer(0U, particle_position_buffer, 0U, 16U);
glEnableVertexAttribArray(0U);
glVertexAttribBinding(0U, 0U);
glVertexAttribFormat(0U, 4, GL_FLOAT, GL_FALSE, 0U);
glBindVertexBuffer(1U, particle_color_buffer, 0U, 4U);
glEnableVertexAttribArray(1U);
glVertexAttribBinding(1U, 1U);
glVertexAttribFormat(1U, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0U);
GL::throw_error();
}
void GLCUDAParticles::reset()
{
particles.reset(&initial_position[0] + 0 * num_particles, &initial_position[0] + 1 * num_particles, &initial_position[0] + 2 * num_particles, &initial_position[0] + 3 * num_particles, &initial_color[0]);
}
float GLCUDAParticles::update(int steps, float dt)
{
auto mapped_resources = CUDA::graphics::map_resources(particle_position_buffer_resource.get(), particle_color_buffer_resource.get());
auto mapped_positions = CUDA::graphics::get_mapped_buffer(particle_position_buffer_resource.get());
auto mapped_colors = CUDA::graphics::get_mapped_buffer(particle_color_buffer_resource.get());
throw_error(cudaEventRecord(particles_begin.get()));
for (int i = 0; i < steps; ++i)
particles.update(static_cast<float*>(mapped_positions.ptr), static_cast<std::uint32_t*>(mapped_colors.ptr), dt);
throw_error(cudaEventRecord(particles_end.get()));
throw_error(cudaEventSynchronize(particles_end.get()));
return CUDA::elapsed_time(particles_begin.get(), particles_end.get());
}
void GLCUDAParticles::draw(bool draw_bounding_box) const
{
pipeline.draw(0, num_particles, particles_vao);
if(draw_bounding_box)
bounding_box.draw();
}
<file_sep>/src/particles/ParticleDemo.h
#ifndef INCLUDED_PARTICLEDEMO
#define INCLUDED_PARTICLEDEMO
#pragma once
#include <filesystem>
class ParticleDemo
{
public:
void run(std::filesystem::path output_file, const std::filesystem::path& input_file, int N, int subsample, float dt, int cuda_device);
};
#endif // INCLUDED_PARTICLEDEMO
<file_sep>/src/particles/GLRenderer.h
#ifndef INCLUDED_RENDERER
#define INCLUDED_RENDERER
#pragma once
#include <cstdint>
#include <chrono>
#include <GL/gl.h>
#include <GL/platform/Renderer.h>
#include <GL/platform/Context.h>
#include <GL/platform/Window.h>
#include <GL/platform/DefaultDisplayHandler.h>
#include <utils/image.h>
#include "GLScene.h"
class GLRenderer : public virtual GL::platform::Renderer, private GL::platform::DefaultDisplayHandler
{
GL::platform::Window window;
GL::platform::Context context;
GL::platform::context_scope<GL::platform::Window> ctx;
int framebuffer_width;
int framebuffer_height;
GLScene* scene = nullptr;
bool frozen = true;
std::chrono::nanoseconds timestep;
int max_frames;
int step_count = 0;
long long frame_count = 0;
std::chrono::steady_clock::time_point last_update;
std::chrono::steady_clock::time_point next_fps_tick = std::chrono::steady_clock::now();
std::chrono::nanoseconds simulation_time;
float update_time = 0.0f;
bool show_fps = false;
void resize(int width, int height, GL::platform::Window*) override;
void update_window_title(float dt);
public:
GLRenderer(int max_frames, float dt, bool frozen);
void reset();
bool toggle_freeze();
bool toggle_fps();
void step(int steps = 1);
void render() override;
image2D<std::uint32_t> screenshot() const;
void attach(GL::platform::MouseInputHandler* mouse_input);
void attach(GL::platform::KeyboardInputHandler* keyboard_input);
void attach(GLScene* scene);
};
#endif // INCLUDED_RENDERER
<file_sep>/src/hdr_pipeline/HDRPipeline.cpp
#include <utils/CUDA/error.h>
#include <utils/CUDA/memory.h>
#include "HDRPipeline.h"
HDRPipeline::HDRPipeline(int width, int height)
: frame_width(width),
frame_height(height),
d_input_image(CUDA::malloc<float>(width * height * 4)),
d_output_image(CUDA::malloc_zeroed<std::uint32_t>(width * height))
{
}
void tonemap(std::uint32_t* out, const float* in, int width, int height, float exposure, float brightpass_threshold);
void HDRPipeline::process(cudaArray_t out, cudaArray_t in, float exposure, float brightpass_threshold)
{
throw_error(cudaMemcpy2DFromArray(d_input_image.get(), frame_width * 16U, in, 0, 0, frame_width * 16U, frame_height, cudaMemcpyDeviceToDevice));
tonemap(d_output_image.get(), d_input_image.get(), frame_width, frame_height, exposure, brightpass_threshold);
throw_error(cudaMemcpy2DToArray(out, 0, 0, d_output_image.get(), frame_width * 4U, frame_width * 4U, frame_height, cudaMemcpyDeviceToDevice));
}
<file_sep>/src/particles/GLParticleReplay.h
#ifndef INCLUDED_GL_PARTICLE_REPLAY
#define INCLUDED_GL_PARTICLE_REPLAY
#pragma once
#include <cstdint>
#include <memory>
#include <vector>
#include <chrono>
#include <GL/gl.h>
#include <GL/vertex_array.h>
#include <GL/buffer.h>
#include "particle_system_state.h"
#include "GLScene.h"
#include "GLParticlePipeline.h"
#include "GLBoundingBox.h"
class GLParticleReplayBuilder : public virtual ParticleReplayBuilder
{
std::size_t num_particles;
std::vector<std::chrono::nanoseconds> t;
std::vector<float> position_data;
std::vector<std::uint32_t> color_data;
math::float3 bb_min;
math::float3 bb_max;
void add_frame(std::chrono::nanoseconds dt, const float* position, const std::uint32_t* color) override;
public:
GLParticleReplayBuilder(std::size_t num_particles, const float* position, const std::uint32_t* color, const ParticleSystemParameters& params);
std::tuple<std::unique_ptr<GLScene>, math::float3, math::float3> finish();
};
class GLParticleReplay : public virtual GLScene
{
GLsizei num_particles;
std::chrono::nanoseconds time = std::chrono::nanoseconds(0);
int frame = 0;
GLParticlePipeline pipeline;
GL::VertexArray particles_vao;
GLBoundingBox bounding_box;
std::vector<std::chrono::nanoseconds> frame_times;
GL::Buffer particle_position_buffer;
GL::Buffer particle_color_buffer;
public:
GLParticleReplay(std::size_t num_particles, std::vector<std::chrono::nanoseconds> frame_times, const float* position, const std::uint32_t* color, const math::float3& bb_min, const math::float3& bb_max);
void reset() override;
float update(int steps, float dt) override;
void draw(bool draw_bounding_box) const override;
};
#endif // INCLUDED_GL_PARTICLE_REPLAY
<file_sep>/src/particles/GLBoundingBox.cpp
#include <GL/error.h>
#include "GLBoundingBox.h"
extern const char bounding_box_vs[];
extern const char bounding_box_fs[];
GLBoundingBox::GLBoundingBox(const math::float3& bb_min, const math::float3& bb_max)
{
{
auto vs = GL::compileVertexShader(bounding_box_vs);
auto fs = GL::compileFragmentShader(bounding_box_fs);
glAttachShader(prog, vs);
glAttachShader(prog, fs);
GL::linkProgram(prog);
}
glProgramUniform3f(prog, 0, bb_max.x - bb_min.x, bb_max.y - bb_min.y, bb_max.z - bb_min.z);
glProgramUniform3f(prog, 1, (bb_min.x + bb_max.x) * 0.5f, (bb_min.y + bb_max.y) * 0.5f, (bb_min.z + bb_max.z) * 0.5f);
{
//GLfloat vertices[] = {
// -1.0f, -1.0f, -1.0f,
// 1.0f, -1.0f, -1.0f,
// -1.0f, 1.0f, -1.0f,
// 1.0f, 1.0f, -1.0f,
// -1.0f, -1.0f, 1.0f,
// 1.0f, -1.0f, 1.0f,
// -1.0f, 1.0f, 1.0f,
// 1.0f, 1.0f, 1.0f,
//};
GLushort indices[] = {
6, 0, 4,
0, 6, 2,
5, 3, 7,
3, 5, 1,
1, 2, 3,
2, 1, 0,
4, 7, 6,
7, 4, 5,
0, 5, 4,
5, 0, 1,
6, 3, 2,
3, 6, 7
};
glBindVertexArray(vao);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer);
glBufferStorage(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, 0U);
}
GL::throw_error();
}
void GLBoundingBox::draw() const
{
glEnable(GL_BLEND);
glDepthMask(GL_FALSE);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glBindVertexArray(vao);
glUseProgram(prog);
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, nullptr);
//glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
GL::throw_error();
}
<file_sep>/src/hdr_pipeline/HDRPipeline.h
#ifndef INCLUDED_HDRPIPELINE
#define INCLUDED_HDRPIPELINE
#pragma once
#include <cstdint>
#include <cuda_runtime_api.h>
#include <utils/CUDA/memory.h>
class HDRPipeline
{
int frame_width;
int frame_height;
CUDA::unique_ptr<float> d_input_image;
CUDA::unique_ptr<std::uint32_t> d_output_image;
public:
HDRPipeline(int width, int height);
void process(cudaArray_t out, cudaArray_t in, float exposure, float brightpass_threshold);
};
#endif // INCLUDED_HDRPIPELINE
<file_sep>/src/hdr_pipeline/envmap.cpp
#include <cassert>
#include <utility>
#include <optional>
#include <variant>
#include <stdexcept>
#include <utils/io/radiance.h>
#include <utils/io/pfm.h>
#include "envmap.h"
namespace
{
template <bool flip>
class image_sink : public ImageIO::Sink, ImageIO::Sink::ImageSink
{
std::optional<image2D<std::array<float, 4>>> image;
void accept_row(const float* row, std::size_t j) override
{
for (std::size_t i = 0; i < width(*image); ++i)
(*image)(i, flip ? height(*image) - j - 1 : j) = { row[3 * i + 0], row[3 * i + 1], row[3 * i + 2], 0.0f };
}
ImageIO::Sink::ImageSink& accept_R32F(std::size_t width, std::size_t height) override
{
throw std::runtime_error("environment map must be an RGB image");
}
ImageIO::Sink::ImageSink& accept_RGB32F(std::size_t width, std::size_t height) override
{
image.emplace(width, height);
return *this;
}
public:
image2D<std::array<float, 4>> finish()
{
assert(image);
return std::move(*image);
}
};
}
image2D<std::array<float, 4>> load_envmap(const std::filesystem::path& filename, bool flip)
{
std::variant<image_sink<false>, image_sink<true>> sink;
if (flip)
sink.emplace<image_sink<true>>();
else
sink.emplace<image_sink<false>>();
if (filename.extension() == ".pfm")
PFM::load(std::visit([](auto&& a) -> ImageIO::Sink& { return a; }, sink), filename);
else if (filename.extension() == ".hdr")
Radiance::load(std::visit([](auto&& a) -> ImageIO::Sink& { return a; }, sink), filename);
else
throw std::runtime_error("unknown file extension '" + filename.extension().string() + '\'');
return std::visit([](auto&& a) { return a.finish(); }, sink);
}
<file_sep>/src/particles/GLScene.cpp
#include <GL/error.h>
#include "GLScene.h"
GLScene::GLScene()
{
glBindBuffer(GL_UNIFORM_BUFFER, camera_uniform_buffer);
glBufferStorage(GL_UNIFORM_BUFFER, Camera::uniform_buffer_size, nullptr, GL_DYNAMIC_STORAGE_BIT);
GL::throw_error();
}
void GLScene::draw(int viewport_width, int viewport_height)
{
if (!camera)
return;
std::byte camera_uniform_data[Camera::uniform_buffer_size];
camera->writeUniformBuffer(camera_uniform_data, viewport_width * 1.0f / viewport_height);
glBindBufferBase(GL_UNIFORM_BUFFER, 0U, camera_uniform_buffer);
glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(camera_uniform_data), camera_uniform_data);
draw(draw_bounding_box);
}
bool GLScene::toggle_bounding_box()
{
return draw_bounding_box = !draw_bounding_box;
}
void GLScene::attach(const Camera* camera)
{
this->camera = camera;
}
<file_sep>/src/hdr_pipeline/InputHandler.cpp
#include <utils/io/png.h>
#include <utils/screenshot.h>
#include "GLRenderer.h"
#include "InputHandler.h"
InputHandler::InputHandler(OrbitalNavigator& navigator, GLRenderer& renderer)
: navigator(navigator), renderer(renderer)
{
}
void InputHandler::keyDown(GL::platform::Key key, GL::platform::Window*)
{
switch (key)
{
case GL::platform::Key::F8:
PNG::saveImageR8G8B8A8(open_screenshot_file("HDRPipeline.png"), renderer.screenshot());
break;
default:
break;
}
}
void InputHandler::keyUp(GL::platform::Key, GL::platform::Window*)
{
}
void InputHandler::buttonDown(GL::platform::Button button, int x, int y, GL::platform::Window* window)
{
navigator.buttonDown(button, x, y, window);
}
void InputHandler::buttonUp(GL::platform::Button button, int x, int y, GL::platform::Window* window)
{
navigator.buttonUp(button, x, y, window);
}
void InputHandler::mouseMove(int x, int y, GL::platform::Window* window)
{
navigator.mouseMove(x, y, window);
}
void InputHandler::mouseWheel(int d, GL::platform::Window* window)
{
navigator.mouseWheel(d, window);
}
<file_sep>/src/particles/main.cpp
#include <utility>
#include <exception>
#include <iostream>
#include <iomanip>
#include <filesystem>
#include <utils/argparse.h>
#include "ParticleDemo.h"
using namespace std::literals;
namespace
{
std::ostream& print_usage(std::ostream& out)
{
return out << R"""(usage: particles [{options}] <file>
options:
-o <file> save replay to <file>
--device <i> use CUDA device <i>. default: 0
--timestep <dt> simulation time step <dt> s. default: 0.01 s
-N <N> run <N> simulation frames. default: 2000
--subsample <n> record only every n-th simulation frame. default: 8
--frozen start simulation frozen. default: false
)""";
}
}
int main(int argc, char* argv[])
{
try
{
ParticleDemo demo;
int cuda_device = 0;
float dt = 0.01f;
int N = 2000;
int subsample = 8;
bool frozen = false;
std::filesystem::path particles_file;
std::filesystem::path output_file;
for (const char* const* a = argv + 1; *a; ++a)
{
if (argparse::parseIntArgument(cuda_device, a, "--device"sv));
else if (argparse::parseFloatArgument(dt, a, "--timestep"sv));
else if (argparse::parseIntArgument(N, a, "-N"sv));
else if (argparse::parseIntArgument(subsample, a, "--subsample"sv));
else if (argparse::parseBoolFlag(a, "--frozen"sv))
frozen = true;
else if (const char* str = argparse::parseStringArgument(a, "-o"sv))
output_file = str;
else
particles_file = *a;
}
if (particles_file.empty())
throw argparse::usage_error("expected input file");
demo.run(std::move(output_file), particles_file, N, subsample, dt, cuda_device);
}
catch (const argparse::usage_error& e)
{
std::cerr << "ERROR: " << e.what() << '\n' << print_usage;
return -127;
}
catch (const std::exception& e)
{
std::cerr << "ERROR: " << e.what() << '\n';
return -1;
}
catch (...)
{
std::cerr << "ERROR: unknown exception\n";
return -128;
}
return 0;
}
<file_sep>/src/hdr_pipeline/GLScene.h
#ifndef INCLUDED_GLSCENE
#define INCLUDED_GLSCENE
#pragma once
#include <GL/shader.h>
#include <GL/buffer.h>
#include <GL/texture.h>
#include <GL/vertex_array.h>
#include <utils/Camera.h>
#include <utils/image.h>
class GLScene
{
GL::VertexArray vao_env;
GL::VertexArray vao_model;
GL::Buffer vertex_buffer;
GL::Buffer index_buffer;
GL::Program prog_env;
GL::Program prog_model;
GL::Buffer camera_uniform_buffer;
GL::Texture envmap;
//GL::Sampler envmap_sampler;
GLsizei num_indices;
const Camera& camera;
public:
GLScene(const Camera& camera, const image2D<std::array<float, 4>>& env, const float* vertex_data, GLsizei num_vertices, const std::uint32_t* index_data, GLsizei num_indices);
void draw(int framebuffer_width, int framebuffer_height) const;
};
#endif // INCLUDED_GLSCENE
<file_sep>/src/particles/GLParticleDemo.h
#ifndef INCLUDED_GL_PARTICLE_DEMO
#define INCLUDED_GL_PARTICLE_DEMO
#include <memory>
#include <tuple>
#include <filesystem>
#include <utils/math/vector.h>
#include "GLScene.h"
std::tuple<std::unique_ptr<GLScene>, math::float3, math::float3> load_scene(const std::filesystem::path& path, int cuda_device);
#endif // INCLUDED_GL_PARTICLE_DEMO
<file_sep>/src/particles/GLScene.h
#ifndef INCLUDED_GLSCENE
#define INCLUDED_GLSCENE
#pragma once
#include <GL/buffer.h>
#include <utils/Camera.h>
class GLScene
{
const Camera* camera = nullptr;
GL::Buffer camera_uniform_buffer;
bool draw_bounding_box = true;
protected:
virtual void draw(bool bounding_box) const = 0;
GLScene();
public:
virtual ~GLScene() = default;
void attach(const Camera* navigator);
bool toggle_bounding_box();
virtual void reset() = 0;
virtual float update(int steps, float dt) = 0;
void draw(int viewport_width, int viewport_height);
};
#endif // INCLUDED_GLSCENE
<file_sep>/src/hdr_pipeline/GLScene.cpp
#include <cmath>
#include <GL/error.h>
#include <utils/io/pfm.h>
#include <utils/Camera.h>
#include "GLScene.h"
extern const char env_vs[];
extern const char env_fs[];
extern const char model_vs[];
extern const char model_fs[];
GLScene::GLScene(const Camera& camera, const image2D<std::array<float, 4>>& env, const float* vertex_data, GLsizei num_vertices, const std::uint32_t* index_data, GLsizei num_indices)
: camera(camera), num_indices(num_indices)
{
{
auto vs = GL::compileVertexShader(env_vs);
auto fs = GL::compileFragmentShader(env_fs);
glAttachShader(prog_env, vs);
glAttachShader(prog_env, fs);
GL::linkProgram(prog_env);
}
{
auto vs = GL::compileVertexShader(model_vs);
auto fs = GL::compileFragmentShader(model_fs);
glAttachShader(prog_model, vs);
glAttachShader(prog_model, fs);
GL::linkProgram(prog_model);
}
glBindBuffer(GL_UNIFORM_BUFFER, camera_uniform_buffer);
glBufferStorage(GL_UNIFORM_BUFFER, Camera::uniform_buffer_size, nullptr, GL_DYNAMIC_STORAGE_BIT);
GL::throw_error();
{
glBindTexture(GL_TEXTURE_2D, envmap);
glTexStorage2D(GL_TEXTURE_2D, /*static_cast<GLsizei>(std::log2(std::max(width(env), height(env)))) +*/ 1, GL_RGBA16F, static_cast<GLsizei>(width(env)), static_cast<GLsizei>(height(env)));
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, static_cast<GLsizei>(width(env)), static_cast<GLsizei>(height(env)), GL_RGBA, GL_FLOAT, data(env));
//glGenerateMipmap(GL_TEXTURE_2D);
//glSamplerParameteri(envmap_sampler, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
//glSamplerParameteri(envmap_sampler, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
//glSamplerParameteri(envmap_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
}
GL::throw_error();
if (num_indices)
{
glBindVertexArray(vao_model);
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
glBufferStorage(GL_ARRAY_BUFFER, num_vertices * 6 * 4U, vertex_data, 0U);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer);
glBufferStorage(GL_ELEMENT_ARRAY_BUFFER, num_indices * 4U, index_data, 0U);
glBindVertexBuffer(0U, vertex_buffer, 0U, 24U);
glEnableVertexAttribArray(0U);
glEnableVertexAttribArray(1U);
glVertexAttribFormat(0U, 3, GL_FLOAT, GL_FALSE, 0U);
glVertexAttribFormat(1U, 3, GL_FLOAT, GL_FALSE, 12U);
glVertexAttribBinding(0U, 0U);
glVertexAttribBinding(1U, 0U);
GL::throw_error();
}
}
void GLScene::draw(int framebuffer_width, int framebuffer_height) const
{
std::byte camera_uniform_data[Camera::uniform_buffer_size];
camera.writeUniformBuffer(camera_uniform_data, framebuffer_width * 1.0f / framebuffer_height);
glBindBufferBase(GL_UNIFORM_BUFFER, 0U, camera_uniform_buffer);
glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(camera_uniform_data), camera_uniform_data);
//glEnable(GL_CULL_FACE);
//glDisable(GL_CULL_FACE);
//glFrontFace(GL_CCW);
glClearColor(0.6f, 0.7f, 1.0f, 1.0f);
glClearDepth(1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDisable(GL_DEPTH_TEST);
glDepthMask(GL_FALSE);
glBindVertexArray(vao_env);
glUseProgram(prog_env);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, envmap);
//glBindSampler(0, envmap_sampler);
glUniform1i(0, 0);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 3);
GL::throw_error();
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glBindVertexArray(vao_model);
glUseProgram(prog_model);
glUniform1i(0, 0);
glDrawElements(GL_TRIANGLES, num_indices, GL_UNSIGNED_INT, nullptr);
GL::throw_error();
}
<file_sep>/src/particles/InputHandler.cpp
#include <string_view>
#include <iostream>
#include <utils/screenshot.h>
#include <utils/io/png.h>
#include "GLScene.h"
#include "GLRenderer.h"
#include "InputHandler.h"
using namespace std::literals;
InputHandler::InputHandler(OrbitalNavigator& navigator, GLRenderer& renderer, GLScene& scene)
: navigator(navigator), renderer(renderer), scene(scene)
{
std::cout << R"""(controls:
[space] pause
[right] advance by one frame
[page down] advance by 10 frames
[backspace] reset
[F2] toggle bounding box
[F8] take screenshot
)"""sv << std::flush;
}
void InputHandler::keyDown(GL::platform::Key key, GL::platform::Window*)
{
switch (key)
{
case GL::platform::Key::RIGHT:
renderer.step();
break;
case GL::platform::Key::PAGE_DOWN:
renderer.step(10);
break;
case GL::platform::Key::SPACE:
renderer.toggle_freeze();
break;
case GL::platform::Key::BACKSPACE:
renderer.reset();
break;
case GL::platform::Key::F1:
renderer.toggle_fps();
break;
case GL::platform::Key::F2:
scene.toggle_bounding_box();
break;
case GL::platform::Key::F8:
PNG::saveImageR8G8B8A8(open_screenshot_file("Particles.png"), renderer.screenshot());
break;
default:
break;
}
}
void InputHandler::keyUp(GL::platform::Key, GL::platform::Window*)
{
}
void InputHandler::buttonDown(GL::platform::Button button, int x, int y, GL::platform::Window* window)
{
navigator.buttonDown(button, x, y, window);
}
void InputHandler::buttonUp(GL::platform::Button button, int x, int y, GL::platform::Window* window)
{
navigator.buttonUp(button, x, y, window);
}
void InputHandler::mouseMove(int x, int y, GL::platform::Window* window)
{
navigator.mouseMove(x, y, window);
}
void InputHandler::mouseWheel(int d, GL::platform::Window* window)
{
navigator.mouseWheel(d, window);
}
<file_sep>/src/particles/particle_system_module.h
#ifndef INCLUDED_PARTICLE_SYSTEM_MODULE
#define INCLUDED_PARTICLE_SYSTEM_MODULE
#pragma once
#include <cstddef>
#include <cstdint>
extern "C"
{
struct ParticleSystemParameters
{
float bb_min[3];
float bb_max[3];
float min_particle_radius;
float max_particle_radius;
float gravity[3];
//float damping;
float bounce;
float coll_attraction;
float coll_damping;
float coll_shear;
float coll_spring;
};
struct ParticleSystem;
using create_particles_func = ParticleSystem*(std::size_t num_particles, const float* x, const float* y, const float* z, const float* r, const std::uint32_t* color, const ParticleSystemParameters& params);
using reset_particles_func = void(ParticleSystem* particles, const float* x, const float* y, const float* z, const float* r, const std::uint32_t* color);
using update_particles_func = void(ParticleSystem* particles, float* position, std::uint32_t* color, float dt);
using destroy_particles_func = void(ParticleSystem* particles);
}
#endif // INCLUDED_PARTICLE_SYSTEM_MODULE
<file_sep>/src/particles/ParticleSystem.h
#ifndef INCLUDED_PARTICLE_SYSTEM
#define INCLUDED_PARTICLE_SYSTEM
#pragma once
#include <cuda_runtime_api.h>
#include "particle_system_module.h"
class ParticleSystem
{
const std::size_t num_particles;
const ParticleSystemParameters params;
float* pos;
float3* prev_pos;
std::uint32_t* c;
uint2* grid_hash_index;
int* cell_begin_idx;
int* cell_end_idx;
unsigned int sim_steps = 0;
public:
ParticleSystem(std::size_t num_particles, const float* x, const float* y, const float* z, const float* r, const std::uint32_t* color, const ParticleSystemParameters& params);
void reset(const float* x, const float* y, const float* z, const float* r, const std::uint32_t* color);
void update(float* position, std::uint32_t* color, float dt);
};
#endif // INCLUDED_PARTICLE_SIMULATION
<file_sep>/src/hdr_pipeline/HDRDemo.h
#ifndef INCLUDED_HDRDEMO
#define INCLUDED_HDRDEMO
#pragma once
#include <cstdint>
#include <vector>
#include <filesystem>
#include <utils/io/obj.h>
class HDRDemo : private virtual OBJ::MeshSink
{
math::float3 bb_min = { 1.0f, 1.0f, 1.0f };
math::float3 bb_max = { -1.0f, -1.0f, -1.0f };
std::vector<float> vertices;
std::vector<std::uint32_t> indices;
int add_vertex(const math::float3& position, const math::float3& normal) override;
void add_triangle(int v_1, int v_2, int v_3) override;
void run(const std::filesystem::path& output_file, const std::filesystem::path& envmap, float exposure, float brightpass_threshold, int test_runs);
public:
void add_model(const std::filesystem::path& path);
void run(const std::filesystem::path& output_file, const std::filesystem::path& envmap, int cuda_device, float exposure_value, float brightpass_threshold, int test_runs);
};
#endif // INCLUDED_HDRDEMO
<file_sep>/src/particles/GLBoundingBox.h
#ifndef INCLUDED_GL_BOUNDING_BOX
#define INCLUDED_GL_BOUNDING_BOX
#pragma once
#include <GL/gl.h>
#include <GL/shader.h>
#include <GL/vertex_array.h>
#include <GL/buffer.h>
#include <utils/math/vector.h>
class GLBoundingBox
{
GL::VertexArray vao;
GL::Program prog;
GL::Buffer index_buffer;
public:
GLBoundingBox(const math::float3& bb_min, const math::float3& bb_max);
void draw() const;
};
#endif // INCLUDED_GL_BOUNDING_BOX
<file_sep>/src/particles/particle_system_state.cpp
#include <cstdint>
#include <stdexcept>
#include <memory>
#include <fstream>
#include <string_view>
#include <iostream>
#include <zlib.h>
#include <utils/io/compression.h>
#include <utils/io.h>
#include "particle_system_state.h"
using namespace std::literals;
namespace
{
template <typename T>
auto alloc_buffer(std::size_t num_particles)
{
return std::unique_ptr<T[]>(new T[num_particles]);
}
std::ostream& write_header(std::ostream& file, std::size_t num_particles, bool is_replay)
{
if (!write<std::int64_t>(file, is_replay ? -static_cast<std::int64_t>(num_particles) : static_cast<std::int64_t>(num_particles)))
throw std::runtime_error("failed to write particles file header");
return file;
}
auto read_header(std::istream& file)
{
auto num_particles = read<std::int64_t>(file);
if (!file)
throw std::runtime_error("failed to read particles file header");
struct header_info
{
std::size_t num_particles;
bool is_replay;
};
return header_info { static_cast<std::size_t>(num_particles < 0 ? -num_particles : num_particles), num_particles < 0 };
}
void write(std::ostream& file, zlib_writer& writer, const ParticleSystemParameters& params)
{
writer(file, params.bb_min);
writer(file, params.bb_max);
writer(file, params.min_particle_radius);
writer(file, params.max_particle_radius);
writer(file, params.gravity);
writer(file, params.bounce);
writer(file, params.coll_attraction);
writer(file, params.coll_damping);
writer(file, params.coll_shear);
writer(file, params.coll_spring);
}
void read(ParticleSystemParameters& params, zlib_reader& reader, std::istream& file)
{
reader(params.bb_min, file);
reader(params.bb_max, file);
reader(params.min_particle_radius, file);
reader(params.max_particle_radius, file);
reader(params.gravity, file);
reader(params.bounce, file);
reader(params.coll_attraction, file);
reader(params.coll_damping, file);
reader(params.coll_shear, file);
reader(params.coll_spring, file);
}
void write_initial_particle_state(std::ostream& file, zlib_writer& writer, std::size_t num_particles, const float* x, const float* y, const float* z, const float* r, const std::uint32_t* color, const ParticleSystemParameters& params)
{
writer(file, params);
writer(file, &x[0], num_particles);
writer(file, &y[0], num_particles);
writer(file, &z[0], num_particles);
writer(file, &r[0], num_particles);
writer(file, &color[0], num_particles);
}
void read_initial_particle_state(zlib_reader& reader, std::size_t num_particles, float* x, float* y, float* z, float* r, std::uint32_t* color, ParticleSystemParameters& params, std::istream& file)
{
reader(params, file);
reader(&x[0], num_particles, file);
reader(&y[0], num_particles, file);
reader(&z[0], num_particles, file);
reader(&r[0], num_particles, file);
reader(&color[0], num_particles, file);
}
void write_frame_data(std::ostream& file, zlib_writer& writer, std::size_t num_particles, std::chrono::nanoseconds dt, const float* positions, const std::uint32_t* colors)
{
writer(file, static_cast<std::int64_t>(dt.count()));
writer(file, positions, num_particles * 4);
writer(file, colors, num_particles);
}
zlib_reader& read_frame_data(zlib_reader& reader, std::size_t num_particles, std::chrono::nanoseconds& dt, float* positions, std::uint32_t* colors, std::istream& file)
{
dt = std::chrono::nanoseconds(reader.read<std::int64_t>(file));
reader(positions, num_particles * 4, file);
reader(colors, num_particles, file);
return reader;
}
}
std::ostream& save_particle_state(std::ostream& file, std::size_t num_particles, const float* x, const float* y, const float* z, const float* r, const std::uint32_t* color, const ParticleSystemParameters& params)
{
write_header(file, num_particles, false);
zlib_writer writer;
write_initial_particle_state(file, writer, num_particles, x, y, z, r, color, params);
return writer.finish(file);
}
ParticleReplayWriter::ParticleReplayWriter(std::ostream& file, std::size_t num_particles, const float* x, const float* y, const float* z, const float* r, const std::uint32_t* color, const ParticleSystemParameters& params)
: num_particles(num_particles)
{
write_header(file, num_particles, true);
write_initial_particle_state(file, writer, num_particles, x, y, z, r, color, params);
}
void ParticleReplayWriter::add_frame(std::ostream& file, std::chrono::nanoseconds dt, const float* positions, const std::uint32_t* colors)
{
write_frame_data(file, writer, num_particles, dt, positions, colors);
}
std::ostream& ParticleReplayWriter::finish(std::ostream& file)
{
return writer.finish(file);
}
std::istream& load_particles(ParticleSystemBuilder& builder, std::istream& file)
{
auto [num_particles, is_replay] = read_header(file);
zlib_reader reader;
ParticleSystemParameters params;
auto position = alloc_buffer<float>(num_particles * 4);
auto color = alloc_buffer<std::uint32_t>(num_particles);
read_initial_particle_state(reader, num_particles, &position[0] + 0 * num_particles, &position[0] + 1 * num_particles, &position[0] + 2 * num_particles, &position[0] + 3 * num_particles, &color[0], params, file);
if (is_replay)
{
auto& replay_builder = builder.add_particle_replay(num_particles, &position[0], &color[0], params);
while (reader)
{
std::chrono::nanoseconds dt;
read_frame_data(reader, num_particles, dt, &position[0], &color[0], file);
replay_builder.add_frame(dt, &position[0], &color[0]);
}
}
else
{
builder.add_particle_simulation(num_particles, std::move(position), std::move(color), params);
}
return file;
}
void save_particle_state(const std::filesystem::path& filename, std::size_t num_particles, const float* x, const float* y, const float* z, const float* r, const std::uint32_t* colors, const ParticleSystemParameters& params)
{
std::ofstream file(filename, std::ios::binary);
if (!file)
throw std::runtime_error("failed to open '" + filename.string() + '\'');
save_particle_state(file, num_particles, x, y, z, r, colors, params);
}
void load_particles(ParticleSystemBuilder& builder, const std::filesystem::path& filename)
{
std::ifstream file(filename, std::ios::binary);
if (!file)
throw std::runtime_error("failed to open '" + filename.string() + '\'');
load_particles(builder, file);
}
<file_sep>/src/particles/GLParticlePipeline.h
#ifndef INCLUDED_GL_PARTICLE_PIPELINE
#define INCLUDED_GL_PARTICLE_PIPELINE
#pragma once
#include <GL/gl.h>
#include <GL/shader.h>
class GLParticlePipeline
{
GL::Program particle_prog;
public:
GLParticlePipeline();
void draw(GLsizei offset, GLsizei num_particles, GLuint vao) const;
};
#endif // INCLUDED_GL_PARTICLE_PIPELINE
<file_sep>/src/particles/CMakeLists.txt
cmake_minimum_required(VERSION 3.18)
if (CUDAToolkit_FOUND)
project(particles CXX CUDA)
else ()
project(particles CXX)
endif ()
set(SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
add_library(particle_system_state
"${SOURCE_DIR}/particle_system_state.h"
"${SOURCE_DIR}/particle_system_state.cpp"
)
configure_project(particle_system_state)
target_include_directories(particle_system_state PUBLIC "${SOURCE_DIR}")
target_link_libraries(particle_system_state PUBLIC utils)
if (CUDAToolkit_FOUND)
add_library(particle_system SHARED
"${SOURCE_DIR}/particles.cu"
"${SOURCE_DIR}/ParticleSystem.h"
"${SOURCE_DIR}/ParticleSystem.cpp"
"${SOURCE_DIR}/particle_system_module.h"
"${SOURCE_DIR}/particle_system_module.cpp"
)
configure_project(particle_system)
target_link_libraries(particle_system PRIVATE CUDA_utils)
set_target_properties(particle_system PROPERTIES PREFIX "")
endif ()
add_executable(particles
"${SOURCE_DIR}/ParticleSystemLoader.h"
"${SOURCE_DIR}/ParticleDemo.h"
"${SOURCE_DIR}/main.cpp"
)
if (INTERACTIVE)
target_sources(particles PRIVATE
"${SOURCE_DIR}/GLSL/particle.vs.glsl"
"${SOURCE_DIR}/GLSL/particle.gs.glsl"
"${SOURCE_DIR}/GLSL/particle.fs.glsl"
"${SOURCE_DIR}/GLSL/bounding_box.vs.glsl"
"${SOURCE_DIR}/GLSL/bounding_box.fs.glsl"
"${SOURCE_DIR}/InputHandler.h"
"${SOURCE_DIR}/InputHandler.cpp"
"${SOURCE_DIR}/GLParticlePipeline.h"
"${SOURCE_DIR}/GLParticlePipeline.cpp"
"${SOURCE_DIR}/GLBoundingBox.h"
"${SOURCE_DIR}/GLBoundingBox.cpp"
"${SOURCE_DIR}/GLScene.h"
"${SOURCE_DIR}/GLScene.cpp"
"${SOURCE_DIR}/GLParticleReplay.h"
"${SOURCE_DIR}/GLParticleReplay.cpp"
"${SOURCE_DIR}/GLRenderer.h"
"${SOURCE_DIR}/GLRenderer.cpp"
"${SOURCE_DIR}/GLParticleDemo.h"
"${SOURCE_DIR}/GLParticleDemo.cpp"
)
endif ()
if (CUDAToolkit_FOUND)
if (INTERACTIVE)
target_sources(particles PRIVATE
"${SOURCE_DIR}/GLCUDAParticles.h"
"${SOURCE_DIR}/GLCUDAParticles.cpp"
"${SOURCE_DIR}/GLCUDAParticleDemo.cpp"
)
else ()
target_sources(particles PRIVATE
"${SOURCE_DIR}/CUDAParticles.h"
"${SOURCE_DIR}/CUDAParticles.cpp"
"${SOURCE_DIR}/NoGLCUDAParticleDemo.cpp"
)
endif ()
target_link_libraries(particles CUDA_utils)
add_dependencies(particles particle_system)
else ()
if (INTERACTIVE)
target_sources(particles PRIVATE
"${SOURCE_DIR}/GLNoCUDAParticleDemo.cpp"
)
else ()
message(FATAL_ERROR "cannot build particles in neither interactive mode nor with CUDA")
endif ()
endif ()
configure_project(particles)
target_link_libraries(particles particle_system_state utils)
if (INTERACTIVE)
target_link_libraries(particles_shaders GLSL_utils)
endif ()
<file_sep>/src/particles/ParticleSystem.cpp
#include "ParticleSystem.h"
#include <iostream>
#include <math.h>
ParticleSystem::ParticleSystem(std::size_t num_particles, const float* x, const float* y, const float* z, const float* r, const std::uint32_t* color, const ParticleSystemParameters& params)
: num_particles(num_particles)
, params(params)
{
void* p1; void* p2; void* p3;
void* g1;
void* f1; void* f2;
cudaMalloc(&p1, num_particles * sizeof(float3));
cudaMalloc(&p2, num_particles * 4 * sizeof(float));
cudaMalloc(&p3, num_particles * sizeof(std::uint32_t));
cudaMalloc(&g1, num_particles * sizeof(uint2));
int resolution = powf((params.bb_max[0] - params.bb_min[0]) / (params.max_particle_radius * 2),3); // side x side x side
cudaMalloc(&f1, resolution * sizeof(int));
cudaMalloc(&f2, resolution * sizeof(int));
prev_pos = static_cast<float3*>(p1);
pos = static_cast<float*>(p2);
c = static_cast<uint32_t*>(p3);
grid_hash_index = static_cast<uint2*>(g1);
cell_begin_idx = static_cast<int*>(f1);
cell_end_idx = static_cast<int*>(f2);
reset(x, y, z, r, color);
}
void update_particles(float* position, float3* prev_pos, float dt, uint2* grid_hash_index, int* cell_begin_idx, int* cell_end_idx,
ParticleSystemParameters params, std::size_t num_particles);
void init_particles(float* position, std::uint32_t* color, float3* prev_pos, float* pos, std::uint32_t* clr, ParticleSystemParameters params,
std::size_t num_particles);
void ParticleSystem::reset(const float* x, const float* y, const float* z, const float* r, const std::uint32_t* color)
{
sim_steps = 0;
cudaMemcpy(pos + 0 * num_particles, x, num_particles * sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(pos + 1 * num_particles, y, num_particles * sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(pos + 2 * num_particles, z, num_particles * sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(pos + 3 * num_particles, r, num_particles * sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(c, color, num_particles * sizeof(std::uint32_t), cudaMemcpyHostToDevice);
}
void ParticleSystem::update(float* position, std::uint32_t* color, float dt)
{
if (sim_steps == 0) {
init_particles(position, color, prev_pos, pos, c, params, num_particles);
}
update_particles(position, prev_pos, dt, grid_hash_index, cell_begin_idx, cell_end_idx, params, num_particles);
cudaFree(grid_hash_index);
sim_steps++;
}
<file_sep>/src/hdr_pipeline/main.cpp
#include <exception>
#include <iostream>
#include <iomanip>
#include <filesystem>
#include <utils/argparse.h>
#include "HDRDemo.h"
using namespace std::literals;
namespace
{
std::ostream& print_usage(std::ostream& out)
{
return out << R"""(usage: hdr_pipeline [{options}] {<input-file>}
options:
--device <i> use CUDA device <i>, default: 0
--exposure <v> set exposure value to <v>, default: 0.0
--brightpass <v> set brightpass threshold to <v>, default: 0.9
--test-runs <N> average timings over <N> test runs, default: 1
)""";
}
}
int main(int argc, char* argv[])
{
try
{
HDRDemo demo;
std::filesystem::path envmap;
int cuda_device = 0;
float exposure_value = 0.0f;
float brightpass_threshold = 0.9f;
int test_runs = 1;
for (const char* const* a = argv + 1; *a; ++a)
{
if (!argparse::parseIntArgument(cuda_device, a, "--device"sv))
if (!argparse::parseFloatArgument(exposure_value, a, "--exposure"sv))
if (!argparse::parseFloatArgument(brightpass_threshold, a, "--brightpass"sv))
if (!argparse::parseIntArgument(test_runs, a, "--test-runs"))
{
std::filesystem::path input_file = *a;
auto ext = input_file.extension();
if (ext == ".hdr"sv || ext == ".pfm"sv)
envmap = std::move(input_file);
else
demo.add_model(input_file);
}
}
if (envmap.empty())
throw argparse::usage_error("expected input file");
if (test_runs < 0)
throw argparse::usage_error("number of test runs cannot be negative");
demo.run(envmap.filename().replace_extension(".png"), envmap, cuda_device, exposure_value, brightpass_threshold, test_runs);
}
catch (const argparse::usage_error& e)
{
std::cerr << "ERROR: " << e.what() << '\n' << print_usage;
return -127;
}
catch (const std::exception& e)
{
std::cerr << "ERROR: " << e.what() << '\n';
return -1;
}
catch (...)
{
std::cerr << "ERROR: unknown exception\n";
return -128;
}
return 0;
}
<file_sep>/src/particles/GLCUDAParticleDemo.cpp
#include <utility>
#include <stdexcept>
#include <variant>
#include <vector>
#include <iostream>
#include <utils/CUDA/error.h>
#include <utils/CUDA/device.h>
#include "particle_system_state.h"
#include "ParticleSystemLoader.h"
#include "GLCUDAParticles.h"
#include "GLParticleReplay.h"
#include "GLParticleDemo.h"
std::tuple<std::unique_ptr<GLScene>, math::float3, math::float3> load_scene(const std::filesystem::path& path, int cuda_device)
{
CUDA::print_device_properties(std::cout, cuda_device) << '\n' << '\n' << std::flush;
throw_error(cudaSetDevice(cuda_device));
class SceneBuilder : private virtual ParticleSystemBuilder
{
struct simulation_data
{
std::size_t num_particles;
std::unique_ptr<float[]> position;
std::unique_ptr<std::uint32_t[]> color;
ParticleSystemParameters params;
};
std::variant<simulation_data, GLParticleReplayBuilder> data;
void add_particle_simulation(std::size_t num_particles, std::unique_ptr<float[]> position, std::unique_ptr<std::uint32_t[]> color, const ParticleSystemParameters& params) override
{
data.emplace<simulation_data>(simulation_data { num_particles, std::move(position), std::move(color), params });
}
ParticleReplayBuilder& add_particle_replay(std::size_t num_particles, const float* position, const std::uint32_t* color, const ParticleSystemParameters& params) override
{
return data.emplace<GLParticleReplayBuilder>(num_particles, position, color, params);
}
public:
auto load(const std::filesystem::path& path)
{
load_particles(*this, path);
struct ParticleSystemFactory
{
std::tuple<std::unique_ptr<GLScene>, math::float3, math::float3> operator ()(simulation_data& data)
{
static auto module = particle_system_module("particle_system");
math::float3 bb_min = { data.params.bb_min[0], data.params.bb_min[1], data.params.bb_min[2] };
math::float3 bb_max = { data.params.bb_max[0], data.params.bb_max[1], data.params.bb_max[2] };
auto particles = module.create_instance(data.num_particles, &data.position[0] + 0 * data.num_particles, &data.position[0] + 1 * data.num_particles, &data.position[0] + 2 * data.num_particles, &data.position[0] + 3 * data.num_particles, &data.color[0], data.params);
return {
std::make_unique<GLCUDAParticles>(std::move(particles), data.num_particles, std::move(data.position), std::move(data.color), bb_min, bb_max),
bb_min,
bb_max
};
}
auto operator ()(GLParticleReplayBuilder& builder)
{
return builder.finish();
}
};
return std::visit(ParticleSystemFactory(), data);
}
};
SceneBuilder scene_builder;
return scene_builder.load(path);
}
<file_sep>/src/particles/particle_system_state.h
#ifndef INCLUDED_PARTICLE_SYSTEM_STATE
#define INCLUDED_PARTICLE_SYSTEM_STATE
#pragma once
#include <cstddef>
#include <cstdint>
#include <memory>
#include <chrono>
#include <iosfwd>
#include <filesystem>
#include <utils/io/compression.h>
#include "particle_system_module.h"
struct ParticleReplayBuilder
{
virtual void add_frame(std::chrono::nanoseconds dt, const float* positions, const std::uint32_t* colors) = 0;
protected:
ParticleReplayBuilder() = default;
ParticleReplayBuilder(const ParticleReplayBuilder&) = default;
ParticleReplayBuilder(ParticleReplayBuilder&&) = default;
ParticleReplayBuilder& operator =(const ParticleReplayBuilder&) = default;
ParticleReplayBuilder& operator =(ParticleReplayBuilder&&) = default;
~ParticleReplayBuilder() = default;
};
struct ParticleSystemBuilder
{
virtual void add_particle_simulation(std::size_t num_particles, std::unique_ptr<float[]> position, std::unique_ptr<std::uint32_t[]> color, const ParticleSystemParameters& params) = 0;
virtual ParticleReplayBuilder& add_particle_replay(std::size_t num_particles, const float* position, const std::uint32_t* color, const ParticleSystemParameters& params) = 0;
protected:
ParticleSystemBuilder() = default;
ParticleSystemBuilder(const ParticleSystemBuilder&) = default;
ParticleSystemBuilder(ParticleSystemBuilder&&) = default;
ParticleSystemBuilder& operator =(const ParticleSystemBuilder&) = default;
ParticleSystemBuilder& operator =(ParticleSystemBuilder&&) = default;
~ParticleSystemBuilder() = default;
};
class ParticleReplayWriter
{
zlib_writer writer;
std::size_t num_particles;
public:
ParticleReplayWriter(std::ostream& file, std::size_t num_particles, const float* x, const float* y, const float* z, const float* r, const std::uint32_t* color, const ParticleSystemParameters& params);
void add_frame(std::ostream& file, std::chrono::nanoseconds dt, const float* positions, const std::uint32_t* colors);
std::ostream& finish(std::ostream& file);
};
std::ostream& save_particle_state(std::ostream& file, std::size_t num_particles, const float* x, const float* y, const float* z, const float* r, const std::uint32_t* color, const ParticleSystemParameters& params);
void save_particle_state(const std::filesystem::path& filename, std::size_t num_particles, const float* x, const float* y, const float* z, const float* r, const std::uint32_t* color, const ParticleSystemParameters& params);
std::istream& load_particles(ParticleSystemBuilder& builder, std::istream& file);
void load_particles(ParticleSystemBuilder& builder, const std::filesystem::path& filename);
#endif // INCLUDED_PARTICLE_SYSTEM_STATE
<file_sep>/src/hdr_pipeline/GLRenderer.h
#ifndef INCLUDED_GLRENDERER
#define INCLUDED_GLRENDERER
#pragma once
#include <cstdint>
#include <string>
#include <optional>
#include <chrono>
#include <GL/gl.h>
#include <GL/platform/Renderer.h>
#include <GL/platform/Context.h>
#include <GL/platform/Window.h>
#include <GL/platform/DefaultDisplayHandler.h>
#include <GL/shader.h>
#include <GL/texture.h>
#include <GL/framebuffer.h>
#include <GL/vertex_array.h>
#include <cuda_runtime_api.h>
#include <utils/CUDA/event.h>
#include <utils/CUDA/graphics_interop.h>
#include <utils/image.h>
#include "HDRPipeline.h"
class GLScene;
class GLRenderer : public virtual GL::platform::Renderer, private GL::platform::DefaultDisplayHandler
{
GL::platform::Window window;
GL::platform::Context context;
GL::platform::context_scope<GL::platform::Window> ctx;
const GLScene* scene = nullptr;
std::optional<HDRPipeline> pipeline;
int framebuffer_width;
int framebuffer_height;
GL::Texture hdr_buffer;
GL::Texture ldr_buffer;
GL::Renderbuffer depth_buffer;
GL::Framebuffer fbo;
GL::VertexArray vao;
GL::Program fullscreen_prog;
GL::Sampler sampler;
CUDA::graphics::unique_resource hdr_buffer_resource;
CUDA::graphics::unique_resource ldr_buffer_resource;
float exposure;
float brightpass_threshold;
long frame_count = 0;
std::string title;
std::chrono::steady_clock::time_point next_fps_tick = std::chrono::steady_clock::now();
float pipeline_time = 0.0f;
CUDA::unique_event pipeline_begin = CUDA::create_event();
CUDA::unique_event pipeline_end = CUDA::create_event();
void resize(int width, int height, GL::platform::Window*) override;
public:
GLRenderer(std::string title, int width, int height, float exposure, float brightpass_threshold);
image2D<std::uint32_t> screenshot() const;
void attach(GL::platform::MouseInputHandler* mouse_input);
void attach(GL::platform::KeyboardInputHandler* keyboard_input);
void attach(const GLScene* scene);
void render() override;
};
#endif // INCLUDED_GLRENDERER
<file_sep>/src/particles/GLCUDAParticles.h
#ifndef INCLUDED_GL_CUDA_PARTICLES
#define INCLUDED_GL_CUDA_PARTICLES
#pragma once
#include <cstddef>
#include <cstdint>
#include <GL/gl.h>
#include <GL/shader.h>
#include <GL/vertex_array.h>
#include <GL/buffer.h>
#include <cuda_runtime_api.h>
#include <utils/CUDA/event.h>
#include <utils/CUDA/graphics_interop.h>
#include <utils/dynamic_library.h>
#include "GLScene.h"
#include "particle_system_module.h"
#include "ParticleSystemLoader.h"
#include "GLParticlePipeline.h"
#include "GLBoundingBox.h"
class GLCUDAParticles : public virtual GLScene
{
particle_system_instance particles;
GLsizei num_particles;
GLParticlePipeline pipeline;
GL::VertexArray particles_vao;
GLBoundingBox bounding_box;
GL::Buffer particle_position_buffer;
GL::Buffer particle_color_buffer;
CUDA::graphics::unique_resource particle_position_buffer_resource;
CUDA::graphics::unique_resource particle_color_buffer_resource;
CUDA::unique_event particles_begin;
CUDA::unique_event particles_end;
std::unique_ptr<float[]> initial_position;
std::unique_ptr<std::uint32_t[]> initial_color;
public:
GLCUDAParticles(particle_system_instance particles, std::size_t num_particles, std::unique_ptr<float[]> position, std::unique_ptr<std::uint32_t[]> color, const math::float3& bb_min, const math::float3& bb_max);
void reset() override;
float update(int steps, float dt) override;
void draw(bool draw_bounding_box) const override;
};
#endif // INCLUDED_GL_CUDA_PARTICLES
<file_sep>/README.md
# Interacting Particles Simulation
In this document we will briefly describe the implementation of physical based particle collision system using a uniform grid structure. The main idea of uniform grid-based simulation for implementation for the project have been derived from the NVIDA white paper by <NAME> [3]. The code in the repository contains our implementation of the same.
## Introduction
There are three main stages involved in the particle simulation.
1. Particles setup
2. Constructing a uniform grid structure
3. Collision of large number of particles
These implementations are found in : [ParticleSystem.h](src/particles/ParticleSystem.h) , [ParticleSystem.cpp](src/particles/ParticleSystem.cpp) and [particles.cu](src/particles/particles.cu)
The initial simulation involved containing the particles within a bounding box. At each position, the particle behaviour is described by Verlet integration version of Newtons equation of motions. Followed by inter-particles collision simulation by considering various types of forces acting on the particles during collisions.
As a naïve collision algorithm of checking each particle with each other is not feasible option, we use a uniform spatial grid structure following by a simple position-based linear hashing to check for collisions. This algorithm is much faster than the naïve collision approach and is its implementation is within the code provided.
In the following sections, we first explain the uniform grid structure creation to facilitate localising the particles withing the gird. Next, we explain the hashing-based collision search algorithm to simulate particle collisions.
## Uniform Grid Structure
In this project, we follow uniform grid structure[1], we divide the entire space of the bounding box into a grid cells of equal size. Each particle could then be associated with a gird cell on which it overlaps. As a direct benefit of this, the collision check between particles is much simpler task, given a specific cell, neighbouring cells are trivially located and the particles in those cells are checked for collision.
We use the two times the parameter `max_particle_radius` to set the grid cell resolution, we consider this parameter as the upper bound to the particle size. With a realistic assumption of no interparticle penetration and the particles can overlap with multiple grid cells, we resolve collisions within a cell by processing 27 neighbouring cells with pair wise tests. In our current implementation, the grid structure is generated from scratch at every time step and the performance is constant regardless of the particle position in the bounding box.
In the next section we detail out the hashing-based grid structure generation and how we utilize it to perform collisions.
## Hashed Storage and Collisions
With a goal to use a dense array to store the entire gird structure, we map each grid cell into a hash table. We use a simple position-based linear hashing to wrap the particle coordinates into a hash table. In our implementation, the kernel `calculate_hash_kernel` calculates a hash value for each particle based on its bounding box coordinates. The result is stored in the global memory as `grid_hash_index` an `uint2` pair array (cell hash, particle id).
As the hash values are directly related to the position of the particles, we can determine the particles in the same grid cell and the neighbouring grid cells based on the hash values. Find the candidates for collision examination, we devise a two-step process:
1. First, we sort the hash values of the particles using the Thrust library’s sorting method, a fast, efficient radix sorting method for CUDA-capable devices [2]. This provides us an array of particle ids ordered by grid cell positions.
2. Next, we pass this array to the kernel `find_cell_start_kernel` to find the beginning particle index for given grid cell. The kernel compares the hash values of the current particle and previous particle from the sorted list. In those instances where the hash values do not match, indicates that the particle is in a different cell. We write this index value as the starting position for the new particle into the array `cell_start_idx` and ending position for the previous particle into the array `cell_end_idx`. In this manner we generate a starting and beginning position for all the cells.

The figure above shows the unifrom grid creation and assignment of cell starting indices on 4x4 grid world. Source:[3]
Finally, we utilize, the beginning and ending indices for each grid cells and the hash values of each particles to determine the forces acting on the particle. Based on the grid cell in which a particle is located, the method `calculate_acceleration` loops over 27 grid cells and checks for collisions for all the particles in those grid cells. If a collision is detected then, we update the particles position based on equations (1) – (9) [4].
## Conclusion
We want to bring it the notice to the evaluators of the project that this implementation could not be listed in the performance leader board as the implementation could not pass the benchmark evaluations. We suspect this could be due to mismatch in the CUDA compute capability mismatch. Unfortunately due to time constraints we could not fix the issues to make a successful submission.
In order to show the working of our implementation, we demonstrate the particle simulation on NVIDIA GTX 960 GPU (compute capability 3.0) and share the recording. The video can be found in the location: `assets\report\demo.mkv`

The gif above is a short clip of our final particles simulation. And longer version is available at https://www.youtube.com/embed/2dWDSQVpvF8
### References
[1] <NAME>., Real-Time Collision Detection, <NAME> 2005
[2] https://docs.nvidia.com/cuda/thrust/index.html#sorting
[3] <NAME>. 2010. Particle simulation using cuda. NVIDIA Whitepaper 6 (2010), 121–128.
[4] Assignment 4b, GPU Programming Course, Winter Semester 2020, Saarland University.
<file_sep>/src/hdr_pipeline/run_noninteractive.cpp
#include <cstdint>
#include <cmath>
#include <iostream>
#include <iomanip>
#include <cuda_runtime_api.h>
#include <utils/image.h>
#include <utils/io/png.h>
#include <utils/math/vector.h>
#include <utils/CUDA/error.h>
#include <utils/CUDA/memory.h>
#include <utils/CUDA/array.h>
#include <utils/CUDA/event.h>
#include "envmap.h"
#include "HDRPipeline.h"
#include "HDRDemo.h"
namespace
{
std::ostream& pad(std::ostream& out, int n)
{
for (int i = n; i > 0; --i) out.put(' ');
return out;
}
}
void HDRDemo::run(const std::filesystem::path& output_file, const std::filesystem::path& envmap_path, float exposure, float brightpass_threshold, int test_runs)
{
if (!vertices.empty() || !indices.empty())
std::cerr << "\nWARNING: scene geometry ignored in noninteractive mode\n";
std::cout << "\nreading " << envmap_path << '\n' << std::flush;
auto envmap = load_envmap(envmap_path, false);
int image_width = static_cast<int>(width(envmap));
int image_height = static_cast<int>(height(envmap));
auto hdr_frame = CUDA::create_array(width(envmap), height(envmap), { 32, 32, 32, 32, cudaChannelFormatKindFloat });
auto ldr_frame = CUDA::create_array(width(envmap), height(envmap), { 8, 8, 8, 8, cudaChannelFormatKindUnsigned });
throw_error(cudaMemcpy2DToArray(hdr_frame.get(), 0, 0, data(envmap), image_width * 16U, image_width * 16U, image_height, cudaMemcpyHostToDevice));
HDRPipeline pipeline(image_width, image_height);
auto pipeline_begin = CUDA::create_event();
auto pipeline_end = CUDA::create_event();
float pipeline_time = 0.0f;
std::cout << '\n' << test_runs << " test run(s):\n";
int padding = static_cast<int>(std::log10(test_runs));
int next_padding_shift = 10;
for (int i = 0; i < test_runs; ++i)
{
throw_error(cudaEventRecord(pipeline_begin.get()));
pipeline.process(ldr_frame.get(), hdr_frame.get(), exposure, brightpass_threshold);
throw_error(cudaEventRecord(pipeline_end.get()));
throw_error(cudaEventSynchronize(pipeline_end.get()));
auto t = CUDA::elapsed_time(pipeline_begin.get(), pipeline_end.get());
if ((i + 1) >= next_padding_shift)
{
--padding;
next_padding_shift *= 10;
}
pad(std::cout, padding) << "t_" << (i + 1) << ": " << std::setprecision(2) << std::fixed << t << " ms\n" << std::flush;
pipeline_time += t;
}
std::cout << "avg time: " << std::setprecision(2) << std::fixed << pipeline_time / test_runs << " ms\n" << std::flush;
image2D<std::uint32_t> output(image_width, image_height);
throw_error(cudaMemcpy2DFromArray(data(output), width(output) * 4U, ldr_frame.get(), 0, 0, image_width * 4U, image_height, cudaMemcpyDeviceToHost));
std::cout << "\nsaving " << output_file << '\n' << std::flush;
PNG::saveImageR8G8B8(output_file.string().c_str(), output);
}
<file_sep>/src/hdr_pipeline/CMakeLists.txt
cmake_minimum_required(VERSION 3.18)
if (CUDAToolkit_FOUND)
project(hdr_pipeline CXX CUDA)
set(SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
add_executable(hdr_pipeline
"${SOURCE_DIR}/envmap.cpp"
"${SOURCE_DIR}/envmap.h"
"${SOURCE_DIR}/HDRPipeline.h"
"${SOURCE_DIR}/HDRPipeline.cpp"
"${SOURCE_DIR}/hdr_pipeline.cu"
"${SOURCE_DIR}/HDRDemo.h"
"${SOURCE_DIR}/HDRDemo.cpp"
"${SOURCE_DIR}/main.cpp"
)
if (INTERACTIVE)
target_sources(hdr_pipeline PRIVATE
"${SOURCE_DIR}/GLSL/envmap"
"${SOURCE_DIR}/GLSL/fullscreen_triangle.vs.glsl"
"${SOURCE_DIR}/GLSL/fullscreen_triangle.fs.glsl"
"${SOURCE_DIR}/GLSL/env.vs.glsl"
"${SOURCE_DIR}/GLSL/env.fs.glsl"
"${SOURCE_DIR}/GLSL/model.vs.glsl"
"${SOURCE_DIR}/GLSL/model.fs.glsl"
"${SOURCE_DIR}/InputHandler.h"
"${SOURCE_DIR}/InputHandler.cpp"
"${SOURCE_DIR}/GLRenderer.h"
"${SOURCE_DIR}/GLRenderer.cpp"
"${SOURCE_DIR}/GLScene.h"
"${SOURCE_DIR}/GLScene.cpp"
"${SOURCE_DIR}/run_interactive.cpp"
)
else ()
target_sources(hdr_pipeline PRIVATE
"${SOURCE_DIR}/run_noninteractive.cpp"
)
endif ()
configure_project(hdr_pipeline)
if (INTERACTIVE)
target_link_libraries(hdr_pipeline_shaders GLSL_utils)
endif ()
target_link_libraries(hdr_pipeline utils CUDA_utils)
endif ()
<file_sep>/src/particles/CUDAParticles.h
#ifndef INCLUDED_CUDA_PARTICLES
#define INCLUDED_CUDA_PARTICLES
#pragma once
#include <cstddef>
#include <cstdint>
#include <memory>
#include <iosfwd>
#include <cuda_runtime_api.h>
#include <utils/CUDA/memory.h>
#include <utils/CUDA/event.h>
#include "particle_system_module.h"
#include "ParticleSystemLoader.h"
class ParticleReplayWriter;
class CUDAParticles
{
particle_system_instance particles;
std::size_t num_particles;
CUDA::unique_ptr<float> position_buffer;
CUDA::unique_ptr<std::uint32_t> color_buffer;
CUDA::unique_event particles_begin;
CUDA::unique_event particles_end;
std::unique_ptr<float[]> position_download_buffer;
std::unique_ptr<std::uint32_t[]> color_download_buffer;
public:
CUDAParticles(particle_system_module& module, std::size_t num_particles, std::unique_ptr<float[]> position, std::unique_ptr<std::uint32_t[]> color, const ParticleSystemParameters& params);
float update(std::ostream& file, ParticleReplayWriter& writer, int steps, float dt);
};
#endif // INCLUDED_CUDA_PARTICLES
<file_sep>/src/particles/NoGLCUDAParticleDemo.cpp
#include <utility>
#include <iostream>
#include <iomanip>
#include <filesystem>
#include <utils/dynamic_library.h>
#include <utils/CUDA/error.h>
#include <utils/CUDA/device.h>
#include <utils/math/vector.h>
#include "particle_system_state.h"
#include "ParticleSystemLoader.h"
#include "CUDAParticles.h"
#include "ParticleDemo.h"
namespace
{
auto load(std::ostream& output_file, const std::filesystem::path& path)
{
class SceneBuilder : private virtual ParticleSystemBuilder, private virtual ParticleReplayBuilder
{
std::size_t num_particles;
std::unique_ptr<float[]> position;
std::unique_ptr<std::uint32_t[]> color;
ParticleSystemParameters params;
void add_particle_simulation(std::size_t num_particles, std::unique_ptr<float[]> position, std::unique_ptr<std::uint32_t[]> color, const ParticleSystemParameters& params) override
{
this->num_particles = num_particles;
this->position = std::move(position);
this->color = std::move(color);
this->params = params;
}
ParticleReplayBuilder& add_particle_replay(std::size_t num_particles, const float* position, const std::uint32_t* color, const ParticleSystemParameters& params) override
{
throw std::runtime_error("particle replay not supported in non-interactive mode");
return *this;
}
void add_frame(std::chrono::nanoseconds dt, const float* positions, const std::uint32_t* colors) override
{
}
public:
auto load(std::ostream& output_file, const std::filesystem::path& path)
{
load_particles(*this, path);
if (!position)
throw std::runtime_error("file did not contain a particle system");
static auto module = particle_system_module("particle_system");
struct result_t { ParticleReplayWriter writer; CUDAParticles particles; };
return result_t {
ParticleReplayWriter(output_file, num_particles, &position[0] + 0 * num_particles, &position[0] + 1 * num_particles, &position[0] + 2 * num_particles, &position[0] + 3 * num_particles, &color[0], params),
CUDAParticles(module, num_particles, std::move(position), std::move(color), params)
};
}
};
SceneBuilder scene_builder;
return scene_builder.load(output_file, path);
}
std::ostream& pad(std::ostream& out, int n)
{
for (int i = n; i > 0; --i) out.put(' ');
return out;
}
}
void ParticleDemo::run(std::filesystem::path output_file, const std::filesystem::path& input_file, int N, int subsample, float dt, int cuda_device)
{
CUDA::print_device_properties(std::cout, cuda_device) << '\n' << '\n' << std::flush;
throw_error(cudaSetDevice(cuda_device));
if (output_file.empty())
output_file = std::filesystem::path(input_file).filename().replace_extension(".particlereplay");
{
std::ofstream out(output_file, std::ios::binary);
if (!out)
throw std::runtime_error("failed to open output file \"" + output_file.string() + '"');
auto [writer, particles] = load(out, input_file);
float particles_time = 0.0f;
std::cout << '\n' << N << " frame(s):\n";
int padding = static_cast<int>(std::log10(N));
int next_padding_shift = 10;
for (int i = 0; i < N; i += subsample)
{
auto t = particles.update(out, writer, subsample, dt) / subsample;
if ((i + 1) >= next_padding_shift)
{
--padding;
next_padding_shift *= 10;
}
pad(std::cout, padding) << "t_" << (i + 1) << ": " << std::setprecision(2) << std::fixed << t << " ms\n" << std::flush;
particles_time += t;
}
std::cout << "avg time: " << std::setprecision(2) << std::fixed << particles_time / N << " ms\n" << std::flush;
writer.finish(out);
}
}
<file_sep>/src/particles/CUDAParticles.cpp
#include <utils/dynamic_library.h>
#include <utils/CUDA/error.h>
#include "particle_system_state.h"
#include "CUDAParticles.h"
CUDAParticles::CUDAParticles(particle_system_module& module, std::size_t num_particles, std::unique_ptr<float[]> position, std::unique_ptr<std::uint32_t[]> color, const ParticleSystemParameters& params)
: particles(module.create_instance(num_particles, &position[0] + 0 * num_particles, &position[0] + 1 * num_particles, &position[0] + 2 * num_particles, &position[0] + 3 * num_particles, &color[0], params)),
num_particles(num_particles),
position_buffer(CUDA::malloc<float>(4 * num_particles)),
color_buffer(CUDA::malloc<std::uint32_t>(num_particles)),
particles_begin(CUDA::create_event()),
particles_end(CUDA::create_event()),
position_download_buffer(new float[ 4 * num_particles]),
color_download_buffer(new std::uint32_t[num_particles])
{
}
float CUDAParticles::update(std::ostream& file, ParticleReplayWriter& writer, int steps, float dt)
{
throw_error(cudaEventRecord(particles_begin.get()));
for (int i = 0; i < steps; ++i)
particles.update(position_buffer.get(), color_buffer.get(), dt);
throw_error(cudaEventRecord(particles_end.get()));
throw_error(cudaEventSynchronize(particles_end.get()));
throw_error(cudaMemcpy(position_download_buffer.get(), position_buffer.get(), 4 * num_particles * sizeof(float), cudaMemcpyDeviceToHost));
throw_error(cudaMemcpy(color_download_buffer.get(), color_buffer.get(), num_particles * sizeof(std::uint32_t), cudaMemcpyDeviceToHost));
writer.add_frame(file, steps * std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::duration<float>(dt)), position_download_buffer.get(), color_download_buffer.get());
return CUDA::elapsed_time(particles_begin.get(), particles_end.get());
}
<file_sep>/src/hdr_pipeline/HDRDemo.cpp
#include <limits>
#include <iostream>
#include <cuda_runtime_api.h>
#include <utils/CUDA/error.h>
#include <utils/CUDA/device.h>
#include "HDRDemo.h"
int HDRDemo::add_vertex(const math::float3& position, const math::float3& normal)
{
int i = static_cast<int>(size(vertices)) / 6;
vertices.push_back(position.x);
vertices.push_back(position.y);
vertices.push_back(position.z);
vertices.push_back(normal.x);
vertices.push_back(normal.y);
vertices.push_back(normal.z);
if (position.x < bb_min.x)
bb_min.x = position.x;
if (position.x > bb_max.x)
bb_max.x = position.x;
if (position.y < bb_min.y)
bb_min.y = position.y;
if (position.y > bb_max.y)
bb_max.y = position.y;
if (position.z < bb_min.z)
bb_min.z = position.z;
if (position.z > bb_max.z)
bb_max.z = position.z;
return i;
}
void HDRDemo::add_triangle(int v_1, int v_2, int v_3)
{
indices.push_back(v_1);
indices.push_back(v_2);
indices.push_back(v_3);
}
void HDRDemo::add_model(const std::filesystem::path& path)
{
std::cout << "reading " << path << '\n' << std::flush;
if (indices.empty())
{
bb_min = { std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max() };
bb_max = { -std::numeric_limits<float>::max(), -std::numeric_limits<float>::max(), -std::numeric_limits<float>::max() };
}
OBJ::readTriangles(*this, path);
std::cout << '\n';
}
void HDRDemo::run(const std::filesystem::path& output_file, const std::filesystem::path& envmap, int cuda_device, float exposure_value, float brightpass_threshold, int test_runs)
{
CUDA::print_device_properties(std::cout, cuda_device) << '\n' << std::flush;
throw_error(cudaSetDevice(cuda_device));
run(output_file, envmap, std::exp2(exposure_value), brightpass_threshold, test_runs);
}
<file_sep>/src/hdr_pipeline/envmap.h
#ifndef INCLUDED_ENVMAP
#define INCLUDED_ENVMAP
#pragma once
#include <filesystem>
#include <array>
#include <utils/image.h>
image2D<std::array<float, 4>> load_envmap(const std::filesystem::path& filename, bool flip = false);
#endif // INCLUDED_ENVMAP
| 4090cd933f20888b433b0493e5601aeee8c08832 | [
"Markdown",
"CMake",
"C++"
] | 45 | C++ | prraoo/particle-collision | 34c684cda50c497e90482b30adf12d361eae0960 | bbbbef118e35d77eff37c9c88d80cdf449d1df9c |
refs/heads/main | <file_sep># Import all necessary modules
import os
import cv2 # OpenCV
import pydicom # DICOM
import numpy as np
import shutil # File operations
import pathlib # File operations
import PIL # Images
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
# Change these variables as is necessary or convenient
# Training
dcm_dir = 'images_dcm/' # Input directory containing DICOM images
png_dir = 'images_png/' # Output directory to save converted PNG images
epochs = 2
batch_size = 1
# Prediction
class_names = ['Brain', 'Lung'] # Alphabetized list of possible classes (for prediction only - should correspond with training classes)
dcm_path = 'dcm_image.dcm' # image path for prediction
# Both/Misc
mode = 'train' # train or predict
model_path = 'saved_model.keras'
window_center = 50 # Window center for image normalization
window_width = 350 # Window width for image normalization
image_height = 512
image_width = 512
# Helper function to normalize DICOM images
def window_image(png_image, window_center, window_width, intercept, slope):
# Rescale the image
png_image = (png_image * slope + intercept)
# Define minimum and maximum values based on window center and width
png_image_min = window_center - window_width
png_image_max = window_center + window_width
# Clip values outside the window range
png_image[png_image < png_image_min] = png_image_min
png_image[png_image > png_image_max] = png_image_max
return png_image
# Convert single DICOM to PNG
def convert_image(dcm_path):
# Read the DICOM file
try:
dicom_ds = pydicom.read_file(dcm_path)
except FileNotFoundError:
print('Error: DICOM file not found. Please ensure the path contained in dcm_path is correct.')
exit()
# Get the image data
png_image = dicom_ds.pixel_array
# Get the intercept and slope for image rescaling, use default values if they are not provided
intercept = dicom_ds.RescaleIntercept if 'RescaleIntercept' in dicom_ds else -1024
slope = dicom_ds.RescaleSlope if 'RescaleSlope' in dicom_ds else 1
# Normalize the image
png_image = window_image(png_image, window_center, window_width, intercept, slope)
# Convert image data type to 8-bit unsigned integer
png_image = png_image.astype(np.uint8)
return png_image
# Convert multiple DICOM to PNG
def convert_batch_images(subdirectory):
# Get the list of all files in the DICOM directory
dcm_dir_files = [dcm_file for dcm_file in os.listdir(dcm_dir + subdirectory)]
# Process each file
for dcm_file in dcm_dir_files:
# Process only DICOM files
if dcm_file.lower().endswith('.dcm'):
# Get PNG image
png_image = convert_image(dcm_dir + subdirectory + dcm_file)
# Save the image in PNG format, replace original file extension '.dcm' with '.png'
cv2.imwrite(png_dir + subdirectory + dcm_file.lower().replace('.dcm', '.png'), png_image)
# Train a model
def train():
# Create the PNG directory if it does not exist
try:
os.mkdir(png_dir)
# If it exists, remove all files and directories inside
except FileExistsError:
shutil.rmtree(png_dir) # Remove the directory and all its contents
os.mkdir(png_dir) # Recreate the directory
# For each top-level directory (but not further subdirectory) in dcm_dir, convert all DICOM images
try:
for item in os.scandir(dcm_dir):
if item.is_dir():
subdirectory = str(item.path).split('/', 1)[-1] + '/' # Remove dcm_dir from path and add slash
os.mkdir(png_dir + subdirectory)
convert_batch_images(subdirectory) # Convert all DICOM in subdirectory to PNG
except FileNotFoundError:
print("Error: Please ensure that the directory in dcm_dir exists.")
shutil.rmtree(png_dir) # Delete created directory
exit()
# TensorFlow standard is data_dir for input images
data_dir = pathlib.Path(png_dir)
# Create training and validation datasets (80/20 split)
train_ds = tf.keras.utils.image_dataset_from_directory(data_dir, validation_split = 0.2, subset = 'training', seed = 123, image_size = (image_height, image_width), batch_size = batch_size)
val_ds = tf.keras.utils.image_dataset_from_directory(data_dir, validation_split = 0.2, subset = 'validation', seed = 123, image_size = (image_height, image_width), batch_size = batch_size)
class_names = train_ds.class_names # Override global variable
# Configure the dataset for performance
train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size = tf.data.AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size = tf.data.AUTOTUNE)
# Standardize the data
normalization_layer = layers.Rescaling(1./255)
normalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))
image_batch, labels_batch = next(iter(normalized_ds))
# Create the model
model = Sequential([
layers.Rescaling(1./255, input_shape = (image_height, image_width, 3)),
layers.Conv2D(16, 3, padding = 'same', activation = 'relu'),
layers.MaxPooling2D(),
layers.Conv2D(32, 3, padding = 'same', activation = 'relu'),
layers.MaxPooling2D(),
layers.Conv2D(64, 3, padding = 'same', activation = 'relu'),
layers.MaxPooling2D(),
layers.Flatten(),
layers.Dense(128, activation = 'relu'),
layers.Dense(len(class_names))
])
# Compile and train the model
model.compile(optimizer = 'adam', loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits = True), metrics = ['accuracy'])
history = model.fit(train_ds, validation_data = val_ds, epochs = epochs)
# Save the model
model.save(model_path)
# Delete all PNG files
shutil.rmtree(png_dir)
# Predict from DICOM image
def predict():
# Convert DCM to PNG
png_image = convert_image(dcm_path)
# Save the image in PNG format
png_path = dcm_path.lower().replace('.dcm', '.png')
cv2.imwrite(png_path, png_image)
# Load a saved model
try:
model = tf.keras.models.load_model(model_path)
except IOError:
print('I/O error. Please ensure that the file in model_path exists.')
os.remove(png_path) # Delete created PNG
exit()
# Load the PNG image into TensorFlow
img = tf.keras.utils.load_img(png_path, target_size = (image_height, image_width))
img_array = tf.keras.utils.img_to_array(img)
img_array = tf.expand_dims(img_array, 0) # Create a batch
# Predict which class the image belongs to
predictions = model.predict(img_array)
score = tf.nn.softmax(predictions[0])
try:
print('Class: {} | Confidence: {:.2f}%'.format(class_names[np.argmax(score)], 100 * np.max(score)))
except IndexError:
print('Error: Please ensure that the values in class_names correspond with the classes from the trained model.')
os.remove(png_path) # Delete created PNG
exit()
# Delete created PNG
os.remove(png_path)
# Main function
def main():
if mode == "train":
train()
elif mode == "predict":
predict()
else:
print("Error: Mode must be 'train' or 'predict'.")
exit() # Redundant (for now)
# Call main function when run directly from Python interpreter (change this if running from another program)
if __name__ == '__main__':
main()
<file_sep># DeepCT
A simple DICOM (CT, MRI, etc.) image classification framework for Python that uses PyDicom and TensorFlow. Based on [this](https://www.tensorflow.org/tutorials/images/classification) TensorFlow tutorial.
# How to Use
Default variables are located beneath the imports at the top of DeepCT.py. These variables can be changed to fit your environment.
To train a model, store classes of .dcm images in the directory associated with the dcm_dir variable. (The default is 'images_dcm'.) The classes must be in different subdirectories - for example, 'images_dcm/brain' would be one and 'images_dcm/lung' would be another. Batch size, number of epochs, etc. can be changed from the default variables. The model will be saved in the location associated with the model_path variable. (The default is 'saved_model.keras'. Note: .keras files are recommended over the legacy .h5 files.) The program uses a supervised learning process with 80% of images used for training and 20% used for validation.
To predict the class of an image, change the "mode" variable from "train" to "predict." The path of the .dcm image to be classified should be stored in the dcm_path variable.
# Dependencies
Note: Versions more recent than those specified have not been tested with this software.
#### Python
The latest version tested is Python 3.11.2.
#### pydicom
```pip3 install pydicom```
Used for working with .dcm/.dicom images. Tested version is 2.4.2.
#### TensorFlow
```pip3 install tensorflow```
The latest tested version is 2.13.0. Many other dependencies, such as NumPy, should be installed along with TensorFlow. GPU support is also included if CUDA drivers are installed.
#### PIL
```pip3 install pillow```
Used for working with .png images. Tested version is 10.0.0.
#### Misc
```pip3 install pyyaml h5py```
Used for working with model storage files other than the default .keras.
#### OpenGL API
```apt install libgl1 libglib2.0-0```
On Debian 12 (Linux Kernel 6.1), these OpenGL packages were required.
| 9dc90ed973f4afaf82fd6ab0d7ea6e81cffae131 | [
"Markdown",
"Python"
] | 2 | Python | aidanelm/DeepCT | 71cb29836a63507d9a68e8e1727434d084254e0a | 7770d998a1c8666a8a6ad624faa51ab1642114c5 |
refs/heads/branch1 | <file_sep>class Portfolio < ApplicationRecord
has_many :technologies
accepts_nested_attributes_for :technologies,
reject_if: lambda {|attrs| attrs['name'].blank?}
validates_presence_of :title, :body, :main_image, :thumb_image
def self.ang # sql query first way
where(subtitle:"Angular")
end
scope :ruby_rails, -> {where(subtitle: 'Ruby on rails')} # sql query second way
after_initialize :set_default_values_portfolio # first way to create default values is like i did in enum status default 0.
#This is second way of creating default valuesvalues are set aft initialization ie aft new action in portfolio_controller.
#setting default values for images
def set_default_values_portfolio
self.main_image ||= "http://placehold.it/600x400" # self.=> is similar to 'this' keyword. referencing this specific portfolio.
#if main_image is nil put my default value else put users inputted image value
self.thumb_image||= "http://placehold.it/350x200" #setting default values for images
end
end
<file_sep>class AddSlugToBlogs < ActiveRecord::Migration[5.2]
def change
add_column :blogs, :slug, :string #adding column slug on blog
add_index :blogs, :slug, unique: true # to make slug unique i need to add index and unique
end
end
<file_sep>class AddBadgeToSkills < ActiveRecord::Migration[5.2]
def change
add_column :skills, :badge, :text #badge is for image so its data type is text
end
end
<file_sep>class Skill < ApplicationRecord
includes Placeholder
validates_presence_of :title, :percent_utilize
after_initialize :set_default_values_skill # first way to create default values is like i did in enum status default 0.
#This is second way of creating default valuesvalues are set aft initialization ie aft new action in skill_controller.
#setting default values for images
def set_default_values_skill
self.badge ||= Placeholder.image_generator(height: 250, width: 250) # self.=> is similar to 'this' keyword. referencing this specific skill.
#if main_image is nil put my default value else put users inputted image value
#setting default values for images
end
end
<file_sep>Rails.application.routes.draw do
devise_for :users, path: '', path_names: {sign_in: 'login', sign_out: 'logout', sign_up: 'register'}
devise_for :views
resources :portfolios, except: [:show]
get 'portfolio/:id', to: 'portfolios#show', as: 'portfolio_show' #mapping rhs with lhs
get 'portfolios/angular', to: 'portfolios#displayangular' # localhost/portfolio/angular
#get 'angular', to: 'portfolios#displayangular' #localhost/angular
#get 'portfolios/angular', to: 'portfolios#displayangular' # localhost/portfolios/angular
#get 'pages/about'
get 'about-me', to: 'pages#about' #can put any name in lhs about, about-me etc
#get 'pages/contact'
get 'contact', to: 'pages#contact'
resources :blogs do
member do
get :toggle_status
end
end
root to: 'pages#home' #in localhost home page is shown
end
<file_sep>#create a module not class
module DeviseWhitelistStrongparams
extend ActiveSupport::Concern
included do
#configure_permitted_parameters :: just a name I gave
before_action :configure_permitted_parameters, if: :devise_controller?
end
def configure_permitted_parameters
# this syntax is from rails 5. older one wont work
devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name, :phone_number]) #sign_up is name used for registration new
devise_parameter_sanitizer.permit(:account_update, keys: [:first_name, :last_name, :phone_number]) # account_update is the name that devise uses for edit registration
end
end
<file_sep>module ApplicationHelper
def login_helper
if current_user
link_to "logout", destroy_user_session_path, method: :delete
else # if no user
(link_to "register", new_user_registration_path) +
"<br>".html_safe +
(link_to "log-in", new_user_session_path)
end
end
def source_helper # login from fb, twitter
if session[:mero_session]
greeting ="Thankyou for visiting me from: #{session[:mero_session]}"
content_tag(:p,greeting,class: "source-greeting")
end
end
end
<file_sep>class ApplicationController < ActionController::Base
include DeviseWhitelistStrongparams
before_action :my_set_source #just name mysetsource
before_action :set_title
def my_set_source
session[:mero_session] = params[:query] if params[:query] # if says if q is there as parameter do this.
#query just name it can be like [:q], [:pot]etc
end
def set_title
@page_title=" Dev Camp"
end
end
<file_sep>class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates_presence_of :first_name, :last_name
def fname
self.first_name.split.first # eg User.last=> <NAME> then self refers to <NAME>. self if not write also ok.
#in this case I have taken whole first name so can write up to self.first_name #self.first_name.split[0]
end
def lname
self.last_name.split.first
#self.last_name.split[0]
end
end
| 919b3899c7cf0254a64cdb5fc4c7912c59d40796 | [
"Ruby"
] | 9 | Ruby | kabitabhandari/practiceRuby01 | 0c6ede929ab3e665c0d84dc4733f64e387c25ee5 | 60ad534eaa6cd7cb85c648753cc03f7ef4883fa0 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using RazorSpy.Contracts;
using RazorSpy.Contracts.SyntaxTree;
using ReactiveUI;
namespace RazorSpy.ViewModel
{
[Export]
public class MainViewModel : ReactiveObject
{
private ReactiveCollection<Lazy<IRazorEngine, IRazorEngineMetadata>> _engines = new ReactiveCollection<Lazy<IRazorEngine, IRazorEngineMetadata>>();
private Lazy<IRazorEngine, IRazorEngineMetadata> _selectedEngine;
private string _razorCode;
private RazorLanguage _selectedLanguage;
private bool _designTimeMode;
private IEnumerable<Block> _generatedTree;
private string _generatedCode;
private string _status;
private ObservableAsPropertyHelper<IEnumerable<RazorLanguage>> _languages;
private ObservableAsPropertyHelper<bool> _multiEngine;
private ObservableAsPropertyHelper<bool> _singleEngine;
public string Status
{
get { return _status; }
set { _status = this.RaiseAndSetIfChanged(m => m.Status, value); }
}
public string RazorCode
{
get { return _razorCode; }
set { _razorCode = this.RaiseAndSetIfChanged(m => m.RazorCode, value); }
}
[ImportMany]
public ReactiveCollection<Lazy<IRazorEngine, IRazorEngineMetadata>> Engines
{
get { return _engines; }
set { _engines = this.RaiseAndSetIfChanged(m => m.Engines, value); }
}
public Lazy<IRazorEngine, IRazorEngineMetadata> SelectedEngine
{
get { return _selectedEngine; }
set { _selectedEngine = this.RaiseAndSetIfChanged(m => m.SelectedEngine, value); }
}
public RazorLanguage SelectedLanguage
{
get { return _selectedLanguage; }
set { _selectedLanguage = this.RaiseAndSetIfChanged(m => m.SelectedLanguage, value); }
}
public bool DesignTimeMode
{
get { return _designTimeMode; }
set { _designTimeMode = this.RaiseAndSetIfChanged(m => m.DesignTimeMode, value); }
}
public IEnumerable<Block> GeneratedTree
{
get { return _generatedTree; }
private set { _generatedTree = this.RaiseAndSetIfChanged(m => m.GeneratedTree, value); }
}
public string GeneratedCode
{
get { return _generatedCode; }
private set { _generatedCode = this.RaiseAndSetIfChanged(m => m.GeneratedCode, value); }
}
public IEnumerable<RazorLanguage> Languages
{
get { return _languages.Value; }
}
public bool MultiEngine
{
get { return _multiEngine.Value; }
}
public bool SingleEngine
{
get { return _singleEngine.Value; }
}
public MainViewModel()
{
_multiEngine = this.ObservableToProperty(
Engines.Changed.Select(_ => Engines.Count > 1),
vm => vm.MultiEngine);
_singleEngine = this.ObservableToProperty(
Engines.Changed.Select(_ => Engines.Count == 1),
vm => vm.SingleEngine);
_languages = this.ObservableToProperty(
this.ObservableForProperty(vm => vm.SelectedEngine)
.Select(_ => SelectedEngine.Value.Languages),
vm => vm.Languages);
_languages.Subscribe(_ => EnsureLanguage());
Engines.Changed.Subscribe(_ => EnsureEngine());
Observable.Merge(
this.ObservableForProperty(vm => vm.DesignTimeMode).IgnoreValues(),
this.ObservableForProperty(vm => vm.SelectedEngine).IgnoreValues(),
this.ObservableForProperty(vm => vm.SelectedLanguage).IgnoreValues(),
this.ObservableForProperty(vm => vm.RazorCode).IgnoreValues())
.ObserveOn(RxApp.DeferredScheduler)
.Subscribe(_ => Regenerate());
this.PropertyChanged += MainViewModel_PropertyChanged;
}
void MainViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
}
private void EnsureLanguage()
{
if (Languages != null && Languages.Any() && (SelectedLanguage == null || !Languages.Contains(SelectedLanguage)))
{
SelectedLanguage = Languages.FirstOrDefault();
}
}
private void EnsureEngine()
{
if (Engines != null && Engines.Any() && (SelectedEngine == null || !Engines.Contains(SelectedEngine)))
{
SelectedEngine = Engines.FirstOrDefault();
}
}
private void Regenerate()
{
if (SelectedEngine != null && SelectedLanguage != null && !String.IsNullOrEmpty(RazorCode))
{
Status = "Compiling...";
// Configure the host
IRazorEngine engine = SelectedEngine.Value;
ITemplateHost host = engine.CreateHost();
host.Language = SelectedLanguage;
host.DesignTimeMode = DesignTimeMode;
// Generate the template
GenerationResult result;
using (TextReader reader = new StringReader(RazorCode))
{
result = SelectedEngine.Value.Generate(reader, host);
}
if (result != null)
{
GeneratedCode = result.Code.GenerateString(SelectedLanguage.CreateCodeDomProvider());
GeneratedTree = new[] { result.Document };
Status = result.Success ? "Success" : "Errors during compilation";
return;
}
}
GeneratedCode = String.Empty;
GeneratedTree = null;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Text;
namespace RazorSpy
{
public static class ObservableExtensions
{
public static IObservable<Unit> IgnoreValues<T>(this IObservable<T> self)
{
return self.Select(_ => Unit.Default);
}
}
}
| 0877c1fe01d1d754bd00d1084f1c8f83c1a4bc3d | [
"C#"
] | 2 | C# | Kathy2013/RazorSpy | b270d8251df716c021c22357097309ca42b631c2 | 487d54d57b59d0cc34413cc303ed152f2d2c2f79 |
refs/heads/main | <file_sep>module konakuni {
}<file_sep>package konakuni;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
//System.out.println("Hello World");
//Test Digital Book
DigitalBook book1 = new DigitalBook();
PurchaseDate datebuy = new PurchaseDate("24","07","2021");
book1.setDigitalBook("D-Book1","Buku Digital 1",1, 560, datebuy);
System.out.println(book1.toString());
//Test Physical Book
PhysicalBook book2 = new PhysicalBook();
book2.setPhysicalBook("P-Book2","Buku Physical 1", 1, 230, false);
System.out.println(book2.toString());
}
}
<file_sep>package konakuni;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DigitalBook extends Book{
private int memorySize;
private PurchaseDate purchaseDate;
public DigitalBook() {
super();
// TODO Auto-generated constructor stub
}
public DigitalBook(String iSBN, String title, int quantity, int memSize, PurchaseDate dt) {
super(iSBN, title, quantity);
this.memorySize = memSize;
this.purchaseDate = dt;
// TODO Auto-generated constructor stub,
}
public void setDigitalBook(String iSBN, String title, int quantity, int memSize, PurchaseDate dt) {
// TODO Auto-generated method stub
super.setBook(iSBN, title, quantity);
this.memorySize = memSize;
this.purchaseDate = dt;
}
public Double estimatedPrice() {
//Does hardcover included ?
//
Double estimateprice = 0.0;
int addKB = 0;
Double additionalprice = 0.0;
if(this.memorySize < 200) { //less than 100 pages
return checkDiscount(estimateprice + 30.0);
}
else if( this.memorySize >= 200 && this.memorySize <= 500) {
return checkDiscount(estimateprice + 30.0);
}
else if( this.memorySize > 500) {
addKB = this.memorySize - 500;
//System.out.println(addKB);
additionalprice = (double) (addKB / 30 * 3);
return checkDiscount(100.00 + additionalprice);
}
return checkDiscount(estimateprice);
}
public Double checkDiscount(Double estimatedPrice) {
if(this.purchaseDate.getDay() == "22" && this.purchaseDate.getMonth() == "07") {
return estimatedPrice = estimatedPrice - (estimatedPrice * 0.1);
}
return estimatedPrice;
}
public int getMemorySize() {
return memorySize;
}
public void setMemorySize(int memorySize) {
this.memorySize = memorySize;
}
@Override
public String toString() {
return "DigitalBook [memorySize=" + memorySize + ", purchaseDate=" + purchaseDate.toString() + ", quantity=" + quantity
+ ", estimatedPrice()=" + estimatedPrice() + ", getQuantity()=" + getQuantity() + ", toString()="
+ super.toString() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + "]";
}
}
| afc830a8d9432367ed0b40de6e15ac48e332c8c7 | [
"Java"
] | 3 | Java | jerza90/konakuni-bookstore | f01941a45f5f9e8b4f254460bfa39350c159e78f | 68f830fc5395a61a053bc2008a92b5be8de3e344 |
refs/heads/master | <repo_name>KacperWodiany/CesarCipher<file_sep>/src/test/java/DecoderTest.java
import org.junit.BeforeClass;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
public class DecoderTest {
private static final int SHIFT = 3;
private static Decoder decoder;
@BeforeClass
public static void beforeClass(){
CodingDictionary dictionary = new CodingDictionary();
decoder = new Decoder(dictionary, SHIFT);
}
@Test
public void shouldDecodeDToAWhenShiftIsEqualToThree() {
char testCharacter = 'D';
char resultChar = decoder.code(testCharacter);
assertThat(resultChar, is(equalTo('A')));
}
@Test
public void shouldDecodeCToZWhenShiftIsEqualToThree() {
char testCharacter = 'C';
char resultChar = decoder.code(testCharacter);
assertThat(resultChar, is(equalTo('Z')));
}
@Test
public void shouldOnlyEncodeLetters() {
String testLine = "~`!@#$%^&*()_ +-=1234567890{}[]:;'<,>.?/|";
String resultLine = decoder.code(testLine);
assertThat(resultLine, is(equalTo(testLine)));
}
@Test
public void shouldDecodeZruogToWORLDWhenShiftIsEqualToThree() {
String testLine = "Zruog";
String resultLine = decoder.code(testLine);
assertThat(resultLine, is(equalTo("WORLD")));
}
}<file_sep>/src/main/java/CesarCipher.java
public class CesarCipher {
public static void main(String[] args){
final String line = "Hello world!";
System.out.println("Original: " + line);
final CodingDictionary dict = new CodingDictionary();
final int shift = 3;
final Coder encoder = new Encoder(dict, shift);
final String encodedLine = encoder.code(line);
System.out.println("Encoded: " + encodedLine);
final Coder decoder = new Decoder(dict, shift);
final String decodedLine = decoder.code(encodedLine);
System.out.println("Decoded: " + decodedLine);
}
}
<file_sep>/src/test/java/MapCreatorTest.java
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
public class MapCreatorTest {
private static Object keyOne;
private static Object keyTwo;
private static List<Object> keys;
private static Object valueOne;
private static Object valueTwo;
private static List<Object> values;
@BeforeClass
public static void beforeClass(){
keyOne = new Object();
keyTwo = new Object();
keys = Arrays.asList(keyOne,keyTwo);
valueOne = new Object();
valueTwo = new Object();
values = Arrays.asList(valueOne, valueTwo);
}
@Test
public void shouldHandleZippingListOfObjects() {
Map<Object, Object> resultMap = MapCreator.zipToMap(keys, values);
final Map<Object, Object> correctResultMap = new HashMap<>();
correctResultMap.put(keyOne, valueOne);
correctResultMap.put(keyTwo, valueTwo);
assertThat(resultMap, is(equalTo(correctResultMap)));
}
}<file_sep>/src/main/java/Encoder.java
public class Encoder extends Coder{
public Encoder(CodingDictionary dictionary, int shift) {
super.dictionary = dictionary;
super.codingMap = dictionary.createCodingMap(shift);
}
}
<file_sep>/src/main/java/MapCreator.java
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class MapCreator {
public static <K,V> Map<K, V> zipToMap(List<K> keys, List<V> values){
Iterator<K> keyIterator = keys.iterator();
Iterator<V> valueIterator = values.iterator();
return IntStream.range(0, keys.size()).boxed()
.collect(Collectors.toMap(i -> keyIterator.next(), i -> valueIterator.next()));
}
}
<file_sep>/src/main/java/CharacterCollector.java
import java.util.List;
import java.util.stream.Collectors;
public class CharacterCollector {
public static List<Character> format(String line){
return split(
prepare(line));
}
public static List<Character> split(String line){
return line
.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.toList());
}
public static String prepare(String line){
return line
.trim()
.toUpperCase();
}
public static String merge(List<Character> characters){
StringBuilder lineBuilder = new StringBuilder();
for(Character character : characters){
lineBuilder.append(character);
}
return lineBuilder.toString();
}
}
<file_sep>/settings.gradle
rootProject.name = 'Cesar Cipher'
| 2cab341b590476bba1f5d27fe744dc882cc3da1f | [
"Java",
"Gradle"
] | 7 | Java | KacperWodiany/CesarCipher | cde43a1494e45cfe4e754a8be29ff5bf229bd0d4 | 6cb941ccc10ea1a50d199f0a6406cd97e049b981 |
refs/heads/main | <file_sep># Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import NamedTuple
from kfp.components import InputPath, OutputPath
def automl_evaluate_model_for_nlp(
mlpipeline_metrics_path: OutputPath('UI_metrics'),
gcp_project_id: str,
gcp_region: str,
api_endpoint: str = None,
model_name: str = None,
) -> NamedTuple('Outputs', [('auprc', float), ('f1', float), ('recall', float), ('precision', float)]):
import subprocess
import sys
# we could build a base image that includes these libraries if we don't want to do
# the dynamic installation when the step runs.
subprocess.run([sys.executable, '-m', 'pip', 'install', 'googleapis-common-protos==1.6.0', '--no-warn-script-location'],
env={'PIP_DISABLE_PIP_VERSION_CHECK': '1'}, check=True)
subprocess.run([sys.executable, '-m', 'pip', 'install', 'google-cloud-automl==0.9.0', '--quiet', '--no-warn-script-location'],
env={'PIP_DISABLE_PIP_VERSION_CHECK': '1'}, check=True)
import google
import logging
from google.api_core.client_options import ClientOptions
from google.cloud import automl
import time
import json
logging.getLogger().setLevel(logging.INFO) # TODO: make level configurable
if api_endpoint:
client_options = ClientOptions(api_endpoint=api_endpoint)
client = automl.AutoMlClient(client_options=client_options)
else:
client = automl.AutoMlClient()
# A resource that represents Google Cloud Platform location.
project_location = client.location_path(gcp_project_id, gcp_region)
print("List of model evaluations:")
for evaluation in client.list_model_evaluations(model_name, ""):
if evaluation.display_name == '':
logging.info("Model evaluation name: {}".format(evaluation.name))
logging.info(
"Model annotation spec id: {}".format(
evaluation.annotation_spec_id
)
)
logging.info("Create Time:")
logging.info("\tseconds: {}".format(evaluation.create_time.seconds))
logging.info("\tnanos: {}".format(evaluation.create_time.nanos / 1e9))
logging.info(
"Evaluation example count: {}".format(
evaluation.evaluated_example_count
)
)
logging.info(
"Model evaluation metrics - auprc: {}".format(
evaluation.classification_evaluation_metrics.au_prc
)
)
auprc = evaluation.classification_evaluation_metrics.au_prc
for eva_num in evaluation.classification_evaluation_metrics.confidence_metrics_entry:
if eva_num.confidence_threshold == 0.5:
logging.info(
"Model evaluation metrics (threshold = 0.5): {}".format(
eva_num
)
)
f1 = eva_num.f1_score
recall = eva_num.recall
precision = eva_num.precision
break
break
print('overall threshold = 0.5, F1: {}, recall: {}, auprc: {}, precision: {}'.format(f1, recall, auprc, precision))
metrics = {
'metrics': [{
'name': 'precision-score', # The name of the metric. Visualized as the column name in the runs table.
'numberValue': precision, # The value of the metric. Must be a numeric value.
'format': "PERCENTAGE", # The optional format of the metric. Supported values are "RAW" (displayed in raw format) and "PERCENTAGE" (displayed in percentage format).
},
{
'name': 'recall-score', # The name of the metric. Visualized as the column name in the runs table.
'numberValue': recall, # The value of the metric. Must be a numeric value.
'format': "PERCENTAGE", # The optional format of the metric. Supported values are "RAW" (displayed in raw format) and "PERCENTAGE" (displayed in percentage format).
},
{
'name': 'f1-score', # The name of the metric. Visualized as the column name in the runs table.
'numberValue': f1, # The value of the metric. Must be a numeric value.
'format': "PERCENTAGE", # The optional format of the metric. Supported values are "RAW" (displayed in raw format) and "PERCENTAGE" (displayed in percentage format).
},
{
'name': 'auprc', # The name of the metric. Visualized as the column name in the runs table.
'numberValue': auprc, # The value of the metric. Must be a numeric value.
'format': "PERCENTAGE", # The optional format of the metric. Supported values are "RAW" (displayed in raw format) and "PERCENTAGE" (displayed in percentage format).
}
]
}
with open(mlpipeline_metrics_path, 'w') as mlpipeline_metrics_file:
mlpipeline_metrics_file.write(json.dumps(metrics))
return (auprc, f1, recall, precision)
if __name__ == '__main__':
import kfp
kfp.components.func_to_container_op(automl_evaluate_model_for_nlp,
output_component_file='evaluate_component.yaml',
base_image='python:3.7'
)
<file_sep>
#automl_deploy function request:
{
"kfp":"abcdes****-dot-us-central2.pipelines.googleusercontent.com", #AI platform pipeline instance client
"template_url": "https://storage.googleapis.com/your_bucket_name/kubeflow/pipeline.yaml", # use your pipeline url
"dataset_display_name": "abc_123", #automl dataset name
"dataset_path":"gs://your_bucket_name/data/automl/text_training.csv", #dataset file gcs uri
"name": "abc_123" #name suffix for kubeflow job
}
#After run, the runid will be in the response.
#get_automl_status function request:
check kubeflow status:
{
"kfp": "abcdes****-dot-us-central2.pipelines.googleusercontent.com",
"runid": "2b245945-e504-4403-a24f-ac851ee6c481"
}
<file_sep># Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import NamedTuple
def automl_import_data_for_nlp(
# dataset_path,
gcs_path: str,
gcp_project_id: str,
gcp_region: str,
dataset_id: str,
api_endpoint: str = None,
) -> NamedTuple('Outputs', [('dataset_id', str)]):
import sys
import subprocess
subprocess.run([sys.executable, '-m', 'pip', 'install', 'googleapis-common-protos==1.6.0',
'--no-warn-script-location'], env={'PIP_DISABLE_PIP_VERSION_CHECK': '1'}, check=True)
subprocess.run([sys.executable, '-m', 'pip', 'install', 'google-cloud-automl==0.9.0', '--quiet',
'--no-warn-script-location'], env={'PIP_DISABLE_PIP_VERSION_CHECK': '1'}, check=True)
import google
import logging
from google.api_core.client_options import ClientOptions
from google.cloud import automl
logging.getLogger().setLevel(logging.INFO) # TODO: make level configurable
if api_endpoint:
client_options = ClientOptions(api_endpoint=api_endpoint)
client = automl.AutoMlClient(client_options=client_options)
else:
client = automl.AutoMlClient()
dataset_full_id = client.dataset_path(gcp_project_id, gcp_region, dataset_id)
current_dataset = client.get_dataset(dataset_full_id)
if current_dataset.example_count > 0:
logging.info("Dataset has data already.")
logging.info("Dataset example count: {}".format(current_dataset.example_count))
# Get the multiple Google Cloud Storage URIs.
input_uris = gcs_path.split(",")
gcs_source = automl.types.GcsSource(input_uris=input_uris)
input_config = automl.types.InputConfig(gcs_source=gcs_source)
#dataset_full_id = client.dataset_path(gcp_project_id, gcp_region, dataset_id)
response = client.import_data(dataset_full_id, input_config)
logging.info("Processing import... This can take a while.")
# synchronous check of operation status.
logging.info("Data imported. {}".format(response.result()))
logging.info("Response metadata: {}".format(response.metadata))
logging.info("Operation name: {}".format(response.operation.name))
logging.info("Dataset id: {}".format(dataset_id))
return [dataset_id]
if __name__ == '__main__':
import kfp
kfp.components.func_to_container_op(automl_import_data_for_nlp,
output_component_file='import_component.yaml', base_image='python:3.7')
<file_sep>import kfp
import kfp_server_api
import time
import string
import json
import google.auth
import google.auth.transport.requests
import logging
def pipeline_deploy(request):
request_json = request.get_json()
kfp_id = request_json['kfp']
pipeline_file_url = request_json.get('template_url' , 'https://storage.googleapis.com/your_bucket_name/pipeline.yaml')
dataset_display_name = request_json['dataset_display_name']
dataset_path = request_json['dataset_path']
creds, projects = google.auth.default()
auth_req = google.auth.transport.requests.Request()
creds.refresh(auth_req)
client = kfp.Client(host=kfp_id, existing_token=creds.token)
#create pipeline using url
suffix = request_json['name']
pipeline_name = 'nlp-pipeline-'+ suffix
run_name = 'nlp-run-' + suffix
thread = client.pipelines.list_pipelines(async_req=True)
result = thread.get()
for pipeline in result.pipelines:
if pipeline.name == pipeline_name:
return 'Please specify a new name.'
api_url = kfp_server_api.models.ApiUrl(pipeline_file_url)
api_pipeline = kfp_server_api.models.ApiPipeline(
name=pipeline_name,
url=api_url)
thread = client.pipelines.create_pipeline(api_pipeline, async_req=True)
result = thread.get()
default_version_id = result.default_version.id # pipeline id
logging.info('pipeline id: {}'.format(default_version_id))
# Create an experiment.
experiment_name = 'nlp-experiment-' + suffix
experiment = client.experiments.create_experiment(body={'name' : experiment_name})
experiment_id = experiment.id
logging.info('experiment id: {}'.format(experiment_id))
# Create a run
resource_references = []
key = kfp_server_api.models.ApiResourceKey(id=experiment_id, type=kfp_server_api.models.ApiResourceType.EXPERIMENT)
reference = kfp_server_api.models.ApiResourceReference(key=key, relationship=kfp_server_api.models.ApiRelationship.OWNER)
resource_references.append(reference)
parameters = []
parameter = kfp_server_api.ApiParameter(name='gcp_project_id', value=projects)
parameters.append(parameter)
parameter = kfp_server_api.ApiParameter(name='gcp_region', value='us-central1')
parameters.append(parameter)
parameter = kfp_server_api.ApiParameter(name='dataset_display_name', value=dataset_display_name)
parameters.append(parameter)
parameter = kfp_server_api.ApiParameter(name='api_endpoint', value='')
parameters.append(parameter)
parameter = kfp_server_api.ApiParameter(name='gcs_path', value=dataset_path)
parameters.append(parameter)
parameter = kfp_server_api.ApiParameter(name='model_prefix', value='nlpmodel')
parameters.append(parameter)
pipeline_spec = kfp_server_api.ApiPipelineSpec(parameters=parameters, pipeline_id=default_version_id)
run = client.runs.create_run(body={'name':run_name, 'resource_references': resource_references, 'pipeline_spec': pipeline_spec})
run_id = run.run.id
logging.info('run id: {}'.format(run_id))
return run_id<file_sep>#!/bin/bash
source env.sh
# exit if any subcommand has error
set -euxo pipefail
#create service account and config it
ADMIN_NAME='kf-automl'
gcloud iam service-accounts create $ADMIN_NAME
gcloud projects add-iam-policy-binding $PROJECT_ID --member "serviceAccount:$ADMIN_NAME@$PROJECT_ID.iam.gserviceaccount.com" --role "roles/owner"
gcloud iam service-accounts keys create "$PWD/$ADMIN_NAME.json" --iam-account $ADMIN_NAME@$PROJECT_ID.iam.<EMAIL>account.com
export GOOGLE_APPLICATION_CREDENTIALS="$PWD/$ADMIN_NAME.json"
gcloud projects add-iam-policy-binding $PROJECT_ID --member="serviceAccount:$PROJECT_ID@appspot.gserviceaccount.com" --role=roles/storage.admin
gcloud projects add-iam-policy-binding $PROJECT_ID --member="serviceAccount:$<EMAIL>_NAME@$PROJECT_ID.iam.<EMAIL>.com" --role=roles/automl.editor
gcloud projects add-iam-policy-binding $PROJECT_ID --member="serviceAccount:$ADMIN_NAME@$PROJECT_ID.iam.gserviceaccount.com" --role=roles/logging.logWriter
gcloud projects add-iam-policy-binding $PROJECT_ID --member="serviceAccount:$ADMIN_NAME@$PROJECT_ID.iam.gserviceaccount.com" --role=roles/monitoring.metricWriter
gcloud projects add-iam-policy-binding $PROJECT_ID --member="serviceAccount:$ADMIN_NAME@$PROJECT_ID.iam.<EMAIL>account.com" --role=roles/monitoring.viewer
gcloud projects add-iam-policy-binding $PROJECT_ID --member="serviceAccount:$ADMIN_NAME@$PROJECT_ID.iam.gserviceaccount.com" --role=roles/storage.objectViewer
gcloud projects get-iam-policy $PROJECT_ID --flatten="bindings[].members" --format="table(bindings.role, bindings.members)" --filter="bindings.role:roles/container.admin OR bindings.role:roles/viewer"
gcloud projects get-iam-policy $PROJECT_ID --flatten="bindings[].members" --format="table(bindings.role, bindings.members)" --filter="bindings.role:roles/iam.serviceAccountAdmin"
<file_sep>PROJECT_ID='kf-automl-nlp'
# bucket to store intermediate data
BUCKET_NAME='kf-automl'
GCP_REGION='us-central1'
echo "project id: $PROJECT_ID bucket: $BUCKET_NAME region: $GCP_REGION"
#set project name in cli
gcloud config set project $PROJECT_ID<file_sep>kfp==1.0.0
kfp-server-api==1.0.0
google-auth==1.6.3<file_sep>import kfp
import kfp_server_api
import time
import string
import json
import google.auth
import google.auth.transport.requests
def run_finished(run_status: string) -> bool:
return run_status in {'Succeeded', 'Failed', 'Error', 'Skipped', 'Terminated'}
def run_succeeded(run_status: string) -> bool:
return run_status in {'Succeeded'}
def get_node_status(run_obj):
node_status = []
#overall_status = []
manifest = json.loads(run_obj.pipeline_runtime.workflow_manifest)
for item in manifest['status']['nodes']:
if '.' in manifest['status']['nodes'][item]['name']:
node_status.append({
'name': manifest['status']['nodes'][item]['name'].split(".")[-1],
'phase': manifest['status']['nodes'][item]['phase'],
'startTime': manifest['status']['nodes'][item]['startedAt']
})
else:
overal_status= manifest['status']['nodes'][item]['phase']
node_status.sort(key = lambda x : x['startTime'])
print('overal_status: {}'.format(overal_status))
for item in node_status:
print('{}: {}'.format(item['name'],item['phase']))
return overal_status, node_status
def get_metrics(run_obj):
metrics = []
print('Final metrics:')
for i in range(len(run_obj.run.metrics)):
print('{}: {}'.format(run_obj.run.metrics[i].name, run_obj.run.metrics[i].number_value))
metrics.append({'name': run_obj.run.metrics[i].name, 'value': run_obj.run.metrics[i].number_value})
return metrics
def get_model_id(run_obj):
manifest = json.loads(run_obj.pipeline_runtime.workflow_manifest)
for item in manifest['status']['nodes']:
if 'create-model' in manifest['status']['nodes'][item]['name']:
for entity in manifest['status']['nodes'][item]['outputs']['parameters']:
if 'model_id' in entity['name']:
print('model id: {}'.format(entity['value']))
model_id = entity['value']
break
return model_id
def run_status(request):
request_json = request.get_json()
creds, projects = google.auth.default()
auth_req = google.auth.transport.requests.Request()
creds.refresh(auth_req)
kfp_id = request_json['kfp']
client = kfp.Client(host=kfp_id, existing_token=creds.token)
run_id = request_json['runid']
run_current = client.runs.get_run(run_id)
response_body = {}
if run_succeeded(run_current.run.status):
overal_status, node_status = get_node_status(run_current)
response_body['status'] = overal_status
response_body['nodes'] = node_status
response_body['metrics'] = get_metrics(run_current)
response_body['model_id'] = get_model_id(run_current)
else:
overal_status, node_status = get_node_status(run_current)
response_body['status'] = overal_status
response_body['nodes'] = node_status
response_body['metrics'] = ''
response_body['model_id'] = ''
response_json = json.dumps(response_body)
return response_json<file_sep>source env.sh
#enable services
gcloud services enable 'translate.googleapis.com'
gcloud services enable 'cloudfunctions.googleapis.com'
gcloud services enable 'language.googleapis.com'
gcloud services enable 'automl.googleapis.com'
gcloud services enable 'firestore.googleapis.com'
# create firestore
gcloud app create --region='us-central' || echo "App already created, skip"
gcloud alpha firestore databases create --region='us-central'
# create bucket
gsutil mb gs://$BUCKET_NAME/ || echo "bucket already exists, skip creation"
#copy kubeflow pipeline template to your bucket and make it public
gsutil cp kubeflow-automl/pipeline.yaml gs://$BUCKET_NAME/kubeflow/pipeline.yaml
gsutil acl ch -u AllUsers:R gs://$BUCKET_NAME/kubeflow/pipeline.yaml
#deploy all the functions, please go the folder and deploy it.
#in function-kubeflow/pipeline_deploy folder
gcloud functions deploy automl_deploy --entry-point pipeline_deploy --runtime python37 --trigger-http
#in function-kubeflow/inquire_run_status folder
gcloud functions deploy get_automl_status --entry-point run_status --runtime python37 --trigger-http<file_sep>gcloud functions deploy get_automl_status --entry-point run_status --runtime python37 --trigger-http
gcloud functions deploy automl_deploy --entry-point pipeline_deploy --runtime python37 --trigger-http
<file_sep># Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import kfp.dsl as dsl
import kfp.gcp as gcp
import kfp.components as comp
import json
import time
create_dataset_op = comp.load_component_from_file(
'./create_dataset/dataset_component.yaml'
)
import_data_op = comp.load_component_from_file(
'./import_data_from_gcs/import_component.yaml'
)
train_model_op = comp.load_component_from_file(
'./create_model/model_component.yaml')
eval_model_op = comp.load_component_from_file(
'./create_model/evaluate_component.yaml')
deploy_model_op = comp.load_component_from_file(
'./deploy_model/deploy_component.yaml'
)
config_firestore_op = comp.load_component_from_file(
'./param_firestore/firestore_component.yaml'
)
@dsl.pipeline(
name='AutoML NLP',
description='Demonstrate an AutoML NLP workflow'
)
def automl_nlp( #pylint: disable=unused-argument
gcp_project_id: str = '',
gcp_region: str = 'us-central1',
dataset_display_name: str = '',
api_endpoint: str = '',
gcs_path: str = '',
model_prefix: str = 'nlpmodel',
):
create_dataset = create_dataset_op(
gcp_project_id=gcp_project_id,
gcp_region=gcp_region,
dataset_display_name=dataset_display_name,
api_endpoint=api_endpoint
)
# Disable cache
#task_never_use_cache = create_dataset
#task_never_use_cache.execution_options.caching_strategy.max_cache_staleness = "P0D"
import_data = import_data_op(
gcp_project_id=gcp_project_id,
gcp_region=gcp_region,
dataset_id=create_dataset.outputs['dataset_id'],
api_endpoint=api_endpoint,
gcs_path=gcs_path
)
train_model = train_model_op(
gcp_project_id=gcp_project_id,
gcp_region=gcp_region,
dataset_id=import_data.outputs['dataset_id'],
api_endpoint=api_endpoint,
model_prefix=model_prefix
)
import_data.after(create_dataset)
train_model.after(import_data)
eval_model = eval_model_op(
gcp_project_id=gcp_project_id,
gcp_region=gcp_region,
api_endpoint=api_endpoint,
model_name=train_model.outputs['model_name']
)
deploy_model = deploy_model_op(
gcp_project_id=gcp_project_id,
gcp_region=gcp_region,
api_endpoint=api_endpoint,
model_display_name=train_model.outputs['model_display_name'],
model_id=train_model.outputs['model_id']
)
config_firestore = config_firestore_op(
gcp_project_id=gcp_project_id,
gcp_region=gcp_region,
model_id=deploy_model.outputs['model_id']
)
eval_model.after(train_model)
deploy_model.after(train_model)
config_firestore.after(deploy_model)
if __name__ == '__main__':
import kfp.compiler as compiler
compiler.Compiler().compile(automl_nlp, __file__ + '.tar.gz')
<file_sep># Use GCP AI Platform Pipeline to build AutoML NLP Training and Deployment Pipeline
## Objective
This project is to use AI Platform Pipeline to orchestrate AutoML NLP Workflow, automating the data importing, training, evaluation and deployment process.
## Architecture
This project uses Function as a Http trigger. There are two functions, including pipeline deployment function, and pipeline status inquring function.
The whole workflow uses AI Platform pipeline(based on Kubeflow) as orchestrator. The core service is the pipeline is AutoML NLP service, for text classification model customization. After AutoML model is deployed, the model_id will be stored in Firestore.

## Deployment Steps
1. Create a project in GCP
2. Use *env.sh*, to config the project_id variables in CLI. When running *env.sh*, all the variables will be added to environment.

3. Use *service_account.sh*, modify the parameter of ADMIN_NAME, to config the service account.

4. Enable the related GCP service use *config.sh*
5. Create App Engine and Firestore use *config.sh*

6. Use *config.sh* to create GCS bucket, copy the local Kubeflow template to that bucket, and set it as public.

7. Next, use commands in *config.sh* to deploy the two functions. automl_deploy is the automl pipeline function,get_automl_status is to inquire pipeline running status.

8. Open AI platform pipeline service in GCP UI, create an instance, and get the client url of this instance.

9. Use this client url and GCS path of the training data, we can call the Http function to start AutoML end-to-end workflow. In *test_function_command.sh* under function-kubeflow folder, we can see how to form the function request body.

To deploy AutoML pipeline, we put AI Platform Pipeline client url, Kubeflow template url, AutoML NLP dataset display name, training data GCS path, and Kubeflow name (to name this time's Kubeflow pipeline and run) in the body.
To inquire pipeline status, we put AI Platform Pipeline client url, and this time's run id(runid will be in the response body of above request) in the body.
10. After starting automl_deploy, we can also directly check the status in AI platform pipeline(Kubeflow) monitor UI.

## Code Description
1) *config.sh*, *env.sh*, *service_account.sh* are all deployment related scripts.
2) Function-kubeflow includes code of two functions, *function_deploy_command.sh* is the script to show how to deploy function (*config.sh* also has the command). *test_function_command.sh* is to show how to use the functions.
3) Kubeflow-automl is the source code of pipeline template. You can also modify the source code and generate your own Kubeflow template using *template_generate.sh*. In *config.sh*, we directly upload the ready template from local to GCS.

<file_sep>#compile components
python dateset_component.py
#compile template
dsl-compile --py automl_nlp_pipeline_caip.py --output automl_nlp_pipeline_caip.tar.gz<file_sep># Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import NamedTuple
def config_firestore(
gcp_project_id: str,
gcp_region: str,
model_id: str,
) -> NamedTuple('Outputs', [('collection', str), ('document', str)]):
import sys
import subprocess
subprocess.run([sys.executable, '-m', 'pip', 'install', 'googleapis-common-protos==1.6.0',
'--no-warn-script-location'], env={'PIP_DISABLE_PIP_VERSION_CHECK': '1'}, check=True)
subprocess.run([sys.executable, '-m', 'pip', 'install', 'google-cloud-firestore==1.6.2', '--quiet',
'--no-warn-script-location'], env={'PIP_DISABLE_PIP_VERSION_CHECK': '1'}, check=True)
import google
import logging
from google.api_core.client_options import ClientOptions
from google.cloud import firestore
#logging.getLogger().setLevel(logging.INFO) # TODO: make level configurable
db = firestore.Client()
collection_name = 'nlp_config'
document_name = 'automl_config'
app_template = db.collection('nlp_config').document('automl_config')
app_template.set({'model_id': model_id})
return (collection_name, document_name)
if __name__ == '__main__':
import kfp
kfp.components.func_to_container_op(config_firestore,
output_component_file='firestore_component.yaml', base_image='python:3.7')
| 115a24c9318e5c96f42786c6029e06c7520d5d9a | [
"Markdown",
"Python",
"Text",
"Shell"
] | 14 | Python | cloudymoma/kubeflow-automl-nlp-example | f14bbed1bbda341a685f6988d320cc5928340580 | 72a94f12e8d500530d2a065a0898d80230f7e253 |
refs/heads/master | <file_sep>from tkinter import * #tkinter is built-in package for GUI.
from tkinter import ttk #some tkinter object need to be imported explicitly. we will use it to create combobox.
from tkinter import messagebox #some tkinter object need to be imported explicitly.
from atomicMass import * #atomicMass is a library that contains all the elements with their atomic mass value.
my_list=["H","He","Li","Be","B","C","N","O","F","Ne","Na","Mg","Al","Si",
"P","S","Cl","Ar","K","Ca","Sc","Ti","V","Cr","Mn","Fe","Co","Ni",
"Cu","Zn","Ga","Ge","As","Se","Br","Kr","Rb","Sr","Y","Zr","Nb","Mo",
"Tc","Ru","Rh","Pd","Ag","Cd","In","Sn","Sb","Te","I","Xe","Cs","Ba",
"La","Ce","Pr","Nd","Pm","Sm","Eu","Gd","Tb","Dy","Ho","Er","Tm","Yb",
"Lu","Hf","Ta","W","Re","Os","Ir","Pt","Au","Hg","Tl","Pb","Bi","Po",
"At","Rn","Fr","Ra","Ac","Th","Pa","U","Np","Pu","Am","Cm","Bk","Cf",
"Es","Fm","Md","No","Lr","Rf","Db","Sg","Bh","Hs","Mt","Ds","Rg","Cn","Nh","Fl","Mc","Lv","Ts","Og"]
# my_list is a list contains all chemical elements to be used later.
class App: #class that contains all needed functions.
def is_number(self, P): #function to check if the entered value is number or not.
if str.isdigit(P) or P == "" or P == ".": #if p is a digit return true
return True
else: #if not it will show an error massage to the user
messagebox.showerror("Error", "Atom and mass values should be a number ! ")
return False
#we will use above function to check if the atoms value entered by the user is a number.
# otherwise error massage will appear.
def __init__(self, root):#function used for all GUI related code.
# root is the main window.. all the widgets will be inside it.
# GUI will be divided into two frames one fo the equation entry and other for calculation
self.topFrame = Frame(root) #this command will create the top frame in the root.
self.bottomFrame = Frame(root) #this command will create the bottom frame in the root.
self.topFrame.grid(row=2) #this command will place the top frame in the root. in the second row of the window
self.bottomFrame.grid(row=14) #this command will place the bottom frame in the root.
vcmd = (self.topFrame.register(self.is_number))
# vcmd will use the function self.is_number each time it's called.
#introduction label
self.intro = Label(root , text="This chemical equation balancer can help you to balance an "
"unbalanced equation. This balancer can also help you check whether the equation"
" is balanced or not ")
# placing the label in row 1 of root windo.
self.intro.grid(row=1, sticky=W)
#staring reactant 1 related widgets.
self.react1Label = Label(self.topFrame, text="reactant1:")
#this command will create a label inside top frame.
# the label widget text parameter is the text that will be shown to the user.
self.react1Label.grid(row=2, column=0, sticky=W)
# placing the label in row 2 and first column , sticky=W means to the end west of the location.
self.elem1Label = Label(self.topFrame, text="element1:", bg="yellow")
#this command will create a label inside top frame. bg is the background color of the label
self.elem1Label.grid(row=3, column=2, sticky=W)
# placing the label in row 3 and column 2.
self.combo1 = ttk.Combobox(self.topFrame, values=my_list, width=6, state="readonly")
#this will create a comobobox that consists of all chemical elements to choose from.
# user will use this combo to choose the element in the equation (both for reactant and product
# first combo is self.combo1 which is for the first element in reactant 1.
# state = "readonly" means user can not enter into comobobox new value , he just can choose from the list.
#combobox need to use ttk (imported before)
self.combo1.grid(row=3, column=3, sticky=W)
# placing self.combo1 in row 3 and column 3.
self.atoms1Label = Label(self.topFrame, text="atom1:")
# this command will create a label inside top frame.
self.atoms1Label.grid(row=3, column=4, sticky=W)
# placing the label in row 3 and column 4.
self.atoms1Entry = Entry(self.topFrame, width=6 , validate = "key", validatecommand=(vcmd, '%P'))
# Entry widget to enter the atom amount in top frame.
# validate option determines the type of event that triggers the validation
#validatecommand will use the vcmd and the entry from the user to make sure it is a number.
# self.atoms1Entry is for the first atom ( atom for element 1 in reactant 1)
self.atoms1Entry.grid(row=3, column=5, sticky=W)
# placing the entry in row 3 and column 5.
self.atoms1Entry.insert(END, 0)
# the default value is 0 if the user did not choose an element.
#if the user choose an element he needs to change the 0 to valid atom number.
self.elem2Label = Label(self.topFrame, text="element2:", bg="yellow")
# this command will create a label inside top frame.
self.elem2Label.grid(row=3, column=8, sticky=W)
# placing the label in row 3 and column 8.
self.combo2 = ttk.Combobox(self.topFrame, values=my_list, width=6, state="readonly")
# second combo is self.combo2 which is for the second element in reactant 1.
self.combo2.grid(row=3, column=9, sticky=W)
# placing the combo in row 3 and column 9.
self.atoms2Label = Label(self.topFrame, text="atom2:")
# this command will create a label inside top frame.
self.atoms2Label.grid(row=3, column=10, sticky=W)
# placing the label in row 3 and column 10.
self.atoms2Entry = Entry(self.topFrame, width=6 , validate = "key", validatecommand=(vcmd, '%P'))
# self.atoms2Entry is for the second atom ( atom for element 2 in reactant 1)
self.atoms2Entry.insert(END, 0)
# the default value is 0 if the user did not choose an element.
# if the user choose an element he needs to change the 0 to valid atom number.
self.atoms2Entry.grid(row=3, column=11, sticky=W)
# placing the entry in row 3 and column 11.
#done from reactant 1 widgets.
# -------------------------
#starting reactant2 related widgets
#same as reactant1 but with different variables name.
self.plusLabel = Label(self.topFrame, text="+")
# this command will create a label inside top frame.
self.plusLabel.grid(row=4, column=0, sticky=W)
# placing the label in row 4 and column 0.
self.react2Label = Label(self.topFrame, text="reactant2:")
# this command will create a label inside top frame.
self.react2Label.grid(row=5, column=0, sticky=W)
# placing the label in row 5 and column 0.
self.elem3Label = Label(self.topFrame, text="element1:", bg="yellow")
# this command will create a label inside top frame.
self.elem3Label.grid(row=6, column=2, sticky=W)
# placing the label in row 6 and column 2.
self.combo3 = ttk.Combobox(self.topFrame, values=my_list, width=6, state="readonly")
# third combo is self.combo3 which is for the first element in reactant 2.
self.combo3.grid(row=6, column=3, sticky=W)
# placing the combo in row 6 and column 3.
self.atoms3Label = Label(self.topFrame, text="atom1")
# this command will create a label inside top frame.
self.atoms3Label.grid(row=6, column=4, sticky=W)
# placing the label in row 6 and column 4.
self.atoms3Entry = Entry(self.topFrame, width=6 , validate = "key", validatecommand=(vcmd, '%P'))
# self.atoms3Entry is for atom of element 1 in reactant 2
self.atoms3Entry.grid(row=6, column=5, sticky=W)
# placing the entry in row 6 and column 5.
self.atoms3Entry.insert(END, 0)
# the default value is 0 if the user did not choose an element.
# if the user choose an element he needs to change the 0 to valid atom number.
self.elem4Label = Label(self.topFrame, text="element2:", bg="yellow")
# this command will create a label inside top frame.
self.elem4Label.grid(row=6, column=8, sticky=W)
# placing the label in row 6 and column 8.
self.combo4 = ttk.Combobox(self.topFrame, values=my_list, width=6, state="readonly")
# fourth combo is self.combo4 which is for the second element in reactant 2.
self.combo4.grid(row=6, column=9, sticky=W)
# placing the combo in row 6 and column 9.
self.atoms4Label = Label(self.topFrame, text="atom2:")
# this command will create a label inside top frame.
self.atoms4Label.grid(row=6, column=10, sticky=W)
# placing the label in row 6 and column 10.
self.atoms4Entry = Entry(self.topFrame, width=6 , validate = "key", validatecommand=(vcmd, '%P'))
# self.atoms4Entry is for atom of element 2 in reactant 2
self.atoms4Entry.grid(row=6, column=11, sticky=W)
# placing the entry in row 6 and column 11.
self.atoms4Entry.insert(END, 0)
# the default value is 0 if the user did not choose an element.
# if the user choose an element he needs to change the 0 to valid atom number.
#end of reactant 2 related widgets.
# -----------------------------------
#starting product 1 related widgets
self.equalLabel = Label(self.topFrame, text="=>")
# this command will create a label inside top frame.
self.equalLabel.grid(row=7, column=0, sticky=W)
# placing the label in row 7 and column 0.
self.product1Label = Label(self.topFrame, text="product1:")
# this command will create a label inside top frame.
self.product1Label.grid(row=8, column=0, sticky=W)
# placing the label in row 8 and column 0.
self.elem11Label = Label(self.topFrame, text="element1:", bg="yellow")
# this command will create a label inside top frame
self.elem11Label.grid(row=9, column=2, sticky=W)
# placing the label in row 9 and column 2.
self.combo11 = ttk.Combobox(self.topFrame, values=my_list, width=6, state="readonly")
# fifth combo is self.combo11 which is for the first element in product 1.
self.combo11.grid(row=9, column=3, sticky=W)
# placing the combo in row 9 and column 3.
self.atoms11Label = Label(self.topFrame, text="atom1")
# this command will create a label inside top frame
self.atoms11Label.grid(row=9, column=4, sticky=W)
# placing the label in row 9 and column 4.
self.atoms11Entry = Entry(self.topFrame, width=6 , validate = "key", validatecommand=(vcmd, '%P'))
# self.atoms11Entry is for atom of element 1 in product 1.
self.atoms11Entry.grid(row=9, column=5, sticky=W)
# placing the entry in row 9 and column 5.
self.atoms11Entry.insert(END, 0)
# the default value is 0 if the user did not choose an element.
# if the user choose an element he needs to change the 0 to valid atom number.
self.elem22Label = Label(self.topFrame, text="element2:", bg="yellow")
# this command will create a label inside top frame
self.elem22Label.grid(row=9, column=8, sticky=W)
# placing the label in row 9 and column 8.
self.combo22 = ttk.Combobox(self.topFrame, values=my_list, width=6, state="readonly")
# sixth combo is self.combo22 which is for the second element in product 1.
self.combo22.grid(row=9, column=9, sticky=W)
# placing the combo in row 9 and column 9.
self.atoms22Label = Label(self.topFrame, text="atom2:")
# this command will create a label inside top frame
self.atoms22Label.grid(row=9, column=10, sticky=W)
# placing the label in row 9 and column 10.
self.atoms22Entry = Entry(self.topFrame, width=6 , validate = "key", validatecommand=(vcmd, '%P'))
# self.atoms22Entry is for atom of element 2 in product 1.
self.atoms22Entry.grid(row=9, column=11, sticky=W)
# placing the entry in row 9 and column 11.
self.atoms22Entry.insert(END, 0)
# the default value is 0 if the user did not choose an element.
# if the user choose an element he needs to change the 0 to valid atom number.
#end of product 1 related widgets.
# ---------------------------------------
#starting product 2 related widgets.
self.plus2Label = Label(self.topFrame, text="+")
# this command will create a label inside top frame
self.plus2Label.grid(row=10, column=0, sticky=W)
# placing the label in row 10 and column 0.
self.product2Label = Label(self.topFrame, text="product2:")
# this command will create a label inside top frame
self.product2Label.grid(row=11, column=0, sticky=W)
# placing the label in row 11 and column 0.
self.elem33Label = Label(self.topFrame, text="element1:", bg="yellow")
# this command will create a label inside top frame
self.elem33Label.grid(row=12, column=2, sticky=W)
# placing the label in row 12 and column 2.
self.combo33 = ttk.Combobox(self.topFrame, values=my_list, width=6, state="readonly")
# seventh combo is self.combo33 which is for the first element in product 2.
self.combo33.grid(row=12, column=3, sticky=W)
# placing the combo in row 12 and column 3.
self.atoms33Label = Label(self.topFrame, text="atom1")
# this command will create a label inside top frame
self.atoms33Label.grid(row=12, column=4, sticky=W)
# placing the label in row 12 and column 4.
self.atoms33Entry = Entry(self.topFrame, width=6 ,validate = "key", validatecommand=(vcmd, '%P'))
# self.atoms33Entry is for atom of element 1 in product 2.
self.atoms33Entry.grid(row=12, column=5, sticky=W)
# placing the entry in row 12 and column 5.
self.atoms33Entry.insert(END, 0)
# the default value is 0 if the user did not choose an element.
# if the user choose an element he needs to change the 0 to valid atom number.
self.elem44Label = Label(self.topFrame, text="element2:", bg="yellow")
# this command will create a label inside top frame
self.elem44Label.grid(row=12, column=8, sticky=W)
# placing the label in row 12 and column 8.
self.combo44 = ttk.Combobox(self.topFrame, values=my_list, width=6, state="readonly")
# eighth combo is self.combo44 which is for the second element in product 2.
self.combo44.grid(row=12, column=9, sticky=W)
# placing the combo in row 12 and column 9.
self.atoms44Label = Label(self.topFrame, text="atom2:")
# this command will create a label inside top frame
self.atoms44Label.grid(row=12, column=10, sticky=W)
# placing the label in row 12 and column 10.
self.atoms44Entry = Entry(self.topFrame, width=6 , validate = "key", validatecommand=(vcmd, '%P'))
# self.atoms44Entry is for atom of element 2 in product 2.
self.atoms44Entry.grid(row=12, column=11, sticky=W)
# placing the entry in row 12 and column 11.
self.atoms44Entry.insert(END, 0)
# the default value is 0 if the user did not choose an element.
# if the user choose an element he needs to change the 0 to valid atom number.
#end of product two related widgets.
#all chemical equation related widgets has been done.
# -----------------------------------
#starting the bottom frame widgets.
self.button1 = Button(self.bottomFrame, text="enter to check if the equation is balance", fg="blue",
command=lambda: self.IsBalance())
# create a button in the bottom frame.
# text is what will appear in the button for the user.
# fg = "blue is the font color of the text.
# command=lambda: self.IsBalance() means when the user click the button self.IsBalance() function will be called.
# this button will call the function to check if the chemical equation entered is valid or not.
self.button1.grid(row=14)
# place the button in the window.
self.balancelabel = Label(self.bottomFrame)
# this command will create a label inside bottom frame
# no text in this label , so it will be hidden
# we will fill this text as needed in self.IsBalance() function
#this label to show the user if the entered equation is balance or not.
self.balancelabel.grid(column=1, row=14)
# placing the label in row 14 and column 1.
#------------------------------------
self.MassLabel2 = Label(self.bottomFrame,
text="choose the number of reactant with known mass then enter mass value:",
bg="yellow")
# this command will create a label inside bottom frame
# this label will ask the user to choose which reactant is mass known and ask him to enter the mass.
self.MassLabel2.grid(row=16)
# place the label in the window.
self.combomass = ttk.Combobox(self.bottomFrame, values=['1','2'], width=6, state="readonly")
# create a combobox to make the user choose which reactant is mass known 1 or 2.
# he can not enter a value he just can choose from the list.
self.combomass.grid(row=16, column=1)
# place the combo in the window.
self.MassEntry = Entry(self.bottomFrame, width=6, validate="key",validatecommand=(vcmd, '%P'))
# entry widget to enter the mass amount of known reactant.
# only digits are allowed to be entered.
self.MassEntry.grid(row=16, column=2)
# place the entry in the window.
self.MassEntry.insert(END, 1)
#default value is 1 . user will change is as needed.
self.button3 = Button(self.bottomFrame, text="enter to calculate mass", fg="blue",
command=lambda: self.MoleToMass())
# create a button in the bottom frame.
#this button for calculating the mass value of the other reactant.
# when clicked self.MoleToMass() function will be called.
self.button3.grid(row=17)
# place the button in the window.
self.Resultlabel = Label(self.bottomFrame)
# this label is to display the mass result to the user
self.Resultlabel.grid( row=18)
#place the label in the window.
# the end of the GUI widgets code.
#-----------------------------------
#-------------------------------
#starting IsBalance(self) function to check if the entered rection is blance or not.
# if not balanced it will balance the reaction and print the balance one to the user.
def IsBalance(self):
self.elem1 = self.combo1.get()
# self.elem1 will get the value chosen from self.combo1 (element 1 of reactant 1)
self.elem2 = self.combo2.get()
# self.elem2 will get the value chosen from self.combo2 (element 2 of reactant 1)
self.elem3 = self.combo3.get()
# self.elem3 will get the value chosen from self.combo3 (element 1 of reactant 2)
self.elem4 = self.combo4.get()
# self.elem4 will get the value chosen from self.combo4 (element 2 of reactant 2)
self.elem11 = self.combo11.get()
# self.elem11 will get the value chosen from self.combo11 (element 1 of product 1)
self.elem22 = self.combo22.get()
# self.elem22 will get the value chosen from self.combo22 (element 2 of product 1)
self.elem33 = self.combo33.get()
# self.elem33 will get the value chosen from self.combo33 (element 1 of product 2)
self.elem44 = self.combo44.get()
# self.elem44 will get the value chosen from self.combo44 (element 2 of product 2)
self.atom1 = int(self.atoms1Entry.get())
# self.atom1 will get the value entered in self.atoms1Entry (first element's atom of reactant 1)
self.atom2 = int(self.atoms2Entry.get())
# self.atom2 will get the value entered in self.atoms2Entry (second element's atom of reactant 1)
self.atom3 = int(self.atoms3Entry.get())
# self.atom3 will get the value entered in self.atoms3Entry (first element's atom of reactant 2)
self.atom4 = int(self.atoms4Entry.get())
# self.atom4 will get the value entered in self.atoms4Entry (second element's atom of reactant 2)
self.atom11 = int(self.atoms11Entry.get())
# self.atom11 will get the value entered in self.atoms11Entry (first element's atom of product 1)
self.atom22 = int(self.atoms22Entry.get())
# self.atom22 will get the value entered in self.atoms22Entry (second element's atom of product 1)
self.atom33 = int(self.atoms33Entry.get())
# self.atom33 will get the value entered in self.atoms33Entry (first element's atom of product 2)
self.atom44 = int(self.atoms44Entry.get())
# self.atom44 will get the value entered in self.atoms44Entry (second element's atom of product 2)
if self.elem1 !="" and self.atom1 <= 0 or self.elem2 !="" and self.atom2 <= 0 or self.elem3 !="" and \
self.atom3 <= 0 or self.elem4 !="" and self.atom4 <= 0 or self.elem11 !="" and self.atom11 <= 0 or\
self.elem22 !="" and self.atom22 <= 0 or self.elem33 !="" and self.atom33 <= 0 or self.elem44 !="" and \
self.atom44 <= 0:
messagebox.showerror("Error", "if you choose an element then atom value should be greater than 0")
# if the user selected an item then entered atom value in any atom's entries is less than 0
# it will show an error massage to the user.
if self.elem1 == "" or self.elem3 == "" or self.elem11 == "":
messagebox.showerror("Error", "you should have at least two reactants and one product ")
self.balancelabel['text'] = ""
return
# if the user did not entered two reactants and one product error massage will be shown
# each chemical reaction need to have at least two reactants and one product
# if the if statement is true it will go out from the function.
reactant = [
{self.elem1: self.atom1, self.elem2: self.atom2},
{self.elem3: self.atom3, self.elem4: self.atom4}]
# creating a reactant dictionary to save all reactants information
product = [
{self.elem11: self.atom11, self.elem22: self.atom22},
{self.elem33: self.atom33, self.elem44: self.atom44}]
# creating a product dictionary to save all reactants information
merged = {}
# creating an empty dictionary to save all reactants elements with the number of their atoms
for d in reactant:
for k, v in d.items():
if k not in merged: merged[k] = []
merged[k].append(v)
# loop through reactant dictionary and add each element as a key in merged dictionary.
# add the number of atoms of this element as it's values.
# for example [H:[2,1]] if it appear as H2 in reactant 1 and H in reactant 2.
Result = {key: sum(values) for key, values in merged.items()}
# Result dictionary will sum the atoms value of each element and add it as a value for reactants side.
# this will give us the total number of atoms used for each element in the reactant side
# for example: [H : 3]
merged2 = {}
# creating an empty dictionary to save all product elements with the number of their atoms
for d in product:
for k, v in d.items():
if k not in merged2: merged2[k] = []
merged2[k].append(v)
# loop through product dictionary and add each element as a key in merged2 dictionary.
# add the number of atoms of this element as it's values.
# for example [H:[2,1]] if it appear as H2 in product 1 and H in product 2.
Result1 = {key: sum(values) for key, values in merged2.items()}
# Result1 dictionary will sum the atoms value of each element and add it as a value for products side.
# this will give us the total number of atoms used for each element in the product side
# for example: [H : 3]
# we will use these dictionaries as basices to do the balancing.
# -----------------------------
# first let's checks if the entered reaction is balanced or not!
'''the if statement will use the result and result1 dictionaries to do the comparision.
it will compare two things:
first: if the element used in one side but not in the other
second: if the total number of atoms for each element used in the reactant
side do not equal the total number
of atoms in the product sides '''
if Result != Result1:
self.balancelabel['text'] = "not balance"
# if not equal it will print not balance in the label that was created as empty before.
# then we need to divide the reaction more
# r1 will save only the elements of the first reactant
# where element name is the key and number of atoms is the value
# example : r1 = [ H:2 , O:2]
# the loop will go through the first reactant elements in r1
# then the if statement will check if element 2 is empty
# if the first reactant consists of only one element then it will remove the empty one.
# this will reduce r1 size and will get rid of the 0 in the atom entry.
# for example if reactant 1 is only : Na
# remember that element 1 of the first reactant must be filled.
r1 = reactant[0]
for key in r1.copy():
if key == "":
r1.pop(key)
# r2 will save only the elements of the second reactant
# where element name is the key and number of atoms is the value
# we will repeat the same thing for reactant 2
# save it in r2 then remove the empty element !
# remember that element 1 of the second reactant must be filled.
r2 = reactant[1]
for key in r2.copy():
if key == "":
r2.pop(key)
# p1 will save only the elements of the first product
# where element name is the key and number of atoms is the value
# we will repeat the same thing for product 1
# save it in p1 then remove the empty element !
# remember that element 1 of the first product must be filled.
p1 = product[0]
for key in p1.copy():
if key == "":
p1.pop(key)
# p2 will save only the elements of the second product
# where element name is the key and number of atoms is the value
# we will repeat the same thing for product 2
# save it in p2 then remove the empty element !
# remember that product 2 may it be all empty.
p2 = product[1]
for key in p2.copy():
if key == "":
p2.pop(key)
# remove the empty element from Result!
for key in Result.copy():
if Result[key] == 0:
Result.pop(key)
# remove the empty element from Result1!
for key in Result1.copy():
if Result1[key] == 0:
Result1.pop(key)
#print dictionaries before balancing
print("Reactant dictionary: ", Result)
print("Product dictionary: ", Result1)
#------------------------------------
#lets check if the user enter an element in one side only which is considred as wrong entry
# the element entered the reaction should go out from the reaction and vise versa.
'''loop through r1 and r2 using the the key and if this key is not found
in both products then below
text will be shown to the user in the label. and then it will go out from the function'''
for key in r1 or key in r2:
if key not in p1 and key not in p2:
self.balancelabel['text'] = "wrong entry! element should be in the products side as well"
return
'''loop through p1 and p2 using the the key and if this key is not found in both reactants then below
text will be shown to the user in the label. and then it will go out from the function'''
for key in p1 or key in p2:
if key not in r1 and key not in r2:
self.balancelabel['text'] = "wrong entry! element should be in the reactants side as well"
return
# if the Result == result1 then it means the reaction is balanced.
# balanced will be printed in the label.
else:
self.balancelabel['text'] = "balance"
# until here we checked if the reaction is balanced or not and if all entries are right.
# we are done from the first part of the function
# if the reaction is not balanced then we need to balance it
# starting the process of balancing the reaction next:
while Result != Result1: # as long as it's not balanced yet !
for key in Result: # for each element in the reactants side do the followings:
if key in Result1 and Result[key] != Result1[key]:
'''if you find this key in the product side and the total atoms value is not the same
that means this element is not balanced '''
''' we will assess this element through multiple cases:
we have four potential cases:
1- its total atom value of an element is 1 in the reactants side.
2- its total atom value of an element is 1 in the product side.
3- the reminder of the division between total atoms of one side over the other is 0.
4- the reminder of the division between total atoms of one side over the other is not 0.
each element will go over one of these options'''
# first case total atom value of an element is 1 in the reactants side:
if Result[key] == 1: # if the total atoms value in reactant side is one
coff = Result1[key] # the coefficient will be the number of atoms in the product side.
'''for example : if we have H in reactant side and 2H in product side ,
coefficient will be 2.
multiplying H in the reactant side by 2 this will equal 2H = 2H '''
# we need to know if this element in reactant 1 or 2
# because the total number of atom of this element is 1
# so it will be either in reactant 1 or 2:
if key in r1: # if this element is in reactant1
r1.update((k, coff * r1[k]) for k in r1)
'''update the total atom value of this element in reactant1 by multiply the number
of atom of this element which is 1 with the coefficient'''
Result.update((k, r1[k]) for k in r1)
# we will update the total number of atoms for this element in the Result as well.
# we need to update Result to check if result == Result1 after the new coefficient
elif key in r2:
# if this element is in reactant2 we will do the same thing but we will update r2
r2.update((k, coff * r2[k]) for k in r2)
# we will update the total number of atoms for this element in the Result as well.
# we need to update Result to check if result == Result1 after the new coefficient
Result.update((k, r2[k]) for k in r2)
# second case total atom value of an element is 1 in the product side:
elif Result1[key] == 1:
'''if the total number of atoms is 1 in the product side we will do the same but in opposite way
we will multiply the element in the product side by the number of atoms in the reactant side.'''
coff = Result[key]
# coefficient value equal to total number of atom of this element in the reactant side
# because the total number of atom of this element is 1 so it will be either in product 1 or 2:
if key in p1: # if this element in product1
p1.update((k, coff * p1[k]) for k in p1) #update p1 with the new value
'''update the total atom value of this element in product1 by multiply the number
of atom of this element which is 1 with the coefficient'''
Result1.update((k, p1[k]) for k in p1) #update Result1 with the new value
elif key in p2: # if this element in product2
p2.update((k, coff * p2[k]) for k in p2)
# update p2 with the new value
'''update the total atom value of this element in product2 by multiply the number
of atom of this element which is 1 with the coefficient'''
Result1.update((k, p2[k]) for k in p2) #update Result1 with the new value
# if the total atom value of an element is greater than 1 then:
#third case: the reminder of the division between total atoms of one side over the other is 0.
# checks if the total atom value in each side can be divided by each other
elif Result[key] % Result1[key] == 0 or Result1[key] % Result[key] == 0:
# if the reminder is 0
m = min(Result[key], Result1[key])
# we will check which side of the same element has smaller total of atoms and save it in m
g = max(Result[key], Result1[key])
# we will check which side of the same element has greater total of atoms and save it in g
coff = int(g / m)
''' dividing the m by g will give us the coefficient and we will multiply it
by the element in the smaller side
for example 2H = 4H (not balanced) -> 4/2 = 2 -> 2*2 H = 4H -> 4H=4H (balanced)'''
if Result[key] < Result1[key]: # if reactant side is the smaller then
if key in r1: # check if element in reactant 1?
r1.update((k, coff * r1[k]) for k in r1)
'''update the total atom value of this element in reactant1 by multiply the number
of atom of this element with the coefficient'''
Result.update((k, r1[k]) for k in r1) # update Result1 with the new value
elif key in r2: # check if element in reactant 2?
r2.update((k, coff * r2[k]) for k in r2)
'''update the total atom value of this element in reactant1 by multiply the number
of atom of this element with the coefficient'''
Result.update((k, r2[k]) for k in r2) # update Result1 with the new value
elif Result[key] > Result1[key]:
# if product side is the smaller then we will repeat the same thing but in the product side instead.
if key in p1: # check if element in product 1?
p1.update((k, coff * p1[k]) for k in p1)
'''update the total atom value of this element in product1 by multiply the number
of atom of this element with the coefficient'''
Result1.update((k, p1[k]) for k in p1) # update Result1 with the new value
elif key in p2: # check if element in product 2?
p2.update((k, coff * p2[k]) for k in p2)
'''update the total atom value of this element in product1 by multiply the number
of atom of this element with the coefficient'''
Result1.update((k, p2[k]) for k in p2) # update Result1 with the new value
# fourth case: the reminder of the division between total atoms of one side over the other is not 0.
# if they are not dividable by each other
# we need to multiply each side by the total amount of atoms in the other side
elif Result[key] % Result1[key] != 0 or Result1[key] % Result[key] != 0:
coff1 = Result[key]
# let make coefficient1 == to total number of atoms of an element in reactant side
coff2 = Result1[key]
# let make coefficient2 == to total number of atoms of an element in product side
if key in r1: # check if element in reactant 1?
r1.update((k, coff2 * r1[k]) for k in r1)
'''then we need to multiply it by the total number of atoms of product side which is
coefficient2 '''
Result.update((k, r1[k]) for k in r1) # update Result1 with the new value
elif key in r2: # check if element in reactant 2?
r2.update((k, coff2 * r2[k]) for k in r2)
'''then we need to multiply it by the total number of atoms of product side which is
coefficient2 '''
Result.update((k, r2[k]) for k in r2) # update Result1 with the new value
if key in p1: # check if element in product 1?
p1.update((k, coff1 * p1[k]) for k in p1)
'''then we need to multiply it by the total number of atoms of product side which is
coefficient1 '''
Result1.update((k, p1[k]) for k in p1) # update Result1 with the new value
elif key in p2: # check if element in product 2?
p2.update((k, coff1 * p2[k]) for k in p2)
'''then we need to multiply it by the total number of atoms of product side which is
coefficient1 '''
Result1.update((k, p2[k]) for k in p2) # update Result1 with the new value
for key in Result:
if key in r1 and key in r2:
# if element in both reactant 1 and 2 sum the value and add it to result
Result[key] = r1[key] + r2[key] # update Result1 with the new value
for key in Result1:
if key in p1 and key in p2:
# if element in both products 1 and 2 sum the value and add it to result1
Result1[key] = p1[key] + p2[key] # update Result1 with the new value
#print the dictionaries after balancing
print("Reactant1 dictionary: " , Result)
print("Product1 dictionary: " , Result1)
if Result == Result1: # check if they are equal now
# if total atom number for each element is equal in both side so it finally balance!
# this section is to print the answer to end user
for key in r1: # for each element in reactant 1
if key != "": # if element is not empty
self.total1 = r1[key] # save the total atom value in variable total and exist the loop
break # we need just the first element
for key in r2: # for each element in reactant 2
if key != "": # if element is not empty
self.total2 = r2[key] # save the total atom value in variable total and exist the loop
break # we need just the first element
for key in p1:
if key != "": # for each element in product 1
self.total3 = p1[key] # if element is not empty
# save the total atom value in variable total and exist the loop
break # we need just the first element
# because product2 is allowed to be empty but reactant 1 , 2 product1 must at leas have one element
if p2 == {}: #if the whole product is empty make the total 0
self.total4 = 0
else:
for key in p2: #if there is element
self.total4 = p2[key] # save the total atom value in variable total and exist the loop
break
# coefficient1 to display:
'''coefficient1 will be before reactant 1 coefficient1 is equal to the total number of atoms of the
first element of the reactant 1 after balancing / total number of atoms of the element before balancing'''
self.coefficient1 = int(self.total1 / self.atom1)
'''coefficient2 will be before reactant 2 coefficient2 is equal to the total number of atoms of the
first element of the reactant 2 after balancing / total number of atoms of the element before balancing'''
self.coefficient2 = int(self.total2 / self.atom3)
'''coefficient3 will be before product 1 coefficient3 is equal to the total number of atoms of the
first element of the product 1 after balancing / total number of atoms of the element before balancing'''
self.coefficient3 = int(self.total3 / self.atom11)
# if the total is 0 or total atoms is 0 that mean product 2 is empty and no need for coefficient
if self.total4 == 0 or self.atom33 == 0:
self.coefficient4 = 0
else: #otherwise calculate the coefficient
self.coefficient4 = int(self.total4 / self.atom33)
'''coefficient4 will be before product 2 coefficient4 is equal to the total number of atoms of the
first element of the product 2 after balancing / total number of atoms of the element before balancing'''
print("coefficient1: " + str(self.coefficient1))
print("coefficient2: " + str(self.coefficient2))
print("coefficient3: " + str(self.coefficient3))
print("coefficient4: " + str(self.coefficient4))
plus1= " + "
new = ",+" #to use it in display
self.answer = "the balance form is: " + str(self.coefficient1)+self.elem1+str(self.atom1)+self.elem2+\
str(self.atom2) + plus1 + str(self.coefficient2)+self.elem3+str(self.atom3)+self.elem4+str(self.atom4)+"=" \
+str(self.coefficient3)+self.elem11+str(self.atom11)+self.elem22+str(self.atom22)+new \
+str(self.coefficient4)+self.elem33+str(self.atom33)+self.elem44+str(self.atom44)
'''self.answer will print out the new chemical reaction after balancing with the new
coefficient placed before each reactant and product as needed'''
if str(self.coefficient4) == '0' :
# if coefficient4 = 0 that means there is no product 2 so we need to remove the second + sign
self.answer= self.answer.replace(new,'') # replace + with empty space.
self.answer= self.answer.replace("0",'')
# if atom = 0 that means empty element no need to display it.
self.answer = self.answer.replace("1", '')
# if the atom or coefficient equal 1 no need to display 1 it's understood.
self.AfterBalancelabel = Label(self.bottomFrame, text= self.answer) # print final answer to the label.
self.AfterBalancelabel.grid(row=15) # place the label
#second function is to calculate MolecularWeight 1 ( for the first reactant)
def MolecularWeight1(self):
element1AtomicMass = 0 # assign 0 to reactant1AtomicMass as initial value.
element2AtomicMass = 0
for self.element , self.AtomicMass in MM_of_Elements.items():
'''MM_of_Elements is a dictionary consist of all chemical elements as a key and their atomic values as a
a value , for example {He : 4.002602, 'Sc': 44.955912, 'Ti': 47.867,}
self.element will return element name and self.AtomicMass will return the atomic mass value
so, we will loop through MM_of_Elements'''
if self.element == self.elem1:
'''if we found element in MM_of_Elements == to element 1 or element 2 in reactant1 we will
add it to variable reactant1AtomicMass'''
element1AtomicMass += self.AtomicMass
print("element name: " , self.elem1, "atomic mass: ", self.AtomicMass)
if self.element == self.elem2:
element2AtomicMass += self.AtomicMass
print("element name: ", self.elem2, "atomic mass: ", self.AtomicMass)
'''after we get the atomic mass for reactant 1 we need to multiply it with the total
atoms values of this reactant to get Molecular_Weight for reactant1'''
self.Molecular_Weight1 = (self.atom1 * element1AtomicMass) +(self.atom2 * element2AtomicMass)
# saving the result in variable self.Molecular_Weight1
reactant = self.elem1 + str(self.atom1) + self.elem2 + str(self.atom2)
print("reactant name:", reactant, "Molecular Weigh: ", self.Molecular_Weight1)
return self.Molecular_Weight1
#return this variable to be used in other functions as needed.
# THIRD function is to calculate MolecularWeight 2 ( for the SECOND reactant)
def MolecularWeight2(self):
element1AtomicMass = 0 # assign 0 to reactant1AtomicMass as initial value.
element2AtomicMass = 0
for self.element, self.AtomicMass in MM_of_Elements.items():
'''MM_of_Elements is a dictionary consist of all chemical
elements as a key and their atomic values as a a value ,
for example {He : 4.002602, 'Sc': 44.955912, 'Ti': 47.867,}
self.element will return element name and self.AtomicMass will return the atomic mass value
so, we will loop through MM_of_Elements'''
if self.element == self.elem3:
'''if we found element in MM_of_Elements == to element 1 or element 2 in reactant2 we will
add it to variable reactant1AtomicMass'''
element1AtomicMass += self.AtomicMass
if self.element == self.elem4:
element2AtomicMass += self.AtomicMass
'''after we get the atomic mass for reactant 2 we need to multiply it with the total
atoms values of this reactant to get Molecular_Weight for reactant2'''
self.Molecular_Weight2 = (self.atom3 * element1AtomicMass) + (self.atom4 * element2AtomicMass)
# saving the result in variable self.Molecular_Weight1
reactant = self.elem3 + str(self.atom3) + self.elem4 + str(self.atom4)
print("reactant name:", reactant, "Molecular Weigh: ", self.Molecular_Weight2)
return self.Molecular_Weight2
# return this variable to be used in other functions as needed.
# FOURTH function is to calculate Mole 1 (mole for reactant with known mass)
def Mole1(self):
'''to calculate the mole for the first reactant we need
to divide the entered mass by MolecularWeight
we will get the mass from self.MassEntry , MolecularWeight
was calculated before so we will just call
the function , if the known mass for reactant 1 we will call
MolecularWeight1 and if the known mass
for reactant 2 we will call MolecularWeight2'''
Mass1 = int(self.MassEntry.get())
if Mass1 <= 0: #to assert that entered mass is greater than 0
messagebox.showerror("Error", "Mass value should be greater than 0 ! ")
if self.elem1 == "" or self.elem3 == "" or self.elem11 == "":
#if the user did not enter correct reactaion format it will not alculate the mass and error massage will show up.
messagebox.showerror("Error", "you should have at least two reactants and one product ")
return
self.choosen = self.combomass.get() # get for which reactant the known mass is
if self.choosen == '1': # if the mass for reactant 1
mw1 = self.MolecularWeight1() # call MolecularWeight1 function and save the result in variable mw1.
self.Mole_1 = Mass1 / mw1 # self.Mole_1 will be equal to division result.
print("Mole1: " , self.Mole_1)
return self.Mole_1 # return the result.
elif self.choosen == '2': # if the mass for reactant 2
mw2 = self.MolecularWeight2() # call MolecularWeight2 function and save the result in variable mw2.
self.Mole_1 = Mass1 / mw2 # self.Mole_1 will be equal to division result.
print("Mole1: " , self.Mole_1)
return self.Mole_1 # return the result.
else: # if user did not chhose a reactant with knawn mass it will arise an error massage.
messagebox.showerror("Error", "you should choose the reactant number first ")
# FIFTH function is to calculate Mole ratio between two reactants.
def Moleratio (self):
''' if the entered reaction is already balanced then the ratio between
coefficient1 and coefficient2
is already 1 because all of them eqaul 1'''
c = self.combomass.get()
if self.balancelabel.cget("text") == "balance": # check if the entered reaction is already balance
if c == '1' or c == '2':
self.ratio = 1
else:
''' if the entered reaction is not balanced then we need to
calculate mole ratio between reactants
mole ratio = coefficient of reactant with unknown mass
/ coefficient of reactant with unknown mass '''
if c == '1':
''' if the user choose c==1 that means the entered mass was
for reactant 1 then the known coefficient
will be for reactant 1 which is equal to coefficient 1 and unknown
coefficient will equal coefficient 2'''
self.ratio = self.coefficient2 / self.coefficient1
elif c == '2':
''' if the user choose c==2 that means the entered mass was for
reactant 2 then the known coefficient
will be for reactant 2 which is equal to coefficient 2 and unknown
coefficient will equal coefficient 2'''
self.ratio = self.coefficient1 / self.coefficient2
print("ratio" , self.ratio)
return self.ratio # return the result.
# SIXTH function is to calculate Mole for the reactant with unknown mas.
def MoleRatioToMole(self):
''' to calculate the mole of the reactant with unknown mass
we need to divide the mole of known mass
by the mole ratio '''
Mole_r1 = self.Mole1() # get the mole of reactant with known mass from self.Mole1() function.
Ratio = self.Moleratio() # get the mole ratio from self.Moleratio() function.
Mole2 = Mole_r1/Ratio # calculate the mole of reactant with unkown mass
print("mol2: ", Mole2)
return Mole2 # return the result.
# LAST function is to calculate mass for the reactant.
def MoleToMass(self):
''' to calculate the mass of the reactant with unknown mass we need to
multyply the mole of that reactant
by its MolecularWeight , if the known mass for reactant 1 we
will call MolecularWeight2 and if the known mass
for reactant 2 we will call MolecularWeight1'''
self.choosen = self.combomass.get() # get for which reactant the known mass is
Mole_r2 = self.MoleRatioToMole() # get the mole value of the reactant
if self.choosen == '1': # if the known mass for reactant 1
# we need the MolecularWeight for reactant with unknown mass so we will need reactant 2 MolecularWeight
mw2 = self.MolecularWeight2() # call MolecularWeight2 function and save the result in variable mw2.
self.FinalMass = Mole_r2 * mw2 # final mass is result of multiplication between mole and MolecularWeight
reactant = self.elem3 + str(self.atom3) + self.elem4 + str(self.atom4) # print reactant name to user
reactant = reactant.replace("0", '') # do not show any 0 in display (if second element does not exist)
reactant = reactant.replace("1", '') # do not show any 0 in display (if number of atoms is 1)
self.Resultlabel['text'] = "The mass value for the reactant" , reactant , "=" , self.FinalMass ,"g"
# print final mass value in self.Resultlabel
elif self.choosen == '2' : # if the known mass for reactant 2
# we need the MolecularWeight for reactant with unknown mass so we will need reactant 1 MolecularWeight
mw1 = self.MolecularWeight1() # call MolecularWeight1 function and save the result in variable mw1.
self.FinalMass = Mole_r2 * mw1 # final mass is result of multiplication between mole and MolecularWeight
reactant = self.elem1 + str(self.atom1) + self.elem2 + str(self.atom2) # print reactant name to user
reactant = reactant.replace("0", '') # do not show any 0 in display (if second element does not exist)
reactant = reactant.replace("1", '') # do not show any 0 in display (if number of atoms is 1)
self.Resultlabel['text'] = "The mass value for the reactant" , reactant + "=" , self.FinalMass ,"g"
print("Final Mass: ", self.FinalMass)
# print final mass value in self.Resultlabel
root = Tk() # this command will create blank window "object" from class Tk(), the name of this window is root.
app = App(root) #call the class
app.IsBalance() # call the function
root.mainloop() # makes the window display until the user close it.
| 04ac1361be1409d8a644f93f91424db0c6d90385 | [
"Python"
] | 1 | Python | deemaalomair1/CAS741project | 74866a8c324943548d7d18439e6d72fcffff085e | c381f5e224b30618b39954dd0575cb0fdd989d02 |
refs/heads/master | <repo_name>aidar-zinnatullin/avito_hobby<file_sep>/Avito_Hobby.R
library(rvest)
library(XML)
library(stringr)
library(RCurl)
library(tidyverse)
library(lubridate)
library(purrr)
############ Working staff
scrape_avito_hobby <- function(html){
hobbies <- read_html(html)
# variables that we're interested in
titles <- html_nodes(hobbies, '.item-description-title')
titles <- html_text(titles)
titles <- unlist(titles)
prices <- html_nodes(hobbies,'.about')
prices <- html_text(prices)
prices <- unlist(prices)
dates <- html_nodes(hobbies,'.data .c-2')
dates <- html_text(dates)
dates <- unlist(dates)
# putting together into a data frame
df <- data.frame(
titles = titles,
prices = prices,
dates = dates,
stringsAsFactors=F)
return(df)
}
avito_hobbies <- list()
avito_hobbies[[1]] <- scrape_avito_hobby(url)
str(avito_hobbies)
base_url <- "https://www.avito.ru/kazan/hobbi_i_otdyh?p="
pages <- seq(1, 100, by=1)
for (i in 1:length(pages)){
# informative message about progress of loop
message(i, '/', length(pages))
# prepare URL
url <- paste(base_url, pages[i], sep="")
# scrape website
avito_hobbies[[i]] <- scrape_avito_hobby(url)
# wait a couple of seconds between URL calls
Sys.sleep(2)
}
avito_hobbies <- do.call(rbind, avito_hobbies)
write.csv(avito_hobbies, "avito_hobbi.csv")
str(avito_hobbies)
df <- read.csv("avito_hobbi.csv")
str(df)
df$prices
df$prices <- gsub("[^0-9\\.]", "", df$prices)
df$prices[df$prices == ""] <- NA
df$prices <- as.numeric(as.character(df$prices))
median(df$prices, na.rm = TRUE)
mean(df$prices, na.rm = T)
which.max(df$prices)
df[944,]
str(df)
tab <- table(df$titles) # frequency table
tab <- sort(tab, decreasing=TRUE) # sorting the table from most to least common
fg <- as.data.frame(tab)
head(tab)
summary(df$prices)
agg <- aggregate(df$prices, by=list(titles=df$title), FUN=mean)
dffff <- agg[order(agg$x, decreasing = T),] # ordering from highest to lowest
dffff[which.max(dffff$x),]
write.csv(dffff, "top_kazan_by_hobbi.csv")
library(wordcloud)
library(tm)
library(wordcloud)
library(RColorBrewer)
library(SnowballC)
corp <- Corpus(VectorSource(df$titles))
corp <- tm_map(corp, removePunctuation)
corp <- tm_map(corp, removeNumbers)
corp <- tm_map(corp, content_transformer(tolower))
corp <- tm_map(corp, removeWords, c("требуется", "без", "для", "на", "из", "по", "за", "не",
"Казань", "казань", "требуются", "магазина", "тц", "работа", "работы"))
corp <- tm_map(corp, stripWhitespace); #inspect(docs[1])
corp <- tm_map(corp, stemDocument)
tdm <- TermDocumentMatrix(corp)
m <- as.matrix(tdm)
v <- sort(rowSums(m),decreasing=TRUE)
d <- data.frame(word = names(v),freq=v, stringsAsFactors = FALSE)
head(d, 10)
wordcloud(words = d$word, freq = d$freq, scale = c(4, .2), min.freq = 1,
max.words=45, random.order=FALSE, rot.per=.35,
colors=brewer.pal(8, "Dark2"))
| 565eda79ce8cc5428b991de4d386ebc14c92345b | [
"R"
] | 1 | R | aidar-zinnatullin/avito_hobby | 8c49cf9f906d9585d113b6a04bc698228ce2434e | 10df3b219ddd6135c9c746656cf1a96ec37dd26f |
refs/heads/master | <file_sep>import React, {useEffect, useCallback} from 'react'
import {ScrollView, View, Text, StyleSheet, Image, Button, Alert} from 'react-native'
import {useDispatch, useSelector} from "react-redux";
import {THEME} from "../theme";
import {HeaderButtons, Item} from "react-navigation-header-buttons";
import {AppHeaderIcon} from "../components/AppHeaderIcon";
import {removePost, toggleBooked} from "../store/actions/post";
export const PostScreen = ({ navigation }) => {
const dispatch = useDispatch();
const postId = navigation.getParam('postId');
const post = useSelector(({post: {allPosts}}) => allPosts.find(({id}) => id === postId));
const booked = useSelector(state => state.post.bookedPosts.some(({id}) => id === postId));
useEffect(() => {
navigation.setParams({ booked })
}, [booked]);
const toggleHandler = useCallback(() => {
dispatch(toggleBooked(post))
}, [dispatch, post]);
useEffect(() => {
navigation.setParams({ toggleHandler })
}, [toggleHandler]);
const removeHandler = () => {
Alert.alert(
'Post removing',
'Are you sure you want to remove this post?',
[
{
text: 'Cancel',
style: 'cancel'
},
{
text: 'Remove',
style: 'destructive',
onPress: () => {
navigation.navigate('Main');
dispatch(removePost(postId))
}
}
],
{ cancelable: false }
)
};
if (!post) {
navigation.navigate('Main');
return null;
}
return (
<View>
<Image source={{uri: post.img}} style={styles.image}/>
<ScrollView style={styles.textWrap}>
<Text>{post.text}</Text>
</ScrollView>
<Button
title='Remove'
color={THEME.DANGER_COLOR}
onPress={removeHandler}
/>
</View>
)
};
PostScreen.navigationOptions = ({ navigation }) => {
const isBooked = navigation.getParam('booked');
const toggleHandler = navigation.getParam('toggleHandler');
const iconName = isBooked ? 'ios-star' : 'ios-star-outline';
return {
headerRight: (
<HeaderButtons HeaderButtonComponent={AppHeaderIcon}>
<Item
title="Take photo"
iconName={iconName}
onPress={toggleHandler}
/>
</HeaderButtons>
),
}
};
const styles = StyleSheet.create({
image: {
width: '100%',
height: 200
},
textWrap: {
padding: 10
}
});
| b2132db160174f8df79a3139da881e30229f5305 | [
"JavaScript"
] | 1 | JavaScript | fokysland/react-native-blog | 88b1d0c0d76707c4212824d4b5d7707bf79c5e03 | 032dc50e1c672a5d6f0c87af29d5039c6adda890 |
refs/heads/master | <repo_name>abhishekd1977/datasciencecoursera<file_sep>/corr.R
###Week#2 Quiz- Part 3###########
corr <- function(directory, threshold = 0){
setwd(directory)
file_list <- list.files()
dataset <- head(read.csv(file_list[1], header = TRUE, sep = ","), n = 0)
for (x in file_list){
dataset <- rbind(dataset, read.csv(x, header = TRUE, sep = ","))
}
cr = dataset[complete.cases(dataset), ]
complete_data_df <- data.frame(table(cr$ID))
colnames(complete_data_df) <- c("id", "nobs")
cor.result <- by(cr[,2:3], cr$ID, function(cr) {cor(cr$sulfate, cr$nitrate)})
cor.result.dataframe <- as.data.frame(as.matrix(cor.result))
colnames(cor.result.dataframe) <- c("cor")
merged.data <- cbind(complete_data_df, cor.result.dataframe)
final.data <- subset(merged.data, nobs > threshold, select = "cor")
final.data[[1]]
}<file_sep>/exploratory-data-analysis/plot1.R
library(dplyr)
setwd("/Users/abhishekdubey/abhishek-git-repos/datasciencecoursera/exploratory-data-analysis")
mydata <- read.csv("household_power_consumption.txt", sep = ";", stringsAsFactors = FALSE, na.strings = "?") %>%
filter(Date %in% c("1/2/2007", "2/2/2007"))
hist(mydata$Global_active_power, col = "red", xlab = "Global Active Power (kilowatts)", main = "Global Active Power")
dev.copy(png, file = "plot1.png")
dev.off()<file_sep>/exploratory-data-analysis/plot2.R
library(dplyr)
setwd("/Users/abhishekdubey/abhishek-git-repos/datasciencecoursera/exploratory-data-analysis")
mydata <- read.csv("household_power_consumption.txt", sep = ";", stringsAsFactors = FALSE, na.strings = "?") %>%
filter(Date %in% c("1/2/2007", "2/2/2007"))
datetime = strptime(with(mydata, paste(Date, Time)), "%d/%m/%Y %H:%M:%S")
mydata$datetime <- datetime
plot(mydata$datetime, mydata$Global_active_power, type = "l", xlab = "", ylab = "Global Active Power (kilowatts)")
dev.copy(png, file = "plot2.png")
dev.off()<file_sep>/getting-and-cleaning-data-course-project/run_analysis.R
#########
library(dplyr)
setwd("/Users/abhishekdubey/abhishek-git-repos/datasciencecoursera/UCI_HAR_Dataset")
##Read features data
features <- read.table(file = "features.txt", header = FALSE, stringsAsFactors = FALSE)
##Read activity labels data
activity_labels <- read.table(file = "activity_labels.txt", header = FALSE, stringsAsFactors = FALSE)
################# TRAIN DATA PROCESSING- START #################################
setwd("/Users/abhishekdubey/abhishek-git-repos/datasciencecoursera/UCI_HAR_Dataset/train")
##Read X_train data. Assign column names to x_train data from features
x_train <- read.table(file = "X_train.txt", header = FALSE, stringsAsFactors = FALSE)
colnames(x_train) <- features[,2]
##Read subject_train data. Assign column names to subject_train data
subject_train <- read.table(file = "subject_train.txt", header = FALSE, stringsAsFactors = FALSE)
colnames(subject_train) <- c("subject")
##Read y_train(activity) data. Merge y_train data with activity_labels data. Assign column names to merged data.
y_train <- read.table(file = "y_train.txt", header = FALSE, stringsAsFactors = FALSE)
y_train <- merge(y_train, activity_labels, by.x = "V1", by.y = "V1")
colnames(y_train) <- c("activity_id", "activity_name")
##Remove columns with duplicate names. This is needed as dplyr SELECT functions gives ERROR with duplicate columns
x_train <- x_train[ !duplicated(names(x_train))]
##Select columns with names containing test "mean" or "std". Filter data upfront.
##Attach subject data
##Attach activity data
##Attach a new column data_type with value="train" for all rows.
x_train <- x_train %>%
select(matches("std|mean")) %>%
cbind(subject_train) %>%
cbind(activity_name = y_train$activity_name)
################# TRAIN DATA PROCESSING- END ###################################
################# TEST DATA PROCESSING- START ##################################
setwd("/Users/abhishekdubey/abhishek-git-repos/datasciencecoursera/UCI_HAR_Dataset/test")
##Read X_test data. Assign column names to x_test data from features
x_test <- read.table(file = "X_test.txt", header = FALSE, stringsAsFactors = FALSE)
colnames(x_test) <- features[,2]
##Read subject_test data. Assign column names to subject_test data
subject_test <- read.table(file = "subject_test.txt", header = FALSE, stringsAsFactors = FALSE)
colnames(subject_test) <- c("subject")
##Read y_test(activity) data. Merge y_test data with activity_labels data. Assign column names to merged data.
y_test <- read.table(file = "y_test.txt", header = FALSE, stringsAsFactors = FALSE)
y_test <- merge(y_test, activity_labels, by.x = "V1", by.y = "V1")
colnames(y_test) <- c("activity_id", "activity_name")
##Remove columns with duplicate names. This is needed as dplyr SELECT functions gives ERROR with duplicate columns
x_test <- x_test[ !duplicated(names(x_test))]
##Select columns with names containing test "mean" or "std". Filter data upfront.
##Attach subject data
##Attach activity data
##Attach a new column data_type with value="train" for all rows.
x_test <- x_test %>%
select(matches("std|mean")) %>%
cbind(subject_test) %>%
cbind(activity_name = y_test$activity_name)
################# TEST DATA PROCESSING- END ####################################
##Merge train and test data
merged_data <- rbind(x_train, x_test)
sprintf("Dimension of merged data is: %s", paste(as.character(dim(merged_data)), collapse = ", "))
#Create a second, independent tidy data set with the average of each variable for each activity and each subject.
final_data <- merged_data %>%
group_by(subject, activity_name) %>%
summarise_each(funs(mean))
setwd("/Users/abhishekdubey/abhishek-git-repos/datasciencecoursera/UCI_HAR_Dataset")
write.table(final_data, file = "tidy-data-set.txt", row.names = FALSE)
sprintf("Dimension of final data is: %s", paste(as.character(dim(final_data)), collapse = ", "))
<file_sep>/pollutantmean.R
###Week#2 Quiz- Part 1###########
pollutantmean <- function(directory, pollutant, id = 1:332) {
setwd(directory)
file_list <- list.files()
dataset <- head(read.csv(file_list[1], header = TRUE, sep = ","), n = 0)
for (x in file_list){
dataset <- rbind(dataset, read.csv(x, header = TRUE, sep = ","))
}
filtered_data <- subset(dataset, ID %in% c(id))
mean(filtered_data[, pollutant], na.rm = TRUE)
}
######Test Cases
##pollutantmean("specdata", "sulfate", 1:10)
## [1] 4.064
##pollutantmean("specdata", "nitrate", 70:72)
## [1] 1.706
##pollutantmean("specdata", "nitrate", 23)
## [1] 1.281<file_sep>/exploratory-data-analysis/course-project-2/course-project-2.R
## Read file
library(dplyr)
library(ggplot2)
setwd("/Users/abhishekdubey/abhishek-git-repos/datasciencecoursera/exploratory-data-analysis/course-project-2")
## This first line will likely take a few seconds. Be patient!
NEI <- readRDS("summarySCC_PM25.rds")
SCC <- readRDS("Source_Classification_Code.rds")
## 1. Have total emissions from PM2.5 decreased in the United States from 1999 to 2008?
## Using the base plotting system, make a plot showing the total PM2.5 emission from all sources for each of the years 1999, 2002, 2005, and 2008.
pm25summary <- select(NEI, year, Emissions) %>% group_by(year) %>% summarize(EmissionsSum = sum(Emissions))
plot(pm25summary$year, pm25summary$EmissionsSum, type = "l", lwd = 2, xlab = "Year", ylab = "Total Emissions Across All Sources")
dev.copy(png, file = "plot1.png")
dev.off()
## 2. Have total emissions from PM2.5 decreased in the Baltimore City, Maryland (fips == "24510") from 1999 to 2008?
## Use the base plotting system to make a plot answering this question.
pm25Baltimore <- filter(NEI, fips == "24510") %>% select(year, Emissions) %>% group_by(year) %>% summarize(EmissionsSum = sum(Emissions))
plot(pm25Baltimore$year, pm25Baltimore$EmissionsSum, type = "l", lwd = 2, xlab = "Year", ylab = "Total Emissions Across All Sources for Baltimore City")
dev.copy(png, file = "plot2.png")
dev.off()
## 3. Of the four types of sources indicated by the type (point, nonpoint, onroad, nonroad) variable,
## which of these four sources have seen decreases in emissions from 1999–2008 for Baltimore City?
## Which have seen increases in emissions from 1999–2008? Use the ggplot2 plotting system to make a plot answer this question.
pm25SumBySources <- select(NEI, year, Emissions, type) %>% group_by(year, type) %>% summarize(EmissionsSum = sum(Emissions))
g <- ggplot(pm25SumBySources, aes(year, EmissionsSum, colour = as.factor(type)))
g + geom_point() + geom_smooth(method="lm", se=FALSE, col="steelblue") + facet_grid(. ~ type)
dev.copy(png, file = "plot3.png")
dev.off()
## 4. Across the United States, how have emissions from coal combustion-related sources changed from 1999–2008?
sectorData <- filter(SCC, EI.Sector %in% c("Fuel Comb - Electric Generation - Coal",
"Fuel Comb - Comm/Institutional - Coal",
"Fuel Comb - Industrial Boilers, ICEs - Coal")) %>% select(SCC, EI.Sector)
pm25summary <- merge(NEI, sectorData, by.x = "SCC", by.y = "SCC") %>% select(year, Emissions, EI.Sector) %>%
group_by(year, EI.Sector) %>% summarize(EmissionsSum = sum(Emissions))
g <- ggplot(pm25summary, aes(year, EmissionsSum, colour = as.factor(EI.Sector)))
g + geom_point() + geom_line(aes(group = EI.Sector))
dev.copy(png, file = "plot4.png")
dev.off()
## 5. How have emissions from motor vehicle sources changed from 1999–2008 in Baltimore City?
sectorDataVehicles <- filter(SCC, EI.Sector %in% c("Mobile - On-Road Gasoline Heavy Duty Vehicles",
"Mobile - On-Road Diesel Light Duty Vehicles",
"Mobile - On-Road Gasoline Light Duty Vehicles",
"Mobile - On-Road Diesel Heavy Duty Vehicles")) %>% select(SCC, EI.Sector)
pm25summary <- merge(NEI, sectorDataVehicles, by.x = "SCC", by.y = "SCC") %>% select(year, Emissions, EI.Sector) %>%
group_by(year, EI.Sector) %>% summarize(EmissionsSum = sum(Emissions))
g <- ggplot(pm25summary, aes(year, EmissionsSum, colour = as.factor(EI.Sector)))
g + geom_point() + geom_line(aes(group = EI.Sector))
dev.copy(png, file = "plot5.png")
dev.off()
## 6. Compare emissions from motor vehicle sources in Baltimore City with emissions from motor vehicle sources in
## Los Angeles County, California (fips == "06037"). Which city has seen greater changes over time in motor vehicle emissions?
sectorDataVehicles <- filter(SCC, EI.Sector %in% c("Mobile - On-Road Gasoline Heavy Duty Vehicles",
"Mobile - On-Road Diesel Light Duty Vehicles",
"Mobile - On-Road Gasoline Light Duty Vehicles",
"Mobile - On-Road Diesel Heavy Duty Vehicles")) %>% select(SCC, EI.Sector)
pm25summary <- merge(NEI, sectorDataVehicles, by.x = "SCC", by.y = "SCC") %>%
filter(fips == "24510" | fips == "06037") %>%
select(year, Emissions, fips) %>%
group_by(year, fips) %>% summarize(EmissionsSum = sum(Emissions))
g <- ggplot(pm25summary, aes(year, EmissionsSum, colour = as.factor(fips)))
g + geom_point() + geom_line(aes(group = fips))
dev.copy(png, file = "plot6.png")
dev.off()
<file_sep>/getting-and-cleaning-data-course-project/CodeBook.md
###Course Project Codebook
####Raw Data and the Program Objective
1. The raw data has been provided in 3 different files- A. The main data with observations. B. The subject data C. The activity data(Only Codes).
2. The activity data needs to be enriched with the activity names, before it can be attached to main file.
3. The 3 files listed above need to be converted to one single file for each of test and train datasets.
4. Once we have one file each for test and train data, then these need to be merged to a single file.
####Tidy data set
1. The tidy dataset has total 88 columns- 86 columns are the observations, one column is subject and one column is activity.
2. I have purposefully filtered the "std" and "mean" columns first (For both test and train datasets), before merging test and train datasets. This is done so that we remove the overhead of unnecessary columns while calling rbind function on 2 datasets.
3. Dimension of final data in file "tidy-data-set.txt" is: (40, 88).
4. The overall code schema and steps have been elaborated in file README.md.
<file_sep>/best.R
best <- function(state, outcome){
setwd("/Users/abhishekdubey/abhishek-git-repos/datasciencecoursera/rprog_data_ProgAssignment3-data")
## Read outcome data
my_df <- read.csv("outcome-of-care-measures.csv", header = TRUE, na.strings = "Not Available", stringsAsFactors = FALSE)
outcomes <- c("heart attack"=11, "heart failure"=17, "pneumonia"=23)
state.names <- my_df[, "State"]
## Check that state and outcome are valid
if (!(outcome %in% names(outcomes)))
stop("invalid outcome")
if (!(state %in% state.names))
stop("invalid state")
## Return hospital name in that state with lowest 30-day death rate
outcome.state <- na.omit(subset(my_df[, c(2,7,outcomes[outcome])], State == state))
outcome.state.ordered <- outcome.state[order(outcome.state[, 3], outcome.state[, 1]), ]
outcome.state.ordered[1, "Hospital.Name"]
}<file_sep>/reproducible-research/course_project_2/rep_research_course_project2.Rmd
---
title: "Reproducible Research: Peer Assessment 2"
output:
html_document:
keep_md: true
---
## Title:
#####Explore the NOAA storm database and detrmine events causing most harm to population health and economic consequences.
## Synopsis:
#####The basic goal of this assignment is to explore the NOAA Storm Database and detrmine which types of events are most harmful to population health and causing greatest economic consequences. This analysis requires calculating a) Total dollar value of damage to property and crop combined by Event type b) Total number of fatalities and injuries combined by Event type. The result of this analysis is represented as top 5 events causing either population health issues or economic consequences. The results have been shown in tabular form and in 2 plots. The results suggest that "Tornado" event is causing highest number of fatalities and Injuries. Highest property damage has been caused by event "Flood", whereas highest crop damage has been caused by event "Hurricane".
## Data Processing
##### As part of data processing, we want to derive summarized values by Event Type for following-
##### Total Fatalities
##### Total Injuries
##### Total Fatalities and Injuries Combined
##### Total Dollar value of Property Damage
##### Total Dollar value of Crop Damage
##### Total Dollar value of Property Damage and Crop Damage Combined
##### Select Top 5 rows for Event Type vs each of above mentioned derived attibutes in descending order
##### Data Processing Steps-
##### 1. Read the csv file using read.csv function.
##### 2. Handle exponent value of PROPDMGEXP and CROPDMGEXP columns.
##### 3. Derive a multipler and store it into a new column in Storm dataset.
##### 4. Use this multiplier to derive total dollar vale of property damage and crop damage. Store these values in 2 separate columns in Storm dataset.
##### 5. Derive total dollar value of property damage and crop damage combined together.
##### 6. Derive total combined value of fatalities and injuries by adding up "FATALITIES" and "INJURIES". Store this value in a new column in Storm dataset.
##### 7. Arrange each of "Total Derived Values" in descending order with respect to Event Type.
```{r}
library(dplyr)
library(ggplot2)
setwd(
"/Users/abhishekdubey/abhishek-git-repos/datasciencecoursera/reproducible-research/course_project_2"
)
stormData <- read.csv(file = "repdata_data_StormData.csv", header = TRUE, stringsAsFactors = FALSE)
```
**Handle exponent value of PROPDMGEXP and CROPDMGEXP columns-<br>**
** These are possible values of CROPDMGEXP and PROPDMGEXP- H,h,K,k,M,m,B,b,+,-,?,0,1,2,3,4,5,6,7,8, and blank-character <br>**
** H,h = hundreds = 100 <br>**
** K,k = kilos = thousands = 1,000 <br>**
** M,m = millions = 1,000,000 <br>**
** B,b = billions = 1,000,000,000 <br>**
** (+) = 1 <br>**
** (-) = 0 <br>**
** (?) = 0 <br>**
** black/empty character = 0 <br>**
** numeric 0..8 = 10 <br>**
**I have defined a new column PROPDMG_CROPDMG_MULTIPLIER in the storm dataset. The value stored in this column is a numeric multiplier based on above mentioned conditions. We will multiply columns PROPDMG and CROPDMG with PROPDMG_CROPDMG_MULTIPLIER to derive the dollar value of "Property Damage" and "Crop Damage" respectively**
```{r}
stormData[stormData$PROPDMGEXP %in% c("-","?",""), "PROPDMG_CROPDMG_MULTIPLIER"] = 0
stormData[stormData$PROPDMGEXP %in% c("+"), "PROPDMG_CROPDMG_MULTIPLIER"] = 1
stormData[stormData$PROPDMGEXP %in% c("0","1","2","3","4","5","6","7","8"), "PROPDMG_CROPDMG_MULTIPLIER"] = 10
stormData[stormData$PROPDMGEXP %in% c("H","h"), "PROPDMG_CROPDMG_MULTIPLIER"] = 100
stormData[stormData$PROPDMGEXP %in% c("K","k"), "PROPDMG_CROPDMG_MULTIPLIER"] = 1000
stormData[stormData$PROPDMGEXP %in% c("M","m"), "PROPDMG_CROPDMG_MULTIPLIER"] = 1000000
stormData[stormData$PROPDMGEXP %in% c("B","b"), "PROPDMG_CROPDMG_MULTIPLIER"] = 1000000000
STORM_DATA_SUMMARIZED <- select(stormData,
EVTYPE,
FATALITIES,
INJURIES,
PROPDMG,
CROPDMG,
PROPDMG_CROPDMG_MULTIPLIER) %>%
mutate(FATALITIES_AND_INJURIES_COMBINED = FATALITIES + INJURIES) %>%
mutate(PROPDMG_DOLLAR_VALUE = PROPDMG*PROPDMG_CROPDMG_MULTIPLIER) %>%
mutate(CROPDMG_DOLLAR_VALUE = CROPDMG*PROPDMG_CROPDMG_MULTIPLIER) %>%
mutate(DOLLAR_VALUE_FOR_PROP_AND_CROP_DAMAGE_COMBINED =
PROPDMG_DOLLAR_VALUE + CROPDMG_DOLLAR_VALUE) %>%
select(EVTYPE,
FATALITIES,
INJURIES,
FATALITIES_AND_INJURIES_COMBINED,
PROPDMG_DOLLAR_VALUE,
CROPDMG_DOLLAR_VALUE,
DOLLAR_VALUE_FOR_PROP_AND_CROP_DAMAGE_COMBINED) %>%
group_by(EVTYPE) %>%
summarize(TOTAL_FATALITIES = sum(FATALITIES),
TOTAL_INJURIES = sum(INJURIES),
TOTAL_FATALITIES_AND_INJURIES =
sum(FATALITIES_AND_INJURIES_COMBINED),
TOTAL_PROPDMG_DOLLAR_VALUE = sum(PROPDMG_DOLLAR_VALUE),
TOTAL_CROPDMG_DOLLAR_VALUE = sum(CROPDMG_DOLLAR_VALUE),
TOTAL_DOLLAR_VALUE_FOR_PROP_AND_CROP_DAMAGE =
sum(DOLLAR_VALUE_FOR_PROP_AND_CROP_DAMAGE_COMBINED)
) %>%
select(
EVTYPE,
TOTAL_FATALITIES,
TOTAL_INJURIES,
TOTAL_FATALITIES_AND_INJURIES,
TOTAL_PROPDMG_DOLLAR_VALUE,
TOTAL_CROPDMG_DOLLAR_VALUE,
TOTAL_DOLLAR_VALUE_FOR_PROP_AND_CROP_DAMAGE
)
STORM_DATA_TOP5_FATALITIES <- STORM_DATA_SUMMARIZED %>%
select(EVTYPE, TOTAL_FATALITIES) %>%
arrange(desc(TOTAL_FATALITIES)) %>%
top_n(5)
STORM_DATA_TOP5_INJURIES <- STORM_DATA_SUMMARIZED %>%
select(EVTYPE, TOTAL_INJURIES) %>%
arrange(desc(TOTAL_INJURIES)) %>%
top_n(5)
STORM_DATA_TOP5_FATALITIES_AND_INJURIES_COMBINED <- STORM_DATA_SUMMARIZED %>%
select(EVTYPE, TOTAL_FATALITIES_AND_INJURIES) %>%
arrange(desc(TOTAL_FATALITIES_AND_INJURIES)) %>%
top_n(5)
STORM_DATA_TOP5_PROPDMG_DOLLAR_VALUE <- STORM_DATA_SUMMARIZED %>%
select(EVTYPE, TOTAL_PROPDMG_DOLLAR_VALUE) %>%
arrange(desc(TOTAL_PROPDMG_DOLLAR_VALUE)) %>%
top_n(5)
STORM_DATA_TOP5_CROPDMG_DOLLAR_VALUE <- STORM_DATA_SUMMARIZED %>%
select(EVTYPE, TOTAL_CROPDMG_DOLLAR_VALUE) %>%
arrange(desc(TOTAL_CROPDMG_DOLLAR_VALUE)) %>%
top_n(5)
STORM_DATA_TOP5_PROP_AND_CROP_DAMAGE_COMBINED <- STORM_DATA_SUMMARIZED %>%
select(EVTYPE, TOTAL_DOLLAR_VALUE_FOR_PROP_AND_CROP_DAMAGE) %>%
arrange(desc(TOTAL_DOLLAR_VALUE_FOR_PROP_AND_CROP_DAMAGE)) %>%
top_n(5)
```
## Results
##### Top 5 Fatalities by Event Type
```{r}
STORM_DATA_TOP5_FATALITIES
```
##### Top 5 Injuries by Event Type
```{r}
STORM_DATA_TOP5_INJURIES
```
##### Top 5 Fatalities and Injuries Combined by Event Type
```{r}
STORM_DATA_TOP5_FATALITIES_AND_INJURIES_COMBINED
g <- ggplot(STORM_DATA_TOP5_FATALITIES_AND_INJURIES_COMBINED, aes(EVTYPE, log(TOTAL_FATALITIES_AND_INJURIES)))
g + geom_point() + geom_line() + labs(x = "Event Type") + labs(y = "log(Total Fatalities and Injuries)") + labs(title = "Top 5 Fatalities and Injuries by Event Type")
```
##### Top 5 Property Damage in Dollar Value by Event Type
```{r}
STORM_DATA_TOP5_PROPDMG_DOLLAR_VALUE
```
##### Top 5 Crop Damage in Dollar Value by Event Type
```{r}
STORM_DATA_TOP5_CROPDMG_DOLLAR_VALUE
```
##### Top 5 Property and Crop Damage Combined in Dollar Value by Event Type
```{r}
STORM_DATA_TOP5_PROP_AND_CROP_DAMAGE_COMBINED
g <- ggplot(STORM_DATA_TOP5_PROP_AND_CROP_DAMAGE_COMBINED, aes(EVTYPE, log(TOTAL_DOLLAR_VALUE_FOR_PROP_AND_CROP_DAMAGE)))
g + geom_point() + geom_line() + labs(x = "Event Type") + labs(y = "log(Total Dollar value of Property and Crop Damage Combined)") + labs(title = "Top 5 Dollar value of Property and Crop Damage by Event Type")
```
####Results Summary
##### 1. "Tornado" event is causing highest number of fatalities and Injuries.
##### 2. Highest property damage has been caused by event "Flood".
##### 3. Highest crop damage has been caused by event "Hurricane".
##### 4. Highest property and crop damage combined has been caused by event "Hurricane".
<file_sep>/complete.R
###Week#2 Quiz- Part 2###########
complete <- function(directory, id = 1:332){
setwd(directory)
file_list <- list.files()
dataset <- head(read.csv(file_list[1], header = TRUE, sep = ","), n = 0)
for (x in file_list){
dataset <- rbind(dataset, read.csv(x, header = TRUE, sep = ","))
}
filtered_data <- subset(dataset, ID %in% c(id))
complete_data = filtered_data[complete.cases(filtered_data), ]
complete_data_df <- data.frame(table(complete_data$ID))
colnames(complete_data_df) <- c("id", "nobs")
complete_data_df
}
#######Test Cases
#> complete("/Users/abhishekdubey/abhishek-git-repos/datasciencecoursera/specdata",1)
#id nobs
#1 1 117
##This test case did not pass. The expected output should be ordered as 30, 29....25
#> complete("/Users/abhishekdubey/abhishek-git-repos/datasciencecoursera/specdata",30:25)
#id nobs
#1 25 463
#2 26 586
#3 27 338
#4 28 475
#5 29 711
#6 30 932
<file_sep>/exploratory-data-analysis/plot4.R
library(dplyr)
setwd("/Users/abhishekdubey/abhishek-git-repos/datasciencecoursera/exploratory-data-analysis")
mydata <- read.csv("household_power_consumption.txt", sep = ";", stringsAsFactors = FALSE, na.strings = "?") %>%
filter(Date %in% c("1/2/2007", "2/2/2007"))
datetime = strptime(with(mydata, paste(Date, Time)), "%d/%m/%Y %H:%M:%S")
mydata$datetime <- datetime
par(mfrow = c(2, 2), mar = c(5, 4, 2, 1))
plot(mydata$datetime, mydata$Global_active_power, type = "l", xlab = "", ylab = "Global Active Power")
plot(mydata$datetime, mydata$Voltage, type = "l", xlab = "datetime", ylab = "Voltage")
plot(mydata$datetime, mydata$Sub_metering_1, type = "l", xlab = "", ylab = "Energy sub metering")
points(mydata$datetime, mydata$Sub_metering_2, type = "l", col = "red")
points(mydata$datetime, mydata$Sub_metering_3, type = "l", col = "blue")
legend("top", col = c("black", "red", "blue"), legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), lty = 1, bty = "n", cex = 0.8)
plot(mydata$datetime, mydata$Global_reactive_power, type = "l", xlab = "datetime", ylab = "Global_reactive_power")
dev.copy(png, file = "plot4.png")
dev.off()<file_sep>/getting-and-cleaning-data-course-project/README.md
###Steps in run_analysis.R
1. Read features data file into a data frame
2. Read activity labels data into a data frame
#### Perform step 1 through 7 first for train data and then for test data.
1. Read X_train data. Assign column names to x_train data from features
2. Read subject_train data. Assign column names to subject_train data
3. Read y_train(activity) data. Merge y_train data with activity_labels data. Assign column names to merged data.
4. Remove columns with duplicate names from x_trains data. This is needed as dplyr SELECT functions gives ERROR with duplicate columns
5. Select columns with names containing "mean" or "std" from x_trains data. Filter data upfront.
6. Attach subject data to x_trains data.
7. Attach activity data to x_trains data.
####Merge test and train datasets and write to a text file
1. Merge train and test data
2. Create a second, independent tidy data set with the average of each variable for each activity and each subject.
3. Write the independent tidy data set to a text file named as "tidy-data-set.txt"
###Important features about the program and output
1. I have purposefully filtered the "std" and "mean" columns first (For both test and train datasets), before merging test and train datasets. This is done so that we remove the overhead of unnecessary columns while calling rbind function on 2 datasets.
2. After filtering columns, dimension of x_train data is: (7352, 88).
3. After filtering columns, dimension of x_test data is: (2947, 88).
4. Dimension of merged data is: (10299, 88).
5. Dimension of final data in file "tidy-data-set.txt" is: (40, 88).
<file_sep>/cachematrix.R
## Put comments here that give an overall description of what your
## functions do
## Write a short comment describing this function
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
setInverse <- function(inverseMatrix) m <<- inverseMatrix
getInverse <- function() m
list(set = set, get = get,
setInverse = setInverse,
getInverse = getInverse)
}
## Write a short comment describing this function
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
## If the inverse has already been calculated (and the matrix has not changed),
## then the cachesolve should retrieve the inverse from the cache.
## One way to find out if matrix is not changed is to multiply it by it's inverse.
## If the result is an Identity matrix (1,0,0,1), then matrix has not changed.
## First create an identity matrix
identityMatrix <- matrix(c(1,0,0,1), nrow = 2, ncol = 2)
m <- x$getInverse()
##This is a two step check in "if" block-
##Step 1: Check if inverseMatrix is not null.
##Step 2: If step 1) is true, check if multiplication of
## input matrix and its inverse matrix is an Identity Matrix
## If both of above is true, then return the Inverse value from "Cache"
## If Inverse Matrix value is null or input matrix has changed, then calculate the inverse value.
if(!is.null(m)) {
n <- x$get()
##Multiply input matrix with its inverse.
result <- m %*% n
##If output of multiplication is Identity Matrix, then it means that input matrix has not changed
if(all.equal(result, identityMatrix)){
message("result == identityMatrix")
message("getting cached data")
return(m)
}
}
data <- x$get()
m <- solve(data, ...)
x$setInverse(m)
m
}
######### How to test the program#######
########### 1st Test Run[Same Matrix]- Data must NOT come from cache##############
##> yy <- makeCacheMatrix(matrix(1:4, nrow = 2, ncol = 2))
##> cacheSolve(yy)
##[,1] [,2]
##$[1,] -2 1.5
##[2,] 1 -0.5
########### 2nd Test Run[Same Matrix]- Data MUST come from cache##############
##> cacheSolve(yy)
##result == identityMatrix
##getting cached data
##[,1] [,2]
##[1,] -2 1.5
##[2,] 1 -0.5
########### 3rd Test Run[Matrix has CHANGED now]- Data must NOT come from cache##############
##> yy <- makeCacheMatrix(matrix(5:8, nrow = 2, ncol = 2))
##> cacheSolve(yy)
##[,1] [,2]
##[1,] -4 3.5
##[2,] 3 -2.5
########### 4th Test Run[Same matrix as Test Case#3]- Data MUST come from cache##############
##> cacheSolve(yy)
##result == identityMatrix
##getting cached data
##[,1] [,2]
##[1,] -4 3.5
##[2,] 3 -2.5
| c3898d5ed158885d757d384d6ea0c3dfc4dc57d1 | [
"Markdown",
"R",
"RMarkdown"
] | 13 | R | abhishekd1977/datasciencecoursera | 1d77610acf8b010e63359b4348d0cbafc7d427a1 | ca8b9ea1e830a13034faf88e58477e776e1c8ad6 |
refs/heads/master | <repo_name>sothebys/awesome-phonenumber<file_sep>/benchmark/test.js
var libs = {
'awesome-phonenumber': function( ) {
var mem1 = process.memoryUsage( );
var time1 = Date.now( );
var PhoneNumber = require( 'awesome-phonenumber' );
var time2 = Date.now( );
PhoneNumber( '0707123456', 'SE' ).getNumber( );
var time3 = Date.now( );
PhoneNumber( '0707123457', 'SE' ).getNumber( );
var time4 = Date.now( );
var mem2 = process.memoryUsage( );
return [ time2 - time1, time3 - time2, time4 - time3, mem2.rss - mem1.rss ];
},
'google-libphonenumber': function( ) {
var mem1 = process.memoryUsage( );
var time1 = Date.now( );
var PNF = require('google-libphonenumber').PhoneNumberFormat;
var phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();
var time2 = Date.now( );
var phoneNumber = phoneUtil.parse('0707123456', 'SE');
phoneUtil.format(phoneNumber, PNF.INTERNATIONAL);
var time3 = Date.now( );
var phoneNumber = phoneUtil.parse('0707123457', 'SE');
phoneUtil.format(phoneNumber, PNF.INTERNATIONAL);
var time4 = Date.now( );
var mem2 = process.memoryUsage( );
return [ time2 - time1, time3 - time2, time4 - time3, mem2.rss - mem1.rss ];
},
'node-phonenumber': function( ) {
var mem1 = process.memoryUsage( );
var time1 = Date.now( );
var phone = require('node-phonenumber');
var phoneUtil = phone.PhoneNumberUtil.getInstance();
var time2 = Date.now( );
var phoneNumber = phoneUtil.parse('0707123456','SE');
var toNumber = phoneUtil.format(phoneNumber, phone.PhoneNumberFormat.INTERNATIONAL);
var time3 = Date.now( );
var phoneNumber = phoneUtil.parse('0707123457','SE');
var toNumber = phoneUtil.format(phoneNumber, phone.PhoneNumberFormat.INTERNATIONAL);
var time4 = Date.now( );
var mem2 = process.memoryUsage( );
return [ time2 - time1, time3 - time2, time4 - time3, mem2.rss - mem1.rss ];
}
};
console.log( libs[ process.argv[ 2 ] ]( ) );
<file_sep>/test.in/awesome-phonenumber/should-compile.ts
'use strict';
import 'mocha';
import { expect } from 'chai';
import PhoneNumber from '../../';
describe('general', function () {
it('should be able to parse a phone number', function () {
var pn = new PhoneNumber('0707123456', 'SE');
expect(pn.isValid()).to.be.true;
expect(pn.isPossible()).to.be.true;
expect(pn.isMobile()).to.be.true;
expect(pn.getNumber('significant')).to.equal('707123456');
expect(pn.canBeInternationallyDialled()).to.equal(true);
expect(pn.toJSON().canBeInternationallyDialled).to.equal(true);
});
it('should be able to create an example phone number', function () {
var pn1 = PhoneNumber.getExample('SE');
expect(pn1.isValid()).to.be.true;
expect(pn1.isPossible()).to.be.true;
var pn2 = PhoneNumber.getExample('SE', 'mobile');
expect(pn2.isValid()).to.be.true;
expect(pn2.isPossible()).to.be.true;
expect(pn2.isMobile()).to.be.true;
expect(pn2.isFixedLine()).to.be.false;
var pn3 = PhoneNumber.getExample('SE', 'fixed-line');
expect(pn3.isValid()).to.be.true;
expect(pn3.isPossible()).to.be.true;
expect(pn3.isMobile()).to.be.false;
expect(pn3.isFixedLine()).to.be.true;
});
it('should be able to format as-you-type', function () {
var ayt = PhoneNumber.getAsYouType('SE');
expect(ayt.addChar('0')).to.equal('0');
expect(ayt.addChar('7')).to.equal('07');
expect(ayt.addChar('0')).to.equal('070');
expect(ayt.addChar('7')).to.equal('070-7');
expect(ayt.addChar('1')).to.equal('070-71');
expect(ayt.addChar('2')).to.equal('070-712');
var pn1 = ayt.getPhoneNumber();
expect(pn1.isValid()).to.be.false;
expect(ayt.addChar('3')).to.equal('070-712 3');
expect(ayt.addChar('4')).to.equal('070-712 34');
expect(ayt.addChar('5')).to.equal('070-712 34 5');
expect(ayt.addChar('6')).to.equal('070-712 34 56');
var pn2 = ayt.getPhoneNumber();
expect(pn2.isValid()).to.be.true;
expect(pn2.isPossible()).to.be.true;
});
it('should be able to convert country code <-> region code', function () {
expect(PhoneNumber.getCountryCodeForRegionCode('SE')).to.equal(46);
expect(PhoneNumber.getRegionCodeForCountryCode(46)).to.equal('SE');
});
it('should be possible to get region code', function () {
var pn = new PhoneNumber('0707123456', 'SE');
expect(pn.getRegionCode()).to.equal('SE');
});
it('should be possible to get the length of geographical area code', function () {
var pn1 = new PhoneNumber('+256481412345');
var pn2 = new PhoneNumber('+256414555555');
expect(pn1.getLengthOfGeographicalAreaCode()).to.equal(3);
expect(pn2.getLengthOfGeographicalAreaCode()).to.equal(2);
});
it('should have supported calling codes', function () {
const codes = PhoneNumber.getSupportedCallingCodes();
expect(codes.length).to.be.above(100);
});
it('should not guess US for invalid region code numbers', function () {
const pn = new PhoneNumber('+80012345678');
expect(pn.getRegionCode()).to.not.equal('US');
});
it('should not guess US for known CA numbers', function () {
const pn = new PhoneNumber('+1613 734.6759', 'CA');
expect(pn.getRegionCode()).to.equal('CA');
});
});
describe('errors', function () {
it('should handle invalid country code', function () {
var pn = new PhoneNumber('+0123');
expect(pn.isValid()).to.be.false;
expect(pn.isPossible()).to.be.false;
expect(pn.toJSON().possibility).to.equal('invalid-country-code');
});
it('should handle invalid country code (and valid region code)', function () {
var pn = new PhoneNumber('+0123', 'SE');
expect(pn.isValid()).to.be.false;
expect(pn.isPossible()).to.be.false;
expect(pn.toJSON().possibility).to.equal('invalid-country-code');
});
it('should handle invalid country code and region code', function () {
var pn = new PhoneNumber('0123', 'XX');
expect(pn.isValid()).to.be.false;
expect(pn.isPossible()).to.be.false;
expect(pn.toJSON().possibility).to.equal('invalid-country-code');
});
it('should handle missing country code', function () {
var pn = new PhoneNumber('0123');
expect(pn.isValid()).to.be.false;
expect(pn.isPossible()).to.be.false;
expect(pn.toJSON().possibility).to.equal('invalid-country-code');
});
it('should handle TOO_SHORT', function () {
var pn = new PhoneNumber('0123', 'SE');
expect(pn.isValid()).to.be.false;
expect(pn.isPossible()).to.be.false;
expect(pn.toJSON().possibility).to.equal('too-short');
});
});
<file_sep>/index.d.ts
declare namespace AwesomePhonenumber {
type PhoneNumberFormat =
'e164' |
'international' |
'national' |
'rfc3966' |
'significant';
type PhoneNumberTypes =
'fixed-line' |
'fixed-line-or-mobile' |
'mobile' |
'pager' |
'personal-number' |
'premium-rate' |
'shared-cost' |
'toll-free' |
'uan' |
'voip' |
'unknown';
class PhoneNumber {
constructor(phoneNumber: string, countryCode?: string);
isValid(): boolean;
canBeInternationallyDialled(): boolean;
getLengthOfGeographicalAreaCode(): number;
isPossible(): boolean;
getType(): PhoneNumberTypes;
isMobile(): boolean;
isFixedLine(): boolean;
getNumber(type?: PhoneNumberFormat): string;
getNumberFrom(regionCode: string): string;
getRegionCode(): string;
toJSON(): any;
static getCountryCodeForRegionCode(regionCode: string): number;
static getRegionCodeForCountryCode(countryCode: number): string;
static getSupportedCallingCodes(): string[];
static getExample(regionCode: string, type?: PhoneNumberTypes): PhoneNumber;
static getAsYouType(regionCode: string): AsYouType;
}
class AsYouType {
addChar(char: string): string;
number(): string;
removeChar(): string;
reset(number?: string): string;
getPhoneNumber(): PhoneNumber;
}
}
export default AwesomePhonenumber.PhoneNumber;
<file_sep>/src/index.js
'use strict';
goog.require('i18n.phonenumbers.AsYouTypeFormatter');
goog.require('i18n.phonenumbers.PhoneNumberFormat');
goog.require('i18n.phonenumbers.PhoneNumberType');
goog.require('i18n.phonenumbers.PhoneNumberUtil');
goog.require('i18n.phonenumbers.PhoneNumberUtil.ValidationResult');
var PhoneNumberType = i18n.phonenumbers.PhoneNumberType;
var PhoneNumberFormat = i18n.phonenumbers.PhoneNumberFormat;
var ValidationResult = i18n.phonenumbers.PhoneNumberUtil.ValidationResult;
var phoneUtil = i18n.phonenumbers.PhoneNumberUtil.getInstance();
function getNumberType(number) {
switch (phoneUtil.getNumberType(number)) {
case PhoneNumberType.FIXED_LINE: return 'fixed-line';
case PhoneNumberType.FIXED_LINE_OR_MOBILE: return 'fixed-line-or-mobile';
case PhoneNumberType.MOBILE: return 'mobile';
case PhoneNumberType.PAGER: return 'pager';
case PhoneNumberType.PERSONAL_NUMBER: return 'personal-number';
case PhoneNumberType.PREMIUM_RATE: return 'premium-rate';
case PhoneNumberType.SHARED_COST: return 'shared-cost';
case PhoneNumberType.TOLL_FREE: return 'toll-free';
case PhoneNumberType.UAN: return 'uan';
case PhoneNumberType.VOIP: return 'voip';
default:
case PhoneNumberType.UNKNOWN: return 'unknown';
}
}
function toNumberType(exportedName) {
switch (exportedName) {
case 'fixed-line': return PhoneNumberType.FIXED_LINE;
case 'fixed-line-or-mobile': return PhoneNumberType.FIXED_LINE_OR_MOBILE;
case 'mobile': return PhoneNumberType.MOBILE;
case 'pager': return PhoneNumberType.PAGER;
case 'personal-number': return PhoneNumberType.PERSONAL_NUMBER;
case 'premium-rate': return PhoneNumberType.PREMIUM_RATE;
case 'shared-cost': return PhoneNumberType.SHARED_COST;
case 'toll-free': return PhoneNumberType.TOLL_FREE;
case 'uan': return PhoneNumberType.UAN;
case 'voip': return PhoneNumberType.VOIP;
default:
case 'unknown': return PhoneNumberType.UNKNOWN;
}
}
function getValidationResult(number) {
try {
switch (phoneUtil.isPossibleNumberWithReason(number)) {
case ValidationResult.IS_POSSIBLE: return 'is-possible';
case ValidationResult.INVALID_COUNTRY_CODE: return 'invalid-country-code';
case ValidationResult.TOO_LONG: return 'too-long';
case ValidationResult.TOO_SHORT: return 'too-short';
}
if (phoneUtil.isPossibleNumber(number))
return 'is-possible';
} catch (err) { }
return 'unknown';
}
function extractRegionCode(phoneNumber) {
if (phoneNumber.charAt(0) !== '+' || phoneNumber.length < 5)
return null;
var firstOne = phoneNumber.substr(1, 1);
var firstTwo = phoneNumber.substr(1, 2);
var firstThree = phoneNumber.substr(1, 3);
var regionCode;
regionCode = PhoneNumber.getRegionCodeForCountryCode(firstOne);
if (regionCode !== 'ZZ')
return regionCode;
regionCode = PhoneNumber.getRegionCodeForCountryCode(firstTwo);
if (regionCode !== 'ZZ')
return regionCode;
regionCode = PhoneNumber.getRegionCodeForCountryCode(firstThree);
if (regionCode !== 'ZZ')
return regionCode;
return null;
}
/**
* The PhoneNumber class.
* @constructor
*/
function PhoneNumber(phoneNumber, regionCode) {
if (!(this instanceof PhoneNumber))
return new PhoneNumber(phoneNumber, regionCode);
var self = this;
var isInternal =
typeof phoneNumber === 'string'
? false
: function () {
try {
phoneUtil.isValidNumber(phoneNumber);
return true
}
catch (e) {
return false;
}
}();
if (!isInternal) {
if (regionCode && (phoneNumber.charAt(0) === '+')) {
// Ensure region code is valid
var cc = PhoneNumber.getCountryCodeForRegionCode(regionCode);
if (phoneNumber.substr(1, ('' + cc).length) !== '' + cc)
// Wrong region code, let's fix it
regionCode = null;
}
if (!regionCode)
// Guess region code
regionCode = extractRegionCode(phoneNumber);
}
this._json = {
'number': {},
'regionCode': regionCode,
'valid': false,
'possible': false
};
if (isInternal) {
this._number = phoneNumber;
}
else {
this._number = null;
this._json['number']['input'] = phoneNumber;
if (!regionCode) {
this._json['possibility'] = 'invalid-country-code';
return;
}
else {
var cc = PhoneNumber.getCountryCodeForRegionCode(regionCode);
if (cc === 0) {
this._json['possibility'] = 'invalid-country-code';
return;
}
}
try {
this._number = phoneUtil.parse(phoneNumber, regionCode);
}
catch (e) {
this._json['possibility'] = getValidationResult(phoneNumber);
return;
}
}
this._json['number']['international'] =
phoneUtil.format(this._number, PhoneNumberFormat.INTERNATIONAL);
this._json['number']['national'] =
phoneUtil.format(this._number, PhoneNumberFormat.NATIONAL);
this._json['number']['e164'] =
phoneUtil.format(this._number, PhoneNumberFormat.E164);
this._json['number']['rfc3966'] =
phoneUtil.format(this._number, PhoneNumberFormat.RFC3966);
this._json['number']['significant'] =
phoneUtil.getNationalSignificantNumber(this._number);
this._json['canBeInternationallyDialled'] =
phoneUtil.canBeInternationallyDialled(this._number);
this._json['getLengthOfGeographicalAreaCode'] =
phoneUtil.getLengthOfGeographicalAreaCode(this._number);
this._json['possible'] = phoneUtil.isPossibleNumber(this._number);
this._json['valid'] = phoneUtil.isValidNumber(this._number);
this._json['type'] = getNumberType(self._number);
this._json['possibility'] = getValidationResult(self._number);
}
PhoneNumber.getCountryCodeForRegionCode = function (regionCode) {
return phoneUtil.getCountryCodeForRegion(regionCode);
}
PhoneNumber.getRegionCodeForCountryCode = function (countryCode) {
var regionCode = phoneUtil.getRegionCodeForCountryCode(countryCode);
return regionCode;
}
PhoneNumber.getSupportedCallingCodes = function () {
return phoneUtil.getSupportedCallingCodes();
}
PhoneNumber.getExample = function (regionCode, type /* = null */) {
var example;
if (!type)
example = phoneUtil.getExampleNumber(regionCode);
else
example = phoneUtil.getExampleNumberForType(
regionCode, toNumberType(type));
return new PhoneNumber(example, regionCode);
}
PhoneNumber.getAsYouType = function (regionCode) {
return new AsYouType(regionCode);
}
PhoneNumber.prototype.toJSON = function () {
return this._json;
}
PhoneNumber.prototype.canBeInternationallyDialled = function () {
return this._json['canBeInternationallyDialled'];
}
PhoneNumber.prototype.getLengthOfGeographicalAreaCode = function () {
return this._json['getLengthOfGeographicalAreaCode'];
}
PhoneNumber.prototype.isValid = function () {
return this._json['valid'];
}
PhoneNumber.prototype.isPossible = function () {
return this._json['possible'];
}
PhoneNumber.prototype.getType = function () {
return this._json['type'];
}
PhoneNumber.prototype.isMobile = function () {
return this._json['type'] === 'mobile'
|| this._json['type'] === 'fixed-line-or-mobile';
}
PhoneNumber.prototype.isFixedLine = function () {
return this._json['type'] === 'fixed-line'
|| this._json['type'] === 'fixed-line-or-mobile';
}
/**
* The type can be any of 'international', 'national', 'e164', 'rfc3966',
* 'significant'.
*/
PhoneNumber.prototype.getNumber = function (type /* = e164 */) {
type = type == null ? 'e164' : type;
return this._json['number'][type];
}
PhoneNumber.prototype.getNumberFrom = function (regionCode) {
return phoneUtil.formatOutOfCountryCallingNumber(this._number, regionCode);
}
PhoneNumber.prototype.getRegionCode = function () {
return this._json['regionCode'];
}
/**
* The AsYouType class.
* @constructor
*/
function AsYouType(regionCode) {
this._regionCode = regionCode;
this._aytf = new i18n.phonenumbers.AsYouTypeFormatter(regionCode);
this._number = '';
}
AsYouType.prototype.addChar = function (nextChar) {
this._number = this._aytf.inputDigit(nextChar);
return this._number;
}
AsYouType.prototype.number = function () {
return this._number;
}
AsYouType.prototype.removeChar = function () {
var number = this._number;
if (number.length > 0)
this.reset(number.substr(0, number.length - 1));
return this._number;
}
AsYouType.prototype.reset = function (number /* = '' */) {
this._aytf.clear();
if (number)
for (var i = 0, n = number.length; i < n; ++i)
this.addChar(number.charAt(i));
return this._number;
}
AsYouType.prototype.getPhoneNumber = function () {
return new PhoneNumber(this._number, this._regionCode);
}
goog.global =
(typeof exports !== 'undefined')
? exports
: (typeof self !== 'undefined')
? self
: window;
goog.exportSymbol('PhoneNumber', PhoneNumber);
goog.exportSymbol('PhoneNumber.getCountryCodeForRegionCode',
PhoneNumber.getCountryCodeForRegionCode);
goog.exportSymbol('PhoneNumber.getRegionCodeForCountryCode',
PhoneNumber.getRegionCodeForCountryCode);
goog.exportSymbol('PhoneNumber.getSupportedCallingCodes',
PhoneNumber.getSupportedCallingCodes);
goog.exportSymbol('PhoneNumber.getExample',
PhoneNumber.getExample);
goog.exportSymbol('PhoneNumber.getAsYouType',
PhoneNumber.getAsYouType);
goog.exportSymbol('PhoneNumber.prototype.toJSON',
PhoneNumber.prototype.toJSON);
goog.exportSymbol('PhoneNumber.prototype.canBeInternationallyDialled',
PhoneNumber.prototype.canBeInternationallyDialled);
goog.exportSymbol('PhoneNumber.prototype.getLengthOfGeographicalAreaCode',
PhoneNumber.prototype.getLengthOfGeographicalAreaCode);
goog.exportSymbol('PhoneNumber.prototype.isValid',
PhoneNumber.prototype.isValid);
goog.exportSymbol('PhoneNumber.prototype.isPossible',
PhoneNumber.prototype.isPossible);
goog.exportSymbol('PhoneNumber.prototype.getType',
PhoneNumber.prototype.getType);
goog.exportSymbol('PhoneNumber.prototype.isMobile',
PhoneNumber.prototype.isMobile);
goog.exportSymbol('PhoneNumber.prototype.isFixedLine',
PhoneNumber.prototype.isFixedLine);
goog.exportSymbol('PhoneNumber.prototype.getNumber',
PhoneNumber.prototype.getNumber);
goog.exportSymbol('PhoneNumber.prototype.getNumberFrom',
PhoneNumber.prototype.getNumberFrom);
goog.exportSymbol('PhoneNumber.prototype.getRegionCode',
PhoneNumber.prototype.getRegionCode);
goog.exportSymbol('AsYouType', AsYouType);
goog.exportSymbol('AsYouType.prototype.addChar',
AsYouType.prototype.addChar);
goog.exportSymbol('AsYouType.prototype.number',
AsYouType.prototype.number);
goog.exportSymbol('AsYouType.prototype.removeChar',
AsYouType.prototype.removeChar);
goog.exportSymbol('AsYouType.prototype.reset',
AsYouType.prototype.reset);
goog.exportSymbol('AsYouType.prototype.getPhoneNumber',
AsYouType.prototype.getPhoneNumber);
| b923044fd381666e40fa39b569696b18237d80da | [
"JavaScript",
"TypeScript"
] | 4 | JavaScript | sothebys/awesome-phonenumber | b95a9ef5f630c143d2cf62a789c376b8f38635b7 | fae8ab57bc9844774bead5511d54d5a0974d2bce |
refs/heads/main | <file_sep>#include <iostream>
#include <vector>
#include <stdlib.h>
#include "winCheck.h"
// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using namespace std;
//void checkAnswer(bool result);
void winCheck:: wordFinder(char letter,string word)
{
vector< int > arr;
const char searchChar = letter; //letter to find
size_t instanceFinder = word.find (searchChar, 0); //first instance of letter
if(instanceFinder != string::npos){
//push back if it is not the letter
arr.push_back(instanceFinder);
}
while (instanceFinder != string::npos)
{
//this searches for the next character using wordfiner
size_t nCharSearchOffset = instanceFinder + 1;
instanceFinder = word.find(searchChar,nCharSearchOffset);
if(instanceFinder != string::npos){
arr.push_back(instanceFinder);
}
}
// if the size of the array is not = 0, then go and check the answer
if(arr.size() != 0){
for (int i = 0; i < arr.size(); i++){
int k = arr[i];
answer[k] = word.at(k);
guesses++;
if(i == arr.size() - 1){
checkAnswer(true);
}
}
} else {
checkAnswer(false);
}
}
void winCheck:: getAnswer(){
char letter;
cout <<"\n Type a letter or char here: " << endl;
cin >> letter;
// gets passed to see if that is the actual word or not
wordFinder(letter,word);
}
void winCheck:: printAnswer(){
for (int i = 0; i < answer.size(); i++)
if(answer[i] == "null"){
cout << "_ ";
} else {
cout << answer[i]+" ";
}
getAnswer();
}
void winCheck:: checkAnswer(bool result){
if(result == 1) {
if(guesses == word.length()){
cout << word << endl;
cout << "You have completed and have won this round" << endl;
} else {
printAnswer();
}
}
else{
errors++;
if(errors == 7){
cout << " _________ \n";
cout << "| | \n";
cout << "| 0 \n";
cout << "| | \n";
cout << "| /|- \n";
cout << "| / - \n";
cout << "| \n";
cout << "GAME OVER!! "<< endl;
}
else {
switch(errors) {
case 1 :
cout << " _________ \n";
cout << "| | \n";
cout << "| 0 \n";
cout << "| \n";
cout << "| \n";
cout << "| \n";
cout << "| \n";
printAnswer();
break; //optional
case 2 :
cout << " _________ \n";
cout << "| | \n";
cout << "| 0 \n";
cout << "| | \n";
cout << "| \n";
cout << "| \n";
cout << "| \n";
printAnswer();
break; //optional
case 3 :
cout << " _________ \n";
cout << "| | \n";
cout << "| 0 \n";
cout << "| | \n";
cout << "| / \n";
cout << "| \n";
cout << "| \n";
printAnswer();
break; //optional
case 4 :
cout << " _________ \n";
cout << "| | \n";
cout << "| 0 \n";
cout << "| | \n";
cout << "| /| \n";
cout << "| \n";
cout << "| \n";
printAnswer();
break; //optional
case 5 :
cout << " _________ \n";
cout << "| | \n";
cout << "| 0 \n";
cout << "| | \n";
cout << "| /|- \n";
cout << "| \n";
cout << "| \n";
printAnswer();
break; //optional
case 6 :
cout << " _________ \n";
cout << "| | \n";
cout << "| 0 \n";
cout << "| | \n";
cout << "| /|- \n";
cout << "| / \n";
cout << "| \n";
printAnswer();
break; //optional
// you can have any number of case statements.
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<file_sep>#include <iostream>
#include <vector>
#include <stdlib.h>
#include "levels.h"
#include "winCheck.h"
#include "Screen.h"
void level(int mode){
srand (time(NULL));
// change words
winCheck check;
string words[10] = {"penguin","elephant","mexico","walnut","office","juxtaposition","aquamarine","madagascar","ferocious","cupcake"};
int length = sizeof(words)/sizeof(words[0]);
int selectWord = rand() %length;
check.word = words[selectWord];
if (mode == 1)
{
// print message
levels level ;
level.mode = 1;
level.printLevelIntro();
}else if (mode == 2)
{
levels level ;
level.mode = 2;
level.printLevelIntro();
}else if (mode == 3)
{
levels level ;
level.mode = 3;
level.printLevelIntro();
}
for (int i = 0; i < words[selectWord].length(); i++)
{
check.answer.push_back("null");
if(i == words[selectWord].length()-1) {
check.printAnswer();
}
}
}
int main()
{
//print Start screen
Screen window;
window.mode = 1;
window.printScreen();
// mode equals the level of the game
int mode = 1;
level(mode);
mode =2;
level(mode);
mode = 3;
level(mode);
// print End Screen
window.mode = 2;
window.printScreen();
}
<file_sep>#include <iostream>
#include <vector>
#include <stdlib.h>
using namespace std;
class levels
{
// Access specifier
public:
// Data Members
int mode;
// Member Functions()
void printLevelIntro();
};<file_sep>#include <iostream>
#include <vector>
#include <stdlib.h>
using namespace std;
class winCheck {
public :
vector < string > answer;
string word;
int errors = 0;
int guesses = 0;
void wordFinder(char letter,string word);
void getAnswer();
void printAnswer();
void checkAnswer(bool result);
};<file_sep>#include <iostream>
#include <vector>
#include <stdlib.h>
char ** readFile(){
FILE *file;
char string[300];
char ** array = malloc(sizeof(char*) * 30000); // array of pointers -> reprents strings
file = fopen("data_4.txt","r");
int i = 0;
for ( i = 0; i < 30000; i++){
array[i] = malloc(sizeof(char)* 20);
}
i = 0;
while(fgets(string,300,file) != NULL){
sscanf(string,"%s", array[i]);
i++;
}
return array;
}
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver code
int main()
{
char ** array = readFile();
for ( int i = 0; i < 30000; i++){
printf( "%s \n",array[i]);
}
// int arr[] = {64, 34, 25, 12, 22, 11, 90};
// int n = sizeof(arr)/sizeof(arr[0]);
// bubbleSort(arr, n);
// cout<<"Sorted array: \n";
// printArray(arr, n);
return 0;
} <file_sep>
hangman: main2.o levels.o winCheck.o Screen.o
g++ main2.o levels.o winCheck.o Screen.o -o hangman
main2.o : main2.cpp
g++ -c main2.cpp
levels.o: levels.cpp
g++ -c levels.cpp
winCheck.o: winCheck.cpp
g++ -c winCheck.cpp
Screen.o: Screen.cpp
g++ -c Screen.cpp<file_sep>#include <iostream>
#include <vector>
#include <stdlib.h>
using namespace std;
class Screen
{
// Access specifier
public:
// Data Members
int mode;
// Member Functions()
void printScreen();
}; | 0128e628cce2b62c6d93d7dc495a9b490be68b2e | [
"Makefile",
"C++"
] | 7 | C++ | Muhsal-droid/Hangman-game-Code | a611b22e6c16cc36f1d96244cec28ffd2aaab9fb | 0e8ee449d66ca83e1c00629f2c1f78ba2e17d110 |
refs/heads/master | <repo_name>cristolintan/dbms1819-ecommerce-t18<file_sep>/app.js
var express = require('express');
var exphbs = require('express-handlebars'); // "express-handlebars"
var nodeMailer = require('nodemailer');
var bodyParser = require('body-parser');
var path = require('path');
var app = express();
// var id = null;
const Brand = require('./models/brands');
const Product = require('./models/products');
const Category = require('./models/category');
const Customer = require('./models/customer');
var { Client } = require('pg');
var port = process.env.PORT || 3000;
var client = new Client({
database: 'df3gq2mc17vt1f',
user: 'ehmwtqxcvqrmdd',
password: '<PASSWORD>',
host: 'ec2-54-225-76-201.compute-1.amazonaws.com',
port: 5432,
ssl: true
});
// connect to database
client.connect()
.then(function () {
console.log('connected to database!');
})
.catch(function (err) {
console.log('cannot connect to database!');
});
app.engine('handlebars', exphbs({defaultLayout: 'main', adminLayout:'admin'})); app.set('view engine', 'handlebars');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function (req, res) {
res.render('client/home',{layout: 'main'});
});
app.get('/login', function (req, res) {
res.render('login');
});
app.get('/signup', function (req, res) {
res.render('signup');
});
app.post('/signup', function (req, res) {
res.render('signup');
console.log('sign up data',req.body);
});
app.get('/admin', function (req, res) {
var mostOrderedBrand;
var mostOrderedCategory;
var mostOrderedProduct;
var leastOrderedProduct;
var topCustomersMostOrder;
var topCustomersHighestPayment;
var topcustomer = [];
var top = [];
var top = [];
var top = [];
var top = [];
var top = [];
var top = [];
var top = [];
Customer.topCustomersMostOrder(client, {}, function (result) {
topCustomersMostOrder = result;
});
Customer.topCustomersHighestPayment(client, {}, function (result) {
topCustomersHighestPayment = result;
});
Brand.mostOrderedBrand(client, {}, function (result) {
mostOrderedBrand = result;
});
Category.mostOrderedCategory(client, {}, function (result) {
mostOrderedCategory = result;
});
Product.mostOrderedProduct(client, {}, function (result) {
mostOrderedProduct = result;
});
Product.leastOrderedProduct(client, {}, function (result) {
leastOrderedProduct = result;
res.render('admin/home', {
layout:'admin',
mostOrderedBrand: mostOrderedBrand,
mostOrderedCategory: mostOrderedCategory,
mostOrderedProduct: mostOrderedProduct,
leastOrderedProduct: leastOrderedProduct,
topCustomersMostOrder: topCustomersMostOrder,
topCustomersHighestPayment: topCustomersHighestPayment
});
});
});
//app.get('/client/product', function (req, res) {
// client.query('SELECT * FROM products', (req, data1) => {
// res.render('client/product', {
// layout:'main',
// data: data1.rows
// });
// });
//});
app.get('/client/product',(req, res) => {
Product.list(client,{},function(product){
res.render('client/product',{
layout:'main' ,
product: product
});
});
});
//app.get('/admin/product', function (req, res) {
// client.query('SELECT * FROM products', (req, data1) => {
// res.render('admin/product', {
// layout:'admin',
// data: data1.rows
// });
// });
//});
app.get('/admin/product',(req, res) => {
Product.list(client,{},function(product){
res.render('admin/product',{
layout:'admin',
product: product
});
});
});
app.get('/client/products/:userId', function (req, res) {
const userId = req.params.userId;
var temp3 = [];
var temp4 = [];
var temp5 = [];
var desktop = [];
var products = [];
var category = [];
var brand = [];
var x;
client.query('SELECT * FROM products where product_id=' + userId + ' ', (req, data3) => {
for (x = 0; x < data3.rowCount; x++) {
temp3[x] = data3.rows[x];
}
products = temp3;
client.query('SELECT * FROM products_category where category_id=' + products[0].category_id + ' ', (req, data4) => {
for (x = 0; x < data4.rowCount; x++) {
temp4[x] = data4.rows[x];
} category = temp4;
client.query('SELECT * FROM brands where brand_id=' + products[0].brand_id + ' ', (req, data5) => {
for (x = 0; x < data5.rowCount; x++) {
temp5[x] = data5.rows[x];
} brand = temp5;
var str = products[0].description;
var desc = str.split(',');
res.render('client/productView', {
layout:'main',
prod_id: products[0].product_id,
prod_picture: products[0].picture,
prod_name: products[0].name,
prod_desc: desc,
prod_tagline: products[0].tagline,
prod_price: products[0].price,
prod_warranty: products[0].warranty,
categoryname: category[0].name,
brandname: brand[0].name
});
});
});
});
});
app.get('/admin/products/:userId', function (req, res) {
const userId = req.params.userId;
var temp3 = [];
var temp4 = [];
var temp5 = [];
var desktop = [];
var products = [];
var category = [];
var brand = [];
var x;
console.log(desktop);
client.query('SELECT * FROM products where product_id=' + userId + ' ', (req, data3) => {
for (x = 0; x < data3.rowCount; x++) {
temp3[x] = data3.rows[x];
}
products = temp3;
client.query('SELECT * FROM products_category where category_id=' + products[0].category_id + ' ', (req, data4) => {
for (x = 0; x < data4.rowCount; x++) {
temp4[x] = data4.rows[x];
} category = temp4;
client.query('SELECT * FROM brands where brand_id=' + products[0].brand_id + ' ', (req, data5) => {
for (x = 0; x < data5.rowCount; x++) {
temp5[x] = data5.rows[x];
} brand = temp5;
var str = products[0].description;
var desc = str.split(',');
res.render('admin/productView', {
prod_id: products[0].product_id,
prod_picture: products[0].picture,
prod_name: products[0].name,
prod_desc: desc,
prod_tagline: products[0].tagline,
prod_price: products[0].price,
prod_warranty: products[0].warranty,
categoryname: category[0].name,
brandname: brand[0].name
});
});
});
});
});
app.post('/send-email/:userId', function (req, res) {
const userId = req.params.userId;
client.query("INSERT INTO customer (name,email,first_name,last_name,street,municipality,province,zipcode) VALUES ('"+req.body.name+"') ");
res.render('createBrand');
res.redirect('/categories');
});
app.get('/admin/brands', function (req, res) {
Brand.list(client,{},function(brands){
res.render('admin/brands',{
layout:'admin',
brands: brands
});
});
});
app.get('/client/brands', function (req, res) {
Brand.list(client,{},function(brands){
res.render('client/brands',{
layout:'main',
brands: brands
});
});
});
app.get('/admin/createbrand', function (req, res) {
res.render('admin/createBrand',{
layout:'admin'
});
});
app.post('/admin/brand/submit', function (req, res) {
console.log(req.body.name);
client.query("INSERT INTO brands (name,description) VALUES ('" + req.body.name + "','" + req.body.description + "')ON CONFLICT (name) DO NOTHING; ");
//res.render('createBrand');
res.redirect('/admin/brands');
});
app.get('/client/categories',function (req, res) {
Category.list(client,{},function(category){
res.render('client/categories',{
layout:'main',
category: category
});
});
})
//app.get('/admin/categories', function (req, res) {
// client.query('SELECT * FROM products_category ORDER BY category_id ASC', (req, data1) => {
// console.log(data1.rows);
// res.render('admin/categories', {
// layout:'admin',
// data: data1.rows
// });
// });
//});
app.get('/admin/categories',function (req, res) {
Category.list(client,{},function(category){
res.render('admin/categories',{
layout:'admin',
category: category
});
});
})
app.get('/admin/createcategory', function (req, res) {
res.render('admin/createCategory',{
layout:'admin'
});
});
app.post('/admin/category/submit', function (req, res) {
console.log(req.body.name);
client.query("INSERT INTO products_category (name) VALUES ('" + req.body.name + "') ON CONFLICT (brand_name) DO NOTHING;");
res.redirect('/admin/categories');
});
app.get('/admin/createproduct', function (req, res) {
var temp4 = [];
var temp5 = [];
var category = [];
var brand = [];
var x = '';
client.query('SELECT * FROM products_category ORDER BY category_id ASC', (req, data4) => {
for (x = 0; x < data4.rowCount; x++) {
temp4[x] = data4.rows[x];
} category = temp4;
client.query('SELECT * FROM brands ORDER BY brand_id ASC', (req, data5) => {
for (x = 0; x < data5.rowCount; x++) {
temp5[x] = data5.rows[x];
} brand = temp5;
res.render('admin/createProduct', {
layout:'admin',
categorydata: category,
branddata: brand
});
});
});
});
app.post('/admin/product/submit', function (req, res) {
client.query("INSERT INTO products (name,description,tagline,price,warranty,category_id,brand_id,picture) VALUES ('" + req.body.name + "','" + req.body.description + "','" + req.body.tagline + "','" + req.body.price + "','" + req.body.warranty + "','" + req.body.category + "','" + req.body.brand + "','" + req.body.picture + "')ON CONFLICT (brand_name) DO NOTHING; ");
res.redirect('/admin/product');
});
app.get('/admin/product/update/:userId', function (req, res) {
const userId = req.params.userId;
var temp3 = [];
var temp4 = [];
var temp5 = [];
var desktop = [];
var products = [];
var category = [];
var brand = [];
var x;
client.query('SELECT * FROM products where product_id=' + userId + ' ', (req, data3) => {
for (x = 0; x < data3.rowCount; x++) {
temp3[x] = data3.rows[x];
} products = temp3;
client.query('SELECT * FROM products_category ORDER BY category_id ASC ', (req, data4) => {
for (x = 0; x < data4.rowCount; x++) {
temp4[x] = data4.rows[x];
} category = temp4;
client.query('SELECT * FROM brands ORDER BY brand_id ASC ', (req, data5) => {
for (x = 0; x < data5.rowCount; x++) {
temp5[x] = data5.rows[x];
} brand = temp5;
res.render('admin/productupdate', {
layout:'admin',
prod_id: products[0].product_id,
prod_name: products[0].name,
prod_desc: products[0].description,
prod_tagline: products[0].tagline,
prod_picture: products[0].picture,
prod_price: products[0].price,
prod_warranty: products[0].warranty,
prod_cat_id: products[0].category_id,
prod_brand_id: products[0].brand_id,
categorydata: category,
branddata: brand
});
});
});
});
});
app.post('/admin/product/updatesubmit/:userId', function (req, res) {
const userId = req.params.userId;
// console.log(req.body.category);
client.query("UPDATE products SET name = '" + req.body.name + "',description = '" + req.body.description + "',tagline='" + req.body.tagline + "',price='" + req.body.price + "',warranty='" + req.body.warranty + "',category_id= '" + req.body.category + "',brand_id= '" + req.body.brand + "',picture= '" + req.body.picture + "' WHERE product_id='" + userId + "' ");
// res.render('createBrand');
res.redirect('/admin/product');
});
app.get('/admin/customers', function (req, res) {
client.query('SELECT * FROM customer', (req, data1) => {
console.log(data1);
res.render('admin/customers', {
layout:'admin',
data: data1.rows
});
});
});
app.get('/admin/customer/:custId', function (req, res) {
const custId = req.params.custId;
var temp4 = [];
var temp5 = [];
var category = [];
var brand = [];
var customer = [];
var orders = '';
var x = '';
console.log(brand);
console.log(category);
client.query('SELECT * FROM customer WHERE customer_id=' + custId + ' ', (req, data4) => {
for (x = 0; x < data4.rowCount; x++) {
temp4[x] = data4.rows[x];
} customer = temp4;
console.log(customer);
client.query('SELECT * FROM orders INNER JOIN products on orders.product_id=products.product_id where customer_id=' + custId + ' ', (req, data5) => {
for (x = 0; x < data5.rowCount; x++) {
temp5[x] = data5.rows[x];
} orders = temp5;
console.log(orders);
res.render('admin/customerView', {
layout:'admin',
first_name: customer[0].first_name,
last_name: customer[0].last_name,
email: customer[0].email,
street: customer[0].street,
municipality: customer[0].municipality,
province: customer[0].province,
zipcode: customer[0].zipcode,
data2: orders
});
});
});
});
app.get('/admin/orders', function (req, res) {
client.query('SELECT * FROM orders INNER JOIN customer ON orders.customer_id=customer.customer_id INNER JOIN products ON orders.product_id=products.product_id ORDER BY orders_id ASC', (req, data1) => {
console.log(data1.rows);
res.render('admin/orders', {
layout:'admin',
data: data1.rows
});
});
});
app.post('/client/send-email/:userId', function (req, res) {
const userId = req.params.userId;
client.query("SELECT * FROM customer where email='" + req.body.email + "' ", (req2, data4) => {
// console.log(data4);
console.log(data4.rowCount);
if (data4.rowCount >= 1) {
client.query("SELECT * FROM customer where email='" + req.body.email + "' ", (req3, data11) => {
client.query("INSERT INTO orders (customer_id,product_id,quantity,order_date) VALUES ('" + data11.rows[0].customer_id + "','" + userId + "','" + req.body.quantity + "',CURRENT_TIMESTAMP)");
let transporter = nodeMailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: '<EMAIL>',
pass: '<PASSWORD>'
}
});
let mailOptions = {
from: req.body.email, // sender address
to: '<EMAIL>', // list of receivers
subject: 'Team 18 Order Form', // Subject line
text: '<p>Here is the new customer order request! <br> <b>Product Id</b>: ' + userId + '<br> <b>Product Quantity:</b> ' + req.body.quantity + '<br> <b>Customer Name</b>: ' + req.body.fname + ' ' + req.body.lname + ' <br> <b>Email</b>: ' + req.body.email + '<br> <b>Street</b>: ' + req.body.street + ' <br> <b>Municipality</b>: ' + req.body.municipality + ' <br> <b>Province</b>: ' + req.body.province + ' <br> <b>Zipcode</b>: ' + req.body.zipcode + '</p>', // plain text body
html: '<p>Here is the new customer order request! <br> <b>Product Id</b>: ' + userId + '<br> <b>Product Quantity:</b> ' + req.body.quantity + '<br> <b>Customer Name</b>: ' + req.body.fname + ' ' + req.body.lname + ' <br> <b>Email</b>: ' + req.body.email + '<br> <b>Street</b>: ' + req.body.street + ' <br> <b>Municipality</b>: ' + req.body.municipality + ' <br> <b>Province</b>: ' + req.body.province + ' <br> <b>Zipcode</b>: ' + req.body.zipcode + '</p>'// html body
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
res.render('client/error',{
layout:'main'
});
return console.log(error);
}
let mailOptions2 = {
from: '<EMAIL>', // sender address
to: req.body.email, // list of receivers
subject: 'Team 18 Product Order Form', // Subject line
text: '<p>Here are your order request details!! <br> <b>Product Id</b>: ' + userId + '<br> <b>Product Quantity:</b> ' + req.body.quantity + '<br> <b>Customer Name</b>: ' + req.body.fname + ' ' + req.body.lname + ' <br> <b>Email</b>: ' + req.body.email + '<br> <b>Street</b>: ' + req.body.street + ' <br> <b>Municipality</b>: ' + req.body.municipality + ' <br> <b>Province</b>: ' + req.body.province + ' <br> <b>Zipcode</b>: ' + req.body.zipcode + '</p>', // plain text body
html: '<p>Here are your order request details!! <br> <b>Product Id</b>: ' + userId + '<br> <b>Product Quantity:</b> ' + req.body.quantity + '<br> <b>Customer Name</b>: ' + req.body.fname + ' ' + req.body.lname + ' <br> <b>Email</b>: ' + req.body.email + '<br> <b>Street</b>: ' + req.body.street + ' <br> <b>Municipality</b>: ' + req.body.municipality + ' <br> <b>Province</b>: ' + req.body.province + ' <br> <b>Zipcode</b>: ' + req.body.zipcode + '</p>'// html body
};
transporter.sendMail(mailOptions2, (error2, info2) => {
if (error2) {
res.render('client/error',{
layout:'main'
});
return console.log(error2);
}
console.log('Message %s sent: %s', info2.messageId, info2.response);
res.render('client/orderSuccess',{
layout:'main'
});
});
});
});
} else if (data4.rowCount === 0) {
console.log('no data exist!');
client.query("INSERT INTO customer (email,first_name,last_name,street,municipality,province,zipcode) VALUES ('" + req.body.email + "','" + req.body.fname + "','" + req.body.lname + "','" + req.body.street + "','" + req.body.municipality + "','" + req.body.province + "','" + req.body.zipcode + "')");
client.query("SELECT * FROM customer where email='" + req.body.email + "' ", (req4, data11) => {
console.log(data11.rows[0].customer_id + ' ' + userId + ' ' + req.body.quantity);
client.query("INSERT INTO orders (customer_id,product_id,quantity,order_date) VALUES ('" + data11.rows[0].customer_id + "','" + userId + "','" + req.body.quantity + "',CURRENT_TIMESTAMP)");
let transporter = nodeMailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: '<EMAIL>',
pass: '<PASSWORD>'
}
});
let mailOptions = {
from: req.body.email, // sender address
to: '<EMAIL>', // list of receivers
subject: 'Team 18 Product Order Form', // Subject line
text: '<p>Please check your order details <br> <b>Product Id</b>: ' + userId + '<br> <b>Product Quantity:</b> ' + req.body.quantity + '<br> <b>Customer Name</b>: ' + req.body.fname + ' ' + req.body.lname + ' <br> <b>Email</b>: ' + req.body.email + '<br> <b>Street</b>: ' + req.body.street + ' <br> <b>Municipality</b>: ' + req.body.municipality + ' <br> <b>Province</b>: ' + req.body.province + ' <br> <b>Zipcode</b>: ' + req.body.zipcode + '</p>', // plain text body
html: '<p>Please check your order details <br> <b>Product Id</b>: ' + userId + '<br> <b>Product Quantity:</b> ' + req.body.quantity + '<br> <b>Customer Name</b>: ' + req.body.fname + ' ' + req.body.lname + ' <br> <b>Email</b>: ' + req.body.email + '<br> <b>Street</b>: ' + req.body.street + ' <br> <b>Municipality</b>: ' + req.body.municipality + ' <br> <b>Province</b>: ' + req.body.province + ' <br> <b>Zipcode</b>: ' + req.body.zipcode + '</p>'// html body
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
res.render('client/error',{
layout:'main'
});
return console.log(error);
}
let mailOptions2 = {
from: '<EMAIL>', // sender address
to: req.body.email, // list of receivers
subject: 'Team 18 Product Order Form', // Subject line
text: '<p>Please check your order details!! <br> <b>Product Id</b>: ' + userId + '<br> <b>Product Quantity:</b> ' + req.body.quantity + '<br> <b>Customer Name</b>: ' + req.body.fname + ' ' + req.body.lname + ' <br> <b>Email</b>: ' + req.body.email + '<br> <b>Street</b>: ' + req.body.street + ' <br> <b>Municipality</b>: ' + req.body.municipality + ' <br> <b>Province</b>: ' + req.body.province + ' <br> <b>Zipcode</b>: ' + req.body.zipcode + '</p>', // plain text body
html: '<p>Please check your order details!! <br> <b>Product Id</b>: ' + userId + '<br> <b>Product Quantity:</b> ' + req.body.quantity + '<br> <b>Customer Name</b>: ' + req.body.fname + ' ' + req.body.lname + ' <br> <b>Email</b>: ' + req.body.email + '<br> <b>Street</b>: ' + req.body.street + ' <br> <b>Municipality</b>: ' + req.body.municipality + ' <br> <b>Province</b>: ' + req.body.province + ' <br> <b>Zipcode</b>: ' + req.body.zipcode + '</p>'// html body
};
transporter.sendMail(mailOptions2, (error2, info2) => {
if (error2) {
res.render('client/error',{
layout:'main'
});
return console.log(error2);
}
console.log('Message %s sent: %s', info2.messageId, info2.response);
res.render('client/OrderSuccess');
});
});
});
}
});
});
app.listen(port, function () {
console.log('Server started at port ' + port);
});
<file_sep>/models/customer.js
var exports = module.exports = {};
var Customer = {
topCustomersHighestPayment: (client, filter, callback) => {
const query = `
SELECT first_name,last_name,SUM(products.price) AS totalprice FROM ((customer INNER JOIN orders ON customer.customer_id = orders.customer_id) INNER JOIN products ON products.product_id = orders.product_id) GROUP BY customer.customer_id ORDER BY totalprice DESC LIMIT 10;
`;
client.query(query, (req, result) => {
// console.log(result.rows);
callback(result.rows);
});
},
topCustomersMostOrder: (client, filter, callback) => {
const query = `
SELECT first_name,last_name,COUNT(orders.orders_id) AS num_orders FROM customer INNER JOIN orders ON customer.customer_id = orders.customer_id GROUP BY orders.customer_id,customer.customer_id ORDER BY num_orders DESC LIMIT 10
`;
client.query(query, (req, result) => {
// console.log(result.rows);
callback(result.rows);
});
}
};
module.exports = Customer;
<file_sep>/README.md
# dbms1819-ecommerce-t18
| a6bd37b5461794f97090d4829a7434a042196d3d | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | cristolintan/dbms1819-ecommerce-t18 | 4692517345ba940cf22ec1f7c5e5bff620ade055 | fd7bd34aa2e75ab7d9f22890b61a375b83cacaa4 |
refs/heads/master | <file_sep>package main
import (
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/sky-uk/gonsx"
"github.com/sky-uk/gonsx/api/service"
)
func dataSourceService() *schema.Resource {
return &schema.Resource{
Read: dataSourceServiceRead,
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"scopeid": {
Type: schema.TypeString,
Optional: true,
Default: "globalroot-0",
},
},
}
}
func dataSourceServiceRead(data *schema.ResourceData, meta interface{}) error {
nsxclient := meta.(*gonsx.NSXClient)
getAllAPI := service.NewGetAll(data.Get("scopeid").(string))
err := nsxclient.Do(getAllAPI)
if err != nil {
return err
}
name := data.Get("name").(string)
if getAllAPI.StatusCode() != 200 {
return fmt.Errorf("Failed to lookup service %s: unexpected HTTP status %d", name, getAllAPI.StatusCode())
}
for _, application := range getAllAPI.GetResponse().Applications {
if application.Name == name {
data.SetId(application.ObjectID)
return nil
}
}
return fmt.Errorf("Service %s not found", name)
}
| 6d03420f2519d37fb24befae473408696e8f25b7 | [
"Go"
] | 1 | Go | anjilinux/terraform-provider-nsx | 53d166f78284afd18e952a58883dc666968b5773 | 0f61b14ba14445b74ac3b18174e8ab17c77b66ff |
refs/heads/master | <repo_name>f0unix/twitterMiner<file_sep>/twitterminer/bcolors/__init__.py
import os, sys
def check_os():
if os.name == "nt":
operating_system = "windows"
if os.name == "posix":
operating_system = "posix"
return operating_system
if check_os() == "posix":
class bcolors:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERL = '\033[4m'
ENDC = '\033[0m'
backBlack = '\033[40m'
backRed = '\033[41m'
backGreen = '\033[42m'
backYellow = '\033[43m'
backBlue = '\033[44m'
backMagenta = '\033[45m'
backCyan = '\033[46m'
backWhite = '\033[47m'
def disable(self):
self.PURPLE = ''
self.CYAN = ''
self.BLUE = ''
self.GREEN = ''
self.YELLOW = ''
self.RED = ''
self.ENDC = ''
self.BOLD = ''
self.UNDERL = ''
self.backBlack = ''
self.backRed = ''
self.backGreen = ''
self.backYellow = ''
self.backBlue = ''
self.backMagenta = ''
self.backCyan = ''
self.backWhite = ''
self.DARKCYAN = ''
# if we are windows or something like that then define colors as nothing
else:
class bcolors:
PURPLE = ''
CYAN = ''
DARKCYAN = ''
BLUE = ''
GREEN = ''
YELLOW = ''
RED = ''
BOLD = ''
UNDERL = ''
ENDC = ''
backBlack = ''
backRed = ''
backGreen = ''
backYellow = ''
backBlue = ''
backMagenta = ''
backCyan = ''
backWhite = ''
def disable(self):
self.PURPLE = ''
self.CYAN = ''
self.BLUE = ''
self.GREEN = ''
self.YELLOW = ''
self.RED = ''
self.ENDC = ''
self.BOLD = ''
self.UNDERL = ''
self.backBlack = ''
self.backRed = ''
self.backGreen = ''
self.backYellow = ''
self.backBlue = ''
self.backMagenta = ''
self.backCyan = ''
self.backWhite = ''
self.DARKCYAN = ''
def warning(input):
str = bcolors.YELLOW + "[!] " + bcolors.ENDC + input
print(str)
def error(input):
str = bcolors.RED + "[x] " + bcolors.ENDC + input
print(str)
def info(input):
str = bcolors.GREEN + "[?] " + bcolors.ENDC + input
print(str)
def prompt(message, arg):
yes = set(['yes','y', 'ye', ''])
no = set(['no','n'])
sys.stdout.write(bcolors.CYAN + "[>]" + bcolors.ENDC + " " + message + "(y/n):")
choice = raw_input().lower()
if choice in yes:
return True
elif choice in no:
return False
else:
prompt(message,arg)
<file_sep>/twitterminer/__init__.py
import pkg_resources, json, time, string, operator, datetime, codecs, tweepy
from collections import Counter
from twitterminer.bcolors import *
from twitterminer.mining import *
from twitterminer import *
from tweepy import Stream
from tweepy.streaming import StreamListener
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
try:
__version__ = pkg_resources.get_distribution(__name__).version
except:
__version__ = '1.0'
def authenticate():
with open('config/twitter_access_tokens.json', 'r') as configuration_file:
config = json.load(configuration_file)
auth = tweepy.OAuthHandler(config['consumer_key'], config['consumer_secret'])
auth.set_access_token(config['access_token'], config['access_secret'])
return auth
def connect_to_twitter():
auth = authenticate()
api = tweepy.API(auth, wait_on_rate_limit=True)
return api
def list_home_timeline(items):
api = connect_to_twitter()
for status in tweepy.Cursor(api.home_timeline).items(items):
print json.dumps(status._json, indent=2)
def list_following():
api = connect_to_twitter()
for friend in tweepy.Cursor(api.friends).items():
print json.dumps(friend._json, indent=2)
class TweetTracker(StreamListener):
"""Custom StreamListener for streaming data."""
def __init__(self, file_name, query):
query_fname = format_filename(query)
self.outfile = "%s" % ( file_name )
# self.outfile = "%s-%s__stream_%s.json" % ( file_name, datetime.date.today() )
def on_data(self, tweet):
try:
with codecs.open(self.outfile, 'a', 'utf-8') as file:
tweet_json = json.loads(tweet, 'utf-8')
if tweet_json['lang'] == 'en' or tweet_json['lang'] == 'ar':
file.write(tweet)
print tweet_json['text']
#print json.dumps(tweet['text'].encode(), indent=2)
return True
except BaseException as e:
print("Error con_data: %s" % str(e))
time.sleep(5)
return True
def on_error(self, status):
print(status)
return True
def format_filename(fname):
"""Convert file name into a safe string.
Arguments:
fname -- the file name to convert
Return:
String -- converted file name
"""
return ''.join(convert_valid(one_char) for one_char in fname)
def convert_valid(one_char):
"""Convert a character into '_' if invalid.
Arguments:
one_char -- the char to convert
Return:
Character -- converted char
"""
valid_chars = "-_.%s%s" % (string.ascii_letters, string.digits)
if one_char in valid_chars:
return one_char
else:
return '_'
def save_tweets_to_file(file_name, query):
file_name = file_validator(file_name)
auth = authenticate()
listener = TweetTracker(file_name, query)
twitter_stream = Stream(auth, listener)
twitter_stream.filter(track=[query])
def preprocessing(file_name):
count = 0
if not os.path.exists(file_name):
error("Files name containing tweets doesn't exist")
exit(1)
else:
miner = mining()
with codecs.open(file_name, 'r') as tweets:
count_all = Counter()
punctuation = list(string.punctuation)
stop = stopwords.words('english') + punctuation + ['rt', 'via', ':', 'RT']
for tweet_line in tweets:
tweet = json.loads(tweet_line)
print(tweet['text'])
tokens = miner.preprocess(tweet['text'])
# print(tokens)
terms_all = [term for term in miner.preprocess(tweet['text']) if term not in stop]
count_all.update(terms_all)
# count the top 5 words in the tweets
print(count_all.most_common(5))
def file_validator(arg):
arg = os.path.abspath(arg)
if not os.path.exists(arg):
info("File does not exist")
info("Creating new file ::: " + arg + ".json" )
file = codecs.open( arg + ".json", "w", "utf-8")
return file.name
else:
warning("File already exist")
prompt("Are you sure you want to replace the current file ", arg + ".json" )
if prompt:
file = codecs.open(arg + ".json", "w", "utf-8")
return file.name
else:
info("Please select a different option")
error("Aborted")
exit()
<file_sep>/AUTHORS.rst
==========
Developers
==========
* f0unix <<EMAIL>>
<file_sep>/twitterminer/skeleton.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This is a skeleton file that can serve as a starting point for a Python
console script. To run this script uncomment the following line in the
entry_points section in setup.cfg:
console_scripts =
fibonacci = twitterminer.skeleton:run
Then run `python setup.py install` which will install the command `fibonacci`
inside your current environment.
Besides console scripts, the header (i.e. until _logger...) of this file can
also be used as template for Python modules.
Note: This skeleton file can be safely removed if not needed!
"""
from __future__ import print_function, absolute_import
import argparse
import sys
import logging
import twitterminer as tm
from twitterminer.bcolors import *
from twitterminer import __version__
import twitterminer as tm
__author__ = "f0unix"
__copyright__ = "f0unix"
__license__ = "GPL"
# defining logging options
_logger = logging.getLogger(__name__)
# add the function you want to call here, this acts like the main class in python that calls and executes from here to call
# everything
def parse_args(args):
parser = argparse.ArgumentParser(
description = "A twitter data mining console program to extract tweets and perform some mining over them")
parser.add_argument(
'--version',
'-v',
action = 'version',
version = 'twitterMiner {ver}'.format(ver=__version__)
)
data_options = parser.add_mutually_exclusive_group()
data_options.add_argument(
'-t',
'--timeline',
nargs = 1,
type = int,
default = 0,
help = 'fetch n-number of tweets from timeline, default = 100 '
)
data_options.add_argument(
'-f',
'--following',
action = 'store_true',
help = 'show following list linked to twitter account',
)
collect_tweets = parser.add_argument_group()
collect_tweets.add_argument(
'-q',
'--query',
dest='query',
help='Twitter query filter to make a specific tweets search',
default= ''
)
collect_tweets.add_argument(
'-c',
'--collected-tweets',
dest='collected_tweets',
help ='File name where tweets should be saved',
default=''
)
data_options.add_argument(
'-pp',
'--preprocessing',
dest='read_tweets',
help='Preprocessing collected tweets',
default=''
)
return parser.parse_args(args)
def main(args):
args = parse_args(args)
print ( args )
if args.collected_tweets == '' and args.query == '' and args.following == False:
error("Please provide one of the argument options")
if (args.collected_tweets == '' and args.query != '') or (args.collected_tweets != '' and args.query == '') :
error("You must provide a query with the file name in which to collect your tweets")
info("twitterminer -c/--collected_tweets file_name -q 'twitter query' ")
if args.collected_tweets != '' and args.query != '':
info("Storing tweets into >>> " + args.collected_tweets + ".json" )
tm.save_tweets_to_file(args.collected_tweets, args.query)
if args.following and args.collected_tweets == '' and args.following == True:
info("Listing followed users")
tm.list_following()
if args.timeline != 0 and ( args.collected_tweets == None and args.query == '' ) :
info("Listing timeline tweets")
tm.list_home_timeline(args.timeline)
if args.read_tweets != '':
info("Preprocessing tweets")
tm.preprocessing(args.read_tweets)
def run():
main(sys.argv[1:])
if __name__ == '__main__':
run()
<file_sep>/requirements.txt
tweepy==3.5.0
nltk==3.2.1
<file_sep>/README.md
# twitterMiner
A command line application designated to mine collected tweets for some knowledge
| 9a2cb34ab864e268962996832a308f8509742b6d | [
"Markdown",
"Python",
"Text",
"reStructuredText"
] | 6 | Python | f0unix/twitterMiner | fbf2a4dc24bed1dcfebe16f6874cf6c7673bd84f | 11a01f120e8f2200aea87fd98644eef5e848aa84 |
refs/heads/master | <repo_name>tomerabergel/Hangman-self.py<file_sep>/hangman.py
def print_welcome_screen(MAX_TRIES):
"""A function that print the Welcome Screen.
:param MAX_TRIES: MAX_TRIES value
:type MAX_TRIES: int
:return: print to screen the welcome screen and The number of guesses of the player
:rtype: None
"""
HANGMAN_ASCII_ART = """
_ _
| | | |
| |__| | __ _ _ __ __ _ _ __ ___ __ _ _ __
| __ |/ _` | '_ \ / _` | '_ ` _ \ / _` | '_ \
| | | | (_| | | | | (_| | | | | | | (_| | | | |
|_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_|
__/ |
|___/"""
print(HANGMAN_ASCII_ART, '\n', MAX_TRIES)
HANGMAN_PHOTOS = {0: "x-------x", 1: """ x-------x
|
|
|
|
|""", 2: """ x-------x
| |
| 0
|
|
|
""", 3: """ x-------x
| |
| 0
| |
|
|
""", 4: """ x-------x
| |
| 0
| /|""""""\\""""""
|
|
""", 5: """ x-------x
| |
| 0
| /|""""""\\""""""
| /
|
""", 6: """ x-------x
| |
| 0
| /|""""""\\""""""
| / """"""\\""""""
|
"""}
def print_hangman(num_of_tries):
"""A function that Show to the player the appropriate position of the hangman on the number of his failed attempts.
:param num_of_tries: num_of_tries value
:type num_of_tries: int
:return: print to screen the appropriate position of the hangman
:rtype: None
"""
if int(num_of_tries) == 0:
print(HANGMAN_PHOTOS[0])
elif int(num_of_tries) == 1:
print(HANGMAN_PHOTOS[1])
elif int(num_of_tries) == 2:
print(HANGMAN_PHOTOS[2])
elif int(num_of_tries) == 3:
print(HANGMAN_PHOTOS[3])
elif int(num_of_tries) == 4:
print(HANGMAN_PHOTOS[4])
elif int(num_of_tries) == 5:
print(HANGMAN_PHOTOS[5])
elif int(num_of_tries) == 6:
print(HANGMAN_PHOTOS[6])
def show_hidden_word(secret_word, old_letters_guessed):
"""A function that returns a string which consists of letters and lower hopes.
The string shows the letters from the old_letters_guessed list that are in the secret_word string in their
appropriate position, and the other letters in the string (which the player has not yet guessed) as underlines.
:param secret_word: secret_word string value
:param old_letters_guessed: old_letters_guessed character's list value
:type secret_word: str
:type old_letters_guessed: list
:return: print to screen the secret word in the form of underscores.
:rtype: None
"""
n = secret_word
for char in secret_word:
c_exist = False
for c in old_letters_guessed:
if char == c:
c_exist = True
n = n.replace(char, c)
break
if c_exist == False:
n = n.replace(char, ' _ ')
print(n)
def choose_word(file_path, index):
"""A function that accepts as parameters: a string that represents a path to a text file that contains spaced words,
and an integer that represents the location of a particular word in the file.
The function returns a word in the position obtained as an argument to the function (index)
that will be used as the secret word for guessing.
:param file_path: Path to text file
:param index: index value
:type file_path: str value that represents a path to a text file
:type index: int
:return: The word from file in the index position, which will be used as the secret word for guessing
:rtype: str
"""
with open(file_path, "r") as file:
text = file.read()
text = text.split(" ")
different_words = []
for w in text:
if str(w) not in different_words:
different_words.append(w)
num_different_words = len(different_words)
while int(index) > len(text):
index = (int(index) - len(text))
secret_word = text[int(index) - 1]
return secret_word
def check_valid_input(letter_guessed, old_letters_guessed):
"""A Boolean function that receives a character and a list of letters that the user has previously guessed.
The function checks the validation of the input and whether it is legal to guess this signal
(i.e., the player has not guessed this signal before) and returns true or false accordingly.
:param letter_guessed: secret_word string value
:param old_letters_guessed: old_letters_guessed character's list value
:type letter_guessed: str
:type old_letters_guessed: list
:return: boolean value that meaning whether the input is valid or not.
:rtype: bool
"""
if (len(letter_guessed) > 1) or (not (letter_guessed.isalpha())) or (
letter_guessed.lower() in old_letters_guessed or (letter_guessed.upper() in old_letters_guessed)):
return False
else:
return True
def try_update_letter_guessed(letter_guessed, old_letters_guessed):
"""The function uses the check_valid_input function to know if the character is valid and has not been guessed in
the past or the character is not valid and / or is already on the guess list.
If the character is invalid or the character has been guessed before, the function prints the
character "X" , below it the list of letters that have already been guessed and returns a False.
If the character is valid and has not been guessed before - the function adds the character to the guess list and returns true.
:param letter_guessed: secret_word string value
:param old_letters_guessed: old_letters_guessed character's list value
:type letter_guessed: str
:type old_letters_guessed: list
:return: boolean value that meaning whether the character is valid and has not been guessed before.
:rtype: bool
"""
if not check_valid_input(letter_guessed, old_letters_guessed):
print('X')
old_letters_guessed.sort()
s = " -> "
print(s.join(old_letters_guessed))
return False
else:
old_letters_guessed += letter_guessed.lower()
return True
def check_win(secret_word, old_letters_guessed):
"""A Boolean function that checking whether the player won the game.
i.e., the function returns True if all the letters that make up the secret word are included
in the list of letters the user guessed. Otherwise, the function returns False
:param secret_word: secret_word string value
:param old_letters_guessed: old_letters_guessed character's list value
:type secret_word: str
:type old_letters_guessed: list
:return: boolean value that meaning whether if all the letters that make up the secret word are included
in the list of letters the user guessed, or not.
:rtype: bool
"""
s = " _ "
n = secret_word
for char in secret_word:
c_exist = False
for c in old_letters_guessed:
if char == c:
c_exist = True
n = n.replace(char, c)
break
if c_exist == False:
n = n.replace(char, ' _ ')
if n.count(' _ ') != 0:
return False
else:
return True
def main():
MAX_TRIES = 6
# Print the Welcome Screen
print_welcome_screen(MAX_TRIES)
# Receive Input from the player: text file path and index of word to guess from the text file
file_path = input("Enter file path: ")
index = int(input("Enter index: "))
print("Let’s start!")
# Initial variables and initial state of the game
num_of_tries = 0
print_hangman(num_of_tries)
secret_word = choose_word(file_path, index)
len_secret_word = len(secret_word)
old_letters_guessed = []
show_hidden_word(secret_word, old_letters_guessed)
# main iteration - Input of one character per round's game.
"""If the character is valid (two or more characters and / or is not an English letter, or guessed it in the past),
type "X" on the screen, and the list of previously guessed letters (as a string in small letters, sorted from small to large and separated by arrows).
Request the player to enter an additional character until the character entered is correct."""
"""After each correct guess, the player will be shown the secret word in the form of underlines
(even if he has guessed partially or has not yet been able to guess at all).
In case of a failed guess - the output will be printed for the player :( and below it a picture of the hangman in a more "advanced" mode"""
"""End of the game:
If the player guesses the whole word correctly - it will be printed on the WIN screen.
If the player guesses six failed attempts - will be printed on the LOSE screen."""
while num_of_tries < MAX_TRIES:
letter_guessed = str(input("Guess a letter: "))
valid_guess = try_update_letter_guessed(letter_guessed, old_letters_guessed)
while valid_guess == False:
letter_guessed = str(input("Guess a letter: "))
valid_guess = try_update_letter_guessed(letter_guessed, old_letters_guessed)
if letter_guessed.lower() in secret_word[:].lower():
if check_win(secret_word, old_letters_guessed):
print("WIN!")
exit(1)
else:
print(":(" + '\n')
num_of_tries += 1
print_hangman(num_of_tries)
show_hidden_word(secret_word, old_letters_guessed)
print("LOSE")
exit(1)
# main program
if __name__ == "__main__":
main()
<file_sep>/README.md
# Hangman-game---self.py
'Hangman' game - Summary project in the Python course of the Israel's National Cyber Directorate. (Campus IL)
A Program that receives from the player:
1) A string that represents a path to a text file. The text file will contain a list of words separated by spaces.
2) An integer representing the location of a particular word in a file. The word in the inputed location will be the secret word the player will have to guess.
From this moment the game will continue according to the rules of "Hangman" - at each stage the player will guess a signal, will receive feedback according to the presence of the letter in the secret word and according to his guesses so far.
| 83e8fe277afcd3c0f7f849ea660f45ec73ec9474 | [
"Markdown",
"Python"
] | 2 | Python | tomerabergel/Hangman-self.py | 8db16b748589ce7d9f3eb2a4f897abaef866b2a8 | 29c1af9ad2091ee7f11005b90745ffcd04cce368 |
refs/heads/master | <file_sep>json.partial! "user_songs/song", user_song: @user_song<file_sep>class Song < ActiveRecord::Base
has_many :user_songs, dependent: :destroy
has_many :users, through: :user_songs
has_many :genres
end
<file_sep>class UserSongsController < ApplicationController
before_action :set_song, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
# GET /songs
# GET /songs.json
def index
@user = User.find(params[:user_id])
@user_songs = @user.user_songs
end
# GET /songs/1
# GET /songs/1.json
def show
end
# GET /songs/new
def new
@user_song = UserSong.new
end
# GET /songs/1/edit
def edit
end
# POST /songs
# POST /songs.json
def create
@user_song = UserSong.new(user_song_params)
respond_to do |format|
if @user_song.save
format.html { redirect_to @user_user_songs_path(current_user), notice: 'Song was successfully created.' }
format.json { render :show, status: :created, location: @user_song }
else
format.html { render :new }
format.json { render json: @user_song.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /songs/1
# PATCH/PUT /songs/1.json
def update
respond_to do |format|
if @user_song.update(user_song_params)
format.html { redirect_to @user_song, notice: 'Song was successfully updated.' }
format.json { render :show, status: :ok, location: @user_song }
else
format.html { render :edit }
format.json { render json: @user_song.errors, status: :unprocessable_entity }
end
end
end
# DELETE /songs/1
# DELETE /songs/1.json
def destroy
@user_song.destroy
respond_to do |format|
format.html { redirect_to user_songs_url, notice: 'Song was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user_song
@user_song = UserSong.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def song_params
params.require(:user_song).permit(:name, :duration, :genre_id)
end
end
| 110f92f5019a8e11e6e1e3fc5cc2b1b404713d50 | [
"Ruby"
] | 3 | Ruby | sugusc21/prueba5 | 3082a7be91dd9e70d0907d30a3c81a82c6ed43d4 | a02c0bd71d02a48d533f6412951059d00fcc2e10 |
refs/heads/master | <file_sep>package com.mengyang.kohler.home.adapter;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.mengyang.kohler.App;
import com.mengyang.kohler.R;
import com.mengyang.kohler.module.bean.BooksListBean;
import java.util.List;
/**
* Description :
* Author : rmy
* Email : <EMAIL>
* Time : 2018/1/29
*/
public class BrochureListAdapter2 extends BaseQuickAdapter<BooksListBean.ResultListBean, BaseViewHolder> {
public BrochureListAdapter2(@Nullable List<BooksListBean.ResultListBean> data) {
super(R.layout.item_home_books_adapter2, data);
}
@Override
protected void convert(BaseViewHolder helper, BooksListBean.ResultListBean item) {
if (item.getPdfUrl() != null && !TextUtils.isEmpty(item.getPdfUrl())) {
helper.setVisible(R.id.iv_brochure_list_adapter_download_item, false);
} else {
helper.setVisible(R.id.iv_brochure_list_adapter_download_item, true);
helper.setText(R.id.tv_brochure_list_adapter_download_item, item.getNameCn());
}
Glide.with(App.getContext()).load(item.getKvUrl()).apply(new RequestOptions().placeholder(R.mipmap.queshengtu)).into((ImageView) helper.getView(R.id.iv_brochure_list_adapter_download_item_img));
helper.addOnClickListener(R.id.iv_brochure_list_adapter_download_item_img);
helper.addOnClickListener(R.id.iv_brochure_list_adapter_download_item);
}
}
<file_sep>package com.mengyang.kohler.module.bean;
/**
* Created by MengYang on 2018/5/22.
*/
public class AzureBotStartBean {
/**
* conversationId : BBXporxIjPNKEHSwCK6BZJ
* token : <KEY>
* expires_in : 1800
* streamUrl : wss://directline.botframework.com/v3/directline/conversations/BBXporxIjPNKEHSwCK6BZJ/stream?watermark=-&t=yTlSJIGr5Ak.dAA.QgBCAFgAcABvAHIAeABJAGoAUABOAEsARQBIAFMAdwBDAEsANgBCAFoASgA.STwBJ7rx0wE.7xYBa2q4JX4.u4fCHhW-nwTt__0o9Arqpr5v4u52ZAWn4E0bs2qhd2s
* referenceGrammarId : e0ae3232-aaac-7150-a9fc-cc78fcee54dc
*/
private String conversationId;
private String token;
private int expires_in;
private String streamUrl;
private String referenceGrammarId;
public String getConversationId() {
return conversationId;
}
public void setConversationId(String conversationId) {
this.conversationId = conversationId;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public int getExpires_in() {
return expires_in;
}
public void setExpires_in(int expires_in) {
this.expires_in = expires_in;
}
public String getStreamUrl() {
return streamUrl;
}
public void setStreamUrl(String streamUrl) {
this.streamUrl = streamUrl;
}
public String getReferenceGrammarId() {
return referenceGrammarId;
}
public void setReferenceGrammarId(String referenceGrammarId) {
this.referenceGrammarId = referenceGrammarId;
}
@Override
public String toString() {
return "BotBean{" +
"conversationId='" + conversationId + '\'' +
", token='" + token + '\'' +
", expires_in=" + expires_in +
", streamUrl='" + streamUrl + '\'' +
", referenceGrammarId='" + referenceGrammarId + '\'' +
'}';
}
}
<file_sep>package com.mengyang.kohler.home.activity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.barlibrary.ImmersionBar;
import com.mengyang.kohler.App;
import com.mengyang.kohler.BaseActivity;
import com.mengyang.kohler.R;
import com.mengyang.kohler.common.net.DefaultObserver;
import com.mengyang.kohler.common.net.IdeaApi;
import com.mengyang.kohler.common.view.TopView;
import com.mengyang.kohler.module.BasicResponse;
import com.mengyang.kohler.module.bean.LiveRealTimeBean;
import java.util.Map;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
/**
* 现场实时投票大图
*/
public class MeetingBigPhotoActivity extends BaseActivity {
@BindView(R.id.tv_meeting_big_photo_top)
TopView tvMeetingBigPhotoTop;
@BindView(R.id.iv_meeting_big_photo)
ImageView ivMeetingBigPhoto;
@BindView(R.id.tv_meeting_big_photo_num)
TextView tvMeetingBigPhotoNum;
@BindView(R.id.iv_meeting_big_photo_left)
ImageView ivMeetingBigPhotoLeft;
@BindView(R.id.iv_meeting_big_photo_right)
ImageView ivMeetingBigPhotoRight;
@BindView(R.id.bt_meeting_big_photo_vote)
Button btMeetingBigPhotoVote;
private int position;
private int mNum;
private String mUrl = "";
private int mId;
private int pageNum = 0;
private int mTotalSize = 0;
@Override
protected int getLayoutId() {
return R.layout.activity_meeting_big_photo;
}
@Override
protected void initValues() {
App.getManager().addActivity(this);
//防止状态栏和标题重叠
ImmersionBar.setTitleBar(this, tvMeetingBigPhotoTop);
position = getIntent().getIntExtra("position", 0);
mTotalSize = getIntent().getIntExtra("totalSize", 0);
if (position == 0)
ivMeetingBigPhotoLeft.setVisibility(View.GONE);
else if ((mTotalSize - 1) == position)
ivMeetingBigPhotoRight.setVisibility(View.GONE);
mNum = getIntent().getIntExtra("num", 0);
tvMeetingBigPhotoNum.setText(mNum + "");
mUrl = getIntent().getStringExtra("url");
Glide.with(App.getContext()).load(mUrl).apply(new RequestOptions().placeholder(R.mipmap.queshengtu)).into(ivMeetingBigPhoto);
mId = getIntent().getIntExtra("id", 0);
}
@Override
protected void initListener() {
}
@Override
protected void initData() {
}
private void getGigPhotoData() {
Map<String, Object> stringMap = IdeaApi.getSign();
//做分页就加
// if ((position + "").length() != 1) {
// pageNum = (int) Math.floor(position / 10);
// }
// stringMap.put("pageNum", pageNum + "");
IdeaApi.getRequestLogin(stringMap);
IdeaApi.getApiService()
.getMeetingLiveRealTime(stringMap)
.compose(MeetingBigPhotoActivity.this.<BasicResponse<LiveRealTimeBean>>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BasicResponse<LiveRealTimeBean>>(MeetingBigPhotoActivity.this, false) {
@Override
public void onSuccess(BasicResponse<LiveRealTimeBean> response) {
int i = position;
if (response.getData().getPageSize() > i) {
if (response.getData().getPageSize() == (i + 1)) {
ivMeetingBigPhotoRight.setVisibility(View.GONE);
}
//做分页就加
// if ((position + "").length() > 1) {
// i = position % 10;
// }
tvMeetingBigPhotoNum.setText(response.getData().getResultList().get(i).getLikeCount() + "");
Glide.with(App.getContext()).load(response.getData().getResultList().get(i).getPicUrl()).apply(new RequestOptions().placeholder(R.mipmap.queshengtu)).into(ivMeetingBigPhoto);
mId = response.getData().getResultList().get(i).getId();
}
}
});
}
@OnClick({R.id.iv_meeting_big_photo_left, R.id.iv_meeting_big_photo_right, R.id.bt_meeting_big_photo_vote})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.iv_meeting_big_photo_left:
position--;
if (position == 0) {
ivMeetingBigPhotoLeft.setVisibility(View.GONE);
} else if (position == 9) {
pageNum--;
}
getGigPhotoData();
ivMeetingBigPhotoRight.setVisibility(View.VISIBLE);
break;
case R.id.iv_meeting_big_photo_right:
ivMeetingBigPhotoLeft.setVisibility(View.VISIBLE);
position++;
getGigPhotoData();
break;
case R.id.bt_meeting_big_photo_vote:
Map<String, Object> stringMap = IdeaApi.getSign();
stringMap.put("id", mId + "");
IdeaApi.getRequestLogin(stringMap);
IdeaApi.getApiService()
.getMeetingLikePicture(stringMap)
.compose(this.<BasicResponse>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BasicResponse>(this, false) {
@Override
public void onSuccess(BasicResponse response) {
mNum += 1;
tvMeetingBigPhotoNum.setText(mNum + "");
}
});
break;
default:
break;
}
}
}
<file_sep>package com.mengyang.kohler.home.adapter;
import android.support.annotation.Nullable;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.mengyang.kohler.App;
import com.mengyang.kohler.R;
import com.mengyang.kohler.module.bean.ArtKohlerBean;
import java.util.List;
/**
* Description :
* Author : rmy
* Email : <EMAIL>
* Time : 2018/3/12
*/
public class ArtKohlerSelectAdapter extends BaseQuickAdapter<ArtKohlerBean.GalleryBean, BaseViewHolder> {
public ArtKohlerSelectAdapter(@Nullable List<ArtKohlerBean.GalleryBean> data) {
super(R.layout.item_art_kohler_select_adapter, data);
}
@Override
protected void convert(BaseViewHolder helper, ArtKohlerBean.GalleryBean item) {
helper.setText(R.id.tv_item_art_select_up, item.getTitle())
.setText(R.id.tv_item_art_select_down, item.getElementDesc());
Glide.with(App.getContext()).load(item.getKvUrl()).apply(new RequestOptions().placeholder(R.mipmap.queshengtu)).into((ImageView) helper.getView(R.id.iv_item_art_select));
}
}
<file_sep>package com.mengyang.kohler.module;
import java.io.Serializable;
import java.util.List;
public class PdfBean {
private List<UserNameBean> list;
public PdfBean() {
}
public PdfBean(List<UserNameBean> list) {
this.list = list;
}
public List<UserNameBean> getList() {
return list;
}
public void setList(List<UserNameBean> list) {
this.list = list;
}
public static class UserNameBean {
private String userName;
private List<UserPdfItemBean> userPdfItemBean;
public UserNameBean() {
}
public UserNameBean(String name) {
this.userName = name;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public List<UserPdfItemBean> getPdfItemList() {
return userPdfItemBean;
}
public void setPdfItemList(List<UserPdfItemBean> list) {
this.userPdfItemBean = list;
}
public static class UserPdfItemBean {
private String bookKVUrl;
private String pathUrl;
private String nameCn;
public String getNameCn() {
return nameCn;
}
public void setNameCn(String nameCn) {
this.nameCn = nameCn;
}
public String getBookKVUrl() {
return bookKVUrl;
}
public String getPathUrl() {
return pathUrl;
}
public void setPathUrl(String pathUrl) {
this.pathUrl = pathUrl;
}
public void setBookKVUrl(String bookKVUrl) {
this.bookKVUrl = bookKVUrl;
}
}
}
}
<file_sep>package com.mengyang.kohler.common.utils;
import android.text.TextUtils;
import android.util.Log;
import com.mengyang.kohler.common.net.IConstants;
import java.io.File;
import java.util.List;
/**
* Created by liusong on 2018/3/2.
*/
public class FileUtil {
/**
* 查看本地是否有PDF文件
*/
public static List<String> judgePdfIsExit(List<String> localTempPdfFileName) {
File file2 = new File(IConstants.ROOT_PATH);
if (!file2.exists()) {
file2.mkdirs();
}
File[] files = file2.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
String fileName = files[i].getName();
if (files[i].isFile() && fileName.endsWith(".pdf")) {
if (!TextUtils.isEmpty(fileName)) {
localTempPdfFileName.add(fileName);
}
Log.i("kohler", "本地的pdfName = " + fileName);
}
}
}
return localTempPdfFileName;
}
}
<file_sep>package com.mengyang.kohler.ar;
import com.allyes.analytics.AIOAnalytics;
import com.gyf.barlibrary.ImmersionBar;
import com.mengyang.kohler.BaseFragment;
import com.mengyang.kohler.R;
import com.mengyang.kohler.common.view.TopView;
import com.mengyang.kohler.main.activity.MainActivity;
import com.umeng.analytics.MobclickAgent;
import butterknife.BindView;
/**
* AR
*/
public class ARFragment extends BaseFragment {
// 这是一个外包小公司,在甲方公司里办公的...别被忽悠了
// 这家老板人品不好,进来说好交社保,但实际上不给你交,工资能拖就拖(有次一拖就3个月)
// 说好的有年终奖也是没有的别想了,过节没有任何东西发,自己带电脑也没有补贴金的~
// 这公司管理混乱趁早走吧兄弟...
@BindView(R.id.tv_ar_top)
TopView tvArTop;
@Override
protected int getLayoutId() {
return R.layout.fragment_ar;
}
@Override
protected void initValues() {
//防止状态栏和标题重叠
ImmersionBar.setTitleBar(getActivity(), tvArTop);
MobclickAgent.onEvent(getActivity(), "arsaoyisao");
}
@Override
protected void initListener() {
}
@Override
protected void initData() {
}
@Override
public void onResume() {
super.onResume();
MobclickAgent.onResume(getActivity());
AIOAnalytics.onPageBegin("arsaoyisao");
}
@Override
public void onPause() {
super.onPause();
MobclickAgent.onPause(getActivity());
AIOAnalytics.onPageEnd("arsaoyisao");
}
}
<file_sep>package com.mengyang.kohler.common.net;
import android.os.Environment;
import com.mengyang.kohler.App;
import com.mengyang.kohler.R;
/**
* Description : 公共参数配置类
* Author : rmy
* Email : <EMAIL>
* Time : 2017/9/22
*/
public class IConstants {
//包名
public static final String PACKAGE_NAME = "com.mengyang.kohler";
/**
* 共享参数
*/
public static final String TOKEN = "token"; //token
public static final String REFRESH_TOKEN = "refreshtoken"; //refreshtoken
public static final String FIRST_APP = "isFirstApp"; //第一次进应用
public static final String IS_LOGIN = "isLogin"; //已经登录
public static final String TYPE = "no_type"; //用户身份 commonUser 普通用户 dealer 经销商 designer 设计师
public static final String POEN_ID = "openId"; //用户唯一标识
public static final String USER_ID = "userId"; //用户uid
public static final String JPUSH_SYSTEM_ID = "registrationId"; //极光系统id
public static final String MEETING_PUSH_MSG = "true"; //获取经销商大会用户设置
public static final String USER_NIKE_NAME = "KOHLER"; //用户昵称
public static final String USER_HEAD_PORTRAIT = ""; //用户头像URL
/**
* 请求码 从60开始
*/
public static final int DELETE_REQUESTCODE = 60;
public static final int AZURE_BACK_ONE = 61;
/**
* 实例化常量
*/
public static final long COMMODITY_CLASSIFICATION_FRAGMENT_BEAN = 1L;
public static final long RESULT_LIST_BEAN = 2L;
public static final long PRO_DETAIL_BEAN = 3L;
public static final long ATTR_LIST_BEAN = 4L;
public static final long PDF_LIST_BEAN = 5L;
public static final long SKU_ATTR_LIST_BEAN = 6L;
public static final String ROOT_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
// 下载存储的文件名
public static final String DOWNLOAD_NAME = "kohler";
}
<file_sep>package com.mengyang.kohler.account.activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.mengyang.kohler.App;
import com.mengyang.kohler.BaseActivity;
import com.mengyang.kohler.R;
import com.mengyang.kohler.common.net.DefaultObserver;
import com.mengyang.kohler.common.net.IdeaApi;
import com.mengyang.kohler.common.net.IdeaApiService;
import com.mengyang.kohler.common.net.Config;
import com.mengyang.kohler.common.utils.DateUtils;
import com.mengyang.kohler.common.net.IConstants;
import com.mengyang.kohler.common.utils.LogUtils;
import com.mengyang.kohler.common.utils.SPUtil;
import com.mengyang.kohler.common.utils.ToastUtil;
import com.mengyang.kohler.common.utils.VerifyUtils;
import com.mengyang.kohler.main.activity.MainActivity;
import com.mengyang.kohler.module.BasicResponse;
import com.mengyang.kohler.module.bean.LoginBean;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* 登录
*/
public class LoginActivity extends BaseActivity {
// 这是一个外包小公司,在甲方公司里办公的...别被忽悠了
// 这家老板人品不好,进来说好交社保,但实际上不给你交,工资能拖就拖(有次一拖就3个月)
// 说好的有年终奖也是没有的别想了,过节没有任何东西发,自己带电脑也没有补贴金的~
// 这公司管理混乱趁早走吧兄弟...
@BindView(R.id.rl_lonin_go_home)
RelativeLayout ivLoninGoHome;
@BindView(R.id.et_login_phone_num)
EditText etLoginPhoneNum;
@BindView(R.id.et_login_pwd)
EditText etLoginPwd;
@BindView(R.id.et_login_verification_code)
EditText etLoginVerificationCode;
@BindView(R.id.iv_login_verification_code)
ImageView ivLoginVerificationCode;
@BindView(R.id.tv_login_forget_pwd)
TextView tvLoginForgetPwd;
@BindView(R.id.bt_login)
Button btLogin;
@BindView(R.id.ll_login_go_register)
LinearLayout tvLoginGoRegister;
private byte[] bytes;//图片验证码进制流
private String time = "";
@Override
protected int getLayoutId() {
return R.layout.activity_login;
}
@Override
protected void initValues() {
App.getManager().addActivity(this);
}
@Override
protected void initListener() {
etLoginPhoneNum.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//输入文本之前的状态
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//输入文字中的状态,count是一次性输入字符数
}
@Override
public void afterTextChanged(Editable editable) {
//输入文字后的状态
if (etLoginPhoneNum.getText().toString().trim().length() == 11 && VerifyUtils.isMobileNumber(etLoginPhoneNum.getText().toString().trim())) {
} else if (etLoginPhoneNum.getText().toString().trim().length() == 11) {
ToastUtil.showToast("请输入正确的手机号码!");
etLoginPhoneNum.setText("");
}
}
});
}
@Override
protected void initData() {
Map<String, Object> stringMap = IdeaApi.getSign();
time = DateUtils.dataOne(DateUtils.getCurrentTime_Today());
stringMap.put("time", time);//时间戳
postAsynHttp(stringMap);
}
/**
* 获取验证码图片
* @param map
*/
private void postAsynHttp(Map map) {
Iterator entries = map.entrySet().iterator();
OkHttpClient mOkHttpClient = new OkHttpClient();
FormBody.Builder builder = new FormBody.Builder();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
String key = entry.getKey() + "";
String value = entry.getValue() + "";
builder.add(key, value);
}
RequestBody formBody = builder.build();
Request request = new Request.Builder()
.url(IdeaApiService.API_SERVER_URL + Config.LOGIN_VERIFICATION_IMG)
.post(formBody)
.build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
bytes = response.body().bytes();
runOnUiThread(new Runnable() {
@Override
public void run() {
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
ivLoginVerificationCode.setImageBitmap(bitmap);
}
});
}
});
}
private void Login() {
Map<String, Object> stringMap = IdeaApi.getSign();
stringMap.put("mobileNo", etLoginPhoneNum.getText().toString().trim());//手机号码
stringMap.put("password", <PASSWORD>Pwd.getText().toString().trim());//用户密码
stringMap.put("time", time);//时间戳得和图片验证码时的一样
stringMap.put("code", etLoginVerificationCode.getText().toString().trim());//验证码
IdeaApi.getRequestLogin(stringMap);
IdeaApi.getApiService()
.getLogin(stringMap)
.compose(this.<BasicResponse<LoginBean>>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BasicResponse<LoginBean>>(this, true) {
@Override
public void onSuccess(BasicResponse<LoginBean> response) {
App.destoryActivity("MainActivity");
SPUtil.put(LoginActivity.this, IConstants.IS_LOGIN, true);
SPUtil.put(LoginActivity.this, IConstants.TOKEN, response.getData().getAccessToken());
SPUtil.put(LoginActivity.this, IConstants.REFRESH_TOKEN, response.getData().getRefreshToken());
SPUtil.put(LoginActivity.this, IConstants.TYPE, response.getData().getType());
SPUtil.put(LoginActivity.this, IConstants.POEN_ID, response.getData().getOpenId());
SPUtil.put(LoginActivity.this, IConstants.USER_ID, response.getData().getOpenId());
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
// /**
// * token刷新成功后重新请求数据,每个请求都重写
// */
// @Override
// public void onTokenUpdateSuccess() {
// super.onTokenUpdateSuccess();
// }
});
}
@OnClick({R.id.rl_lonin_go_home, R.id.tv_login_forget_pwd, R.id.bt_login, R.id.ll_login_go_register, R.id.iv_login_verification_code})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.rl_lonin_go_home:
hideInput();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
break;
case R.id.tv_login_forget_pwd:
startActivity(new Intent(this, ForgetPasswordOneActivity.class));
finish();
break;
case R.id.bt_login:
String phoneNum = etLoginPhoneNum.getText().toString().trim();
String loginPwd = etLoginPwd.getText().toString().trim();
String verificationCode = etLoginVerificationCode.getText().toString().trim();
if (checkPwd(loginPwd)) {
ToastUtil.showToast("密码格式不正确");
return;
}
if (!phoneNum.equals("") && !loginPwd.equals("") && !verificationCode.equals("")) {
Login();
} else {
ToastUtil.showToast(getString(R.string.msg_no_ok));
return;
}
break;
case R.id.ll_login_go_register:
startActivity(new Intent(this, UserRegisterActivity.class));
finish();
break;
case R.id.iv_login_verification_code:
initData();
break;
default:
break;
}
}
}<file_sep>package com.mengyang.kohler.module.bean;
import java.util.List;
/**
* Description :
* Author : rmy
* Email : <EMAIL>
* Time : 2018/2/6
*/
public class BooksListBean {
/**
* pageNum : 0
* pageSize : 10
* resultList : [{"createTime":"2018-02-07 20:12:30","id":8,"isShow":0,"kvUrl":"http://ojd06y9cv.bkt.clouddn.com/4969f7828af22e1ec8d30ecc9e7d2c22.png?/0/w/1280/h/960 \t\t\t\t","nameCn":"经销商手册","pdfUrl":"http://ojd06y9cv.bkt.clouddn.com/619820641c5890217b99e5cc968e526c.pdf \t\t\t\t","videoUrl":"","weight":103},{"createTime":"2018-03-01 16:06:49","id":10,"isShow":0,"kvUrl":"http://ojd06y9cv.bkt.clouddn.com/f408b773150fd3fde06b78d74be11084.jpg?/0/w/1280/h/960 \t\t\t\t","nameCn":"淋浴龙头","pdfUrl":"","videoUrl":"https://v.qq.com/x/page/i056136eut0.html \t\t\t\t","weight":102},{"createTime":"2018-03-01 16:00:26","id":9,"isShow":0,"kvUrl":"http://ojd06y9cv.bkt.clouddn.com/6097371b2204ded4a8e0972a49c04968.jpg?/0/w/1280/h/960 \t\t\t\t","nameCn":"c3座便器盖板","pdfUrl":"","videoUrl":"https://v.qq.com/x/page/x13037qe46q.html \t\t\t\t","weight":101}]
* totalPage : 1
* totalSize : 3
*/
private int pageNum;
private int pageSize;
private int totalPage;
private int totalSize;
private List<ResultListBean> resultList;
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getTotalSize() {
return totalSize;
}
public void setTotalSize(int totalSize) {
this.totalSize = totalSize;
}
public List<ResultListBean> getResultList() {
return resultList;
}
public void setResultList(List<ResultListBean> resultList) {
this.resultList = resultList;
}
public static class ResultListBean {
/**
* createTime : 2018-02-07 20:12:30
* id : 8
* isShow : 0
* kvUrl : http://ojd06y9cv.bkt.clouddn.com/4969f7828af22e1ec8d30ecc9e7d2c22.png?/0/w/1280/h/960
* nameCn : 经销商手册
* pdfUrl : http://ojd06y9cv.bkt.clouddn.com/619820641c5890217b99e5cc968e526c.pdf
* videoUrl :
* weight : 103
*/
private String createTime;
private int id;
private int isShow;
private String kvUrl;
private String nameCn;
private String pdfUrl;
private String videoUrl;
private int weight;
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getIsShow() {
return isShow;
}
public void setIsShow(int isShow) {
this.isShow = isShow;
}
public String getKvUrl() {
return kvUrl;
}
public void setKvUrl(String kvUrl) {
this.kvUrl = kvUrl;
}
public String getNameCn() {
return nameCn;
}
public void setNameCn(String nameCn) {
this.nameCn = nameCn;
}
public String getPdfUrl() {
return pdfUrl;
}
public void setPdfUrl(String pdfUrl) {
this.pdfUrl = pdfUrl;
}
public String getVideoUrl() {
return videoUrl;
}
public void setVideoUrl(String videoUrl) {
this.videoUrl = videoUrl;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
}
<file_sep>package com.mengyang.kohler.common.adapter;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.ColorSpace;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.mengyang.kohler.App;
import com.mengyang.kohler.R;
import com.mengyang.kohler.common.activity.ReservationExperienceActivity;
import com.mengyang.kohler.common.activity.WebViewActivity;
import com.mengyang.kohler.common.entity.Level0Item;
import com.mengyang.kohler.common.entity.Level1Item;
import com.mengyang.kohler.common.net.IConstants;
import com.mengyang.kohler.common.utils.LogUtils;
import com.mengyang.kohler.common.utils.SPUtil;
import com.mengyang.kohler.module.bean.AzureServiceMultimediaBean;
import com.mengyang.kohler.module.bean.QuestionSearchBean;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
/**
* Created by liusong on 2018/2/9.
*/
public class AzureCustomerServiceAdapter extends BaseMultiItemQuickAdapter<MultiItemEntity, BaseViewHolder> {
public static final int TYPE_LEVEL_0 = 0;
public static final int TYPE_LEVEL_1 = 1;
public static final int TYPE_TEXT = 2;
public static final int TYPE_PRODUCT = 3;
public static final int TYPE_USER = 4;
private SimpleDateFormat mDateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private int mHour;
private boolean mPositionLineVisible = true;
/**
* Same as QuickAdapter#QuickAdapter(Context,int) but with
* some initialization data.
*
* @param data A new list is created out of this one to avoid mutable list
*/
public AzureCustomerServiceAdapter(List<MultiItemEntity> data) {
super(data);
addItemType(TYPE_LEVEL_0, R.layout.item_azure_service_list_parent);
addItemType(TYPE_LEVEL_1, R.layout.item_azure_service_list_child);
addItemType(TYPE_TEXT, R.layout.item_azure_service_company_head); //必须设置Item类型,否则空职指针异常
addItemType(TYPE_PRODUCT, R.layout.item_azure_service_product);
addItemType(TYPE_USER, R.layout.item_azure_service_user);
}
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void convert(final BaseViewHolder helper, final MultiItemEntity item) {
switch (item.getItemType()) {
case TYPE_LEVEL_0://父级
final Level0Item level0Item = (Level0Item) item;
//判断分割线是否显示(比较low)
/* if (!mPositionLineVisible)
helper.getView(R.id.view_azure_parent_line).setVisibility(View.VISIBLE);
if (mPositionLineVisible)
helper.getView(R.id.view_azure_parent_line).setVisibility(View.GONE);
if (helper.getView(R.id.view_azure_parent_line).getVisibility() == View.VISIBLE) {
mPositionLineVisible = true;
} else {
mPositionLineVisible = false;
}
if (helper.getLayoutPosition() == 1)
helper.getView(R.id.view_azure_parent_line).setVisibility(View.GONE);
if (helper.getLayoutPosition() == 2 || helper.getLayoutPosition() == 3)
helper.getView(R.id.view_azure_parent_line).setVisibility(View.VISIBLE);*/
helper.setText(R.id.tv_service_list_top_01, level0Item.getParrentLeft());
helper.setText(R.id.tv_service_list_top_02, level0Item.getParrentRight());
helper.setBackgroundColor(R.id.rl_item_parent, Color.argb(77, 255, 255, 255));
helper.addOnClickListener(R.id.tv_service_list_top_01);
helper.addOnClickListener(R.id.tv_service_list_top_02);
// helper.setOnClickListener(R.id.rl_item_parent, new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// int position = helper.getLayoutPosition();
// if (level0Item.isExpanded()) {
// collapse(position);
//// rotationExpandIcon(180, 0, v);
// } else {
// expand(position);
//// rotationExpandIcon(0, 180, v);
// }
// }
// });
break;
case TYPE_LEVEL_1: //子级
final Level1Item level0Item1 = (Level1Item) item;
helper.setText(R.id.tv_azure_list_child_content, level0Item1.getContent());
helper.setBackgroundColor(R.id.rl_item_child, Color.argb(77, 255, 255, 255));
break;
case TYPE_TEXT://客服文本
int adapterPosition = helper.getAdapterPosition();
if ((adapterPosition == 4)) {
RelativeLayout view = helper.getView(R.id.rl_head);
RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) view.getLayoutParams();
layoutParams.setMargins(0, 78, 0, 0);
view.setLayoutParams(layoutParams);
}
final QuestionSearchBean textBean = (QuestionSearchBean) item;
helper.setText(R.id.tv_serviec_user, "客服小科")
.setText(R.id.tv_service_time, parseTiem());
if (textBean.getDescription() != null) {
TextView textview = helper.getView(R.id.tv_service_message);
if (textBean.getDescription().equals("还可以进入科勒预约系统进行门店查询和预约, 点击进入 或 返回")) {
textview.setText(getClickableSpan());
textview.setMovementMethod(LinkMovementMethod.getInstance());
} else
textview.setText(textBean.getDescription());
}
if (mHour >= 0 && mHour < 12) {
helper.setText(R.id.tv_flag, "AM");
} else {
helper.setText(R.id.tv_flag, "PM");
}
break;
case TYPE_PRODUCT:
RelativeLayout view = helper.getView(R.id.rl_azure_service_img);
RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) view.getLayoutParams();
layoutParams.setMargins(0, 78, 0, 0);
view.setLayoutParams(layoutParams);
final AzureServiceMultimediaBean azureServiceMultimediaBean = (AzureServiceMultimediaBean) item;
helper.setBackgroundColor(R.id.ll_azure_service_bg, Color.argb(77, 255, 255, 255));
Glide.with(App.getContext()).load(azureServiceMultimediaBean.getImageUrl()).apply(new RequestOptions().placeholder(R.mipmap.queshengtu)).into((ImageView) helper.getView(R.id.iv_service_product_icon));
helper.setText(R.id.tv_service_time, parseTiem()).setText(R.id.tv_service_product_recommend, azureServiceMultimediaBean.getTitle())
.setText(R.id.tv_service_product_recommend_01, azureServiceMultimediaBean.getElementDesc());
if (mHour >= 0 && mHour < 12) {
helper.setText(R.id.tv_flag, "AM");
} else {
helper.setText(R.id.tv_flag, "PM");
}
helper.addOnClickListener(R.id.ll_azure_service_bg);
break;
case TYPE_USER: //用户
final QuestionSearchBean questionSearchBean = (QuestionSearchBean) item;
helper.setText(R.id.tv_serviec_user_name, (String) SPUtil.get(App.getContext(), IConstants.USER_NIKE_NAME, ""))
.setText(R.id.tv_service_time, parseTiem())
.setText(R.id.tv_service_message, questionSearchBean.getDescription());
//设置头像
Glide.with(App.getContext()).load(SPUtil.get(App.getContext(), IConstants.USER_HEAD_PORTRAIT, ""))
.apply(new RequestOptions().placeholder(R.mipmap.azure_service_photo_w)).into((ImageView) helper.getView(R.id.iv_service_photo));
if (mHour >= 0 && mHour < 12) {
helper.setText(R.id.tv_flag, "AM");
} else {
helper.setText(R.id.tv_flag, "PM");
}
break;
default:
break;
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void rotationExpandIcon(float from, float to, final View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ValueAnimator valueAnimator = ValueAnimator.ofFloat(from, to);//属性动画
valueAnimator.setDuration(500);
valueAnimator.setInterpolator(new DecelerateInterpolator());
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
v.setRotation((Float) valueAnimator.getAnimatedValue());
}
});
valueAnimator.start();
}
}
private String parseTiem() {
long time = System.currentTimeMillis();
final Calendar mCalendar = Calendar.getInstance();
mCalendar.setTimeInMillis(time);
// 取得小时:
mHour = mCalendar.get(Calendar.HOUR_OF_DAY);
// 取得分钟:
int mMinuts = mCalendar.get(Calendar.MINUTE);
String mMinString = null;
String mHourString = null;
if (mMinuts < 10) {
mMinString = "0" + mMinuts;
} else {
mMinString = "" + mMinuts;
}
if (mHour == 0) {
mHourString = "0" + mHour;
} else {
mHourString = "" + mHour;
}
return mHourString + ":" + mMinString;
}
/**
* 获取可点击的SpannableString
*
* @return
*/
private SpannableString getClickableSpan() {
SpannableString spannableString = new SpannableString("还可以进入科勒预约系统进行门店查询和预约, 点击进入 或 返回");
//设置下划线文字
spannableString.setSpan(new UnderlineSpan(), 22, 26, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//设置文字的单击事件
spannableString.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
mContext.startActivity(new Intent(mContext, ReservationExperienceActivity.class));
}
}, 22, 26, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//设置文字的前景色
spannableString.setSpan(new ForegroundColorSpan(App.getContext().getResources().getColor(R.color.colorBluePrimary)), 22, 26, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//设置下划线文字
spannableString.setSpan(new UnderlineSpan(), 29, 31, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//设置文字的单击事件
spannableString.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
App.destoryActivity("AzureCustomerServiceActivity");
}
}, 29, 31, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//设置文字的前景色
spannableString.setSpan(new ForegroundColorSpan(App.getContext().getResources().getColor(R.color.colorBluePrimary)), 29, 31, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableString;
}
}
<file_sep>package com.mengyang.kohler.home.adapter;
import android.support.annotation.Nullable;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.mengyang.kohler.App;
import com.mengyang.kohler.R;
import com.mengyang.kohler.common.utils.LogUtils;
import com.mengyang.kohler.module.bean.KbisBean;
import java.util.List;
/**
* Description :
* Author : rmy
* Email : <EMAIL>
* Time : 2018/2/2
*/
public class KbisVideoAdapter extends BaseQuickAdapter<KbisBean.VideoListBean, BaseViewHolder> {
private int mHeight;
private int mWidth;
public KbisVideoAdapter(@Nullable List<KbisBean.VideoListBean> data) {
super(R.layout.item_kbis_video, data);
}
@Override
protected void convert(final BaseViewHolder helper, final KbisBean.VideoListBean item) {
int position = helper.getLayoutPosition();
// if (position == 2)
Glide.with(App.getContext()).load(item.getKvUrl()).into((ImageView) helper.getView(R.id.iv_kbis));
// ViewGroup.LayoutParams imageLayoutParams = helper.getView(R.id.iv_kbis).getLayoutParams();
// if (helper.getLayoutPosition() % 2 == 0) {
// imageLayoutParams.width = 440;//获取实际展示的图片宽度
// imageLayoutParams.height = 687;//获取最终图片高度
// } else {
// imageLayoutParams.width = 440;//获取实际展示的图片宽度
// imageLayoutParams.height = 440;//获取最终图片高度
// }
// helper.getView(R.id.iv_kbis).setLayoutParams(imageLayoutParams);//应用高度到布局中
helper.setText(R.id.tv_kbis_play_title, item.getTitle())
.setText(R.id.tv_kbis_play_des, item.getElementDesc());
helper.addOnClickListener(R.id.iv_kbis);
helper.addOnClickListener(R.id.iv_kbis_play);
}
}
<file_sep>package com.mengyang.kohler.common.activity;
import android.content.Intent;
import android.graphics.Rect;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.AlphaAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.google.gson.Gson;
import com.mengyang.kohler.App;
import com.mengyang.kohler.BaseActivity;
import com.mengyang.kohler.R;
import com.mengyang.kohler.common.adapter.UserServiceAdapter;
import com.mengyang.kohler.common.entity.Level0Item;
import com.mengyang.kohler.common.entity.Level1Item;
import com.mengyang.kohler.common.net.Config;
import com.mengyang.kohler.common.net.IdeaApi;
import com.mengyang.kohler.common.utils.ToastUtil;
import com.mengyang.kohler.common.view.TopView;
import com.mengyang.kohler.module.bean.AzureServiceBean;
import com.mengyang.kohler.module.bean.AzureServiceMultimediaBean;
import com.mengyang.kohler.module.bean.QuestionSearchBean;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* 客服
*/
public class CustomerServiceActivity extends BaseActivity {
@BindView(R.id.tv_customer_service_top)
TopView tvCustomerServiceTop;
@BindView(R.id.btn_send_message)
Button mBtnSendMessage;
@BindView(R.id.recycler_view_service11)
RecyclerView mRecyclerViewService;
@BindView(R.id.et_question)
EditText mEtQuestion;
@BindView(R.id.rb_customer_01)
RadioButton mRbCustomer01;
@BindView(R.id.rb_customer_02)
RadioButton mRbCustomer02;
@BindView(R.id.rb_customer_03)
RadioButton mRbCustomer03;
@BindView(R.id.ll_customer)
LinearLayout mLlCustomer;
@BindView(R.id.hsv_customer)
HorizontalScrollView mHsvCustomer;
private static final String HEADER_KEY = "Authorization";
// private static final String HEADER_VALUE = "Bearer yTlSJIGr5Ak.cwA.k1Y.hD-eSE5mXqmXFNzB6TX_LI4qqD_TyCPQYOqEK2Lnk68";
private static final String HEADER_VALUE = "Basic [base64(n0lWVV1Lwx8p7tYR:95f19722c7f2544b395bf89c8789ebaa2748020a5bf49162385219ec67c9b0fc)]";
private String mQuestionContent;
// private AzureCustomerServiceAdapter mUserServiceAdapter;
// private static final String URL = "https://directline.botframework.com/";
// private static final String START = URL + "v3/directline/conversations";
// private static final String REQUEST = "/activities";
// private AzureBotStartBean mAzureBotStartBean;
private AzureServiceMultimediaBean mAzureServiceMultimediaBean;
private ArrayList<MultiItemEntity> res;
private UserServiceAdapter mUserServiceAdapter;
@Override
protected int getLayoutId() {
return R.layout.activity_customer_service;
}
@Override
protected void initValues() {
App.addDestoryActivity(this, "CustomerServiceActivity");
App.getManager().addActivity(this);
// //防止状态栏和标题重叠
// ImmersionBar.setTitleBar(this, tvCustomerServiceTop);
initAdapter();
mLlCustomer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
private final Rect r = new Rect();
@Override
public void onGlobalLayout() {
mLlCustomer.getWindowVisibleDisplayFrame(r);
int heightDiff = mLlCustomer.getRootView().getHeight() - (r.bottom - r.top);
boolean isOpen = heightDiff > 100;
if (isOpen) {
mHsvCustomer.clearAnimation();
mHsvCustomer.setVisibility(View.GONE);
} else {
mHsvCustomer.setVisibility(View.VISIBLE);
AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
//设置动画持续时长
alphaAnimation.setDuration(300);
//设置动画结束之后的状态是否是动画的最终状态,true,表示是保持动画结束时的最终状态
alphaAnimation.setFillAfter(true);
//设置动画结束之后的状态是否是动画开始时的状态,true,表示是保持动画开始时的状态
alphaAnimation.setFillBefore(true);
mHsvCustomer.startAnimation(alphaAnimation);
}
}
});
}
private void initAdapter() {
mRecyclerViewService.setLayoutManager(new LinearLayoutManager(this));
mUserServiceAdapter = new UserServiceAdapter(generateData());
mRecyclerViewService.setAdapter(mUserServiceAdapter);
mUserServiceAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
@Override
public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
switch (view.getId()) {
case R.id.ll_home_service_bg:
startActivity(new Intent(CustomerServiceActivity.this, WebViewActivity.class).putExtra("h5url", mAzureServiceMultimediaBean.getH5Url()));
break;
case R.id.tv_service_list_top_01:
TextView textView = (TextView) view;
if (!textView.getText().toString().trim().equals(""))
searchQuestion(textView.getText().toString().trim());
break;
case R.id.tv_service_list_top_02:
TextView textView2 = (TextView) view;
if (!textView2.getText().toString().trim().equals(""))
searchQuestion(textView2.getText().toString().trim());
break;
}
}
});
}
@Override
protected void initListener() {
mRecyclerViewService.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
hideInput();
return false;
}
});
}
@Override
protected void initData() {
// OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(50000, TimeUnit.MILLISECONDS).writeTimeout(50000, TimeUnit.MILLISECONDS).readTimeout(50000, TimeUnit.MILLISECONDS).build();
// Request requestPost = new Request.Builder().url(START).post(RequestBody.create(null, "")).header(HEADER_KEY, HEADER_VALUE).build();
// Call call = okHttpClient.newCall(requestPost);
// call.enqueue(new Callback() {
// @Override
// public void onFailure(Call call, IOException e) {
// e.printStackTrace();
// }
//
// @Override
// public void onResponse(Call call, Response response) {
// mAzureBotStartBean = new Gson().fromJson(response.body().charStream(), AzureBotStartBean.class);
// }
// });
}
@OnClick({R.id.recycler_view_service11, R.id.btn_send_message, R.id.rb_customer_01, R.id.rb_customer_02, R.id.rb_customer_03})
public void onViewClicked(View view) {
switch (view.getId()) {
// case R.id.recycler_view_service11:
//
// break;
case R.id.btn_send_message:
mQuestionContent = mEtQuestion.getText().toString().trim();
mEtQuestion.getText().clear();
mEtQuestion.setFocusable(true);
if (!TextUtils.isEmpty(mQuestionContent)) {
QuestionSearchBean questionSearchBean = new QuestionSearchBean(mQuestionContent, 4);
mUserServiceAdapter.addData(questionSearchBean);
searchQuestion(mQuestionContent);
} else {
ToastUtil.showToast("输入内容不能为空");
}
break;
case R.id.rb_customer_01:
String rb01 = mRbCustomer01.getText().toString().trim();
searchQuestion(rb01);
break;
case R.id.rb_customer_02:
String rb02 = mRbCustomer02.getText().toString().trim();
searchQuestion(rb02);
break;
case R.id.rb_customer_03:
String rb03 = mRbCustomer03.getText().toString().trim();
searchQuestion(rb03);
break;
default:
break;
}
}
private void searchQuestion(String question) {
OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(50000, TimeUnit.MILLISECONDS).writeTimeout(50000, TimeUnit.MILLISECONDS).readTimeout(50000, TimeUnit.MILLISECONDS).build();
// AzureBotSendMsgBean azureBotSendMsgBean = new AzureBotSendMsgBean();
// AzureBotSendMsgBean.FromBean fromBean = new AzureBotSendMsgBean.FromBean();
// fromBean.setId("user_name");
// azureBotSendMsgBean.setType("message");
// azureBotSendMsgBean.setFrom(fromBean);
// azureBotSendMsgBean.setText(question);
Map<String, Object> map = IdeaApi.getSign();
map.put("queryStr", question);
Gson gson = new Gson();
String Authorization = gson.toJson(map);
RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), Authorization);
Request requestPost = new Request.Builder().url(Config.AZURE_AI).post(requestBody).header(HEADER_KEY, HEADER_VALUE).build();
Call call = okHttpClient.newCall(requestPost);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) {
AzureServiceBean azureServiceBean = new Gson().fromJson(response.body().charStream(), AzureServiceBean.class);
// AzureBotAnswerQuestionBean azureBotAnswerQuestionBean = new Gson().fromJson(response.body().charStream(), AzureBotAnswerQuestionBean.class);
final QuestionSearchBean questionSearchBean = new QuestionSearchBean("", 2);
if (!azureServiceBean.getData().getMessage().equals("") && azureServiceBean.getData().getMessage() != null)
questionSearchBean.setDescription(azureServiceBean.getData().getMessage());
if (azureServiceBean.getData().getClickVos().size() > 0) {
for (int i = 0; i < azureServiceBean.getData().getClickVos().size(); i++) {
// String parent_start = StringUtils.identical(azureServiceBean.getData().getClickVos().get(i).getText(), "【", "】");
// String parent_end = azureServiceBean.getData().getClickVos().get(i).getText().substring(parent_start.lastIndexOf("】") + 1, azureServiceBean.getData().getClickVos().get(i).getText().length());
// res.add(new Level0Item(parent_start, parent_end));
String parent_end = azureServiceBean.getData().getClickVos().get(i).getText();//.substring(parent_start.lastIndexOf("】") + 1, azureServiceBean.getData().getClickVos().get(i).getText().length());
res.add(new Level0Item("", parent_end));
// int a = 24;
// String str = StringUtils.identical("【售前问题】(门店预约、产品询价、官方商城地址)", "【", "】");
// LogUtils.i("rmy", "str = " + str);
// int o = str.lastIndexOf("】");
// LogUtils.i("rmy", "o = " + o);
// String ppp = "【售前问题】(门店预约、产品询价、官方商城地址)".substring(o + 1, a);
// LogUtils.i("rmy", "ppp = " + ppp);
// res.add(new Level0Item(str, ppp));
}
}
if (azureServiceBean.getData().getMultimedia().size() > 0) {
for (int i = 0; i < azureServiceBean.getData().getMultimedia().size(); i++) {
mAzureServiceMultimediaBean = new AzureServiceMultimediaBean(azureServiceBean.getData().getMultimedia().get(i).getElementDesc(), azureServiceBean.getData().getMultimedia().get(i).getElementType(), azureServiceBean.getData().getMultimedia().get(i).getH5Url(), azureServiceBean.getData().getMultimedia().get(i).getImageUrl(), azureServiceBean.getData().getMultimedia().get(i).getTitle(), 3);
res.add(mAzureServiceMultimediaBean);
}
}
CustomerServiceActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
mUserServiceAdapter.addData(questionSearchBean);
mRecyclerViewService.scrollToPosition(mUserServiceAdapter.getItemCount() - 1);
}
});
// new Thread() {
// public void run() {
// try {
// sleep(3000);
// answerQuestion(START + "/" + mAzureBotStartBean.getConversationId() + REQUEST + "?watermark=" + azureBotWartBean.getId().substring(23));
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// }.start();
}
});
}
// private void answerQuestion(String answerUrl) {
// OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(50000, TimeUnit.MILLISECONDS).writeTimeout(50000, TimeUnit.MILLISECONDS).readTimeout(50000, TimeUnit.MILLISECONDS).build();
// Request request = new Request.Builder().url(answerUrl).header(HEADER_KEY, HEADER_VALUE).build();
// okHttpClient.newCall(request).enqueue(new Callback() {
// @Override
// public void onFailure(Call call, IOException e) {
// }
//
// @Override
// public void onResponse(Call call, Response response) {
// AzureBotAnswerQuestionBean azureBotAnswerQuestionBean = new Gson().fromJson(response.body().charStream(), AzureBotAnswerQuestionBean.class);
// final QuestionSearchBean questionSearchBean = new QuestionSearchBean("", 2);
// questionSearchBean.setDescription(azureBotAnswerQuestionBean.getActivities().get(0).getText());
// AzureCustomerServiceActivity.this.runOnUiThread(new Runnable() {
// @Override
// public void run() {
// mUserServiceAdapter.addData(questionSearchBean);
// rvAzureBot.scrollToPosition(mUserServiceAdapter.getItemCount() - 1);
// }
// });
// }
// });
// }
private ArrayList<MultiItemEntity> generateData() {
int lv1Count = 3;
res = new ArrayList<>();
QuestionSearchBean textBean = new QuestionSearchBean("Hi~我是科勒客服,需要咨询科勒产品吗,请在对话框输入尝试一下我们的Click to Chat?", 2);
res.add(textBean);
Level0Item lv0 = new Level0Item("【售前问题】", "(门店预约、产品询价、官方商城地址)");
for (int j = 0; j < lv1Count; j++) {
Level1Item lv1 = new Level1Item("更改配送时间?" + j);
lv0.addSubItem(lv1);
}
res.add(lv0);
lv0 = new Level0Item("【产品相关】", "(产品规格/参数、产品SKU)");
for (int j = 0; j < lv1Count; j++) {
Level1Item lv1 = new Level1Item("更改配送时间?" + j);
lv0.addSubItem(lv1);
}
res.add(lv0);
lv0 = new Level0Item("【售后问题】", "(商品故障/损坏、保修查询、客服热线)");
for (int j = 0; j < lv1Count; j++) {
Level1Item lv1 = new Level1Item("更改配送时间?" + j);
lv0.addSubItem(lv1);
}
res.add(lv0);
textBean = new QuestionSearchBean("还可以进入科勒预约系统进行门店查询和预约, 点击进入 或 返回", 2);
res.add(textBean);
// res.add(new QuestionSearchBean("2222222222222222", 3));
return res;
}
}
<file_sep>package com.mengyang.kohler.module.bean;
import java.util.List;
public class AzureServiceBean {
/**
* data : {"clickVos":[{"id":-1,"params":"","text":"","weight":0},{"id":-1,"params":"","text":"","weight":0},{"id":-1,"params":"","text":"","weight":0}],"message":"你好,欢迎使用智能客服系统!我是小科,请多指教。","multimedia":[{"elementDesc":"","elementType":"","h5Url":"","id":-1,"imageUrl":"","params":"","title":"","weight":0},{"elementDesc":"","elementType":"","h5Url":"","id":-1,"imageUrl":"","params":"","title":"","weight":0},{"elementDesc":"","elementType":"","h5Url":"","id":-1,"imageUrl":"","params":"","title":"","weight":0}]}
* error : 200
* message : successful
* status : 1
*/
private DataBean data;
private String error;
private String message;
private int status;
public DataBean getData() {
return data;
}
public void setData(DataBean data) {
this.data = data;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public static class DataBean {
/**
* clickVos : [{"id":-1,"params":"","text":"","weight":0},{"id":-1,"params":"","text":"","weight":0},{"id":-1,"params":"","text":"","weight":0}]
* message : 你好,欢迎使用智能客服系统!我是小科,请多指教。
* multimedia : [{"elementDesc":"","elementType":"","h5Url":"","id":-1,"imageUrl":"","params":"","title":"","weight":0},{"elementDesc":"","elementType":"","h5Url":"","id":-1,"imageUrl":"","params":"","title":"","weight":0},{"elementDesc":"","elementType":"","h5Url":"","id":-1,"imageUrl":"","params":"","title":"","weight":0}]
*/
private String message;
private List<ClickVosBean> clickVos;
private List<MultimediaBean> multimedia;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<ClickVosBean> getClickVos() {
return clickVos;
}
public void setClickVos(List<ClickVosBean> clickVos) {
this.clickVos = clickVos;
}
public List<MultimediaBean> getMultimedia() {
return multimedia;
}
public void setMultimedia(List<MultimediaBean> multimedia) {
this.multimedia = multimedia;
}
public static class ClickVosBean {
/**
* id : -1
* params :
* text :
* weight : 0
*/
private int id;
private String params;
private String text;
private int weight;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getParams() {
return params;
}
public void setParams(String params) {
this.params = params;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
public static class MultimediaBean {
/**
* elementDesc :
* elementType :
* h5Url :
* id : -1
* imageUrl :
* params :
* title :
* weight : 0
*/
private String elementDesc;
private String elementType;
private String h5Url;
private int id;
private String imageUrl;
private String params;
private String title;
private int weight;
public String getElementDesc() {
return elementDesc;
}
public void setElementDesc(String elementDesc) {
this.elementDesc = elementDesc;
}
public String getElementType() {
return elementType;
}
public void setElementType(String elementType) {
this.elementType = elementType;
}
public String getH5Url() {
return h5Url;
}
public void setH5Url(String h5Url) {
this.h5Url = h5Url;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getParams() {
return params;
}
public void setParams(String params) {
this.params = params;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
}
}
<file_sep>package com.mengyang.kohler.module.bean;
import java.util.List;
/**
* Description :
* Author : rmy
* Email : <EMAIL>
* Time : 2018/2/2
*/
public class StoreListBean {
/**
* pageNum : 0
* pageSize : 10
* resultList : [{"address":"徐虹中路21号","distance":777,"latitude":31.194329,"longitude":121.431996,"roomname":"徐汇设计中心","storeId":932,"tel":"64867200"},{"address":"宜山路407号","distance":1108,"latitude":31.192982,"longitude":121.435359,"roomname":"喜盈门国际馆","storeId":933,"tel":"64867200"},{"address":"宜山路450号","distance":996,"latitude":31.190264,"longitude":121.433119,"roomname":"家饰佳","storeId":931,"tel":"64382548"},{"address":"漕溪路198号","distance":2340,"latitude":31.179596,"longitude":121.441297,"roomname":"好饰家装饰精品城","storeId":927,"tel":"64872224"}]
* totalPage : 1
* totalSize : 4
*/
private int pageNum;
private int pageSize;
private int totalPage;
private int totalSize;
private List<ResultListBean> resultList;
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getTotalSize() {
return totalSize;
}
public void setTotalSize(int totalSize) {
this.totalSize = totalSize;
}
public List<ResultListBean> getResultList() {
return resultList;
}
public void setResultList(List<ResultListBean> resultList) {
this.resultList = resultList;
}
public static class ResultListBean {
/**
* address : 徐虹中路21号
* distance : 777
* latitude : 31.194329
* longitude : 121.431996
* roomname : 徐汇设计中心
* storeId : 932
* tel : 64867200
*/
private String address;
private int distance;
private double latitude;
private double longitude;
private String roomname;
private int storeId;
private String tel;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public String getRoomname() {
return roomname;
}
public void setRoomname(String roomname) {
this.roomname = roomname;
}
public int getStoreId() {
return storeId;
}
public void setStoreId(int storeId) {
this.storeId = storeId;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
}
}
<file_sep>package com.mengyang.kohler.home.adapter;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.mengyang.kohler.App;
import com.mengyang.kohler.R;
import com.mengyang.kohler.common.net.IConstants;
import com.mengyang.kohler.common.utils.SPUtil;
import java.util.ArrayList;
/**
* Created by use012 on 2017/5/11.
*/
public class BigAdapter extends PagerAdapter {
private ArrayList<String> mImageViewUrl;
private Context mContext;
public BigAdapter(Context mContext, ArrayList<String> mImageViewUrl) {
this.mImageViewUrl = mImageViewUrl;
this.mContext = mContext;
}
@Override
public int getCount() {
return mImageViewUrl.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, final int position) {
ImageView imageView = new ImageView(mContext);
Glide.with(App.getContext()).load(mImageViewUrl.get(position))
.apply(new RequestOptions().placeholder(R.mipmap.oval)).into(imageView);
// imageView.setBackgroundResource(mImageViewUrl[position]);
/*
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mOnImageClickListener != null) {
// 接口实例化后的而对象,调用重写后的方法
mOnImageClickListener.onClick(v,position);
}
}
});
*/
container.addView(imageView);
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// super.destroyItem(container, position, object);
container.removeView((View) object);
}
/**
* 按钮点击事件对应的接口
*/
private OnImageClickListener mOnImageClickListener;
public interface OnImageClickListener{
public void onClick(View view, int position);
}
/**
*按钮点击事件需要的方法
*/
public void SetImageOnclick(OnImageClickListener OnImageClickListener){
this.mOnImageClickListener=OnImageClickListener;
}
/**
* 触摸事件对应的接口
*/
private OnImageTouchListener mOnImageTouchListener;
public interface OnImageTouchListener{
public void onImageTouch(View v, MotionEvent event);
}
/**
*按钮点击事件需要的方法
*/
public void SetImageTouchListen(OnImageTouchListener onImageTouchListener){
this.mOnImageTouchListener=onImageTouchListener;
}
}
<file_sep>package com.mengyang.kohler.home.activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.widget.TextView;
import com.mengyang.kohler.BaseActivity;
import com.mengyang.kohler.R;
import com.mengyang.kohler.common.net.DefaultObserver;
import com.mengyang.kohler.common.net.IdeaApi;
import com.mengyang.kohler.common.utils.ToastUtil;
import com.mengyang.kohler.home.adapter.MyImageAdapter;
import com.mengyang.kohler.home.view.BottomAnimDialog;
import com.mengyang.kohler.home.view.PhotoViewPager;
import com.mengyang.kohler.module.BasicResponse;
import com.mengyang.kohler.module.bean.ArtKohlerSelectImgBean;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
public class ArtKohlerSelectBigImgActivity extends BaseActivity implements ViewPager.OnPageChangeListener {
@BindView(R.id.vp_art_kohler_select_big_img)
PhotoViewPager vpArtKohlerSelectBigImg;
@BindView(R.id.tv_page_num)
TextView mTvPageNum;
private List<ArtKohlerSelectImgBean.ResultListBean> mArtSelectBean = new ArrayList<>();
private int position;
private MyImageAdapter adapter;
private List<String> Urls;
@Override
protected int getLayoutId() {
return R.layout.activity_art_kohler_select_big_img;
}
@Override
protected void initValues() {
position = getIntent().getIntExtra("position", 0);
Urls = new ArrayList<>();
vpArtKohlerSelectBigImg.addOnPageChangeListener(this);
}
@Override
protected void initListener() {
}
@Override
protected void initData() {
Map<String, Object> stringMap = IdeaApi.getSign();
stringMap.put("groupId", getIntent().getIntExtra("select_img", 0) + "");
IdeaApi.getRequestLogin(stringMap);
IdeaApi.getApiService()
.getArtKohlerSelectImg(stringMap)
.compose(ArtKohlerSelectBigImgActivity.this.<BasicResponse<ArtKohlerSelectImgBean>>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BasicResponse<ArtKohlerSelectImgBean>>(ArtKohlerSelectBigImgActivity.this, false) {
@Override
public void onSuccess(BasicResponse<ArtKohlerSelectImgBean> response) {
mArtSelectBean.clear();
mArtSelectBean.addAll(response.getData().getResultList());
for (int i = 0; i < mArtSelectBean.size(); i++) {
if (mArtSelectBean.get(i).getPicUrl() != null) {
Urls.add(mArtSelectBean.get(i).getPicUrl());
}
}
adapter = new MyImageAdapter(Urls, ArtKohlerSelectBigImgActivity.this);
vpArtKohlerSelectBigImg.setAdapter(adapter);
vpArtKohlerSelectBigImg.setCurrentItem(position, false);
adapter.SetPictureLongClickListenner(new MyImageAdapter.PictureLongClickListenner() {
@Override
public void onPictureLongClick(final String url) {
final BottomAnimDialog dialog = new BottomAnimDialog(ArtKohlerSelectBigImgActivity.this, "保存图片", "取消");
dialog.setClickListener(new BottomAnimDialog.BottonAnimDialogListener() {
@Override
public void onItem1Listener() {
// TO_DO
new Thread() {
@Override
public void run() {
super.run();
Bitmap bitmap = returnBitMap(url);
MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "title", "description");
runOnUiThread(new Runnable() {
@Override
public void run() {
ToastUtil.showToast("图片已保存!");
}
});
}
}.start();
dialog.dismiss();
}
@Override
public void onItem3Listener() {
dialog.dismiss();
}
});
dialog.show();
}
});
}
});
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
mTvPageNum.setText((position + 1) + "/" + Urls.size());
}
@Override
public void onPageScrollStateChanged(int state) {
}
public Bitmap returnBitMap(String url) {
URL myFileUrl = null;
Bitmap bitmap = null;
try {
myFileUrl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
}
<file_sep>package com.mengyang.kohler.account.activity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.mengyang.kohler.App;
import com.mengyang.kohler.BaseActivity;
import com.mengyang.kohler.R;
import com.mengyang.kohler.common.net.DefaultObserver;
import com.mengyang.kohler.common.net.IdeaApi;
import com.mengyang.kohler.common.utils.DateUtils;
import com.mengyang.kohler.common.utils.ToastUtil;
import com.mengyang.kohler.common.utils.VerifyUtils;
import com.mengyang.kohler.main.activity.MainActivity;
import com.mengyang.kohler.module.BasicResponse;
import java.util.Map;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
/**
* 经销商注册
*/
public class DistributorRegisterActivity extends BaseActivity {
// 这是一个外包小公司,在甲方公司里办公的...别被忽悠了
// 这家老板人品不好,进来说好交社保,但实际上不给你交,工资能拖就拖(有次一拖就3个月)
// 说好的有年终奖也是没有的别想了,过节没有任何东西发,自己带电脑也没有补贴金的~
// 这公司管理混乱趁早走吧兄弟...
@BindView(R.id.rl_distributor_register_go_home)
RelativeLayout ivDistributorRegisterGoHome;
@BindView(R.id.et_distributor_register_phone_num)
EditText etDistributorRegisterPhoneNum;
@BindView(R.id.et_distributor_register_distributor_code)
EditText etDistributorRegisterDistributorCode;
@BindView(R.id.et_distributor_register_login_pwd)
EditText etDistributorRegisterLoginPwd;
@BindView(R.id.bt_distributor_register)
Button btDistributorRegister;
@BindView(R.id.tv_distributor_register_go_user_register)
TextView tvDistributorRegisterGoUserRegister;
@BindView(R.id.tv_distributor_register_go_designer_register)
TextView tvDistributorRegisterGoDesignerRegister;
@BindView(R.id.et_distributor_register_phone_num_again)
EditText etDistributorRegisterPhoneNumAgain;
@BindView(R.id.sv_distributor)
ScrollView mSvDistributor;
@Override
protected int getLayoutId() {
return R.layout.activity_distributor_register;
}
@Override
protected void initValues() {
App.getManager().addActivity(this);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
}
@Override
protected void initListener() {
etDistributorRegisterPhoneNum.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//输入文本之前的状态
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//输入文字中的状态,count是一次性输入字符数
}
@Override
public void afterTextChanged(Editable editable) {
//输入文字后的状态
if (etDistributorRegisterPhoneNum.getText().toString().trim().length() == 11 && VerifyUtils.isMobileNumber(etDistributorRegisterPhoneNum.getText().toString().trim())) {
} else if (etDistributorRegisterPhoneNum.getText().toString().trim().length() == 11){
ToastUtil.showToast("请输入正确的手机号码!");
etDistributorRegisterPhoneNum.setText("");
}
}
});
mSvDistributor.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
hideInput();
return false;
}
});
}
@Override
protected void initData() {
}
private void ModifyBindPhone() {
Map<String, Object> stringMap = IdeaApi.getSign();
stringMap.put("mobileNo", etDistributorRegisterPhoneNum.getText().toString().trim());//手机号码
stringMap.put("mobileNoAgain", etDistributorRegisterPhoneNumAgain.getText().toString().trim());//重新输入手机号码
stringMap.put("inviteCode", etDistributorRegisterDistributorCode.getText().toString().trim());//专用码
stringMap.put("password", <PASSWORD>());//用户密码
stringMap.put("type", "dealer");//用户类型
stringMap.put("time", DateUtils.dataOne(DateUtils.getCurrentTime_Today()));//时间戳
IdeaApi.getRequestLogin(stringMap);
IdeaApi.getApiService()
.getUserRegister(stringMap)
.compose(DistributorRegisterActivity.this.<BasicResponse>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BasicResponse>(DistributorRegisterActivity.this, true) {
@Override
public void onSuccess(BasicResponse response) {
startActivity(new Intent(DistributorRegisterActivity.this, LoginActivity.class));
finish();
}
});
}
@OnClick({R.id.rl_distributor_register_go_home, R.id.bt_distributor_register, R.id.tv_distributor_register_go_user_register, R.id.tv_distributor_register_go_designer_register})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.rl_distributor_register_go_home:
hideInput();
startActivity(new Intent(this, MainActivity.class));
finish();
break;
case R.id.bt_distributor_register:
String phoneNum = etDistributorRegisterPhoneNum.getText().toString().trim();
String phoneNumAgain = etDistributorRegisterPhoneNumAgain.getText().toString().trim();
String distributorCode = etDistributorRegisterDistributorCode.getText().toString().trim();
String loginPwd = etDistributorRegisterLoginPwd.getText().toString().trim();
if (checkPwd(loginPwd)) {
ToastUtil.showToast("密码格式不正确");
return;
}
if (!phoneNum.equals("") && !phoneNumAgain.equals("") && !distributorCode.equals("") && !loginPwd.equals("") && phoneNum.length() == 11) {
if (etDistributorRegisterPhoneNum.getText().toString().trim().equals(etDistributorRegisterPhoneNumAgain.getText().toString().trim()))
ModifyBindPhone();
else
ToastUtil.showToast(getString(R.string.phone_num_agreement));
} else {
ToastUtil.showToast(getString(R.string.msg_no_ok));
}
break;
case R.id.tv_distributor_register_go_user_register:
startActivity(new Intent(this, UserRegisterActivity.class));
break;
case R.id.tv_distributor_register_go_designer_register:
startActivity(new Intent(this, DesignerRegisterActivity.class));
break;
default:
break;
}
}
@Override
protected void onStop() {
super.onStop();
}
}
<file_sep>sdk.dir=D:/Andurio_SDK
<file_sep>package com.mengyang.kohler.account.activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.gyf.barlibrary.ImmersionBar;
import com.mengyang.kohler.App;
import com.mengyang.kohler.BaseActivity;
import com.mengyang.kohler.R;
import com.mengyang.kohler.common.net.DefaultObserver;
import com.mengyang.kohler.common.net.IdeaApi;
import com.mengyang.kohler.common.utils.ToastUtil;
import com.mengyang.kohler.common.utils.VerifyUtils;
import com.mengyang.kohler.common.view.TopView;
import com.mengyang.kohler.module.BasicResponse;
import java.util.Map;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
/**
* 修改绑定手机
*/
public class AccountBindPhoneActivity extends BaseActivity {
// 这是一个外包小公司,在甲方公司里办公的...别被忽悠了
// 这家老板人品不好,进来说好交社保,但实际上不给你交,工资能拖就拖(有次一拖就3个月)
// 说好的有年终奖也是没有的别想了,过节没有任何东西发,自己带电脑也没有补贴金的~
// 这公司管理混乱趁早走吧兄弟...
@BindView(R.id.tv_account_bind_phone_top)
TopView tvAccountBindPhoneTop;
@BindView(R.id.et_modify_bind_phone_old_num)
EditText etModifyBindPhoneOldNum;
@BindView(R.id.et_modify_bind_phone_new_num)
EditText etModifyBindPhoneNewNum;
@BindView(R.id.bt_modify_bind_phone_send_out_new_num)
Button btModifyBindPhoneSendOutNewNum;
@BindView(R.id.et_modify_bind_phone_verification_code)
EditText etModifyBindPhoneVerificationCode;
@BindView(R.id.et_modify_bind_phone_pwd)
EditText etModifyBindPhonePwd;
@BindView(R.id.bt_modify_bind_phone_determine)
Button btModifyBindPhoneDetermine;
@Override
protected int getLayoutId() {
return R.layout.activity_account_bind_phone;
}
@Override
protected void initValues() {
App.getManager().addActivity(this);
//防止状态栏和标题重叠
ImmersionBar.setTitleBar(this, tvAccountBindPhoneTop);
}
@Override
protected void initListener() {
etModifyBindPhoneOldNum.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//输入文本之前的状态
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//输入文字中的状态,count是一次性输入字符数
}
@Override
public void afterTextChanged(Editable editable) {
//输入文字后的状态
if (etModifyBindPhoneOldNum.getText().toString().trim().length() == 11 && VerifyUtils.isMobileNumber(etModifyBindPhoneOldNum.getText().toString().trim())) {
} else if (etModifyBindPhoneOldNum.getText().toString().trim().length() == 11){
ToastUtil.showToast("请输入正确的手机号码!");
etModifyBindPhoneOldNum.setText("");
}
}
});
etModifyBindPhoneNewNum.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//输入文本之前的状态
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//输入文字中的状态,count是一次性输入字符数
}
@Override
public void afterTextChanged(Editable editable) {
//输入文字后的状态
if (etModifyBindPhoneNewNum.getText().toString().trim().length() == 11 && VerifyUtils.isMobileNumber(etModifyBindPhoneNewNum.getText().toString().trim())) {
} else {
ToastUtil.showToast("请输入正确的手机号码!");
etModifyBindPhoneNewNum.setText("");
}
}
});
}
@Override
protected void initData() {
}
private void ModifyBindPhone() {
Map<String, Object> stringMap = IdeaApi.getSign();
stringMap.put("mobileNo", etModifyBindPhoneOldNum.getText().toString().trim());//原手机号码
stringMap.put("verifyCode", etModifyBindPhoneVerificationCode.getText().toString().trim());//换绑时的验证码
stringMap.put("newMobileNo", etModifyBindPhoneNewNum.getText().toString().trim());//新手机号码
stringMap.put("pwd", etModifyBindPhonePwd.getText().toString().trim());//密码
IdeaApi.getRequestLogin(stringMap);
IdeaApi.getApiService()
.getModifyBindPhone(stringMap)
.compose(AccountBindPhoneActivity.this.<BasicResponse>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BasicResponse>(AccountBindPhoneActivity.this, true) {
@Override
public void onSuccess(BasicResponse response) {
finish();
}
});
}
private void LoginSMS() {
Map<String, Object> stringMap = IdeaApi.getSign();
stringMap.put("mobileNo", etModifyBindPhoneNewNum.getText().toString().trim());//手机号码
IdeaApi.getRequestLogin(stringMap);
IdeaApi.getApiService()
.getLoginSMS(stringMap)
.compose(AccountBindPhoneActivity.this.<BasicResponse>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BasicResponse>(AccountBindPhoneActivity.this, false) {
@Override
public void onSuccess(BasicResponse response) {
}
});
}
@OnClick({R.id.bt_modify_bind_phone_send_out_new_num, R.id.bt_modify_bind_phone_determine})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.bt_modify_bind_phone_send_out_new_num:
if (!etModifyBindPhoneNewNum.getText().toString().trim().equals(""))
LoginSMS();
else
ToastUtil.showToast(getString(R.string.msg_no_ok));
break;
case R.id.bt_modify_bind_phone_determine:
if (!etModifyBindPhoneOldNum.getText().toString().trim().equals("") && !etModifyBindPhoneNewNum.getText().toString().trim().equals("") && !etModifyBindPhoneVerificationCode.getText().toString().trim().equals("") && !etModifyBindPhonePwd.getText().toString().trim().equals("") && etModifyBindPhoneOldNum.getText().toString().trim().length() == 11)
ModifyBindPhone();
else
ToastUtil.showToast(getString(R.string.msg_no_ok));
break;
}
}
}
<file_sep>package com.mengyang.kohler.whole_category.adapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.ViewGroup;
import com.mengyang.kohler.module.bean.CommodityClassificationTitleBean;
import com.mengyang.kohler.whole_category.fragment.CommodityClassificationFragment;
import java.util.List;
/**
* 商品分类——顶部导航栏适配器
* Created by ywl on 10/15/15.
*/
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments;
public ViewPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
@Override
public int getCount() {
return fragments.size();
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
}
<file_sep>package com.mengyang.kohler.home.activity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import com.gyf.barlibrary.ImmersionBar;
import com.mengyang.kohler.App;
import com.mengyang.kohler.BaseActivity;
import com.mengyang.kohler.R;
import com.mengyang.kohler.common.net.Config;
import com.mengyang.kohler.common.net.IConstants;
import com.mengyang.kohler.common.utils.SPUtil;
import com.mengyang.kohler.common.utils.ToastUtil;
import com.mengyang.kohler.common.view.TopView;
import com.mengyang.kohler.home.adapter.BarrageAdapter;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* 我要爬墙
*/
public class BarrageActivity extends BaseActivity {
@BindView(R.id.tv_barrage_top)
TopView tvBarrageTop;
@BindView(R.id.btn_barrage_send)
Button mBtnBarrageSend;
@BindView(R.id.recycler_view_barrage)
RecyclerView mRecyclerViewBarrage;
@BindView(R.id.et_barrage)
EditText mEtBarrage;
private List<String> mDataList = new ArrayList<>();
private String mContent;
private BarrageAdapter mBarrageAdapter;
@Override
protected int getLayoutId() {
return R.layout.activity_barrage;
}
@Override
protected void initValues() {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
App.getManager().addActivity(this);
//防止状态栏和标题重叠
ImmersionBar.setTitleBar(this, tvBarrageTop);
mRecyclerViewBarrage.setLayoutManager(new LinearLayoutManager(this));
mBarrageAdapter = new BarrageAdapter(mDataList);
mRecyclerViewBarrage.setAdapter(mBarrageAdapter);
}
@Override
protected void initListener() {
mRecyclerViewBarrage.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
hideInput();
return false;
}
});
}
@Override
protected void initData() {
}
@OnClick({R.id.btn_barrage_send})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.btn_barrage_send:
mContent = mEtBarrage.getText().toString().trim();
mEtBarrage.getText().clear();
mEtBarrage.setFocusable(true);
if (!TextUtils.isEmpty(mContent)) {
mBarrageAdapter.addData(SPUtil.get(App.getContext(), IConstants.USER_NIKE_NAME, "") + ": " + mContent);
mRecyclerViewBarrage.scrollToPosition(mBarrageAdapter.getItemCount() - 1);
SendBarrage(SPUtil.get(App.getContext(), IConstants.USER_NIKE_NAME, "") + ": " + mContent);
} else {
ToastUtil.showToast("输入内容不能为空");
}
break;
default:
break;
}
}
private void SendBarrage(final String content) {
new Thread() {
@Override
public void run() {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
JSONObject json = new JSONObject();
try {
json.put("content", content);
} catch (JSONException e) {
e.printStackTrace();
}
//申明给服务端传递一个json串
//创建一个OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
//创建一个RequestBody(参数1:数据类型 参数2传递的json串)
//json为String类型的json数据
RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
//创建一个请求对象
String token = "<KEY>";
String path = Config.MEETING_BARRAGE + token;
String format = String.format(path);
Request request = new Request.Builder()
.url(format)
.post(requestBody)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("123456", "请求失败");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i("123456", "请求成功");
}
});
}
}.start();
}
}
<file_sep>apply plugin: 'com.android.application'
android {
compileSdkVersion 27
aaptOptions.cruncherEnabled = false
aaptOptions.useNewCruncher = false
defaultConfig {
applicationId "com.mengyang.kohler"
minSdkVersion 21
buildToolsVersion '27.0.3'
targetSdkVersion 27
versionCode 6
versionName "1.0.5"
flavorDimensions "versionCode"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
// Enabling multidex support.
multiDexEnabled true
multiDexKeepProguard file("tinkerMultidexKeep.pro")
//keep specific classes using proguard syntax
ndk {
//设置支持的SO库架构(开发者可以根据需要,选择一个或多个平台的so)
abiFilters "armeabi-v7a"//,"armeabi", "arm64-v8a", "x86", "arm64-v8a", "x86_64"
}
manifestPlaceholders = [
JPUSH_PKGNAME: applicationId,
JPUSH_APPKEY : "0532998d33f6cf83a9de9ca9", //JPush上注册的包名对应的appkey.
JPUSH_CHANNEL: "developer-default", //暂时填写默认值即可.
]
}
signingConfigs {
config {
keyAlias 'kohler'
keyPassword 'kohler123'
storeFile file('D:/科勒签名文件/kohler.jks')
storePassword '<PASSWORD>'
}
test {
keyAlias 'test'
keyPassword 'test123'
storeFile file('D:/科勒签名文件/debug_kohler.jks')
storePassword '<PASSWORD>'
}
}
lintOptions {
abortOnError false
checkReleaseBuilds false
// 防止在发布的时候出现因MissingTranslation导致Build Failed!
disable 'MissingTranslation'
}
buildTypes {
release {
//是否混淆
minifyEnabled false
//压缩对齐生成的apk包
zipAlignEnabled true
// shrinkResources true
//混淆的配置文件
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
//签名配置
signingConfig signingConfigs.config
//启用multidex的支持
multiDexEnabled true
applicationVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.apk')) {
// 输出apk名称为boohee_v1.0_2015-01-15_wandoujia.apk
def fileName = "kohler_v${defaultConfig.versionName}_${variant.productFlavors[0].name}.apk"
// output.outputFile = new File(outputFile.parent, fileName)
}
}
}
}
debug {
// signingConfig signingConfigs.test
}
}
//多渠道打包
productFlavors {
huawei {}
xiaomi {}
yingyongbao {}
baidu {}
wandoujia {}
qh360 {}
pp {}
vivo {}
}
productFlavors.all {
flavor -> flavor.manifestPlaceholders = [INSTALL_CHANNEL_VALUE: name]
}
sourceSets {
main {
jniLibs.srcDirs = ['libs']
}
}
buildToolsVersion '28.0.2'
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:multidex:1.0.2'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.1', {
exclude group: 'com.android.support', module: 'support-annotations'
})
implementation 'com.android.support:design:26.+'
implementation 'com.android.support:support-v4:26.1.0'
//测试
testImplementation 'junit:junit:4.12'
//自动绑定控件框架 butterknife
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
//图片加载框架 glide
implementation 'com.github.bumptech.glide:glide:4.1.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.1.1'
// 图片查看
implementation 'com.commit451:PhotoView:1.2.4'
//列表框架 recyclerview
implementation 'com.android.support:recyclerview-v7:26.0.0-alpha1'
//添加retrofit2 的依赖 添加这个依赖就默认添加了okhttp依赖
implementation 'com.squareup.retrofit2:retrofit:2.2.0'
//rxjava
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'io.reactivex.rxjava2:rxjava:2.0.8'
//支持 gson 解析 及 rxjava2
implementation 'com.squareup.retrofit2:converter-gson:2.2.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
//大神写的这个库可以支持到rxjava2.X
implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
//rxjava 绘图
implementation 'com.squareup.retrofit2:converter-scalars:2.2.0'
//可以管理rxjava生命周期
implementation 'com.trello.rxlifecycle2:rxlifecycle:2.1.0'
implementation 'com.trello.rxlifecycle2:rxlifecycle-components:2.1.0'
//okhttp log 工具
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
//万能适配器
implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.34'
//沉浸式状态栏
implementation 'com.gyf.barlibrary:barlibrary:2.3.0'
//轮播图框架 AdPlayBanner (http://www.apkbus.com/blog-771645-68545.html)
implementation 'com.github.ryanlijianchang:AdPlayBanner:v0.7'
//PDF
implementation 'com.github.barteksc:android-pdf-viewer:3.0.0-beta.5'
//卡片View
implementation 'com.android.support:cardview-v7:27.0.2'
//照片选择器 (https://www.jianshu.com/p/a6b5831797d0)
//implementation 'com.github.yudu233:PhotoPicker:1.2.0'
//仿魅族卡片轮播 (https://github.com/pinguo-zhouwei/MZBannerView)
implementation 'com.github.pinguo-zhouwei:MZBannerView:v2.0.0'
//百度地图
implementation files('libs/BaiduLBS_Android.jar')
// 此处以JPush 3.1.1 版本为例。
implementation 'cn.jiguang.sdk:jpush:3.1.1'
// 此处以JCore 1.1.9 版本为例。
implementation 'cn.jiguang.sdk:jcore:1.1.9'
implementation files('libs/jsms_android-1.2.0.jar')
//其中latest.release指代最新Bugly SDK版本号,也可以指定明确的版本号,例如2.2.0
implementation 'com.tencent.bugly:crashreport:latest.release'
//其中latest.release指代最新Bugly SDK版本号,也可以指定明确的版本号,例如2.1.9
implementation 'com.tencent.bugly:crashreport:latest.release'
//其中latest.release指代最新Bugly NDK版本号,也可以指定明确的版本号,例如3.0
implementation 'com.tencent.bugly:nativecrashreport:latest.release'
implementation 'com.umeng.sdk:common:latest.integration'
implementation 'com.umeng.analytics:analytics:latest.integration'
implementation files('libs/SocialSDK_WeiXin_Full.jar')
implementation files('libs/umeng_shareboard_widget.jar')
implementation files('libs/umeng_social_api.jar')
implementation files('libs/umeng_social_net.jar')
implementation files('libs/umeng_social_shareboard.jar')
implementation files('libs/umeng_social_tool.jar')
implementation files('libs/wechat-sdk-android-with-mta-1.1.6.jar')
implementation 'com.facebook.rebound:rebound:0.3.8'
// implementation project(':arscan')
implementation files('libs/ainsight-1.1.3.jar')
//绘图
implementation 'com.contrarywind:Android-PickerView:4.1.3'
implementation 'com.alibaba:fastjson:1.2.46'
implementation files('libs/pldroid-player-2.1.4.jar')
implementation project(':kohlortest_android20180611')
}
<file_sep>package com.mengyang.kohler.module.bean;
import java.util.List;
/**
* Description :
* Author : rmy
* Email : <EMAIL>
* Time : 2018/3/8
*/
public class WeeklyRadioConcertBean {
/**
* pageNum : 0
* pageSize : 10
* resultList : [{"createTime":"2018-03-07 17:25:23","description":"茶可夫斯基是俄罗斯作曲家","id":2,"isDelete":0,"isHidden":0,"kvUrl":"http://www.111.com","redirectUrl":"http://www.baidu.com","title":"又见柴可夫斯基","updateTime":"2018-03-07 17:25:23","weight":0}]
* totalPage : 1
* totalSize : 1
*/
private int pageNum;
private int pageSize;
private int totalPage;
private int totalSize;
private List<ResultListBean> resultList;
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getTotalSize() {
return totalSize;
}
public void setTotalSize(int totalSize) {
this.totalSize = totalSize;
}
public List<ResultListBean> getResultList() {
return resultList;
}
public void setResultList(List<ResultListBean> resultList) {
this.resultList = resultList;
}
public static class ResultListBean {
/**
* createTime : 2018-03-07 17:25:23
* description : 茶可夫斯基是俄罗斯作曲家
* id : 2
* isDelete : 0
* isHidden : 0
* kvUrl : http://www.111.com
* redirectUrl : http://www.baidu.com
* title : 又见柴可夫斯基
* updateTime : 2018-03-07 17:25:23
* weight : 0
*/
private String createTime;
private String description;
private int id;
private int isDelete;
private int isHidden;
private String kvUrl;
private String redirectUrl;
private String title;
private String updateTime;
private int weight;
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getIsDelete() {
return isDelete;
}
public void setIsDelete(int isDelete) {
this.isDelete = isDelete;
}
public int getIsHidden() {
return isHidden;
}
public void setIsHidden(int isHidden) {
this.isHidden = isHidden;
}
public String getKvUrl() {
return kvUrl;
}
public void setKvUrl(String kvUrl) {
this.kvUrl = kvUrl;
}
public String getRedirectUrl() {
return redirectUrl;
}
public void setRedirectUrl(String redirectUrl) {
this.redirectUrl = redirectUrl;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUpdateTime() {
return updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
}
<file_sep>package com.mengyang.kohler.module.bean;
/**
* Description :
* Author : rmy
* Email : <EMAIL>
* Time : 2018/2/1
*/
public class UploadHeadPortraitBean {
/**
* fileUrl : http://ojd06y9cv.bkt.clouddn.com/f78af3474e15824b3785b45402612906.png
* mediaId : 2
* mediaType : 1
* thumbFileUrl : http://ojd06y9cv.bkt.clouddn.com/f78af3474e15824b3785b45402612906.png?/0/w/1280/h/960
*/
private String fileUrl;
private String mediaId;
private String mediaType;
private String thumbFileUrl;
public String getFileUrl() {
return fileUrl;
}
public void setFileUrl(String fileUrl) {
this.fileUrl = fileUrl;
}
public String getMediaId() {
return mediaId;
}
public void setMediaId(String mediaId) {
this.mediaId = mediaId;
}
public String getMediaType() {
return mediaType;
}
public void setMediaType(String mediaType) {
this.mediaType = mediaType;
}
public String getThumbFileUrl() {
return thumbFileUrl;
}
public void setThumbFileUrl(String thumbFileUrl) {
this.thumbFileUrl = thumbFileUrl;
}
}
<file_sep>package com.mengyang.kohler.home.activity;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.allyes.analytics.AIOAnalytics;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.gyf.barlibrary.ImmersionBar;
import com.mengyang.kohler.App;
import com.mengyang.kohler.BaseActivity;
import com.mengyang.kohler.R;
import com.mengyang.kohler.common.activity.WebViewActivity;
import com.mengyang.kohler.common.net.DefaultObserver;
import com.mengyang.kohler.common.net.IdeaApi;
import com.mengyang.kohler.common.view.TopView;
import com.mengyang.kohler.home.adapter.WeeklyRadioConcertAdapter;
import com.mengyang.kohler.module.BasicResponse;
import com.mengyang.kohler.module.bean.WeeklyRadioConcertBean;
import com.umeng.analytics.MobclickAgent;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
/**
* 星广会
*/
public class WeeklyRadioConcertActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener {
@BindView(R.id.tv_home_weekly_radio_concert)
TopView tvHomeWeeklyRadioConcert;
@BindView(R.id.rv_weekly_radio_concert)
RecyclerView rvWeeklyRadioConcert;
@BindView(R.id.srl_weekly_radio_concert)
SwipeRefreshLayout srlWeeklyRadioConcert;
private List<WeeklyRadioConcertBean.ResultListBean> mWeeklyRadioConcertBean;
private WeeklyRadioConcertAdapter mWeeklyRadioConcertAdapter;
private int pageNum = 0; //请求页数
@Override
protected int getLayoutId() {
return R.layout.activity_weekly_radio_concert;
}
@Override
protected void initValues() {
App.getManager().addActivity(this);
//防止状态栏和标题重叠
ImmersionBar.setTitleBar(this, tvHomeWeeklyRadioConcert);
MobclickAgent.onEvent(WeeklyRadioConcertActivity.this, "yinyuehuiliebiao");
LinearLayoutManager layoutManager = new LinearLayoutManager(App.getContext());
rvWeeklyRadioConcert.setLayoutManager(layoutManager);
// 如果可以确定每个item的高度是固定的,设置这个选项可以提高性能
rvWeeklyRadioConcert.setHasFixedSize(true);
rvWeeklyRadioConcert.setItemAnimator(new DefaultItemAnimator());
mWeeklyRadioConcertBean = new ArrayList<>();
mWeeklyRadioConcertAdapter = new WeeklyRadioConcertAdapter(mWeeklyRadioConcertBean);
rvWeeklyRadioConcert.setAdapter(mWeeklyRadioConcertAdapter);
}
@Override
protected void initListener() {
srlWeeklyRadioConcert.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
pageNum = 0;
initData();
srlWeeklyRadioConcert.setRefreshing(false);
}
});
}
@Override
protected void initData() {
Map<String, Object> stringMap = IdeaApi.getSign();
stringMap.put("pageNum", pageNum + "");
IdeaApi.getRequestLogin(stringMap);
IdeaApi.getApiService()
.getWeeklyRadioConcert(stringMap)
.compose(WeeklyRadioConcertActivity.this.<BasicResponse<WeeklyRadioConcertBean>>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BasicResponse<WeeklyRadioConcertBean>>(WeeklyRadioConcertActivity.this, true) {
@Override
public void onSuccess(BasicResponse<WeeklyRadioConcertBean> response) {
if (response.getData().getResultList().size() != 0) {
if (pageNum == 0) {
mWeeklyRadioConcertBean.clear();
mWeeklyRadioConcertBean.addAll(response.getData().getResultList());
if (mWeeklyRadioConcertBean.size() > 0) {
pageNum += 1;
mWeeklyRadioConcertAdapter = new WeeklyRadioConcertAdapter(mWeeklyRadioConcertBean);
rvWeeklyRadioConcert.setAdapter(mWeeklyRadioConcertAdapter);
mWeeklyRadioConcertAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
startActivity(new Intent(WeeklyRadioConcertActivity.this, WebViewActivity.class).putExtra("h5url", mWeeklyRadioConcertBean.get(position).getRedirectUrl()));
}
});
mWeeklyRadioConcertAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
@Override
public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
startActivity(new Intent(WeeklyRadioConcertActivity.this, WebViewActivity.class).putExtra("h5url", mWeeklyRadioConcertBean.get(position).getRedirectUrl()));
}
});
mWeeklyRadioConcertAdapter.setOnLoadMoreListener(WeeklyRadioConcertActivity.this, rvWeeklyRadioConcert); //加载更多
} else {
mWeeklyRadioConcertAdapter.loadMoreEnd();
}
} else {
if (response.getData().getResultList().size() > 0) {
pageNum += 1;
mWeeklyRadioConcertAdapter.addData(response.getData().getResultList());
mWeeklyRadioConcertAdapter.loadMoreComplete(); //完成本次
} else {
mWeeklyRadioConcertAdapter.loadMoreEnd(); //完成所有加载
}
}
} else {
mWeeklyRadioConcertAdapter.loadMoreEnd();
}
}
});
}
@Override
protected void onResume() {
super.onResume();
MobclickAgent.onResume(this);
AIOAnalytics.onPageBegin("yinyuehuiliebiao");
}
@Override
protected void onPause() {
super.onPause();
MobclickAgent.onPause(this);
AIOAnalytics.onPageEnd("yinyuehuiliebiao");
}
@Override
public void onLoadMoreRequested() {
initData();
}
}
<file_sep>package com.mengyang.kohler.account.adapter;
import android.support.annotation.Nullable;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.mengyang.kohler.R;
import com.mengyang.kohler.module.bean.ReservationQueryBean;
import java.util.List;
/**
* Description :
* Author : rmy
* Email : <EMAIL>
* Time : 2018/1/29
*/
public class AccountMineReservationQueryAdapter extends BaseQuickAdapter<ReservationQueryBean.ResultListBean, BaseViewHolder> {
public AccountMineReservationQueryAdapter(@Nullable List<ReservationQueryBean.ResultListBean> data) {
super(R.layout.item_account_mine_reservation_query_adapter, data);
}
@Override
protected void convert(BaseViewHolder helper, ReservationQueryBean.ResultListBean item) {
helper.setText(R.id.tv_reservation_query_time_of_appointment, item.getAppointmentTime())
.setText(R.id.tv_reservation_query_store_address, item.getStoreAddress())
.setText(R.id.tv_reservation_query_reservation_code, item.getCode());
}
}
<file_sep>package com.mengyang.kohler.module;
import com.mengyang.kohler.App;
import com.mengyang.kohler.common.net.IConstants;
import com.mengyang.kohler.common.utils.SPUtil;
/**
* Description :
* Author : rmy
* Email : <EMAIL>
* Time : 2018/2/1
*/
public class BasicRequest {
public String token = (String) SPUtil.get(App.getContext(), IConstants.TOKEN, "");
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
<file_sep>package com.mengyang.kohler.account.activity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.gyf.barlibrary.ImmersionBar;
import com.mengyang.kohler.App;
import com.mengyang.kohler.BaseActivity;
import com.mengyang.kohler.R;
import com.mengyang.kohler.account.adapter.AccountMineReservationQueryAdapter;
import com.mengyang.kohler.common.net.DefaultObserver;
import com.mengyang.kohler.common.net.IdeaApi;
import com.mengyang.kohler.common.view.SpacesItemDecoration;
import com.mengyang.kohler.common.view.TopView;
import com.mengyang.kohler.module.BasicResponse;
import com.mengyang.kohler.module.bean.ReservationQueryBean;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
/**
* 我的账户——预约查询
*/
public class AccountMineReservationQueryActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener {
// 这是一个外包小公司,在甲方公司里办公的...别被忽悠了
// 这家老板人品不好,进来说好交社保,但实际上不给你交,工资能拖就拖(有次一拖就3个月)
// 说好的有年终奖也是没有的别想了,过节没有任何东西发,自己带电脑也没有补贴金的~
// 这公司管理混乱趁早走吧兄弟...
@BindView(R.id.tv_account_reservation_query_top)
TopView tvAccountReservationQueryTop;
@BindView(R.id.rv_account_reservation_query)
RecyclerView rvAccountReservationQuery;
@BindView(R.id.srl_account_reservation_query)
SwipeRefreshLayout srlAccountReservationQuery;
private AccountMineReservationQueryAdapter mAccountMineReservationQueryAdapter;
private List<ReservationQueryBean.ResultListBean> mReservationQueryBean;
private int pageNum = 0; //请求页数
@Override
protected int getLayoutId() {
return R.layout.activity_account_mine_reservation_query;
}
@Override
protected void initValues() {
App.getManager().addActivity(this);
//防止状态栏和标题重叠
ImmersionBar.setTitleBar(this, tvAccountReservationQueryTop);
// 设置管理器
LinearLayoutManager layoutManager = new LinearLayoutManager(App.getContext());
rvAccountReservationQuery.setLayoutManager(layoutManager);
rvAccountReservationQuery.addItemDecoration(new SpacesItemDecoration(16));
// 如果可以确定每个item的高度是固定的,设置这个选项可以提高性能
rvAccountReservationQuery.setHasFixedSize(true);
rvAccountReservationQuery.setItemAnimator(new DefaultItemAnimator());
mReservationQueryBean = new ArrayList<>();
mAccountMineReservationQueryAdapter = new AccountMineReservationQueryAdapter(mReservationQueryBean);
rvAccountReservationQuery.setAdapter(mAccountMineReservationQueryAdapter);
}
@Override
protected void initListener() {
srlAccountReservationQuery.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
pageNum = 0;
initData();
srlAccountReservationQuery.setRefreshing(false);
}
});
}
@Override
protected void initData() {
Map<String, Object> stringMap = IdeaApi.getSign();
stringMap.put("pageNum", pageNum + "");
stringMap.put("pageSize", 10 + "");
IdeaApi.getRequestLogin(stringMap);
IdeaApi.getApiService()
.getUserReserveMsg(stringMap)
.compose(AccountMineReservationQueryActivity.this.<BasicResponse<ReservationQueryBean>>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BasicResponse<ReservationQueryBean>>(AccountMineReservationQueryActivity.this, true) {
@Override
public void onSuccess(BasicResponse<ReservationQueryBean> response) {
if (response != null) {
if (pageNum == 0) {
mReservationQueryBean.clear();
mReservationQueryBean.addAll(response.getData().getResultList());
if (mReservationQueryBean.size() > 0) {
pageNum += 1;
mAccountMineReservationQueryAdapter = new AccountMineReservationQueryAdapter(mReservationQueryBean);
mAccountMineReservationQueryAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM); //动画
mAccountMineReservationQueryAdapter.isFirstOnly(false); //第一次
rvAccountReservationQuery.setAdapter(mAccountMineReservationQueryAdapter);
mAccountMineReservationQueryAdapter.setOnLoadMoreListener(AccountMineReservationQueryActivity.this, rvAccountReservationQuery); //加载更多
} else {
mAccountMineReservationQueryAdapter.loadMoreEnd();
}
} else {
if (response.getData().getResultList().size() > 0) {
pageNum += 1;
mAccountMineReservationQueryAdapter.addData(response.getData().getResultList());
mAccountMineReservationQueryAdapter.loadMoreComplete(); //完成本次
} else {
mAccountMineReservationQueryAdapter.loadMoreEnd(); //完成所有加载
}
}
} else {
mAccountMineReservationQueryAdapter.loadMoreEnd();
}
}
});
}
@Override
public void onLoadMoreRequested() {
initData();
}
}<file_sep>package com.mengyang.kohler.home.adapter;
import android.support.annotation.Nullable;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.mengyang.kohler.App;
import com.mengyang.kohler.R;
import com.mengyang.kohler.module.bean.ArtKohlerBean;
import com.mengyang.kohler.module.bean.ArtKohlerSelectImgBean;
import java.util.List;
/**
* Description :
* Author : rmy
* Email : <EMAIL>
* Time : 2018/3/13
*/
public class ArtKohlerSelectActivityAdapter extends BaseQuickAdapter<ArtKohlerSelectImgBean.ResultListBean, BaseViewHolder> {
public ArtKohlerSelectActivityAdapter(@Nullable List<ArtKohlerSelectImgBean.ResultListBean> data) {
super(R.layout.item_art_kohler_select_adapter, data);
}
@Override
protected void convert(BaseViewHolder helper, ArtKohlerSelectImgBean.ResultListBean item) {
helper.setGone(R.id.tv_item_art_select_up, false)
.setGone(R.id.tv_item_art_select_down, false);
Glide.with(App.getContext()).load(item.getPicUrl()).apply(new RequestOptions().placeholder(R.mipmap.queshengtu)).into((ImageView) helper.getView(R.id.iv_item_art_select));
}
}
<file_sep>package com.mengyang.kohler.common.view;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.loadmore.LoadMoreView;
import com.mengyang.kohler.R;
/**
* Created by liusong on 2018/3/30.
*/
public class MyLoadMoreView extends LoadMoreView {
@Override
public int getLayoutId() {
return R.layout.quick_view_load_more;
}
@Override
public boolean isLoadEndGone() {
return true;
}
@Override
protected int getLoadingViewId() {
return R.id.load_more_loading_view;
}
@Override
protected int getLoadFailViewId() {
return R.id.load_more_load_fail_view;
}
@Override
protected int getLoadEndViewId() {
return 0;
}
}
<file_sep>package com.mengyang.kohler.module.bean;
/**
* Description :
* Author : rmy
* Email : <EMAIL>
* Time : 2018/1/31
*/
public class LoginBean {
/**
* accessToken : <KEY>
* isNew : false
* openId : 1yp5A1nL2uI=
* refreshToken : <KEY>
*/
private String type;
private String accessToken;
private boolean isNew;
private String openId;
private String refreshToken;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public boolean isIsNew() {
return isNew;
}
public void setIsNew(boolean isNew) {
this.isNew = isNew;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
}
<file_sep>package com.mengyang.kohler.whole_category.activity;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.widget.TextView;
import com.gyf.barlibrary.ImmersionBar;
import com.mengyang.kohler.App;
import com.mengyang.kohler.BaseActivity;
import com.mengyang.kohler.R;
import com.mengyang.kohler.common.net.DefaultObserver;
import com.mengyang.kohler.common.net.IdeaApi;
import com.mengyang.kohler.common.view.TopView;
import com.mengyang.kohler.module.BasicResponse;
import com.mengyang.kohler.module.bean.CommodityClassificationTitleBean;
import com.mengyang.kohler.whole_category.adapter.ViewPagerAdapter;
import com.mengyang.kohler.whole_category.fragment.CommodityClassificationFragment;
import com.mengyang.kohler.whole_category.view.NavitationFollowScrollLayoutText;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
/**
* 商品分类
*/
public class CommodityClassificationActivity extends BaseActivity {
@BindView(R.id.tv_commodity_classification_top)
TopView tvCommodityClassificationTop;
@BindView(R.id.nfsl_commodity_classification)
NavitationFollowScrollLayoutText nfslCommodityClassification;
@BindView(R.id.vp_commodity_classification)
ViewPager vpCommodityClassification;
@BindView(R.id.table_layout)
TabLayout mTableLayout;
@BindView(R.id.tv_top_title)
TextView tvTopTitle;
private List<CommodityClassificationTitleBean> mCommodityClassificationTitleBean;
private String[] titles;
private ViewPagerAdapter viewPagerAdapter;
private List<Fragment> fragments;
private boolean mIsPageSelected = true;
private long mListTime;
@Override
protected int getLayoutId() {
return R.layout.activity_commodity_classification;
}
@Override
protected void initValues() {
App.getManager().addActivity(this);
//防止状态栏和标题重叠
ImmersionBar.setTitleBar(this, tvCommodityClassificationTop);
tvTopTitle.setText(getIntent().getStringExtra("classification_title"));
fragments = new ArrayList<>();
mCommodityClassificationTitleBean = new ArrayList<>();
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), fragments);
vpCommodityClassification.setAdapter(viewPagerAdapter);
vpCommodityClassification.setOffscreenPageLimit(2);
}
@Override
protected void initListener() {
}
@Override
protected void initData() {
Map<String, Object> stringMap = IdeaApi.getSign();
stringMap.put("parentId", getIntent().getStringExtra("id"));
IdeaApi.getRequestLogin(stringMap);
IdeaApi.getApiService()
.getCommodityClassificationTitle(stringMap)
.compose(CommodityClassificationActivity.this.<BasicResponse<List<CommodityClassificationTitleBean>>>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BasicResponse<List<CommodityClassificationTitleBean>>>(CommodityClassificationActivity.this, true) {
@Override
public void onSuccess(BasicResponse<List<CommodityClassificationTitleBean>> response) {
mCommodityClassificationTitleBean.clear();
mCommodityClassificationTitleBean = response.getData();
titles = new String[mCommodityClassificationTitleBean.size()];
for (int i = 0; i < mCommodityClassificationTitleBean.size(); i++) {
titles[i] = new String(mCommodityClassificationTitleBean.get(i).getNameCn());
}
nfslCommodityClassification.setViewPager(CommodityClassificationActivity.this, titles, vpCommodityClassification, R.color.black, R.color.black, 12, 12, 24, true, R.color.splilinecolor, 1f, 4f, 4f, 80);
nfslCommodityClassification.setBgLine(CommodityClassificationActivity.this, 1, R.color.white);
nfslCommodityClassification.setNavLine(CommodityClassificationActivity.this, 2, R.color.white);
for (int i = 0; i < mCommodityClassificationTitleBean.size(); i++) {
final CommodityClassificationFragment commodityClassificationFragment = CommodityClassificationFragment.newInstance(mCommodityClassificationTitleBean.get(i).getCmsId() + "");
fragments.add(commodityClassificationFragment);
}
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), fragments);
vpCommodityClassification.setAdapter(viewPagerAdapter);
}
});
}
}
<file_sep>package com.mengyang.kohler.account.activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.mengyang.kohler.App;
import com.mengyang.kohler.BaseActivity;
import com.mengyang.kohler.R;
import com.mengyang.kohler.common.net.Config;
import com.mengyang.kohler.common.net.DefaultObserver;
import com.mengyang.kohler.common.net.IdeaApi;
import com.mengyang.kohler.common.net.IdeaApiService;
import com.mengyang.kohler.common.utils.DateUtils;
import com.mengyang.kohler.common.utils.ToastUtil;
import com.mengyang.kohler.common.utils.VerifyUtils;
import com.mengyang.kohler.main.activity.MainActivity;
import com.mengyang.kohler.module.BasicResponse;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* 设计师注册
*/
public class DesignerRegisterActivity extends BaseActivity {
// 这是一个外包小公司,在甲方公司里办公的...别被忽悠了
// 这家老板人品不好,进来说好交社保,但实际上不给你交,工资能拖就拖(有次一拖就3个月)
// 说好的有年终奖也是没有的别想了,过节没有任何东西发,自己带电脑也没有补贴金的~
// 这公司管理混乱趁早走吧兄弟...
@BindView(R.id.rl_designer_register_go_home)
RelativeLayout rlDesignerRegisterGoHome;
@BindView(R.id.et_designer_register_phone_num)
EditText etDesignerRegisterPhoneNum;
@BindView(R.id.et_designer_register_verification_code)
EditText etDesignerRegisterVerificationCode;
@BindView(R.id.iv_designer_register_verification_code)
ImageView ivDesignerRegisterVerificationCode;
@BindView(R.id.et_designer_register_sms_verification_code)
EditText etDesignerRegisterSmsVerificationCode;
@BindView(R.id.bt_designer_register_send_out_sms)
Button btDesignerRegisterSendOutSms;
@BindView(R.id.et_designer_register_pwd)
EditText etDesignerRegisterPwd;
@BindView(R.id.bt_designer_register)
Button btDesignerRegister;
@BindView(R.id.tv_designer_register_go_login)
TextView tvDesignerRegisterGoLogin;
@BindView(R.id.tv_designer_register_go_user_register)
TextView tvDesignerRegisterGoUserRegister;
@BindView(R.id.tv_designer_register_go_distributor_register)
TextView tvDesignerRegisterGoDistributorRegister;
@BindView(R.id.sv_desiger)
ScrollView mSvDesiger;
private byte[] bytes;//图片验证码进制流
private String time;
@Override
protected int getLayoutId() {
return R.layout.activity_designer_register;
}
@Override
protected void initValues() {
App.getManager().addActivity(this);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
}
@Override
protected void initListener() {
etDesignerRegisterPhoneNum.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//输入文本之前的状态
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//输入文字中的状态,count是一次性输入字符数
}
@Override
public void afterTextChanged(Editable editable) {
//输入文字后的状态
if (etDesignerRegisterPhoneNum.getText().toString().trim().length() == 11 && VerifyUtils.isMobileNumber(etDesignerRegisterPhoneNum.getText().toString().trim())) {
} else if (etDesignerRegisterPhoneNum.getText().toString().trim().length() == 11){
ToastUtil.showToast("请输入正确的手机号码!");
etDesignerRegisterPhoneNum.setText("");
}
}
});
mSvDesiger.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
hideInput();
return false;
}
});
}
@Override
protected void initData() {
Map<String, Object> stringMap = IdeaApi.getSign();
time = DateUtils.dataOne(DateUtils.getCurrentTime_Today());
stringMap.put("time", time);//时间戳
postAsynHttp(stringMap);
}
/**
* 获取验证码图片
*
* @param map
*/
private void postAsynHttp(Map map) {
Iterator entries = map.entrySet().iterator();
OkHttpClient mOkHttpClient = new OkHttpClient();
FormBody.Builder builder = new FormBody.Builder();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
String key = entry.getKey() + "";
String value = entry.getValue() + "";
builder.add(key, value);
}
RequestBody formBody = builder.build();
Request request = new Request.Builder()
.url(IdeaApiService.API_SERVER_URL + Config.LOGIN_VERIFICATION_IMG)
.post(formBody)
.build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
bytes = response.body().bytes();
runOnUiThread(new Runnable() {
@Override
public void run() {
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
ivDesignerRegisterVerificationCode.setImageBitmap(bitmap);
}
});
}
});
}
private void LoginSMS() {
Map<String, Object> stringMap = IdeaApi.getSign();
stringMap.put("mobileNo", etDesignerRegisterPhoneNum.getText().toString().trim());//手机号码
IdeaApi.getRequestLogin(stringMap);
IdeaApi.getApiService()
.getLoginSMS(stringMap)
.compose(DesignerRegisterActivity.this.<BasicResponse>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BasicResponse>(DesignerRegisterActivity.this, false) {
@Override
public void onSuccess(BasicResponse response) {
}
});
}
private void ModifyBindPhone() {
Map<String, Object> stringMap = IdeaApi.getSign();
stringMap.put("mobileNo", etDesignerRegisterPhoneNum.getText().toString().trim());//手机号码
stringMap.put("code", etDesignerRegisterVerificationCode.getText().toString().trim());//验证码
stringMap.put("verifyCode", etDesignerRegisterSmsVerificationCode.getText().toString().trim());//短信验证码
stringMap.put("password", <PASSWORD>());//用户密码
stringMap.put("type", "designer");//用户类型
stringMap.put("time", time);//时间戳
IdeaApi.getRequestLogin(stringMap);
IdeaApi.getApiService()
.getUserRegister(stringMap)
.compose(DesignerRegisterActivity.this.<BasicResponse>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BasicResponse>(DesignerRegisterActivity.this, true) {
@Override
public void onSuccess(BasicResponse response) {
startActivity(new Intent(DesignerRegisterActivity.this, LoginActivity.class));
finish();
}
});
}
@OnClick({R.id.rl_designer_register_go_home, R.id.iv_designer_register_verification_code, R.id.bt_designer_register_send_out_sms, R.id.bt_designer_register, R.id.tv_designer_register_go_login, R.id.tv_designer_register_go_user_register, R.id.tv_designer_register_go_distributor_register})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.rl_designer_register_go_home:
hideInput();
startActivity(new Intent(this, MainActivity.class));
finish();
break;
case R.id.iv_designer_register_verification_code:
initData();
break;
case R.id.bt_designer_register_send_out_sms:
if (!etDesignerRegisterPhoneNum.getText().toString().trim().equals("") && etDesignerRegisterPhoneNum.getText().toString().trim().length() == 11)
LoginSMS();
else
ToastUtil.showToast(getString(R.string.msg_no_ok));
break;
case R.id.bt_designer_register:
String phoneNum = etDesignerRegisterPhoneNum.getText().toString().trim();
String verificationCode = etDesignerRegisterVerificationCode.getText().toString().trim();
String smsCode = etDesignerRegisterSmsVerificationCode.getText().toString().trim();
String registerPwd = etDesignerRegisterPwd.getText().toString().trim();
if (checkPwd(registerPwd)) {
ToastUtil.showToast("密码格式不正确");
return;
}
if (!phoneNum.equals("") && !verificationCode.equals("") && !smsCode.equals("") && !registerPwd.equals("")) {
ModifyBindPhone();
} else {
ToastUtil.showToast(getString(R.string.msg_no_ok));
return;
}
break;
case R.id.tv_designer_register_go_login:
startActivity(new Intent(this, LoginActivity.class));
finish();
break;
case R.id.tv_designer_register_go_user_register:
startActivity(new Intent(this, UserRegisterActivity.class));
finish();
break;
case R.id.tv_designer_register_go_distributor_register:
startActivity(new Intent(this, DistributorRegisterActivity.class));
finish();
break;
default:
break;
}
}
}
<file_sep>package com.mengyang.kohler.home.fragment;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.allyes.analytics.AIOAnalytics;
import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.contrarywind.listener.OnItemSelectedListener;
import com.contrarywind.view.WheelView;
import com.deepano.kohlortest.UnityPlayerActivity;
import com.gyf.barlibrary.ImmersionBar;
import com.mengyang.kohler.BaseFragment;
import com.mengyang.kohler.R;
import com.mengyang.kohler.common.activity.CustomerServiceActivity;
import com.mengyang.kohler.common.activity.WebViewActivity;
import com.mengyang.kohler.common.net.DefaultObserver;
import com.mengyang.kohler.common.net.IConstants;
import com.mengyang.kohler.common.net.IdeaApi;
import com.mengyang.kohler.common.net.IdeaApiService;
import com.mengyang.kohler.common.utils.DateUtils;
import com.mengyang.kohler.common.utils.FileUtil;
import com.mengyang.kohler.common.utils.FileUtils;
import com.mengyang.kohler.common.utils.JsonUtils;
import com.mengyang.kohler.common.utils.SPUtil;
import com.mengyang.kohler.common.utils.ToastUtil;
import com.mengyang.kohler.common.utils.VerifyUtils;
import com.mengyang.kohler.common.view.SpacesItemDecoration;
import com.mengyang.kohler.common.view.TopView;
import com.mengyang.kohler.home.activity.ArtKohlerActivity;
import com.mengyang.kohler.home.activity.DownLoaderPDFActivity;
import com.mengyang.kohler.home.activity.GanChuangActivity;
import com.mengyang.kohler.home.activity.HiKohlerActivity;
import com.mengyang.kohler.home.activity.HomeSearchActivity;
import com.mengyang.kohler.home.activity.KbisActivity;
import com.mengyang.kohler.home.activity.PDFActivity;
import com.mengyang.kohler.home.activity.WeeklyRadioConcertActivity;
import com.mengyang.kohler.home.adapter.BrochureListAdapter2;
import com.mengyang.kohler.module.BasicResponse;
import com.mengyang.kohler.module.bean.BooksListBean;
import com.mengyang.kohler.module.bean.HomeIndexBean;
import com.ryane.banner.AdPageInfo;
import com.ryane.banner.AdPlayBanner;
import com.umeng.analytics.MobclickAgent;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import static com.ryane.banner.AdPlayBanner.ImageLoaderType.GLIDE;
import static com.ryane.banner.AdPlayBanner.IndicatorType.NONE_INDICATOR;
/**
* 主页
*/
public class HomeFragment extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener, View.OnClickListener {
// 这是一个外包小公司,在甲方公司里办公的...别被忽悠了
// 这家老板人品不好,进来说好交社保,但实际上不给你交,工资能拖就拖(有次一拖就3个月)
// 说好的有年终奖也是没有的别想了,过节没有任何东西发,自己带电脑也没有补贴金的~
// 这公司管理混乱趁早走吧兄弟...
@BindView(R.id.tv_home_top)
TopView tvHomeTop;
@BindView(R.id.iv_top_system_msg)
ImageView ivTopSystemMsg;
@BindView(R.id.et_home_search)
EditText etHomeSearch;
@BindView(R.id.ab_home_loop)
AdPlayBanner abHomeLoop;
@BindView(R.id.rv_home_video)
RecyclerView rvHomeVideo;
@BindView(R.id.rv_home_books)
RecyclerView rvHomeBooks;
@BindView(R.id.iv_top_menu)
ImageView ivTopMenu;
@BindView(R.id.iv_home_search)
ImageView ivHomeSearch;
@BindView(R.id.tv_my_brochure_top)
TextView tvMyBrochureTop;
@BindView(R.id.tv_my_brochure_donw)
TextView tvMyBrochureDonw;
@BindView(R.id.iv_top_customer_service)
ImageView ivTopCustomerService;
@BindView(R.id.ll_indicator)
LinearLayout mLlIndicator;
@BindView(R.id.iv_weekly_radio_concert)
ImageView ivWeeklyRadioConcert;
@BindView(R.id.iv_home_appointment)
ImageView ivHomeAppointment;
/**
* 预约 Dialog
*/
private TextView tvAppointmentHelp;
private TextView tvAppointmentProductBig;
private TextView tvAppointmentProductMedium;
private TextView tvAppointmentProductSmall;
private TextView tvAppointmentProductProvince;
private TextView tvAppointmentProductCity;
private TextView tvAppointmentProductAddrKey;
private TextView tvAppointmentAddress;
private EditText etAppointmentName;
private RadioButton rbAppointmentBoy;
private RadioButton rbAppointmentGirl;
private RadioGroup rgAppointment;
private TextView tvAppointmentFamily;
private TextView tvAppointmentInStoreTime;
private EditText etAppointmentPhoneNum;
private Button btAppointmentCommit;
private TimePickerView pvTime;
private Dialog dialog;
private Dialog dialog_one;
private OkHttpClient okHttpClient;
private String url = "http://www.kohler.com.cn/chinaweb/book/add.action";
private String gender = "男";
private List<String> mOptionsItems = new ArrayList<>();
private TextView tvSure;
private TextView tvCancel;
private TextView tvCenterTitle;
//侧滑Meun键的接口回调
private OnFragmentInteractionListener mListener;
private HomeIndexBean mHomeIndexBean;
private HandleViewPager mHandleListenning;
private PopupWindow mNoJurisdictionPopupWindow;
private View mPopLayout;
private BrochureListAdapter2 mMineManualAdapter;
private LinearLayout mLlPopupWindowNoJurisdictuon;
//轮播图集合
private List<AdPageInfo> mDatas = new ArrayList<>();
private List<BooksListBean.ResultListBean> mBooksListBean = new ArrayList<>();
private List<String> mLocalTempPdfFileName = new ArrayList<>();
private int mCurPosition;
private int prevousPosition = 0;
private int pageNum;
private String mPdfTotalPath;
private String mDownLoadKvUrl;
private String mH5_URL = "";
private boolean mIsOpen;
List<String> mProvinceList = new ArrayList<>();
List<String> mBathroomList = new ArrayList<>();
Map<String, String> mSecondMap = new HashMap<>();
Map<String, String> mThirdMap = new HashMap<>();
Map<String, String> mCityMap = new HashMap<>();
Map<String, String> mRoomNameMap = new HashMap<>();
Map<String, String> mAddressMap = new HashMap<>();
private String mSelectedText = "";
private String mSelectedProvince = "";
private String mSelectedCity = "";
private String mSelectedRoomName = "";
private String mSelectedType = "";
private String mSelectedSecond = "";
private String mSelectedThird = "";
private boolean mIsShowDeatilAddress;
private String mJson;
@Override
protected int getLayoutId() {
return R.layout.fragment_home;
}
@Override
protected void initValues() {
//防止状态栏和标题重叠
ImmersionBar.setTitleBar(getActivity(), tvHomeTop);
MobclickAgent.onEvent(getActivity(), "index");
// if (SPUtil.get(App.getContext(), IConstants.TYPE, "").equals("dealer")) {
ivTopCustomerService.setVisibility(View.VISIBLE);
// } else {
// ivTopCustomerService.setVisibility(View.GONE);
// }
//轮播
abHomeLoop.measure(0, 0);
// 设置管理器
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
rvHomeBooks.setLayoutManager(layoutManager);
rvHomeBooks.addItemDecoration(new SpacesItemDecoration(16));
// 如果可以确定每个item的高度是固定的,设置这个选项可以提高性能
rvHomeBooks.setHasFixedSize(true);
rvHomeBooks.setItemAnimator(new DefaultItemAnimator());
if (SPUtil.get(getActivity(), IConstants.TYPE, "").equals("dealer") || SPUtil.get(getActivity(), IConstants.TYPE, "").equals("designer")) {
rvHomeBooks.setVisibility(View.VISIBLE);
tvMyBrochureTop.setVisibility(View.VISIBLE);
tvMyBrochureDonw.setVisibility(View.VISIBLE);
} else {
rvHomeBooks.setVisibility(View.GONE);
tvMyBrochureTop.setVisibility(View.GONE);
tvMyBrochureDonw.setVisibility(View.GONE);
}
abHomeLoop.setImageViewScaleType(AdPlayBanner.ScaleType.CENTER_CROP);
mNoJurisdictionPopupWindow = new PopupWindow(getActivity());
mNoJurisdictionPopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
mNoJurisdictionPopupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
LayoutInflater inflater = LayoutInflater.from(getActivity());
mPopLayout = inflater.inflate(R.layout.popup_window_no_jurisdictuon, null);
mNoJurisdictionPopupWindow.setContentView(mPopLayout);
mNoJurisdictionPopupWindow.setBackgroundDrawable(new ColorDrawable(0x4c000000));
mNoJurisdictionPopupWindow.setOutsideTouchable(false);
mNoJurisdictionPopupWindow.setFocusable(true);
abHomeLoop.setImageViewScaleType(AdPlayBanner.ScaleType.CENTER_CROP);
mLlPopupWindowNoJurisdictuon = mPopLayout.findViewById(R.id.ll_pop_no_jurisdictuon);
mLlPopupWindowNoJurisdictuon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mNoJurisdictionPopupWindow.dismiss();
}
});
}
@Override
public void onResume() {
super.onResume();
MobclickAgent.onResume(getActivity());
AIOAnalytics.onPageBegin("index");
if (((boolean) SPUtil.get(getActivity(), IConstants.IS_LOGIN, false)) == true) {
String userLevel = (String) SPUtil.get(getActivity(), IConstants.TYPE, "");
if (userLevel.equals("dealer") || userLevel.equals("designer")) {
final List<String> listFileName = FileUtil.judgePdfIsExit(mLocalTempPdfFileName);
// TODO: 2018/2/23 ,若是用户手动删除了手机上的文件,还没有做处理
if (listFileName != null && listFileName.size() > 0) {
// TODO: 2018/3/2 ,请求网络获取PDF数据进行对比。
Map<String, Object> stringMap = IdeaApi.getSign();
stringMap.put("pageNum", 0 + "");
IdeaApi.getRequestLogin(stringMap);
IdeaApi.getApiService()
.getBooksList(stringMap)
.compose(this.<BasicResponse<BooksListBean>>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BasicResponse<BooksListBean>>(getActivity(), true) {
@Override
public void onSuccess(BasicResponse<BooksListBean> response) {
//KVurl = http://ojd06y9cv.bkt.clouddn.com/4969f7828af22e1ec8d30ecc9e7d2c22.png?/0/w/1280/h/960
//pdfUrl = http://ojd06y9cv.bkt.clouddn.com/619820641c5890217b99e5cc968e526c.pdf
String substring = "";
mBooksListBean.clear();
if (response != null) {
for (int i = 0; i < response.getData().getResultList().size(); i++) {
String pdfUrl = response.getData().getResultList().get(i).getPdfUrl();
if (pdfUrl != null && !TextUtils.isEmpty(pdfUrl)) {
substring = pdfUrl.substring(pdfUrl.lastIndexOf("/") + 1);
if (listFileName.contains(substring)) {
mBooksListBean.add(response.getData().getResultList().get(i));
//添加到bean里面
}
}
//之后添加到bean放到条目展示
}
if (mMineManualAdapter == null) {
mMineManualAdapter = new BrochureListAdapter2(mBooksListBean);
rvHomeBooks.setAdapter(mMineManualAdapter);
} else {
mMineManualAdapter.notifyDataSetChanged();
}
final String finalSubstring = substring;
mMineManualAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
@Override
public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
mCurPosition = position;
//判断是否这个pdf文件已存在
mPdfTotalPath = IConstants.ROOT_PATH + "/" + finalSubstring;
if (FileUtils.isFileExist(mPdfTotalPath)) {
startActivity(new Intent(getActivity(), PDFActivity.class).putExtra("PdfUrl", mBooksListBean.get(position).getPdfUrl()));
}
}
});
}
listFileName.clear();
mLocalTempPdfFileName.clear();
}
});
} else {
//直接进行获取展示
updateUI();
}
}
}
}
@Override
public void onPause() {
super.onPause();
MobclickAgent.onPause(getActivity());
AIOAnalytics.onPageEnd("index");
}
/**
* 显示
*/
private void updateUI() {
Map<String, Object> stringMap = IdeaApi.getSign();
stringMap.put("pageNum", 0 + "");
IdeaApi.getRequestLogin(stringMap);
IdeaApi.getApiService()
.getBooksList(stringMap)
.compose(this.<BasicResponse<BooksListBean>>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BasicResponse<BooksListBean>>(getActivity(), true) {
@Override
public void onSuccess(BasicResponse<BooksListBean> response) {
if (response != null) {
mBooksListBean.clear();
mBooksListBean.addAll(response.getData().getResultList());
if (mBooksListBean.size() > 0) {
pageNum += 1;
if (mMineManualAdapter == null) {
mMineManualAdapter = new BrochureListAdapter2(mBooksListBean);
rvHomeBooks.setAdapter(mMineManualAdapter);
} else {
mMineManualAdapter.notifyDataSetChanged();
}
mMineManualAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
@Override
public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
mCurPosition = position;
//判断是否这个pdf文件已存在
mPdfTotalPath = IConstants.ROOT_PATH + "/" + mBooksListBean.get(position).getPdfUrl().substring(mBooksListBean.get(position).getPdfUrl().lastIndexOf("/") + 1);
if (FileUtils.isFileExist(mPdfTotalPath)) {
startActivity(new Intent(getActivity(), PDFActivity.class).putExtra("PdfUrl", mBooksListBean.get(position).getPdfUrl()));
} else {//没找到就去下载
mDownLoadKvUrl = mBooksListBean.get(mCurPosition).getKvUrl();
// TODO: 2018/2/11 ,还需要考虑到断点续传的功能,若是客户在下载的过程中退出应用,下次在进来的时候,PDF虽然有了,但是不能显示
String pdfUrl = mBooksListBean.get(position).getPdfUrl();
if (pdfUrl != null && !TextUtils.isEmpty(pdfUrl)) {
Intent intent = new Intent(getActivity(), DownLoaderPDFActivity.class);
intent.putExtra("PdfUrl", mBooksListBean.get(position).getPdfUrl());
intent.putExtra("mPdfTotalPath", mPdfTotalPath);
intent.putExtra("mDownLoadKvUrl", mDownLoadKvUrl);
startActivity(intent);
return;
} else {
String videoUrl = mBooksListBean.get(position).getVideoUrl();
if (videoUrl != null && !TextUtils.isEmpty(videoUrl)) {
startActivity(new Intent(getActivity(), WebViewActivity.class).putExtra("h5url", videoUrl).putExtra("flag", 2));
}
}
}
}
});
} else {
mMineManualAdapter.loadMoreEnd(true);
}
} else {
mMineManualAdapter.loadMoreEnd(true);
}
}
});
}
@Override
protected void initListener() {
}
@Override
protected void initData() {
Map<String, Object> stringMap = IdeaApi.getSign();
IdeaApi.getRequestLogin(stringMap);
IdeaApi.getApiService()
.getUserHomeKV(stringMap)
.compose(this.<BasicResponse<HomeIndexBean>>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BasicResponse<HomeIndexBean>>(getActivity(), false) {
@Override
public void onSuccess(BasicResponse<HomeIndexBean> response) {
etHomeSearch.setFocusableInTouchMode(true);
mHomeIndexBean = response.getData();
boolean noRead = mHomeIndexBean.isNoRead();
if (noRead)
ivTopSystemMsg.setImageResource(R.mipmap.message_new);
for (int i = 0; i < mHomeIndexBean.getKvList().size(); i++) {
ImageView point = new ImageView(getActivity());
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(75, 9);
if (i != 0) {
layoutParams.leftMargin = 6;
point.setEnabled(false);
}
point.setLayoutParams(layoutParams);
point.setBackgroundColor(Color.parseColor("#e3e3e3"));
mLlIndicator.addView(point);
}
for (int i = 0; i < mHomeIndexBean.getKvSize(); i++) {
int clickRedrict = 0;
if (mHomeIndexBean.getKvList().get(i).getClickRedirect().length() > 0) {
clickRedrict = Integer.parseInt(mHomeIndexBean.getKvList().get(i).getClickRedirect());
}
AdPageInfo info = new AdPageInfo("", mHomeIndexBean.getKvList().get(i).getKvUrl(), mHomeIndexBean.getKvList().get(i).getH5Url(), clickRedrict);
mDatas.add(info);
}
abHomeLoop.setImageLoadType(GLIDE);
abHomeLoop.setOnPageClickListener(new AdPlayBanner.OnPageClickListener() {
@Override
public void onPageClick(AdPageInfo info, int postion) {
if (mHandleListenning != null) {
mIsOpen = mHandleListenning.handleListenning();
if (mIsOpen) {
return;
}
}
int clickRedrict = info.getOrder();
if (clickRedrict == 5) {
AIOAnalytics.onEvent("trade_show");
startActivity(new Intent(getActivity(), KbisActivity.class));
} else if (clickRedrict == 4) {
AIOAnalytics.onEvent("ganchuang");
startActivity(new Intent(getActivity(), GanChuangActivity.class));
} else if (clickRedrict == 3) {
AIOAnalytics.onEvent("design_shanghai_banner");
startActivity(new Intent(getActivity(), ArtKohlerActivity.class));
// 暂去掉经销商大会
// } else if (postion == 3 && SPUtil.get(getActivity(), IConstants.TYPE, "").equals("")) {
// AIOAnalytics.onEvent("jingxiaoshangdahui");
// startActivity(new Intent(getActivity(), LoginActivity.class));
// } else if (postion == 3 && SPUtil.get(getActivity(), IConstants.TYPE, "").equals("dealer")) {
// AIOAnalytics.onEvent("jingxiaoshangdahui");
// startActivity(new Intent(getActivity(), MeetingActivity.class));
// } else if (postion == 3 && !SPUtil.get(getActivity(), IConstants.TYPE, "").equals("dealer")) {
// AIOAnalytics.onEvent("jingxiaoshangdahui");
// if (Build.VERSION.SDK_INT == 24) {//android7.0需要单独做适配
// mNoJurisdictionPopupWindow.showAtLocation(getView(), Gravity.NO_GRAVITY, 0, getStatusBarHeight());
// } else {
// mNoJurisdictionPopupWindow.showAtLocation(getView(), Gravity.NO_GRAVITY, 0, 0);
// }
} else if (clickRedrict == 2){
MobclickAgent.onEvent(getActivity(), "arjieshuo");
AIOAnalytics.onEvent("arjieshuo");
Intent intent = new Intent(getActivity(), UnityPlayerActivity.class);
intent.putExtra("flag", "9");
startActivity(intent);
}else if (info.getClickUlr().length() > 0) {
mH5_URL = mHomeIndexBean.getKvList().get(postion).getH5Url() + "";
startActivity(new Intent(getActivity(), WebViewActivity.class).putExtra("h5url", mH5_URL).putExtra("flag", 1));
}
}
});
//自动滚动
abHomeLoop.setAutoPlay(true);
//页码指示器
abHomeLoop.setIndicatorType(NONE_INDICATOR);
//间隔时间
abHomeLoop.setInterval(3000);
//背景
abHomeLoop.setBannerBackground(0xffffffff);
//滑动监听
abHomeLoop.setOnPagerChangeListener(new AdPlayBanner.OnPagerChangeListener() {
@Override
public void onPageSelected(int position) {
//当前页面选中时,先将上一次选中的位置设置为未选中,并将当前的位置记录下来为下一次移动做准备
//mLlIndicator.getChildAt(prevousPosition).setEnabled(false);
if (mLlIndicator != null) {
if (mLlIndicator.getChildAt(prevousPosition) != null) {
mLlIndicator.getChildAt(prevousPosition).setBackgroundColor(Color.parseColor("#e3e3e3"));
prevousPosition = position;
}
//要让对应角标的小圆点选中
View childAt = mLlIndicator.getChildAt(position);
// childAt.setEnabled(true);
childAt.setBackgroundColor(Color.BLACK);
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
//数据源
abHomeLoop.setInfoList((ArrayList<AdPageInfo>) mDatas);
abHomeLoop.setUp();
}
});
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onLoadMoreRequested() {
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_appointment_help:
mOptionsItems.clear();
mOptionsItems.add("商品咨询");
mOptionsItems.add("交货时间");
mOptionsItems.add("工程安排及进度");
mOptionsItems.add("其他");
selectOne(tvAppointmentHelp, mOptionsItems, 0, "帮助");
break;
case R.id.tv_appointment_product_big:
selectOne(tvAppointmentProductBig, mBathroomList, 4, "一级分类");
tvAppointmentProductMedium.setText("请选择");
tvAppointmentProductSmall.setText("请选择");
break;
case R.id.tv_appointment_product_medium:
showSecond(true);
tvAppointmentProductSmall.setText("请选择");
break;
case R.id.tv_appointment_product_small:
showThird(true);
break;
case R.id.tv_appointment_product_province:
selectOne(tvAppointmentProductProvince, mProvinceList, 1, "省");
tvAppointmentProductCity.setText("请选择");
tvAppointmentProductAddrKey.setText("请选择");
tvAppointmentAddress.setText("");
break;
case R.id.tv_appointment_product_city:
showCity(true);
tvAppointmentProductAddrKey.setText("请选择");
tvAppointmentAddress.setText("");
break;
case R.id.tv_appointment_product_addr_key:
mIsShowDeatilAddress = true;
showRoomName(true);
tvAppointmentAddress.setText("");
break;
case R.id.tv_appointment_family:
mOptionsItems.clear();
mOptionsItems.add("一家两口");
mOptionsItems.add("一家三口");
mOptionsItems.add("三世同堂");
mOptionsItems.add("其他");
selectOne(tvAppointmentFamily, mOptionsItems, 0, "家庭状况");
break;
case R.id.tv_appointment_in_store_time:
selectTime();
break;
case R.id.bt_appointment_commit:
AIOAnalytics.onEvent("appoint");
MobclickAgent.onEvent(getActivity(), "appoint");
MobclickAgent.onResume(getActivity());
AIOAnalytics.onPageBegin("appoint");
appointmentCommit();
break;
default:
break;
}
}
private void showRoomName(boolean isShowDia) {
List<String> List2 = new ArrayList<>();
for (Map.Entry<String, String> entry : mRoomNameMap.entrySet()) {
if (entry.getKey().contains(mSelectedCity)) {
String value = entry.getValue();
if (!List2.contains(value)) {
List2.add(value);
}
}
}
selectOne(tvAppointmentProductAddrKey, List2, 3, "门店");
}
private void showCity(boolean isShowDia) {
List<String> List = new ArrayList<>();
for (Map.Entry<String, String> entry : mCityMap.entrySet()) {
if (entry.getKey().contains(mSelectedProvince)) {
String value = entry.getValue();
if (!List.contains(value)) {
List.add(value);
}
}
}
selectOne(tvAppointmentProductCity, List, 2, "市");
}
private void showThird(boolean isShowDia) {
List<String> List4 = new ArrayList<>();
for (Map.Entry<String, String> entry : mThirdMap.entrySet()) {
if (entry.getKey().contains(mSelectedSecond)) {
String value = entry.getValue();
if (!List4.contains(value)) {
List4.add(value);
}
}
}
selectOne(tvAppointmentProductSmall, List4, 6, "三级分类");
}
private void showSecond(boolean isShowDia) {
List<String> List3 = new ArrayList<>();
for (Map.Entry<String, String> entry : mSecondMap.entrySet()) {
if (entry.getKey().contains(mSelectedType)) {
String value = entry.getValue();
if (!List3.contains(value)) {
List3.add(value);
}
}
}
selectOne(tvAppointmentProductMedium, List3, 5, "二级分类");
}
/**
* 单选选择器样式
*
* @param view
* @param item
*/
private void selectOne(final TextView view, final List<String> item, final int type, String content) {
if (item == null || item.size() < 1) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater1 = LayoutInflater.from(getActivity());
View v = inflater1.inflate(R.layout.appointment_one, null);
tvSure = v.findViewById(R.id.tv_sure);
tvCancel = v.findViewById(R.id.tv_cancel);
tvCenterTitle = v.findViewById(R.id.tv_center_title);
tvCenterTitle.setText(content);
tvSure.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mSelectedText = item.get(0);
view.setText(mSelectedText);
dialog_one.dismiss();
handleClickEvent(type);
}
});
tvCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog_one.dismiss();
}
});
WheelView wheelView = v.findViewById(R.id.wv_appointment_one);
wheelView.setCyclic(false);
wheelView.setAdapter(new ArrayWheelAdapter(item));
wheelView.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(final int index) {
tvSure.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mSelectedText = item.get(index);
view.setText(mSelectedText);
dialog_one.dismiss();
handleClickEvent(type);
}
});
tvCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog_one.dismiss();
}
});
}
});
dialog_one = builder.create();
dialog_one.setCanceledOnTouchOutside(false);
dialog_one.show();
dialog_one.getWindow().setContentView(v);
dialog_one.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
switch (view.getId()) {
case R.id.tv_appointment_product_addr_key:
tvAppointmentProductAddrKey.setSingleLine();
tvAppointmentProductAddrKey.setEllipsize(TextUtils.TruncateAt.valueOf("END"));
break;
case R.id.tv_appointment_product_big:
tvAppointmentProductBig.setSingleLine();
tvAppointmentProductBig.setEllipsize(TextUtils.TruncateAt.valueOf("END"));
break;
case R.id.tv_appointment_product_medium:
tvAppointmentProductMedium.setSingleLine();
tvAppointmentProductMedium.setEllipsize(TextUtils.TruncateAt.valueOf("END"));
break;
case R.id.tv_appointment_product_small:
tvAppointmentProductSmall.setSingleLine();
tvAppointmentProductSmall.setEllipsize(TextUtils.TruncateAt.valueOf("END"));
break;
}
}
private void handleClickEvent(int type) {
if (type == 1) {
mSelectedProvince = mSelectedText;
} else if (type == 2) {
mSelectedCity = mSelectedText;
} else if (type == 3) {
mSelectedRoomName = mSelectedText;
} else if (type == 4) {
mSelectedType = mSelectedText;
} else if (type == 5) {
mSelectedSecond = mSelectedText;
} else if (type == 6) {
mSelectedThird = mSelectedText;
}
if (mIsShowDeatilAddress) {
mIsShowDeatilAddress = false;
List<String> List2 = new ArrayList<>();
for (Map.Entry<String, String> entry : mAddressMap.entrySet()) {
if (entry.getKey().contains(mSelectedRoomName)) {
String value = entry.getValue();
if (!List2.contains(value)) {
List2.add(value);
}
}
}
if (List2.size() > 0) {
tvAppointmentAddress.setText(List2.get(0));
}
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(String data);
}
@OnClick({R.id.iv_top_menu, R.id.iv_home_search, R.id.iv_top_customer_service, R.id.tv_home_top, R.id.iv_weekly_radio_concert, R.id.iv_home_appointment})
public void onViewClicked(View view) {
if (getActivity().getCurrentFocus() != null) {
((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(((Activity) getActivity()).getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
switch (view.getId()) {
case R.id.iv_home_search:
if (!etHomeSearch.getText().toString().trim().equals("")) {
startActivity(new Intent(getActivity(), HomeSearchActivity.class).putExtra("etHomeSearch", etHomeSearch.getText().toString().trim()));
}
break;
case R.id.tv_home_top:
mListener.onFragmentInteraction("topView");
break;
case R.id.iv_top_menu:
mListener.onFragmentInteraction("");
break;
case R.id.iv_top_customer_service:
startActivity(new Intent(getContext(), CustomerServiceActivity.class));
break;
case R.id.iv_weekly_radio_concert:
AIOAnalytics.onEvent("yinyuehuiliebiao");
startActivity(new Intent(getContext(), WeeklyRadioConcertActivity.class));
break;
case R.id.iv_home_appointment:
AppointmentDialogInit();
break;
default:
break;
}
}
private void AppointmentDialogInit() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater1 = LayoutInflater.from(getActivity());
View v = inflater1.inflate(R.layout.activity_appointment, null);
tvAppointmentHelp = v.findViewById(R.id.tv_appointment_help);
tvAppointmentProductBig = v.findViewById(R.id.tv_appointment_product_big);
tvAppointmentProductMedium = v.findViewById(R.id.tv_appointment_product_medium);
tvAppointmentProductSmall = v.findViewById(R.id.tv_appointment_product_small);
tvAppointmentProductProvince = v.findViewById(R.id.tv_appointment_product_province);
tvAppointmentProductCity = v.findViewById(R.id.tv_appointment_product_city);
tvAppointmentProductAddrKey = v.findViewById(R.id.tv_appointment_product_addr_key);
tvAppointmentAddress = v.findViewById(R.id.tv_appointment_address);
etAppointmentName = v.findViewById(R.id.et_appointment_name);
rbAppointmentBoy = v.findViewById(R.id.rb_appointment_boy);
rbAppointmentGirl = v.findViewById(R.id.rb_appointment_girl);
rgAppointment = v.findViewById(R.id.rg_appointment);
rgAppointment.check(rbAppointmentBoy.getId());
tvAppointmentFamily = v.findViewById(R.id.tv_appointment_family);
tvAppointmentInStoreTime = v.findViewById(R.id.tv_appointment_in_store_time);
etAppointmentPhoneNum = v.findViewById(R.id.et_appointment_phone_num);
btAppointmentCommit = v.findViewById(R.id.bt_appointment_commit);
tvAppointmentHelp.setOnClickListener(this);
tvAppointmentProductBig.setOnClickListener(this);
tvAppointmentProductMedium.setOnClickListener(this);
tvAppointmentProductSmall.setOnClickListener(this);
tvAppointmentProductProvince.setOnClickListener(this);
tvAppointmentProductCity.setOnClickListener(this);
tvAppointmentProductAddrKey.setOnClickListener(this);
tvAppointmentFamily.setOnClickListener(this);
tvAppointmentInStoreTime.setOnClickListener(this);
btAppointmentCommit.setOnClickListener(this);
dialog = builder.create();
dialog.show();
dialog.getWindow().setContentView(v);//自定义布局应该在这里添加,要在dialog.show()的后面
//清除flags,获取焦点(为了让EditText可以输入)
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
//弹出输入法
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
initJsonData();
parseAssetsJson();
requestAddressData();
}
private void requestAddressData() {
OkHttpClient okHttpClient = new OkHttpClient();
String url2 = "http://www.kohler.com.cn/js/exports_2.json";
Request request = new Request.Builder().url(url2).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String string = response.body().string();
try {
JSONArray jsonArray = new JSONArray(string);
for (int i = 0; i < jsonArray.length(); i++) {
String province = jsonArray.getJSONObject(i).getString("province");
if (!mProvinceList.contains(province)) {
mProvinceList.add(province);
}
String city = jsonArray.getJSONObject(i).getString("city");
String roomname = jsonArray.getJSONObject(i).getString("roomname");
String address = jsonArray.getJSONObject(i).getString("address");
if (mCityMap.containsKey(province)) {
mCityMap.put(province + i, city);
} else {
mCityMap.put(province, city);
}
if (mRoomNameMap.containsKey(city)) {
mRoomNameMap.put(city + i, roomname);
} else {
mRoomNameMap.put(city, roomname);
}
if (mAddressMap.containsKey(roomname)) {
mAddressMap.put(roomname + i, address);
} else {
mAddressMap.put(roomname, address);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
private void parseAssetsJson() {
try {
JSONArray jsonArray = new JSONArray(mJson);
for (int i = 0; i < jsonArray.length(); i++) {
String type = jsonArray.getJSONObject(i).getString("type");
String second = jsonArray.getJSONObject(i).getString("second");
String third = jsonArray.getJSONObject(i).getString("third");
if (!mBathroomList.contains(type)) {
mBathroomList.add(type);
}
if (mSecondMap.containsKey(type)) {
mSecondMap.put(type + i, second);
} else {
mSecondMap.put(type, second);
}
if (mThirdMap.containsKey(second)) {
mThirdMap.put(second + i, third);
} else {
mThirdMap.put(second, third);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* 时间选择器样式
*/
private void selectTime() {
Calendar selectedDate = Calendar.getInstance();
Calendar startDate = Calendar.getInstance();
//startDate.set(2013,1,1);
Calendar endDate = Calendar.getInstance();
//endDate.set(2020,1,1);
//正确设置方式 原因:注意事项有说明
startDate.set(2013, 0, 1);
endDate.set(2020, 11, 31);
pvTime = new TimePickerBuilder(getActivity(), new OnTimeSelectListener() {
@Override
public void onTimeSelect(Date date, View v) {//选中事件回调
tvAppointmentInStoreTime.setText(DateUtils.timedate(date.getTime() + ""));
}
})
.setType(new boolean[]{true, true, true, true, false, false})// 默认全部显示
.setCancelText("取消")//取消按钮文字
.setSubmitText("确定")//确认按钮文字
// .setContentSize(18)//滚轮文字大小
.setTitleSize(18)//标题文字大小
.setTitleText("时间")
.setOutSideCancelable(false)//点击屏幕,点在控件外部范围时,是否取消显示
.isCyclic(false)//是否循环滚动
.setTitleColor(Color.BLACK)//标题文字颜色
.setSubmitColor(Color.BLACK)//确定按钮文字颜色
.setCancelColor(Color.GRAY)//取消按钮文字颜色
.setTitleBgColor(0xFFFFFFFF)//标题背景颜色 Night mode
.setBgColor(0xFFFFFFFF)//滚轮背景颜色 Night mode
.setDate(selectedDate)// 如果不设置的话,默认是系统时间*/
.setRangDate(startDate, endDate)//起始终止年月日设定
.setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
.isCenterLabel(false) //是否只显示中间选中项的label文字,false则每项item全部都带有label。
.isDialog(true)//是否显示为对话框样式
.build();
pvTime.show();
}
private void appointmentCommit() {
okHttpClient = new OkHttpClient.Builder().connectTimeout(IdeaApiService.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS).writeTimeout(IdeaApiService.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS).readTimeout(IdeaApiService.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS).build();
rgAppointment.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (rgAppointment.getCheckedRadioButtonId()) {
case R.id.rb_appointment_boy:
gender = rbAppointmentBoy.getText().toString().trim();
break;
case R.id.rb_appointment_girl:
gender = rbAppointmentGirl.getText().toString().trim();
break;
}
}
});
//提交信息不能为空
if (tvAppointmentProductProvince.getText().toString().trim().equals("请选择") || tvAppointmentProductCity.getText().toString().trim().equals("请选择") || tvAppointmentProductAddrKey.getText().toString().trim().equals("请选择") || tvAppointmentProductBig.getText().toString().trim().equals("请选择") || tvAppointmentProductMedium.getText().toString().trim().equals("请选择") || tvAppointmentProductSmall.getText().toString().trim().equals("请选择") || tvAppointmentInStoreTime.getText().toString().trim().equals("请选择") || etAppointmentPhoneNum.getText().toString().trim().equals("")) {
ToastUtil.showToast("请将信息填写完整!");
} else if (VerifyUtils.isMobileNumber(etAppointmentPhoneNum.getText().toString().trim()) == false) {
ToastUtil.showToast("请填写正确的电话号码!");
} else {
MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
HashMap<String, String> map = new HashMap<>();
map.put("help", tvAppointmentHelp.getText().toString().trim());
map.put("province", tvAppointmentProductProvince.getText().toString().trim());
map.put("city", tvAppointmentProductCity.getText().toString().trim());
map.put("addr_key", tvAppointmentProductAddrKey.getText().toString().trim());
map.put("address", tvAppointmentAddress.getText().toString().trim());
map.put("goods1", tvAppointmentProductBig.getText().toString().trim());
map.put("goods2", tvAppointmentProductMedium.getText().toString().trim());
map.put("goods3", tvAppointmentProductSmall.getText().toString().trim());
map.put("family", tvAppointmentFamily.getText().toString().trim());
map.put("gender", gender);
map.put("name", etAppointmentName.getText().toString().trim());
map.put("time", tvAppointmentInStoreTime.getText().toString().trim());
map.put("telephone", etAppointmentPhoneNum.getText().toString().trim());
map.put("source", "pc");
RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JSON, JsonUtils.toJson(map));
Request requestPost = new Request.Builder().url(url).post(requestBody).build();
Call call = okHttpClient.newCall(requestPost);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ToastUtil.showToast("预约成功!");
MobclickAgent.onPause(getActivity());
AIOAnalytics.onPageEnd("appoint");
dialog.dismiss();
}
});
}
});
}
}
public void stopViewPager() {
if (abHomeLoop != null) {
abHomeLoop.setAutoPlay(false);
}
if (etHomeSearch != null) {
etHomeSearch.setFocusable(false);
etHomeSearch.setFocusableInTouchMode(false);
etHomeSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.onFragmentInteraction("topView");
}
});
}
}
public void startViewPager() {
if (abHomeLoop != null) {
abHomeLoop.setAutoPlay(true);
}
if (etHomeSearch != null) {
etHomeSearch.setFocusable(true);
etHomeSearch.setFocusableInTouchMode(true);
etHomeSearch.setOnClickListener(null);
}
}
public interface HandleViewPager {
boolean handleListenning();
}
public void setHandleListenning(HandleViewPager handleListenning) {
mHandleListenning = handleListenning;
}
//读取本地json生成json字符串
private String initJsonData() {
try {
InputStream is = getResources().getAssets().open("goods.json");
byte[] buffer = new byte[is.available()];
is.read(buffer);
mJson = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return mJson;
}
}
<file_sep>package com.mengyang.kohler.home.activity;
import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import com.allyes.analytics.AIOAnalytics;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.gyf.barlibrary.ImmersionBar;
import com.mengyang.kohler.App;
import com.mengyang.kohler.BaseActivity;
import com.mengyang.kohler.R;
import com.mengyang.kohler.common.net.DefaultObserver;
import com.mengyang.kohler.common.net.IdeaApi;
import com.mengyang.kohler.common.utils.LogUtils;
import com.mengyang.kohler.common.view.GridSpacingItemDecoration;
import com.mengyang.kohler.common.view.TopView;
import com.mengyang.kohler.home.adapter.HomeSearchAdapter;
import com.mengyang.kohler.module.BasicResponse;
import com.mengyang.kohler.module.bean.AllSearchBean;
import com.mengyang.kohler.whole_category.activity.CommodityDetailsActivity;
import com.umeng.analytics.MobclickAgent;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
/**
* 搜索页
*/
public class HomeSearchActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener {
@BindView(R.id.tv_home_search_top)
TopView tvHomeSearchTop;
@BindView(R.id.iv_home_search_remove_search)
ImageView ivHomeSearchRemoveSearch;
@BindView(R.id.et_home_search_activity)
EditText etHomeSearchActivity;
@BindView(R.id.iv_home_search)
ImageView ivHomeSearch;
@BindView(R.id.rv_home_search)
RecyclerView rvHomeSearch;
private HomeSearchAdapter mHomeSearchAdapter;
private List<AllSearchBean.ResultListBean> mAllSearchBean;
private int pageNum = 0; //请求页数
@Override
protected int getLayoutId() {
return R.layout.activity_home_search;
}
@Override
protected void initValues() {
App.getManager().addActivity(this);
//防止状态栏和标题重叠
ImmersionBar.setTitleBar(this, tvHomeSearchTop);
MobclickAgent.onEvent(HomeSearchActivity.this, "search");
AIOAnalytics.onEvent("search");
GridLayoutManager layoutManagerActivity = new GridLayoutManager(App.getContext(), 2);
rvHomeSearch.setLayoutManager(layoutManagerActivity);
rvHomeSearch.addItemDecoration(new GridSpacingItemDecoration(2, 15, false));
rvHomeSearch.setHasFixedSize(true);
rvHomeSearch.setItemAnimator(new DefaultItemAnimator());
etHomeSearchActivity.setText(getIntent().getStringExtra("etHomeSearch"));
mAllSearchBean = new ArrayList<>();
mHomeSearchAdapter = new HomeSearchAdapter(mAllSearchBean);
rvHomeSearch.setAdapter(mHomeSearchAdapter);
}
@Override
protected void initListener() {
}
@Override
protected void initData() {
Map<String, Object> stringMap = IdeaApi.getSign();
stringMap.put("pageNum", pageNum + "");
stringMap.put("pageSize", 10 + "");
stringMap.put("queryStr", etHomeSearchActivity.getText().toString().trim());
IdeaApi.getRequestLogin(stringMap);
IdeaApi.getApiService()
.getAllSearch(stringMap)
.compose(HomeSearchActivity.this.<BasicResponse<AllSearchBean>>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BasicResponse<AllSearchBean>>(HomeSearchActivity.this, true) {
@Override
public void onSuccess(BasicResponse<AllSearchBean> response) {
if (response != null) {
if (pageNum == 0) {
mAllSearchBean.clear();
mAllSearchBean.addAll(response.getData().getResultList());
if (mAllSearchBean.size() > 0) {
pageNum += 1;
mHomeSearchAdapter = new HomeSearchAdapter(mAllSearchBean);
rvHomeSearch.setAdapter(mHomeSearchAdapter);
mHomeSearchAdapter.setOnLoadMoreListener(HomeSearchActivity.this, rvHomeSearch); //加载更多
mHomeSearchAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
startActivity(new Intent(HomeSearchActivity.this, CommodityDetailsActivity.class).putExtra("CommodityDetails_two", mAllSearchBean.get(position).getSkuCode()));
}
});
} else {
mHomeSearchAdapter.loadMoreEnd();
}
} else {
if (response.getData().getResultList().size() > 0) {
pageNum += 1;
mHomeSearchAdapter.addData(response.getData().getResultList());
mHomeSearchAdapter.loadMoreComplete(); //完成本次
} else {
mHomeSearchAdapter.loadMoreEnd(); //完成所有加载
}
}
} else {
mHomeSearchAdapter.loadMoreEnd();
}
}
});
}
@Override
protected void onResume() {
super.onResume();
MobclickAgent.onResume(this);
AIOAnalytics.onPageBegin("search");
}
@Override
protected void onPause() {
super.onPause();
MobclickAgent.onPause(this);
AIOAnalytics.onPageEnd("search");
}
@Override
public void onLoadMoreRequested() {
initData();
}
@OnClick({R.id.iv_home_search_remove_search, R.id.iv_home_search})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.iv_home_search_remove_search:
etHomeSearchActivity.setText("");
break;
case R.id.iv_home_search:
if (!etHomeSearchActivity.getText().toString().trim().equals("")) {
pageNum = 0;
initData();
}
break;
}
}
}
<file_sep>package com.mengyang.kohler.common.activity;
import android.content.Intent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import com.allyes.analytics.AIOAnalytics;
import com.mengyang.kohler.BaseActivity;
import com.mengyang.kohler.R;
import com.mengyang.kohler.common.utils.LogUtils;
import com.mengyang.kohler.common.view.MediaController;
import com.pili.pldroid.player.PLOnCompletionListener;
import com.pili.pldroid.player.PLOnErrorListener;
import com.pili.pldroid.player.PLOnInfoListener;
import com.pili.pldroid.player.PLOnVideoSizeChangedListener;
import com.pili.pldroid.player.widget.PLVideoView;
import com.umeng.analytics.MobclickAgent;
import butterknife.BindView;
public class ARWebViewActivity extends BaseActivity implements PLOnInfoListener, PLOnCompletionListener, PLOnVideoSizeChangedListener, PLOnErrorListener {
// 这是一个外包小公司,在甲方公司里办公的...别被忽悠了
// 这家老板人品不好,进来说好交社保,但实际上不给你交,工资能拖就拖(有次一拖就3个月)
// 说好的有年终奖也是没有的别想了,过节没有任何东西发,自己带电脑也没有补贴金的~
// 这公司管理混乱趁早走吧兄弟...
@BindView(R.id.PLVideoView)
PLVideoView mVideoView;
@BindView(R.id.LoadingView)
View loadingView;
@BindView(R.id.bt_PLVideoView_out)
ImageButton btPLVideoViewOut;
private MediaController mMediaController;
@Override
protected int getLayoutId() {
return R.layout.activity_arweb_view;
}
@Override
protected void initValues() {
AIOAnalytics.onEvent("trade_show_ar_video");
MobclickAgent.onEvent(this, "trade_show_ar_video");
mMediaController = new MediaController(this);
//mVideoView.setMediaController(mMediaController);
if (!getIntent().getStringExtra("AR_url").equals("") && getIntent().getStringExtra("AR_url") != null)
mVideoView.setVideoPath(getIntent().getStringExtra("AR_url"));
mVideoView.setDisplayAspectRatio(PLVideoView.ASPECT_RATIO_FIT_PARENT);
mVideoView.setOnInfoListener(this);
mVideoView.setOnCompletionListener(this);
mVideoView.setOnVideoSizeChangedListener(this);
mVideoView.setOnErrorListener(this);
}
@Override
protected void initListener() {
mVideoView.setBufferingIndicator(loadingView);
btPLVideoViewOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
@Override
protected void initData() {
}
@Override
public void onCompletion() {
mMediaController.refreshProgress();
startActivity(new Intent(this, AzureCustomerServiceActivity.class));
finish();
}
@Override
public boolean onError(int i) {
finish();
return true;
}
@Override
public void onInfo(int i, int i1) {
}
@Override
public void onVideoSizeChanged(int i, int i1) {
}
@Override
protected void onResume() {
super.onResume();
mVideoView.start();
MobclickAgent.onResume(this);
AIOAnalytics.onPageBegin("trade_show_ar_video");
}
@Override
protected void onPause() {
super.onPause();
mVideoView.pause();
MobclickAgent.onPause(this);
AIOAnalytics.onPageEnd("trade_show_ar_video");
}
@Override
protected void onDestroy() {
super.onDestroy();
mVideoView.stopPlayback();
}
}
<file_sep>package com.mengyang.kohler.home.activity;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.gyf.barlibrary.ImmersionBar;
import com.mengyang.kohler.App;
import com.mengyang.kohler.BaseActivity;
import com.mengyang.kohler.R;
import com.mengyang.kohler.common.net.DefaultObserver;
import com.mengyang.kohler.common.net.IdeaApi;
import com.mengyang.kohler.common.view.GridSpacingItemDecoration;
import com.mengyang.kohler.common.view.TopView;
import com.mengyang.kohler.home.adapter.ArtKohlerSelectActivityAdapter;
import com.mengyang.kohler.module.BasicResponse;
import com.mengyang.kohler.module.bean.ArtKohlerSelectImgBean;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
/**
* 精选图片
*/
public class ArtKohlerSelectActivity extends BaseActivity {
@BindView(R.id.tv_art_kohler_select_top)
TopView tvArtKohlerSelectTop;
@BindView(R.id.rv_art_kohler_select)
RecyclerView rvArtKohlerSelect;
@BindView(R.id.srl_art_kohler_select)
SwipeRefreshLayout srlArtKohlerSelect;
private ArtKohlerSelectActivityAdapter mArtKohlerSelectActivityAdapter;
private List<ArtKohlerSelectImgBean.ResultListBean> mArtSelectBean;
@Override
protected int getLayoutId() {
return R.layout.activity_art_kohler_select;
}
@Override
protected void initValues() {
App.getManager().addActivity(this);
//防止状态栏和标题重叠
ImmersionBar.setTitleBar(this, tvArtKohlerSelectTop);
GridLayoutManager layoutManagerActivity = new GridLayoutManager(App.getContext(), 3);
rvArtKohlerSelect.setLayoutManager(layoutManagerActivity);
rvArtKohlerSelect.addItemDecoration(new GridSpacingItemDecoration(3, 15, false));
rvArtKohlerSelect.setHasFixedSize(true);
rvArtKohlerSelect.setItemAnimator(new DefaultItemAnimator());
mArtSelectBean = new ArrayList<>();
mArtKohlerSelectActivityAdapter = new ArtKohlerSelectActivityAdapter(mArtSelectBean);
rvArtKohlerSelect.setAdapter(mArtKohlerSelectActivityAdapter);
}
@Override
protected void initListener() {
srlArtKohlerSelect.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
initData();
srlArtKohlerSelect.setRefreshing(false);
}
});
}
@Override
protected void initData() {
Map<String, Object> stringMap = IdeaApi.getSign();
stringMap.put("groupId", getIntent().getIntExtra("select_img", 0) + "");
IdeaApi.getRequestLogin(stringMap);
IdeaApi.getApiService()
.getArtKohlerSelectImg(stringMap)
.compose(ArtKohlerSelectActivity.this.<BasicResponse<ArtKohlerSelectImgBean>>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BasicResponse<ArtKohlerSelectImgBean>>(ArtKohlerSelectActivity.this, true) {
@Override
public void onSuccess(BasicResponse<ArtKohlerSelectImgBean> response) {
mArtSelectBean.clear();
mArtSelectBean.addAll(response.getData().getResultList());
mArtKohlerSelectActivityAdapter = new ArtKohlerSelectActivityAdapter(mArtSelectBean);
rvArtKohlerSelect.setAdapter(mArtKohlerSelectActivityAdapter);
mArtKohlerSelectActivityAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
startActivity(new Intent(ArtKohlerSelectActivity.this, ArtKohlerSelectBigImgActivity.class).putExtra("select_img", getIntent().getIntExtra("select_img", 0)).putExtra("position", position));
}
});
}
});
}
}
<file_sep>package com.mengyang.kohler.home.activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.allyes.analytics.AIOAnalytics;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.gyf.barlibrary.ImmersionBar;
import com.mengyang.kohler.App;
import com.mengyang.kohler.BaseActivity;
import com.mengyang.kohler.R;
import com.mengyang.kohler.common.activity.AzureCustomerServiceActivity;
import com.mengyang.kohler.common.activity.CustomerServiceActivity;
import com.mengyang.kohler.common.activity.WebViewActivity;
import com.mengyang.kohler.common.net.DefaultObserver;
import com.mengyang.kohler.common.net.IConstants;
import com.mengyang.kohler.common.net.IdeaApi;
import com.mengyang.kohler.common.utils.SPUtil;
import com.mengyang.kohler.common.view.GridSpacingItemDecoration;
import com.mengyang.kohler.common.view.TopView;
import com.mengyang.kohler.module.BasicResponse;
import com.mengyang.kohler.module.bean.MeetingBean;
import com.mengyang.kohler.home.adapter.MeetingAdapter;
import com.umeng.analytics.MobclickAgent;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
/**
* 经销商大会
*/
public class MeetingActivity extends BaseActivity {
@BindView(R.id.tv_meeting_top)
TopView tvMeetingTop;
@BindView(R.id.ll_meeting_msg_reminder_push)
LinearLayout llMeetingMsgReminderPush;
@BindView(R.id.tv_meeting_next_agenda_time)
TextView tvMeetingNextAgendaTime;
@BindView(R.id.tv_meeting_next_agenda_position)
TextView tvMeetingNextAgendaPosition;
@BindView(R.id.tv_meeting_next_agenda_name)
TextView tvMeetingNextAgendaName;
@BindView(R.id.iv_meeting_highlights)
ImageView ivMeetingHighlights;
@BindView(R.id.ll_meeting_next)
LinearLayout llMeetingNext;
@BindView(R.id.tv_meeting_desc)
TextView tvMeetingDesc;
@BindView(R.id.iv_invitation_h5)
ImageView ivInvitationH5;
@BindView(R.id.rv_meeting)
RecyclerView rvMeeting;
@BindView(R.id.tv_meeting_msg_reminder_push)
TextView tvMeetingMsgReminderPush;
@BindView(R.id.iv_meeting_vote)
ImageView ivMeetingVote;
@BindView(R.id.iv_meeting_chat_wall)
ImageView ivMeetingChatWall;
@BindView(R.id.tv_meeting_position_zero_agenda_type)
TextView tvMeetingPositionZeroAgendaType;
@BindView(R.id.tv_meeting_position_zero_agenda_time)
TextView tvMeetingPositionZeroAgendaTime;
@BindView(R.id.tv_meeting_position_zero_agenda_position)
TextView tvMeetingPositionZeroAgendaPosition;
@BindView(R.id.tv_meeting_position_zero_agenda_name)
TextView tvMeetingPositionZeroAgendaName;
@BindView(R.id.ll_meeting_position_zero)
LinearLayout llMeetingPositionZero;
@BindView(R.id.iv_meeting_search_table_number)
ImageView ivMeetingSearchTableNumber;
private PopupWindow mMeetingPopupWindow;
private View mPopLayout;
private MeetingBean mMeetingBean;
private List<MeetingBean.AgendaListBean> mMeetingAdapterBean;
private MeetingAdapter mMeetingAdapter;
//popupwindow 控件
private TextView tvPopMeetingDate;
private TextView tvPopMeetingTime;
private TextView tvPopMeetingPosition;
private TextView tvPopMeetingName;
private TextView tvPopMeetingAbstract;
@Override
protected int getLayoutId() {
return R.layout.activity_meeting;
}
@Override
protected void initValues() {
App.getManager().addActivity(this);
//防止状态栏和标题重叠
ImmersionBar.setTitleBar(this, tvMeetingTop);
MobclickAgent.onEvent(MeetingActivity.this, "jingxiaoshangdahui");
mMeetingPopupWindow = new PopupWindow(this);
mMeetingPopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
mMeetingPopupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
LayoutInflater inflater = LayoutInflater.from(App.getContext());
mPopLayout = inflater.inflate(R.layout.popup_window_meeting, null);
mPopLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mMeetingPopupWindow.dismiss();
}
});
mMeetingPopupWindow.setContentView(mPopLayout);
mMeetingPopupWindow.setBackgroundDrawable(new ColorDrawable(0x4c000000));
mMeetingPopupWindow.setOutsideTouchable(false);
mMeetingPopupWindow.setFocusable(true);
tvPopMeetingDate = mPopLayout.findViewById(R.id.tv_pop_meeting_date);
tvPopMeetingTime = mPopLayout.findViewById(R.id.tv_pop_meeting_time);
tvPopMeetingPosition = mPopLayout.findViewById(R.id.tv_pop_meeting_position);
tvPopMeetingName = mPopLayout.findViewById(R.id.tv_pop_meeting_name);
tvPopMeetingAbstract = mPopLayout.findViewById(R.id.tv_pop_meeting_abstract);
GridLayoutManager layoutManagerActivity = new GridLayoutManager(App.getContext(), 2);
rvMeeting.setLayoutManager(layoutManagerActivity);
rvMeeting.addItemDecoration(new GridSpacingItemDecoration(2, 20, false));
rvMeeting.setHasFixedSize(true);
rvMeeting.setItemAnimator(new DefaultItemAnimator());
rvMeeting.setNestedScrollingEnabled(false);
mMeetingAdapterBean = new ArrayList<>();
mMeetingAdapter = new MeetingAdapter(mMeetingAdapterBean);
rvMeeting.setAdapter(mMeetingAdapter);
//获取推送按钮状态
if ((SPUtil.get(App.getContext(), IConstants.MEETING_PUSH_MSG, "true") + "").equals("true")) {
tvMeetingMsgReminderPush.setText(getResources().getString(R.string.msg_reminder_push_off));
} else {
tvMeetingMsgReminderPush.setText(getResources().getString(R.string.msg_reminder_push_open));
}
}
@Override
protected void initListener() {
}
@Override
protected void initData() {
Map<String, Object> stringMap = IdeaApi.getSign();
IdeaApi.getRequestLogin(stringMap);
IdeaApi.getApiService()
.getMeeting(stringMap)
.compose(MeetingActivity.this.<BasicResponse<MeetingBean>>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BasicResponse<MeetingBean>>(MeetingActivity.this, true) {
@Override
public void onSuccess(BasicResponse<MeetingBean> response) {
mMeetingBean = response.getData();
tvMeetingDesc.setText(mMeetingBean.getMeetingDesc());
// Glide.with(App.getContext()).load(mMeetingBean.getKvUrl()).apply(new RequestOptions().placeholder(R.mipmap.queshengtu)).into();
tvMeetingNextAgendaTime.setText(mMeetingBean.getAgendaList().get(0).getTimeSlot());
tvMeetingNextAgendaPosition.setText(mMeetingBean.getAgendaList().get(0).getPlace());
tvMeetingNextAgendaName.setText(mMeetingBean.getAgendaList().get(0).getTitle());
String agendaType = "";
switch (mMeetingBean.getAgendaList().get(0).getAgendaType()) {
case -1:
agendaType = "过期议程";
break;
case 0:
agendaType = "未来议程";
break;
case 1:
agendaType = " 明日议程";
break;
case 2:
agendaType = "下一议程";
break;
case 3:
agendaType = "当前议程";
break;
}
tvMeetingPositionZeroAgendaType.setText(agendaType);
tvMeetingPositionZeroAgendaTime.setText(mMeetingBean.getAgendaList().get(0).getTimeSlot());
tvMeetingPositionZeroAgendaPosition.setText(mMeetingBean.getAgendaList().get(0).getPlace());
tvMeetingPositionZeroAgendaName.setText(mMeetingBean.getAgendaList().get(0).getTitle());
mMeetingAdapterBean.clear();
mMeetingAdapterBean.addAll(mMeetingBean.getAgendaList());
mMeetingAdapterBean.remove(0);
mMeetingAdapter = new MeetingAdapter(mMeetingAdapterBean);
rvMeeting.setAdapter(mMeetingAdapter);
mMeetingAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
tvPopMeetingDate.setText(mMeetingBean.getAgendaList().get(position + 1).getDateStr());
tvPopMeetingTime.setText(mMeetingBean.getAgendaList().get(position + 1).getTimeSlot());
tvPopMeetingPosition.setText(mMeetingBean.getAgendaList().get(position + 1).getPlace());
tvPopMeetingName.setText(mMeetingBean.getAgendaList().get(position + 1).getTitle());
tvPopMeetingAbstract.setText(mMeetingBean.getAgendaList().get(position + 1).getAgendaDesc());
if (Build.VERSION.SDK_INT == 24) {//android7.0需要单独做适配
mMeetingPopupWindow.showAtLocation(view, Gravity.NO_GRAVITY, 0, getStatusBarHeight());
} else {
mMeetingPopupWindow.showAtLocation(view, Gravity.NO_GRAVITY, 0, 0);
}
}
});
}
});
}
@Override
protected void onResume() {
super.onResume();
MobclickAgent.onResume(this);
AIOAnalytics.onPageBegin("jingxiaoshangdahui");
}
@Override
protected void onPause() {
super.onPause();
MobclickAgent.onPause(this);
AIOAnalytics.onPageEnd("jingxiaoshangdahui");
}
private void AgendaMsgPush(boolean pushMsg) {
Map<String, Object> stringMap = IdeaApi.getSign();
stringMap.put("pushMsg", pushMsg + "");
IdeaApi.getRequestLogin(stringMap);
IdeaApi.getApiService()
.getMeetingUserSettingsModify(stringMap)
.compose(MeetingActivity.this.<BasicResponse>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BasicResponse>(MeetingActivity.this, false) {
@Override
public void onSuccess(BasicResponse response) {
}
});
}
@OnClick({R.id.iv_meeting_search_table_number, R.id.ll_meeting_position_zero, R.id.iv_meeting_highlights, R.id.ll_meeting_next, R.id.iv_invitation_h5, R.id.ll_meeting_msg_reminder_push, R.id.iv_meeting_vote, R.id.iv_meeting_chat_wall})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.ll_meeting_next:
tvPopMeetingDate.setText(mMeetingBean.getAgendaList().get(0).getDateStr());
tvPopMeetingTime.setText(mMeetingBean.getAgendaList().get(0).getTimeSlot());
tvPopMeetingPosition.setText(mMeetingBean.getAgendaList().get(0).getPlace());
tvPopMeetingName.setText(mMeetingBean.getAgendaList().get(0).getTitle());
tvPopMeetingAbstract.setText(mMeetingBean.getAgendaList().get(0).getAgendaDesc());
if (Build.VERSION.SDK_INT == 24) {//android7.0需要单独做适配
mMeetingPopupWindow.showAtLocation(view, Gravity.NO_GRAVITY, 0, getStatusBarHeight());
} else {
mMeetingPopupWindow.showAtLocation(view, Gravity.NO_GRAVITY, 0, 0);
}
break;
case R.id.iv_invitation_h5:
startActivity(new Intent(this, MeetingWebActivity.class).putExtra("meeting_web", mMeetingBean.getInvitationH5Url()));
break;
case R.id.ll_meeting_msg_reminder_push:
if ((SPUtil.get(App.getContext(), IConstants.MEETING_PUSH_MSG, "true") + "").equals("true")) {
tvMeetingMsgReminderPush.setText(getResources().getString(R.string.msg_reminder_push_open));
AgendaMsgPush(false);
SPUtil.put(App.getContext(), IConstants.MEETING_PUSH_MSG, false + "");
} else {
tvMeetingMsgReminderPush.setText(getResources().getString(R.string.msg_reminder_push_off));
AgendaMsgPush(true);
SPUtil.put(App.getContext(), IConstants.MEETING_PUSH_MSG, true + "");
}
break;
case R.id.iv_meeting_vote:
//投票
startActivity(new Intent(this, LiveRealTimeActivity.class));
break;
case R.id.iv_meeting_chat_wall:
//弹幕
startActivity(new Intent(this, BarrageActivity.class));
break;
case R.id.iv_meeting_highlights:
//集锦
startActivity(new Intent(this, WebViewActivity.class).putExtra("h5url", "http://vphotos.cn/HQJs"));
break;
case R.id.ll_meeting_position_zero:
tvPopMeetingDate.setText(mMeetingBean.getAgendaList().get(0).getDateStr());
tvPopMeetingTime.setText(mMeetingBean.getAgendaList().get(0).getTimeSlot());
tvPopMeetingPosition.setText(mMeetingBean.getAgendaList().get(0).getPlace());
tvPopMeetingName.setText(mMeetingBean.getAgendaList().get(0).getTitle());
tvPopMeetingAbstract.setText(mMeetingBean.getAgendaList().get(0).getAgendaDesc());
if (Build.VERSION.SDK_INT == 24) {//android7.0需要单独做适配
mMeetingPopupWindow.showAtLocation(view, Gravity.NO_GRAVITY, 0, getStatusBarHeight());
} else {
mMeetingPopupWindow.showAtLocation(view, Gravity.NO_GRAVITY, 0, 0);
}
break;
case R.id.iv_meeting_search_table_number:
startActivity(new Intent(this, CustomerServiceActivity.class));
break;
default:
break;
}
}
}
<file_sep>package com.mengyang.kohler.whole_category.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;
import com.mengyang.kohler.common.utils.LogUtils;
import java.util.Vector;
/**
* Description :
* Author : rmy
* Email : <EMAIL>
* Time : 2018/2/23
*/
public class ComposeTextView extends View {
// 总高度、宽度
private int sumHeight = 0;
private int maxWidth = 0;
// 一些属性
private int textColor = getResources().getColor(android.R.color.black);
private int textSize = 11;
private int lineSpace = 2; //行间距
private int typeFace = 0;
private String text = "";
private int maxLine = Integer.MAX_VALUE; //最大行数
// 上下左右的距离
private int left_Margin = 0;
private int right_Margin = 45;
private int top_Margin = 0;
private int bottom_Margin = 0;
private Paint mPaint;
public ComposeTextView(Context context, int textWidth) {
super(context);
init(textWidth);
}
public ComposeTextView(Context context, AttributeSet attrs, int textWidth) {
super(context, attrs, 0);
init(textWidth);
}
private void init(int textWidth) {
DisplayMetrics dm = getResources().getDisplayMetrics();
//为属性定义单位
textSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, textSize, dm);
lineSpace = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, lineSpace, dm);
left_Margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, left_Margin, dm);
right_Margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, right_Margin, dm);
top_Margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, top_Margin, dm);
bottom_Margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, bottom_Margin, dm);
int width = dm.widthPixels;
maxWidth = width - left_Margin - right_Margin - textWidth;
mPaint = new Paint();
mPaint.setAntiAlias(true);// 抗锯齿
mPaint.setColor(textColor);
mPaint.setTextSize(textSize);
switch (typeFace) {
case 0:
mPaint.setTypeface(Typeface.DEFAULT);
break;
case 1:
mPaint.setTypeface(Typeface.SANS_SERIF);
break;
case 2:
mPaint.setTypeface(Typeface.SERIF);
break;
case 3:
mPaint.setTypeface(Typeface.MONOSPACE);
break;
default:
mPaint.setTypeface(Typeface.DEFAULT);
break;
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int lineWidth = 0; //字符串所占行宽
int lineHeight = 0; //行高
int lineNum = 0; //总行数
int start = 0; //定位:用于截取字符串
char ch;
int x = 0;
int y = 30; //为了让文字可以显示出来,不至于被遮盖,特别是第一行,这个值要根据字体大小设置,可以设置一个值用来动态控制。
Vector<String> mString = new Vector<String>();
Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
lineHeight = (int) (Math.ceil(fontMetrics.descent - fontMetrics.top) + lineSpace);
// y += Math.ceil(fontMetrics.descent);
for (int i = 0; i < text.length(); i++) {
ch = text.charAt(i);
String str = String.valueOf(ch);
float widths[] = new float[1];
mPaint.getTextWidths(str, widths);
if (ch == '\n') {
lineNum++;
mString.addElement(text.substring(start, i));
start = i + 1;
lineWidth = 0;
} else {
lineWidth += Math.ceil(widths[0]);
if (lineWidth > maxWidth) {
lineNum++;
mString.addElement(text.substring(start, i));
start = i;
i--;
lineWidth = 0;
} else {
if (i == text.length() - 1) {
lineNum++;
mString.addElement(text.substring(start, text.length()));
}
}
}
//判断行数是否大于最大行数
if (lineNum > maxLine) {
lineNum = lineNum < maxLine ? lineNum : maxLine;
float dotWidths[] = new float[3];
String dot = "...";
mPaint.getTextWidths(dot, dotWidths);
int dotWidth = 0;
for (int j = 0; j < 3; j++) {
dotWidth += Math.ceil(dotWidths[j]);
}
String string = (String) mString.elementAt(lineNum - 1);
lineWidth = 0;
for (int j = string.length() - 1; j >= 0; j--) {
float stringWidths[] = new float[j + 1];
String stringSub = string.substring(0, j + 1);
mPaint.getTextWidths(stringSub, stringWidths);
for (int k = 0; k < stringSub.length(); k++) {
lineWidth += Math.ceil(stringWidths[k]);
}
if (lineWidth + dotWidth <= maxWidth) {
while (mString.size() > lineNum - 1) {
mString.remove(mString.size() - 1);
}
mString.addElement(stringSub + dot);
break;
}
lineWidth = 0;
}
break;
}
}
sumHeight = lineHeight * lineNum - lineSpace;
for (int i = 0; i < lineNum; i++) {
//其实设置y的只就是为了迎合这个函数,要是不清楚可以自己百度一下
canvas.drawText((String) mString.elementAt(i), x, y + lineHeight
* i, mPaint);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int measuredWidth = measuredWidth(widthMeasureSpec);
int measuredHeight = measuredHeight(heightMeasureSpec);
this.setMeasuredDimension(measuredWidth, measuredHeight);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
measuredWidth, measuredHeight);
params.topMargin = top_Margin;
params.bottomMargin = bottom_Margin;
params.leftMargin = left_Margin;
params.rightMargin = right_Margin;
this.setLayoutParams(params);
}
private int measuredHeight(int heightMeasureSpec) {
int specMode = MeasureSpec.getMode(heightMeasureSpec);
int specSize = MeasureSpec.getSize(heightMeasureSpec);
initHeight();
// Default size if no limits specified.
int result = sumHeight;
if (specMode == MeasureSpec.AT_MOST) {
result = specSize;
} else if (specMode == MeasureSpec.EXACTLY) {
result = sumHeight;
}
return result;
}
/**
* 初始化高度
*/
private void initHeight() {
int lineHeight = 0;
int lineNum = 0;
int lineWidth = 0;
Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
lineHeight = (int) (Math.ceil(fontMetrics.descent - fontMetrics.top) + lineSpace);
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
String str = String.valueOf(ch);
float widths[] = new float[1];
mPaint.getTextWidths(str, widths);
if (ch == '\n') {
lineNum++;
lineWidth = 0;
} else {
lineWidth += Math.ceil(widths[0]);
if (lineWidth > maxWidth) {
lineNum++;
i--;
lineWidth = 0;
} else {
if (i == text.length() - 1) {
lineNum++;
}
}
}
if (lineNum > maxLine) {
lineNum = lineNum < maxLine ? lineNum : maxLine;
break;
}
}
sumHeight = lineNum * lineHeight - lineSpace;
}
private int measuredWidth(int heightMeasureSpec) {
int specMode = MeasureSpec.getMode(heightMeasureSpec);
int specSize = MeasureSpec.getSize(heightMeasureSpec);
// Default size if no limits specified.
int result = maxWidth;
if (specMode == MeasureSpec.AT_MOST) {
result = specSize;
} else if (specMode == MeasureSpec.EXACTLY) {
result = maxWidth;
}
return result;
}
public int getTextColor() {
return textColor;
}
public void setTextColor(int textColor) {
this.textColor = textColor;
}
public int getTextSize() {
return textSize;
}
public void setTextSize(int textSize) {
this.textSize = textSize;
}
public int getLineSpace() {
return lineSpace;
}
public void setLineSpace(int lineSpace) {
this.lineSpace = lineSpace;
}
public int getTypeFace() {
return typeFace;
}
public void setTypeFace(int typeFace) {
this.typeFace = typeFace;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getLeft_Margin() {
return left_Margin;
}
public void setLeft_Margin(int left_Margin) {
this.left_Margin = left_Margin;
}
public int getRight_Margin() {
return right_Margin;
}
public void setRight_Margin(int right_Margin) {
this.right_Margin = right_Margin;
}
public int getTop_Margin() {
return top_Margin;
}
public void setTop_Margin(int top_Margin) {
this.top_Margin = top_Margin;
}
public int getBottom_Margin() {
return bottom_Margin;
}
public void setBottom_Margin(int bottom_Margin) {
this.bottom_Margin = bottom_Margin;
}
public int getMaxLine() {
return maxLine;
}
public void setMaxLine(int maxLine) {
this.maxLine = maxLine;
}
}
<file_sep>package com.mengyang.kohler.module.bean;
import java.util.List;
/**
* Created by hasee on 2018/5/11.
*/
public class VisionBean {
/**
* pageNum : 0
* pageSize : 10
* resultList : [{"dictCode":"01","dictDesc":"ios","dictDescEn":"","dictId":82,"dictName":"1.0.8","dictType":"APP_VERSION","isDeleted":0,"orderSeq":0,"parentDictCode":"","updateTime":"2018-04-27 17:24:45"},{"dictCode":"02","dictDesc":"android","dictDescEn":"","dictId":83,"dictName":"1.0.6","dictType":"APP_VERSION","isDeleted":0,"orderSeq":0,"parentDictCode":"","updateTime":"2018-04-27 17:25:05"}]
* totalPage : 3
* totalSize : 21
*/
private int pageNum;
private int pageSize;
private int totalPage;
private int totalSize;
private List<ResultListBean> resultList;
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getTotalSize() {
return totalSize;
}
public void setTotalSize(int totalSize) {
this.totalSize = totalSize;
}
public List<ResultListBean> getResultList() {
return resultList;
}
public void setResultList(List<ResultListBean> resultList) {
this.resultList = resultList;
}
public static class ResultListBean {
/**
* dictCode : 01
* dictDesc : ios
* dictDescEn :
* dictId : 82
* dictName : 1.0.8
* dictType : APP_VERSION
* isDeleted : 0
* orderSeq : 0
* parentDictCode :
* updateTime : 2018-04-27 17:24:45
*/
private String dictCode;
private String dictDesc;
private String dictDescEn;
private int dictId;
private String dictName;
private String dictType;
private int isDeleted;
private int orderSeq;
private String parentDictCode;
private String updateTime;
public String getDictCode() {
return dictCode;
}
public void setDictCode(String dictCode) {
this.dictCode = dictCode;
}
public String getDictDesc() {
return dictDesc;
}
public void setDictDesc(String dictDesc) {
this.dictDesc = dictDesc;
}
public String getDictDescEn() {
return dictDescEn;
}
public void setDictDescEn(String dictDescEn) {
this.dictDescEn = dictDescEn;
}
public int getDictId() {
return dictId;
}
public void setDictId(int dictId) {
this.dictId = dictId;
}
public String getDictName() {
return dictName;
}
public void setDictName(String dictName) {
this.dictName = dictName;
}
public String getDictType() {
return dictType;
}
public void setDictType(String dictType) {
this.dictType = dictType;
}
public int getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(int isDeleted) {
this.isDeleted = isDeleted;
}
public int getOrderSeq() {
return orderSeq;
}
public void setOrderSeq(int orderSeq) {
this.orderSeq = orderSeq;
}
public String getParentDictCode() {
return parentDictCode;
}
public void setParentDictCode(String parentDictCode) {
this.parentDictCode = parentDictCode;
}
public String getUpdateTime() {
return updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
}
}
<file_sep>package com.mengyang.kohler.home.fragment;
import android.content.Intent;
import android.view.View;
import com.allyes.analytics.AIOAnalytics;
import com.deepano.kohlortest.UnityPlayerActivity;
import com.gyf.barlibrary.ImmersionBar;
import com.mengyang.kohler.App;
import com.mengyang.kohler.BaseFragment;
import com.mengyang.kohler.R;
import com.mengyang.kohler.common.net.IConstants;
import com.mengyang.kohler.common.utils.LogUtils;
import com.mengyang.kohler.home.activity.KbisActivity;
import com.umeng.analytics.MobclickAgent;
public class KbisARFragment extends BaseFragment {
private static OnActivityPagerView mOnActivityPagerView;
@Override
protected int getLayoutId() {
return R.layout.fragment_kbis_ar;
}
@Override
protected void initValues() {
AIOAnalytics.onEvent("arsaoyisao");
MobclickAgent.onEvent(getActivity(), "arsaoyisao");
}
@Override
protected void initListener() {
}
@Override
protected void initData() {
}
@Override
public void onResume() {
super.onResume();
MobclickAgent.onResume(getActivity());
AIOAnalytics.onPageBegin("arsaoyisao");
}
@Override
public void onPause() {
super.onPause();
MobclickAgent.onPause(getActivity());
AIOAnalytics.onPageEnd("arsaoyisao");
}
public static void setOnActivityPagerView(OnActivityPagerView onActivityPagerView) {
mOnActivityPagerView = onActivityPagerView;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
//TODO now it's visible to user
Intent intent = new Intent(App.getContext(), UnityPlayerActivity.class);
intent.putExtra("flag", "9");
startActivityForResult(intent, IConstants.AZURE_BACK_ONE);
} else {
//TODO now it's invisible to user
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 0) {
switch (requestCode) {
case IConstants.AZURE_BACK_ONE:
mOnActivityPagerView.onActivityPagerView();
break;
}
}
}
public interface OnActivityPagerView {
// TODO: Update argument type and name
void onActivityPagerView();
}
}
<file_sep>package com.mengyang.kohler.home.activity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import com.allyes.analytics.AIOAnalytics;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.gyf.barlibrary.ImmersionBar;
import com.mengyang.kohler.App;
import com.mengyang.kohler.BaseActivity;
import com.mengyang.kohler.R;
import com.mengyang.kohler.common.net.DefaultObserver;
import com.mengyang.kohler.common.net.IdeaApi;
import com.mengyang.kohler.common.utils.LogUtils;
import com.mengyang.kohler.common.utils.PermissionUtils;
import com.mengyang.kohler.common.view.TopView;
import com.mengyang.kohler.main.activity.MainActivity;
import com.mengyang.kohler.module.BasicResponse;
import com.mengyang.kohler.module.bean.StoreListBean;
import com.umeng.analytics.MobclickAgent;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
/**
* 门店地图
*/
public class StoreMapActivity extends BaseActivity {
@BindView(R.id.tv_store_map_top)
TopView tvStoreMapTop;
@BindView(R.id.bt_store_map)
Button btStoreMap;
@BindView(R.id.map_view)
MapView mapView;
private BaiduMap mBaiduMap;
private LocationClient mLocationClient = null;
//是否第一次定位,如果是第一次定位的话要将自己的位置显示在地图 中间
private boolean isFirstLocation = true;
private Marker mMarker; //坐标气球
private MapStatus mMapStatus;
private List<StoreListBean.ResultListBean> mStoreListBean;
private double mMineLatitude; //我的纬度
private double mMineLongitude; //我的经度
private double mStoreLatitude; //气球图标纬度
private double mStoreLongitude; //气球图标经度
@Override
protected int getLayoutId() {
SDKInitializer.initialize(getApplicationContext());
return R.layout.activity_store_map;
}
@Override
protected void initValues() {
App.getManager().addActivity(this);
//防止状态栏和标题重叠
ImmersionBar.setTitleBar(this, tvStoreMapTop);
MobclickAgent.onEvent(StoreMapActivity.this, "fujindianpu");
setOnPermissionListener(new OnPermissionListener() {
@Override
public void openIntent() {
//设置权限监听之后,执行自己的操作
}
});
openPermission(new int[]{PermissionUtils.CODE_LOCATION});//请求权限
//百度地图
mBaiduMap = mapView.getMap();
// 不显示缩放比例尺
mapView.showZoomControls(false);
// 不显示百度地图Logo
mapView.removeViewAt(1);
isFirstLocation = getIntent().getBooleanExtra("isFirstLocation", true);
mStoreLatitude = getIntent().getDoubleExtra("store_latitude", 0);
mStoreLongitude = getIntent().getDoubleExtra("store_longitude", 0);
mStoreListBean = new ArrayList<>();
if (isFirstLocation == false) {
LatLng balloon = new LatLng(mStoreLatitude, mStoreLongitude);
// 改变地图状态,使地图显示在恰当的缩放大小
mMapStatus = new MapStatus.Builder().target(balloon).zoom(15).build();
} else {
// 改变地图状态,使地图显示在恰当的缩放大小
mMapStatus = new MapStatus.Builder().zoom(15).build();
}
MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
mBaiduMap.setMapStatus(mMapStatusUpdate);
mLocationClient = new LocationClient(getApplicationContext());//声明LocationClient类
}
@Override
protected void initListener() {
mLocationClient.registerLocationListener(new BDAbstractLocationListener() {
@Override
public void onReceiveLocation(BDLocation bdLocation) {
//此处的BDLocation为定位结果信息类,通过它的各种get方法可获取定位相关的全部结果
//以下只列举部分获取经纬度相关(常用)的结果信息
//更多结果信息获取说明,请参照类参考中BDLocation类中的说明
mMineLatitude = bdLocation.getLatitude(); //获取定位纬度信息
mMineLongitude = bdLocation.getLongitude(); //获取定位经度信息
AllMarkerOptions();
if (isFirstLocation == false)
getMarkerOptions(mStoreLatitude, mStoreLongitude);
float radius = bdLocation.getRadius(); //获取定位精度,默认值为0.0f
String coorType = bdLocation.getCoorType();
//获取经纬度坐标类型,以LocationClientOption中设置过的坐标类型为准
int errorCode = bdLocation.getLocType();
//获取定位类型、定位错误返回码,具体信息可参照类参考中BDLocation类中的说明
String addr = bdLocation.getAddrStr(); //获取详细地址信息
String country = bdLocation.getCountry(); //获取国家
String province = bdLocation.getProvince(); //获取省份
String city = bdLocation.getCity(); //获取城市
String district = bdLocation.getDistrict(); //获取区县
String street = bdLocation.getStreet(); //获取街道信息
String locationDescribe = bdLocation.getLocationDescribe(); //获取位置描述信息
List<Poi> poiList = bdLocation.getPoiList();
//获取周边POI信息
//POI信息包括POI ID、名称等,具体信息请参照类参考中POI类的相关说明
//将获取的location信息给百度map
MyLocationData data = new MyLocationData.Builder()
.accuracy(bdLocation.getRadius())
// 此处设置开发者获取到的方向信息,顺时针0-360
.direction(100)
.latitude(bdLocation.getLatitude())
.longitude(bdLocation.getLongitude())
.build();
mBaiduMap.setMyLocationData(data);
if (isFirstLocation) {
//获取经纬度
LatLng ll = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
MapStatusUpdate status = MapStatusUpdateFactory.newLatLng(ll);
//mBaiduMap.setMapStatus(status);//直接到中间
mBaiduMap.animateMapStatus(status);//动画的方式到中间
//isFirstLocation = false; //如果要设置一个按钮(点一下就回到定位中心点的那种),就打开,再在按钮事件里写 isFirstLocation = true;
// showInfo("位置:" + bdLocation.getAddrStr());
}
}
});
}
@Override
protected void initData() {
LocationClientOption option = new LocationClientOption();
option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
//可选,设置定位模式,默认高精度
//LocationMode.Hight_Accuracy:高精度;
//LocationMode. Battery_Saving:低功耗;
//LocationMode. Device_Sensors:仅使用设备;
option.setCoorType("bd09ll");
//可选,设置返回经纬度坐标类型,默认gcj02
//gcj02:国测局坐标;
//bd09ll:百度经纬度坐标;
//bd09:百度墨卡托坐标;
//海外地区定位,无需设置坐标类型,统一返回wgs84类型坐标
option.setScanSpan(0);
//可选,设置发起定位请求的间隔,int类型,单位ms
//如果设置为0,则代表单次定位,即仅定位一次,默认为0
//如果设置非0,需设置1000ms以上才有效
option.setOpenGps(true);
//可选,设置是否使用gps,默认false
//使用高精度和仅用设备两种定位模式的,参数必须设置为true
option.setLocationNotify(true);
//可选,设置是否当GPS有效时按照1S/1次频率输出GPS结果,默认false
option.setIgnoreKillProcess(false);
//可选,定位SDK内部是一个service,并放到了独立进程。
//设置是否在stop的时候杀死这个进程,默认(建议)不杀死,即setIgnoreKillProcess(true)
option.SetIgnoreCacheException(false);
//可选,设置是否收集Crash信息,默认收集,即参数为false
option.setWifiCacheTimeOut(5 * 60 * 1000);
//可选,7.2版本新增能力
//如果设置了该接口,首次启动定位时,会先判断当前WiFi是否超出有效期,若超出有效期,会先重新扫描WiFi,然后定位
option.setEnableSimulateGps(false);
//可选,设置是否需要过滤GPS仿真结果,默认需要,即参数为false
option.setIsNeedLocationPoiList(true);
//可选,是否需要地址信息,默认为不需要,即参数为false
//如果开发者需要获得当前点的地址信息,此处必须为true
mLocationClient.setLocOption(option);
}
private void AllMarkerOptions() {
Map<String, Object> stringMap = IdeaApi.getSign();
stringMap.put("pageNum", 0 + "");
stringMap.put("pageSize", 10 + "");
stringMap.put("latitude", mMineLatitude + "");
stringMap.put("longitude", mMineLongitude + "");
IdeaApi.getRequestLogin(stringMap);
IdeaApi.getApiService()
.getStoreList(stringMap)
.compose(this.<BasicResponse<StoreListBean>>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BasicResponse<StoreListBean>>(this, false) {
@Override
public void onSuccess(BasicResponse<StoreListBean> response) {
if (response != null) {
mStoreListBean.clear();
mStoreListBean.addAll(response.getData().getResultList());
for (int i = 0; i < mStoreListBean.size(); i++) {
getMarkerOptions(mStoreListBean.get(i).getLatitude(), mStoreListBean.get(i).getLongitude());
}
}
}
});
}
private void getMarkerOptions(double latitude, double longitude) {
/**
* 绘制Marker,地图上常见的类似气球形状的图层
*/
MarkerOptions markerOptions = new MarkerOptions();//参数设置类
LatLng balloon = new LatLng(latitude, longitude);
// LatLng balloon = new LatLng(31.194388, 121.423831);
markerOptions.position(balloon);//marker坐标位置
BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.pin);
markerOptions.icon(bitmap);//marker图标,可以自定义
markerOptions.draggable(false);//是否可拖拽,默认不可拖拽
markerOptions.anchor(0.5f, 1.0f);//设置 marker覆盖物与位置点的位置关系,默认(0.5f, 1.0f)水平居中,垂直下对齐
markerOptions.alpha(0.8f);//marker图标透明度,0~1.0,默认为1.0
// markerOptions.animateType(MarkerOptions.MarkerAnimateType.drop);//marker出现的方式,从天上掉下
markerOptions.flat(false);//marker突变是否平贴地面
markerOptions.zIndex(1);//index
mMarker = (Marker) mBaiduMap.addOverlay(markerOptions);//在地图上增加mMarker图层
}
@Override
protected void onStart() {
super.onStart();
//开启定位
mBaiduMap.setMyLocationEnabled(true);
if (!mLocationClient.isStarted()) {//如果定位client没有开启,开启定位
mLocationClient.start();
//mLocationClient为第二步初始化过的LocationClient对象
//调用LocationClient的start()方法,便可发起定位请求
}
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
MobclickAgent.onResume(this);
AIOAnalytics.onPageBegin("fujindianpu");
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
MobclickAgent.onPause(this);
AIOAnalytics.onPageEnd("fujindianpu");
}
@Override
protected void onStop() {
super.onStop();
//关闭定位
mBaiduMap.setMyLocationEnabled(false);
if (mLocationClient.isStarted()) {
mLocationClient.stop();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
MapView.setMapCustomEnable(false);
mapView = null;
}
@OnClick({R.id.bt_store_map})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.bt_store_map:
//测距
// LatLng start = new LatLng(39.95676, 116.401394);
// LatLng end = new LatLng(36.63014,114.499574);
// getDistance(start, end);
startActivity(new Intent(this, StoreListActivity.class).putExtra("mine_latitude", mMineLatitude).putExtra("mine_longitude", mMineLongitude));
finish();
break;
}
}
}
<file_sep>package com.mengyang.kohler.home.adapter;
import android.support.annotation.Nullable;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.mengyang.kohler.R;
import com.mengyang.kohler.module.bean.StoreListBean;
import java.util.List;
/**
* Description :
* Author : rmy
* Email : <EMAIL>
* Time : 2018/1/30
*/
public class StoreListAdapter extends BaseQuickAdapter<StoreListBean.ResultListBean, BaseViewHolder> {
public StoreListAdapter(@Nullable List<StoreListBean.ResultListBean> data) {
super(R.layout.item_store_list_adapter, data);
}
@Override
protected void convert(BaseViewHolder helper, StoreListBean.ResultListBean item) {
helper.setText(R.id.tv_store_list_name, item.getRoomname())
.setText(R.id.tv_store_list_address, item.getAddress())
.setText(R.id.tv_store_list_phone, item.getTel())
.setText(R.id.tv_store_list_distance, item.getDistance() + "m");
}
}
<file_sep>package com.mengyang.kohler.whole_category.fragment;
import android.annotation.SuppressLint;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.allyes.analytics.AIOAnalytics;
import com.gyf.barlibrary.ImmersionBar;
import com.mengyang.kohler.BaseFragment;
import com.mengyang.kohler.R;
import com.mengyang.kohler.common.net.DefaultObserver;
import com.mengyang.kohler.common.net.IdeaApi;
import com.mengyang.kohler.common.view.TopView;
import com.mengyang.kohler.main.activity.MainActivity;
import com.mengyang.kohler.module.BasicResponse;
import com.mengyang.kohler.module.bean.NotSelectClassificationBean;
import com.mengyang.kohler.whole_category.adapter.StackAdapter;
import com.mengyang.kohler.whole_category.view.Align;
import com.mengyang.kohler.whole_category.view.Config;
import com.mengyang.kohler.whole_category.view.StackLayoutManager;
import com.umeng.analytics.MobclickAgent;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
/**
* 全品类
*/
public class WholeCategoryFragment extends BaseFragment implements StackLayoutManager.changeListenning {
@BindView(R.id.tv_whole_category_top)
TopView tvWholeCategoryTop;
@BindView(R.id.rv_whole_category)
RecyclerView rvWholeCategory;
@BindView(R.id.iv_top_customer_service)
ImageView ivTopCustomerService;
@BindView(R.id.iv_top_system_msg)
ImageView ivTopSystemMsg;
@BindView(R.id.tv_whole_category_visible)
TextView tv_whole_category_visible;
@BindView(R.id.tv_whole_category_gone)
TextView tv_whole_category_gone;
@BindView(R.id.tv_title_en)
TextView mTvTitleEn;
@BindView(R.id.iv_title)
ImageView mIvTitle;
private List<NotSelectClassificationBean> mNotSelectClassificationBean;
private List<NotSelectClassificationBean> mNotSelectClassificationPositiveSequenceBean;
private StackAdapter mStackAdapter;
@Override
protected int getLayoutId() {
return R.layout.fragment_whole_category;
}
@SuppressLint("ResourceAsColor")
@Override
protected void initValues() {
//防止状态栏和标题重叠
ImmersionBar.setTitleBar(getActivity(), tvWholeCategoryTop);
MobclickAgent.onEvent(getActivity(), "category");
// if (SPUtil.get(App.getContext(), IConstants.TYPE, "").equals("dealer"))
// ivTopCustomerService.setVisibility(View.VISIBLE);
// else
ivTopCustomerService.setVisibility(View.GONE);
ivTopCustomerService.setImageResource(R.mipmap.kefubai);
ivTopSystemMsg.setImageResource(R.mipmap.youxiangbai);
mNotSelectClassificationBean = new ArrayList<>();
mNotSelectClassificationPositiveSequenceBean = new ArrayList<>();
}
@Override
protected void initListener() {
}
@Override
protected void initData() {
Map<String, Object> stringMap = IdeaApi.getSign();
IdeaApi.getRequestLogin(stringMap);
IdeaApi.getApiService()
.getNotSelectClassification(stringMap)
.compose(this.<BasicResponse<List<NotSelectClassificationBean>>>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BasicResponse<List<NotSelectClassificationBean>>>(getActivity(), true) {
@Override
public void onSuccess(BasicResponse<List<NotSelectClassificationBean>> response) {
if (response != null) {
mNotSelectClassificationBean.clear();
mNotSelectClassificationBean = response.getData();
//StackLayoutManager 卡片堆叠框架的index是从右向左,所以遍历List转成从左向右使用
for (int i = mNotSelectClassificationBean.size() - 1; i >= 0; i--) {
if (!TextUtils.isEmpty(mNotSelectClassificationBean.get(i).getKvUrl())) {
mNotSelectClassificationPositiveSequenceBean.add(mNotSelectClassificationBean.get(i));
}
}
Config config = new Config();
config.secondaryScale = 0f;
config.scaleRatio = 0.2f;//上一层堆叠与下层堆叠的 marginBottom
config.maxStackCount = 3;//边缘显示的堆叠层数
config.initialStackCount = mNotSelectClassificationPositiveSequenceBean.size() - 1;
config.space = getResources().getDimensionPixelOffset(R.dimen.item_space);//上一层图片与下一层的距离
config.align = Align.RIGHT;//堆叠显示的方向
StackLayoutManager stackLayoutManager = new StackLayoutManager(config);
stackLayoutManager.setChangeListenning(WholeCategoryFragment.this);
rvWholeCategory.setLayoutManager(stackLayoutManager);
mStackAdapter = new StackAdapter(mNotSelectClassificationPositiveSequenceBean);
rvWholeCategory.setAdapter(mStackAdapter);
}
}
});
}
@Override
public void onResume() {
super.onResume();
MobclickAgent.onResume(getActivity());
AIOAnalytics.onPageBegin("category");
}
@Override
public void onPause() {
super.onPause();
MobclickAgent.onPause(getActivity());
AIOAnalytics.onPageEnd("category");
}
@Override
public void changeListenning(int position) {
if (position >= 1) {
}
if ((mNotSelectClassificationPositiveSequenceBean.size() - 1) == position) {
mIvTitle.setVisibility(View.VISIBLE);
mTvTitleEn.setVisibility(View.GONE);
tv_whole_category_visible.setText("科勒精选");
// mTvTitleEn.setText(mNotSelectClassificationPositiveSequenceBean.get(position).getNameEn());
} else {
tv_whole_category_visible.setText(mNotSelectClassificationPositiveSequenceBean.get(position).getNameEn());
mTvTitleEn.setText(mNotSelectClassificationPositiveSequenceBean.get(position).getNameCn());
mIvTitle.setVisibility(View.GONE);
mTvTitleEn.setVisibility(View.VISIBLE);
}
}
}
<file_sep>package com.mengyang.kohler.module.bean;
/**
* Created by MengYang on 2018/5/22.
*/
public class AzureBotWartBean {
/**
* id : 0001
*/
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public String toString() {
return "WartBean{" +
"id='" + id + '\'' +
'}';
}
}
<file_sep>package com.mengyang.kohler.common.net;
/**
* Description : 接口 URL
* Author : rmy
* Email : <EMAIL>
* Time : 2017/11/loading3
*/
public interface Config {
/**
* 登录
*/
String USER_REGISTER = "authz/account/register"; //用户注册
String APP_LOGIN = "authz/account/login"; //登录
String LOGIN_VERIFICATION_IMG = "authz/account/getCode"; //登录验证码图片
String REFRESH_TOKEN = "authz/token/exchange"; // 更新access_token
String EQUIPMENT_REQISTRATION = "authz/device/register"; //设备注册
String USER_GO_OUT = "authz/account/logout"; //用户退出
String USER_CANCEL_BIND_PHONE = "authz/account/unbindMobile"; //用户解绑手机
String USER_BIND_PHONE = "authz/account/bindMobile"; //用户手机绑定
String USER_MODIFY_BIND_PHONE = "authz/account/updateBindMobile"; //用户换绑手机
String FORGET_PWD = "<PASSWORD>"; //忘记密码
String MODIFY_PWD = "<PASSWORD>"; //修改密码
String LOGIN_SMS = "authz/smscode/doSend"; //登陆短信验证
String CHECK_UP = "dice/list"; //检查更新
/**
* 首页
*/
String HOME_INDEX = "index/index"; //首页
String STORE_LIST = "store/list"; //附近店铺
String ALL_SEARCH = "productSearch/solrByStr"; //全文搜索
String MEETING = "ndc/facadeGetMeetingAndAgenda"; //经销商大会页数据
String MEETING_LIVE_REAL_TIME = "ndc/getPictureList"; //经销商大会现场实时投票
String BOOKS_LIST = "handBook/getHandBooks"; //手册列表
String MEETING_USER_SETTINGS = "user/data/get"; //获取经销商大会用户设置
String MEETING_USER_SETTINGS_MODIFY = "user/data/update"; //修改经销商大会用户设置
String MEETING_LIKE_PICTURE = "ndc/likePicture"; //经销商大会照片点赞
String MEETING_BARRAGE = "http://106.15.92.74/api/v1/danmu/send?access_token="; //弹幕
String WEEKLY_RADIO_CONCERT = "concert/list"; //星广会内容列表
String ART_KOHLER = "ndc/facadeGetMeetingAndAgenda?meetingId=2"; //科勒艺术
String GAN_CHUANG = "ndc/facadeGetMeetingAndAgenda?meetingId=3"; //敢创•科勒亚太艺术展
String ART_KOHLER_SELECT_IMG = "ndc/getPictureListByGroup"; //科勒艺术精选图片
String APPOINTMENT_PATH = "js/exports_2.json"; //预约地址
String KBIS = "ndc/facadeGetMeetingAndAgenda?sign=1&reqTime=1&appType=1&deviceId=1&clientId=1&resultType=1&charset=1&signType=1&ipAddress=1&meetingId=4"; //2018上海厨卫展
String AZURE_AI = "http://ai.glor.cn/queryAll";
/**
* 全品类
*/
String COMMODITY_SEARCH = "productSearch/searchBySku"; //商品redis查找
String SELECT_CLASSIFICATION = "category/selectionList"; //获得精选分类下所有分类
String COMMODITY_CLASSIFICATION = "category/listWithoutSelection";//获得所有非精选分类主界面
String COMMODITY_CLASSIFICATION_TITLE = "category/childList";//商品分类顶部导航栏
String COMMODITY_CLASSIFICATION_BODY = "productSearch/searchByCate";//对应商品分类顶部导航栏的Fragment
String COMMODITY_DETAILS = "productSearch/searchGroupBySku";//商品详情
String ADD_LIKE = "product/insertFavorite"; //用户添加收藏
/**
* 账户
*/
String USER_RESERVE_MSG = "appointment/info"; //获取用户预约信息
String CANCEL_LIKE = "product/deleteFavorite"; //用户取消收藏
String LIKE_LIST = "product/favoriteList"; //用户收藏列表
String MODIFY_HEAD_PORTRAIT = "authz/account/updatePortrait"; //修改头像
String UPLOAD_HEAD_PORTRAIT = "file/uploadMedia"; //上传头像
String MODIFY_NIKE_NAME = "authz/account/updateNickName"; //修改昵称
String FOOT_PRINT = "product/recordList"; //足迹列表
String USER_MSG = "authz/account/getUserInfo"; //用户信息
/**
* 公共
*/
String QUESTION_SEARCH = "question/search"; //客服问题搜索
String SYSTEM_MSG = "system/message/list"; //系统消息列表
}
<file_sep>package com.mengyang.kohler.home.adapter;
import android.support.annotation.Nullable;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.mengyang.kohler.App;
import com.mengyang.kohler.R;
import com.mengyang.kohler.module.bean.AllSearchBean;
import java.util.List;
/**
* Description :
* Author : rmy
* Email : <EMAIL>
* Time : 2018/1/29
*/
public class HomeSearchAdapter extends BaseQuickAdapter<AllSearchBean.ResultListBean, BaseViewHolder> {
public HomeSearchAdapter(@Nullable List<AllSearchBean.ResultListBean> data) {
super(R.layout.item_home_search_adapter, data);
}
@Override
protected void convert(BaseViewHolder helper, AllSearchBean.ResultListBean item) {
helper.setText(R.id.tv_home_search_adapter_product_name, item.getProductName())
.setText(R.id.tv_home_search_adapter_model_name, item.getSkuCode());
Glide.with(App.getContext()).load(item.getListImageUrl()).apply(new RequestOptions().placeholder(R.mipmap.queshengtu)).into((ImageView) helper.getView(R.id.iv_home_search_adapter_item));
}
}
<file_sep>package com.mengyang.kohler.home.activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.widget.ImageView;
import com.allyes.analytics.AIOAnalytics;
import com.gyf.barlibrary.ImmersionBar;
import com.mengyang.kohler.App;
import com.mengyang.kohler.BaseActivity;
import com.mengyang.kohler.R;
import com.mengyang.kohler.common.net.DefaultObserver;
import com.mengyang.kohler.common.net.IdeaApi;
import com.mengyang.kohler.common.view.TopView;
import com.mengyang.kohler.home.fragment.KbisARFragment;
import com.mengyang.kohler.home.fragment.KbisAgendaFragment;
import com.mengyang.kohler.home.fragment.KbisGuideMapFragment;
import com.mengyang.kohler.home.fragment.KbisInterviewFragment;
import com.mengyang.kohler.home.fragment.KbisPhotoFragment;
import com.mengyang.kohler.home.fragment.KbisProductFragment;
import com.mengyang.kohler.home.fragment.KbisVideoFragment;
import com.mengyang.kohler.home.view.MyViewPager;
import com.mengyang.kohler.home.view.NavitationFollowScrollLayoutIonic;
import com.mengyang.kohler.module.BasicResponse;
import com.mengyang.kohler.module.bean.KbisBean;
import com.mengyang.kohler.whole_category.adapter.ViewPagerAdapter;
import com.umeng.analytics.MobclickAgent;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
/**
* 2018科勒上海厨卫展
*/
public class KbisActivity extends BaseActivity implements KbisARFragment.OnActivityPagerView {
@BindView(R.id.tv_kbis_top)
TopView tvKbisTop;
@BindView(R.id.iv_top_back)
ImageView ivTopBack;
@BindView(R.id.nfsl_kbis)
NavitationFollowScrollLayoutIonic nfslKbis;
@BindView(R.id.vp_kbis)
MyViewPager vpKbis;
private List<Fragment> fragments = new ArrayList<>();
private ViewPagerAdapter viewPagerAdapter;
private int[] titles = {R.mipmap.trade_show_guide_map, R.mipmap.trade_show_ar, R.mipmap.trade_show_agenda, R.mipmap.trade_show_video, R.mipmap.trade_show_photo, R.mipmap.trade_show_product, R.mipmap.trade_show_interview};
private int[] unselectedcolor = {R.mipmap.trade_show_guide_map, R.mipmap.trade_show_ar, R.mipmap.trade_show_agenda, R.mipmap.trade_show_video, R.mipmap.trade_show_photo, R.mipmap.trade_show_product, R.mipmap.trade_show_interview};
private int[] setectedcolor = {R.mipmap.trade_show_guide_map_down, R.mipmap.trade_show_ar_down, R.mipmap.trade_show_agenda_down, R.mipmap.trade_show_video_down, R.mipmap.trade_show_photo_down, R.mipmap.trade_show_product_down, R.mipmap.trade_show_interview_down};
@Override
protected int getLayoutId() {
return R.layout.activity_kbis;
}
@Override
protected void initValues() {
App.getManager().addActivity(this);
//沉浸式状态栏初始化白色
ImmersionBar.with(this).fitsSystemWindows(false).statusBarDarkFont(false).init();
//防止状态栏和标题重叠
ImmersionBar.setTitleBar(this, tvKbisTop);
MobclickAgent.onEvent(KbisActivity.this, "trade_show");
ivTopBack.setImageResource(R.mipmap.fanhuibai);
KbisARFragment.setOnActivityPagerView(this);
}
private void showFragment(KbisBean data) {
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), fragments);
vpKbis.setAdapter(viewPagerAdapter);
vpKbis.setOffscreenPageLimit(2);
nfslKbis.setViewPager(KbisActivity.this, titles, vpKbis, unselectedcolor, setectedcolor, 24, true, 2.5f, 10f, 10f, 90);
nfslKbis.setBgLine(KbisActivity.this, 1);
nfslKbis.setNavLine(KbisActivity.this, 2);
Bundle bundle = new Bundle();
bundle.putSerializable("data", data);
//导览图
KbisGuideMapFragment kbisGuideMapFragment = new KbisGuideMapFragment();
fragments.add(kbisGuideMapFragment);
//AR
KbisARFragment kbisARFragment = new KbisARFragment();
fragments.add(kbisARFragment);
//议程
KbisAgendaFragment kbisAgendaFragment = new KbisAgendaFragment();
fragments.add(kbisAgendaFragment);
//视频
KbisVideoFragment kbisVideoFragment = new KbisVideoFragment();
fragments.add(kbisVideoFragment);
//相册
KbisPhotoFragment kbisPhotoFragment = new KbisPhotoFragment();
fragments.add(kbisPhotoFragment);
//产品手册
KbisProductFragment kbisProductFragment = new KbisProductFragment();
fragments.add(kbisProductFragment);
//文稿
KbisInterviewFragment kbisInterviewFragment = new KbisInterviewFragment();
fragments.add(kbisInterviewFragment);
for (int i = 0; i < fragments.size(); i++) {
fragments.get(i).setArguments(bundle);
}
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), fragments);
vpKbis.setAdapter(viewPagerAdapter);
}
@Override
protected void initListener() {
}
@Override
protected void initData() {
IdeaApi.getApiService()
.getKbis()
.compose(this.<BasicResponse<KbisBean>>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BasicResponse<KbisBean>>(this, true) {
@Override
public void onSuccess(BasicResponse<KbisBean> response) {
KbisBean data = response.getData();
showFragment(data);
}
});
}
@Override
protected void onResume() {
super.onResume();
MobclickAgent.onResume(this);
AIOAnalytics.onPageBegin("trade_show");
}
@Override
protected void onPause() {
super.onPause();
MobclickAgent.onPause(this);
AIOAnalytics.onPageEnd("trade_show");
}
@Override
public void onActivityPagerView() {
vpKbis.setCurrentItem(0);
}
}
<file_sep>package com.mengyang.kohler.home.adapter;
import android.support.annotation.Nullable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.mengyang.kohler.App;
import com.mengyang.kohler.R;
import com.mengyang.kohler.module.bean.KbisBean;
import java.util.List;
/**
* Description :
* Author : rmy
* Email : <EMAIL>
* Time : 2018/2/2
*/
public class KbisPdfAdapter extends BaseQuickAdapter<KbisBean.PdfListBean, BaseViewHolder> {
public KbisPdfAdapter(@Nullable List<KbisBean.PdfListBean> data) {
super(R.layout.item_kbis_pdf, data);
}
@Override
protected void convert(BaseViewHolder helper, KbisBean.PdfListBean item) {
Glide.with(App.getContext()).load(item.getKvUrl()).into((ImageView) helper.getView(R.id.iv_kbis_pdf_bg));
LinearLayout llKbisPdf = helper.getView(R.id.ll_kbis_pdf);
RelativeLayout.LayoutParams params_2 = (RelativeLayout.LayoutParams) llKbisPdf.getLayoutParams();
if (helper.getLayoutPosition() % 2 != 0) {
params_2.addRule(RelativeLayout.ALIGN_PARENT_TOP);
params_2.setMargins(0, 10, 0, 0);
} else {
params_2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params_2.setMargins(0, 0, 0, 20);
}
llKbisPdf.setLayoutParams(params_2);
helper.setText(R.id.tv_kbis_pdf_title, item.getTitle())
.setText(R.id.tv_kbis_pdf_name, item.getElementDesc())
.addOnClickListener(R.id.iv_kbis_pdf_bg)
.addOnClickListener(R.id.iv_kbis_pdf_download);
}
}
<file_sep>include ':app', ':kohlortest_android20180611'
<file_sep>package com.mengyang.kohler.module.bean;
/**
* Created by liusong on 2018/5/18.
*/
public class AddressBean {
/**
* area : 华北
* province : 北京
* city : 北京
* roomname : 北京东四环旗舰展厅
* address : 北京市朝阳区东四环中路195号华腾新天地底商 科勒北京旗舰展厅
* tel : 010-87951684
*/
private String area;
private String province;
private String city;
private String roomname;
private String address;
private String tel;
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getRoomname() {
return roomname;
}
public void setRoomname(String roomname) {
this.roomname = roomname;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
}
<file_sep>package com.mengyang.kohler.module.bean;
/**
* Description :
* Author : rmy
* Email : <EMAIL>
* Time : 2018/1/31
*/
public class RefreshTokenBean {
/**
* accessToken : <KEY>
* refreshToken : <KEY>
*/
private String accessToken;
private String refreshToken;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
}
| 0b3bb921764529c5598da1347ea40c698c7e0ada | [
"Java",
"INI",
"Gradle"
] | 53 | Java | RenVeCf/kohler | d27a1aa77f047357f8aef02c57b48f81600c9970 | 2611390fac512815a445fc556aaa3e7a7df4cf70 |
refs/heads/master | <file_sep>/*RISING BTL. Empresa dedicada a la toma de datos para realizar estadísticas y censos nos pide realizar una carga de datos validada e ingresada por ventanas emergentes solamente (para evitar hacking y cargas maliciosas) y luego asignarla a cuadros de textos.
12. Los datos requeridos son los siguientes:
A. Edad, entre 18 y 90 años inclusive.
B. Sexo, “M” para masculino y “F” para femenino
C. Estado civil, 1-para soltero, 2-para casados, 3-para divorciados y 4-para viudos
D. Sueldo bruto, no menor a 8000.
E. Número de legajo, numérico de 4 cifras, sin ceros a la izquierda.
F. Nacionalidad, “A” para argentinos, “E” para extranjeros, “N” para nacionalizados.
*/
function ComenzarIngreso ()
{
var edad = 0;
edad = parseInt(edad);
do{
edad=prompt("ingrese edad");
}while(edad < 18 || edad > 90);
document.getElementById("Edad").value = edad;
var sexo;
sexo = prompt("ingrese su sexo (F o M): ");
while(sexo != "M" && sexo != "F"){
alert("Sexo no valido");
sexo = prompt("ingrese su sexo valido (F o M); ");
}
document.getElementById("Sexo").value = sexo;
// FALTA UNA BANDA COMPLETAR COMPLETAR COMPLETAR COMPLETAR COMPLETAR
}
<file_sep>function mostrar()
{
var rep = 0;
rep = 10;
while(rep > 0){
alert(rep--);
}
}//FIN DE LA FUNCIÓN<file_sep>function mostrar()
{
var impuno;
var impdos;
var imptres;
var impcuatro;
var suma = 0;
suma = parseInt(suma);
impuno = prompt("ingrese primer importe");
impuno = parseInt(impuno);
if(isNaN(impuno)){
impuno = prompt("reingrese numero");
}
impdos = prompt("ingrese segundo importe");
impdos = parseInt(impdos);
if(isNaN(impdos)){
impdos = prompt("reingrese numero");
}
imptres = prompt("ingrese tercer importe");
imptres = parseInt(imptres);
if(isNaN(imptres)){
imptres = prompt("reingrese numero");
}
impcuatro = prompt("ingrese cuarto importe");
impcuatro = parseInt(impcuatro);
if(isNaN(impcuatro)){
impcuatro = prompt("reingrese numero");
}
suma = impuno + impdos + imptres + impcuatro;
var porccien = 0;
porccien = parseInt(porccien);
porccien = suma * 10/100;
var porccin = 0;
porccin = parseInt(porccin);
porccin = suma * 5/100;
var porcquin = 0;
porcquin = parseInt(porcquin);
porcquin = suma * 15/100;
if(impuno >= impdos && impuno >= imptres && impuno >= impcuatro){
alert("el primer importe es el mayor " + impuno);
}else{
if(impdos > imptres && impdos > impcuatro){
alert("el segundo importe es el mayor " + impuno);
}else{
if(imptres > impcuatro){
alert("el tercer importe es el mayor " + imptres);
}else{
alert("el cuarto importe es el mayor " + impcuatro);
}
}
}
/*el prof lo hizo asi
var num1;
var num2;
var num3;
var num4;
var mayor= num1
if(num2>mayor){
mayor=num2;
}
if(num3>mayor){
mayor=num3;
}
if(num4>mayor){
mayor=num4;
}
*/
var porc;
porc = suma - porccien;
var porci;
porci = suma - porccin;
var porq;
porq = suma + porcquin;
if(suma >= 100){
alert("la suma es mayor a 100 el resultado con 10% de dscto. es " + porc);
}else{
if(suma >= 50 && suma < 50){
alert("la suma es mayor a 50 el resultado con 5% de dscto. es " + porci);
}else{
alert("la suma es menor a 50 el resultado con 15% de recargo es " + porq);
}
}
/* var cantidad;
cantidad = prompt("Cantidad de libros comprados");
cantidad = parseInt(cantidad);
var precio;
precio = prompt("Precio total de los libros");
precio = parseInt(precio);
var tarjeta;
tarjeta = confirm("Pagara con tarjeta");
if(cantidad > 2 && precio > 2000){
precio = precio - (precio * 25) / 100;
}else{
if(cantidad > 2 && precio < 2000){
precio = precio - (precio * 10) / 100;
}else{
if(cantidad < 2 && precio > 2000){
precio = precio - (precio * 15) / 100;
}
}
}
if(tarjeta){
precio = precio + (precio * 10) / 100;
alert("Por abonar con tarjeta se le cobrara un recargo del 10% abonando " + precio);
}else{
alert(precio);
}
*/
}
// quedo pendiente arreglar los porcentajes. (el primero esta bien)
<file_sep>function mostrar()
{
var nota;
var sexo;
var contador = 0;
var sumanotas = 0;
var promedio = 0;
var min;
var primera = true;
var aux;
var contadorhombre = 0;
while(contador < 5){
contador++;
nota = prompt("ingrese nota");
nota = parseInt(nota);
if(nota < 0 || nota > 10){
nota = prompt("Reingrese nota entre 0 y 1");
nota = parseInt(nota);
}else{
if(sexo == "M" && nota >= 6){
contadorhombre++;
}
if(primera){
primera = false;
min = nota;
}else{
if(nota < min){
min = nota;
aux = sexo;
}
}
sumanotas = sumanotas + nota;
}
sexo = prompt("ingrese sexo F/M ");
if(sexo != "F" && sexo != "M"){
sexo = prompt("Reingrese sexo valido");
}
}
promedio = Math.round(sumanotas / 5);
alert("El promedio de las notas totales es " + promedio);
alert("La nota mas baja es " + min + " y el sexo de esa persona es " + aux);
alert("La cantidad de varones que su nota fue igual o mayor a 6 es de " + contadorhombre);
}
<file_sep>function mostrar()
{
var numeroUno = prompt("Primer numero");
var numeroDos = prompt("Segundo numero");
if(numeroUno == numeroDos){
alert(numeroUno + numeroDos);
}else{
numeroUno = parseInt(numeroUno);
numeroDos = parseInt(numeroDos);
if(numeroUno > numeroDos){
alert(numeroUno - numeroDos);
}else{
var suma = numeroUno + numeroDos;
alert(suma);
if(suma > 10){
alert("la suma es " + suma + " y supero el 10");
}
}
}
}
<file_sep>function mostrar()
{
//Genero el número RANDOM entre 1 y 10
var nota = Math.round(Math.random()*10);
alert(nota);
if(nota >= 9){
alert("EXCELENTE");
}else{
if(nota >= 4){
alert("APROBO");
}else{
alert("Vamos, la proxima se puede");
}
}
}
//FIN DE LA FUNCIÓN<file_sep>function mostrar()
{
var cantidad = 0;
while(cantidad < 10){
cantidad++;
alert(cantidad);
}
}//FIN DE LA FUNCIÓN<file_sep>function mostrar()
{
for(var numero = 0; numero<=10; numero++){
document.writeln(numero);
}
}<file_sep>function mostrar()
{
var clave = prompt("ingrese el número clave.");
var cont = 0;
while(clave != "utn750"){
cont++;
alert("clave incorrecta");
if(cont < 3){
clave = prompt("Ingrese clave nuevamente");
continue;
}
break;
}
}//FIN DE LA FUNCIÓN
<file_sep>/*3. Para el departamento de Pinturas:
A. Al ingresar una temperatura en Fahrenheit debemos mostrar la temperatura en Centígrados con un mensaje concatenado (ej.: " 32 Fahrenheit son 0 centígrados").
B. Al ingresar una temperatura en Centígrados debemos mostrar la temperatura en Fahrenheit (ej.: "0 centígrados son 32 Fahrenheit ").
*/
var fahr, cent;
function FahrenheitCentigrados ()
{
fahr = parseInt(document.getElementById("Temperatura").value);
cent = Math.floor((fahr - 32) * 5/9);
alert(fahr + " fahrenheit son " + cent + " grados centigrados.");
}
function CentigradosFahrenheit ()
{
cent = parseInt(document.getElementById("Temperatura").value);
fahr = Math.floor((cent * 1.8) + 32);
alert(cent + " grados centigrados son " + fahr + " grados fahrenheit.");
}
<file_sep>function mostrar()
{
for(var numero = 10; numero>=0; numero--){
document.writeln(numero);
}
}<file_sep>function mostrar()
{
var marca;
var peso;
var temp;
var canttemppar = 0;
var primerp = true;
var pesado;
var contador = 0;
var prodpesado;
var contcer = 0;
var aux = 0;
var minimo = 0;
var maximo = 0;
var producto;
while(confirm("Desea ingresar producto?")){
marca = prompt("ingrese la marca");
peso = prompt("ingrese peso");
peso = parseInt(peso);
if(peso>100 || peso<1){
peso = prompt("reingrese peso entre 1 y 100");
peso = parseInt(peso);
}else{
if(primerp){
primerp=false;
pesado = peso;
minimo = peso;
prodpesado = marca;
}else{
if(peso > pesado){
prodpesado = marca;
pesado = peso;
}else{
if(peso < minimo){
minimo = peso;
}
}
}
}
temp = prompt("ingrese temperatura");
if(temp>30 || temp<-30){
temp = prompt("Reingrese temperatura entre 30 y -30");
}else{
if(temp < 0){
contcer++;
}
}
temp = parseInt(temp);
if(temp % 2 == 0){
canttemppar++;
}
aux = aux + peso;
contador++;
}
producto = aux / contador;
producto = Math.round(producto);
document.writeln("A - La cantidad de temperaturas pares son " + canttemppar);
document.writeln(" B - La marca del producto mas pesado es " + prodpesado);
document.writeln(" C - La cantidad de productos que se conservan a menos de 0 grados son " + contcer);
document.writeln(" D - El promedio del peso de todos los productos es " + producto);
document.writeln(" E - El peso maximo es " + pesado + " y el peso minimo es " + minimo);
}
<file_sep>
function mostrar()
{
var mascota1 = prompt("Nombre de mascota 1");
var mascota2 = prompt("Nombre de mascota 2");
var peso1 = parseInt(prompt("Peso de mascota 1"));
var peso2 = parseInt(prompt("Peso de mascota 2"));
alert("tenes dos mascotas " + mascota1 + " y " + mascota2 + " , que pesan " + peso1 + " y " + peso2 + " kilos, la suma de los kilos es " + (peso1 + peso2));
}
<file_sep>function mostrar()
{
var total;
var amigos;
amigos = prompt("Cantidad de amigos");
amigos= parseInt(amigos);
total = prompt("Total a pagar");
total = parseInt(total);
var iva = (total*21)/100;
var propina = ((total + iva)*10)/100;
var final = total + iva + propina;
alert("Cada uno debe pagar " + (final / amigos));
}
<file_sep>function mostrar()
{
var precio = prompt("Precio de la compra");
parseInt(precio);
var descontado = precio - (precio*10)/100;
var resultado = descontado + (descontado*21)/100;
alert("tu compra es de " + precio + " tenes un descuento del 10% queda en " + descontado + " mas el iva es " + resultado);
}
<file_sep>function mostrar()
{
for(repet=1; ; repet++){
alert("hola");
if(repet==9){
break;
}
}
}//FIN DE LA FUNCIÓN<file_sep>function mostrar()
{
var numero;
var letra;
var contadorpar = 0;
var contadorimpar = 0;
var contadorcero = 0;
var positivo = 0;
var contadorpositivo = 0;
var negativo = 0;
var primero = true;
var maximo;
var minimo;
var maxl;
var minl;
while(confirm("desea seguir ingresando?")){
numero = prompt("Ingrese numero");
numero = parseInt(numero);
if(numero < -100 || numero > 100){
numero = prompt("numero invalido, reingrese numero");
}else{
if(numero == 0){
contadorcero++;
}
}
if(numero % 2 == 0){
contadorpar++
}else{
contadorimpar++;
}
letra = prompt("ingrese letra");
if(numero > 0){
positivo = positivo + numero;
contadorpositivo++;
}else{
negativo = negativo + numero;
}
if(primero){
primero = false;
maximo = numero;
minimo = numero;
}else{
if(numero > maximo){
maximo = numero;
maxl = letra;
}else{
if(numero < minimo){
minimo = numero;
minl = letra;
}
}
}
}
document.writeln("1- La cantidad de numeros pares son " + contadorpar);
document.writeln(" 2- La cantidad de numeros impares son " + contadorimpar);
document.writeln(" 3- La cantidad de ceros es " + contadorcero);
document.writeln(" 4- El promedio de los numeros positivos ingresados es " + Math.round((positivo / contadorpositivo)*10)/100);
document.writeln(" 5- La suma de todos los numeros negativos es " + negativo);
document.writeln(" 6- El numero y letra del maximo es " + maximo + maxl + " y del minimo es " + minimo + minl);
}
| 810e4f6704b25b82c22a9b0fd9a0261bbc73a3b4 | [
"JavaScript"
] | 17 | JavaScript | Nico-0906/CursoIngresoJS | bbb515bd03702a0579687b7cb88e82d8d1957567 | 6ed30b084fa08918533e760d9eb8657b986f8389 |
refs/heads/master | <file_sep># !/usr/bin/env python
# _*_ coding:utf-8 _*_
'''
@author: yerik
@contact: <EMAIL>
@time: 2018/9/17 20:27
@desc: config
'''
# 数据库
DB_USER = 'root'
DB_PASSWORD = ''
DB_HOST = 'localhost'
DB_PORT = 3306
DB_NAME = ''
DATABASE_URI = 'mysql+pymysql://' + DB_USER + ':' + DB_PASSWORD + '@' + DB_HOST + ':' + str(
DB_PORT) + '/' + DB_NAME + '?charset=utf8'
# Redis
REDIS_HOST = 'localhost'
REDIS_PORT = 6379
REDIS_PASSWORD = ''
# MongoDB
MONGO_HOST = 'localhost'
MONGO_PORT = 27017
<file_sep># !/usr/bin/env python
# _*_ coding:utf-8 _*_
'''
@author: yerik
@contact: <EMAIL>
@time: 2018/10/19 10:01
@desc:
http://www.cnblogs.com/melonjiang/p/5342383.html
http://www.cnblogs.com/melonjiang/p/5342505.html
'''
import redis
import config
import json
class RedisClient(object):
def __init__(self):
self.r = redis.Redis(host=config.REDIS_HOST, port=config.REDIS_PORT, decode_responses=True)
def keys(self):
result = self.r.keys()
if result is None:
return None
return result
def get(self, key):
result = self.r.get(key)
if result is None:
return None
return json.loads(result)
def set(self, key, val):
if len(val) == 0:
return
self.r.set(key, json.dumps(val))
def rm(self, key):
self.r.delete(key)
# 设置过期时间(秒)
def setex(self, key, val, time=60):
if len(val) == 0:
return
self.r.setex(key, json.dumps(val), time)
# 设置过期时间(毫秒)
def psetex(self, key, val, time=1000):
if len(val) == 0:
return
self.r.psetex(key, time, json.dumps(val))
# 设置新值并返回旧值
def getset(self, key, val):
if len(val) == 0:
return
return self.r.getset(key, json.dumps(val))
# 自增
def incr(self, key, amount=None):
if amount is None:
return self.r.incr(key)
else:
return self.r.incr(key, amount=amount)
# 在key对应的list中添加元素,每个新的元素都添加到列表的最左边
def rpush(self, key, value):
self.r.rpush(key, json.dumps(value))
# 删除列表右侧第一个元素,并返回该值
def lpop(self, key):
return json.loads(self.r.lpop(key))
def lindex(self, key, index=0):
return json.loads(self.r.lindex(key, index))
# 返回列表长度
def llen(self, key):
return self.r.llen(key)
# 分片获取元素
def lrange(self, key, start, end):
return self.r.lrange(key, start, end)
<file_sep># !/usr/bin/env python
# _*_ coding:utf-8 _*_
'''
@author: yerik
@contact: <EMAIL>
@time: 2019/5/31 10:29
@desc:
'''
from base.realestate import RealEstate
from bs4 import BeautifulSoup
class fang(RealEstate):
def describe(self):
return self.deep_extend(super(fang, self).describe(), {
'id': 'fang',
'name': '房天下',
'spelling': False, # True为全拼,False为缩写
"timeout": 20000,
'has': {
'fetchNewHouse': True,
'fetchSecondHandHouse': True,
'fetchRentalLinks': True
},
'urls': {
'new_house_url': 'https://%s.newhouse.fang.com/house/s/',
'second_hand_url': 'https://%s.esf.fang.com/',
'rental_url': 'https://%s.zu.fang.com/'
}
})
def fetch_new_house_home_links(self, url, city):
home_links = []
base_url = 'https://%s.newhouse.fang.com' % city if city != 'bj' else 'https://newhouse.fang.com'
wb_data = self.fetch(url)
soup = BeautifulSoup(wb_data, 'lxml')
page_items = soup.select('li.fr > a')
for i in page_items:
if i.has_attr('class'):
continue
link = base_url + i.get('href')
home_links.append(link)
return home_links
def fetch_new_hourse_links(self, city):
if self.has['fetchNewHouse'] == False:
return None
url = self.urls['new_house_url'] % city if city != 'bj' else 'https://newhouse.fang.com/house/s/'
home_urls = []
while True:
home_urls_ = self.fetch_new_house_home_links(url, city)
if home_urls_[-1] in home_urls:
break
url = home_urls_[-1]
home_urls += home_urls_
home_urls = set(home_urls)
links = []
for i in home_urls:
wb_data = self.fetch(i)
soup = BeautifulSoup(wb_data, 'lxml')
items = soup.select('div.house_value > div.nlcd_name > a')
for i in items:
link = i.get('href')
if link[:2] == '//':
link = 'https:' + link
links.append(link)
return links
def analysis_new_house_page(self, link):
if self.has['fetchNewHouse'] == False:
return None
# TODO
pass
def fetch_rental_links(self, city):
if self.has['fetchRentalLinks'] == False:
return None
url = self.urls['rental_url'] % city if city != 'bj' else 'https://zu.fang.com/'
wb_data = self.fetch(url)
soup = BeautifulSoup(wb_data, 'lxml')
items = soup.select('p.title > a')
links = []
base_url = 'https://%s.zu.fang.com' % city if city != 'bj' else 'https://zu.fang.com/'
for i in items:
link = i.get('href')
links.append(base_url + link)
return links
def analysis_rental_page(self, link):
if self.has['fetchRentalLinks'] == False:
return None
try:
wb_data = self.fetch(link)
soup = BeautifulSoup(wb_data, 'html.parser')
title_tag = soup.select('h1.title')
title = self.format_tag(title_tag[0])
price_tag = soup.select('div.trl-item')
price_strs = self.format_tag(price_tag[0]).split('(')
price = price_strs[0]
deposit_way = price_strs[0][:-1]
base_info_tags = soup.select('div.trl-item1 > div')
lease_way = None
house_type = None
toward = None
address = None
area = None
floor = None
desc = None
return {
'title': title,
'price': price, # 月租
'deposit_way': deposit_way, # 押金方式:押二付一
'lease_way': lease_way, # 租借方式:整租/合租
'house_type': house_type, # 房屋类型
'toward': toward, # 朝向
'address': address, # 地址
'area': area,
'floor': floor,
'build_time': None,
'desc': desc, # 描述
'link': link
}
except Exception as e:
print('数据抓取失败:%s, url:%s' % (str(e), link))
def fetch_second_hand_links(self, city):
if self.has['fetchSecondHandHouse'] == False:
return None
pass
def analysis_second_hand_page(self, link):
if self.has['fetchSecondHandHouse'] == False:
return None
pass
<file_sep># !/usr/bin/env python
# _*_ coding:utf-8 _*_
'''
@author: yerik
@contact: <EMAIL>
@time: 2019/5/23 19:40
@desc:
'''
__all__ = [
'BaseError',
'NetworkError',
'DDoSProtection',
'RequestTimeout',
'RequestError'
]
# -----------------------------------------------------------------------------
class BaseError(Exception):
"""Base class for all exceptions"""
pass
class NetworkError(BaseError):
"""Base class for all errors related to networking"""
pass
class DDoSProtection(NetworkError):
"""Raised whenever DDoS protection restrictions are enforced per user or region/location"""
pass
class RequestTimeout(NetworkError):
"""Raised when the exchange fails to reply in .timeout time"""
pass
class RequestError(NetworkError):
pass
<file_sep># !/usr/bin/env python
# _*_ coding:utf-8 _*_
'''
@author: yerik
@contact: <EMAIL>
@time: 2019/5/23 20:15
@desc:
'''
from base.realestate import RealEstate
from base import errors
from base.errors import BaseError
from base.errors import NetworkError
from base.errors import DDoSProtection
from base.errors import RequestError
from base.errors import RequestTimeout
from crawlers.tongcheng58 import tongcheng58
from crawlers.anjuke import anjuke
from crawlers.leyoujia import leyoujia
from crawlers.fang import fang
realEstate = [
'tongcheng58',
'anjuke',
'leyoujia',
]
base = [
'RealEstate',
'realEstate'
]
__all__ = base + errors.__all__ + realEstate
<file_sep># !/usr/bin/env python
# _*_ coding:utf-8 _*_
'''
@author: yerik
@contact: <EMAIL>
@time: 2019/5/23 19:20
@desc:
'''
from base.errors import NetworkError, DDoSProtection, RequestTimeout, RequestError
from requests import Session
from requests.utils import default_user_agent
from requests.exceptions import HTTPError, Timeout, TooManyRedirects, RequestException
import logging
from ssl import SSLError
import re
import json
import time
__all__ = [
'RealEstate',
]
class RealEstate(object):
id = None
session = None # Session () by default
cookie = None
logger = None # logging.getLogger(__name__) by default
userAgent = None
enableRateLimit = False
rateLimit = 2000 # milliseconds = seconds * 1000
timeout = 10000 # milliseconds = seconds * 1000
userAgent = None
userAgents = {
'chrome': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36',
'chrome39': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36',
}
headers = None
proxy = ''
origin = '*'
proxies = None
verbose = False
minFundingAddressLength = 10 # used in check_address
substituteCommonCurrencyCodes = True
lastRestRequestTimestamp = 0
lastRestPollTimestamp = 0
restRequestQueue = None
restPollerLoopIsRunning = False
rateLimitTokens = 16
rateLimitMaxTokens = 16
rateLimitUpdateTime = 0
last_http_response = None
last_json_response = None
last_response_headers = None
parseJsonResponse = False
def __init__(self, config={}):
self.userAgent = default_user_agent()
self.session = self.session if self.session else Session()
self.logger = self.logger if self.logger else logging.getLogger(__name__)
self.headers = {} if self.headers is None else self.headers
settings = self.deep_extend(self.describe(), config)
for key in settings:
if hasattr(self, key) and isinstance(getattr(self, key), dict):
setattr(self, key, self.deep_extend(getattr(self, key), settings[key]))
else:
setattr(self, key, settings[key])
def __del__(self):
if self.session:
self.session.close()
def handle_errors(self, code, reason, url, method, headers, body):
pass
def prepare_request_headers(self, headers=None):
headers = headers or {}
headers.update(self.headers)
if self.userAgent:
headers.update({'User-Agent': self.userAgents['chrome39']})
if self.proxy:
headers.update({'Origin': self.origin})
headers.update({'Accept-Encoding': 'gzip, deflate'})
return headers
def raise_error(self, exception_type, url=None, method=None, error=None, details=None):
if error:
error = str(error)
output = ' '.join([self.id] + [var for var in (url, method, error, details) if var is not None])
raise exception_type(output)
def fetch(self, url, method='GET', headers=None, body=None):
if self.enableRateLimit:
self.throttle()
"""Perform a HTTP request and return decoded JSON data"""
request_headers = self.prepare_request_headers(headers)
url = self.proxy + url
if self.verbose:
print("\nRequest:", method, url, request_headers, body)
self.logger.debug("%s %s, Request: %s %s", method, url, request_headers, body)
if body:
body = body.encode()
self.session.cookies.clear()
response = None
try:
response = self.session.request(
method,
url,
data=body,
headers=request_headers,
timeout=int(self.timeout / 1000),
proxies=self.proxies
)
self.last_http_response = response.text
self.last_response_headers = response.headers
if self.verbose:
print("\nResponse:", method, url, str(response.status_code), str(response.headers),
self.last_http_response)
self.logger.debug("%s %s, Response: %s %s %s", method, url, response.status_code, response.headers,
self.last_http_response)
response.raise_for_status()
except Timeout as e:
self.raise_error(RequestTimeout, method, url, e)
except TooManyRedirects as e:
self.raise_error(RequestError, url, method, e)
except SSLError as e:
self.raise_error(RequestError, url, method, e)
except HTTPError as e:
self.handle_errors(response.status_code, response.reason, url, method, self.last_response_headers,
self.last_http_response)
self.handle_rest_errors(e, response.status_code, self.last_http_response, url, method)
self.raise_error(RequestError, url, method, e, self.last_http_response)
except RequestException as e: # base exception class
self.raise_error(RequestError, url, method, e, self.last_http_response)
self.handle_errors(response.status_code, response.reason, url, method, None, self.last_http_response)
return self.handle_rest_response(self.last_http_response, url, method, headers, body)
def handle_rest_errors(self, exception, http_status_code, response, url, method='GET'):
error = None
if http_status_code in [418, 429]:
error = DDoSProtection
elif http_status_code in [404, 409, 500, 501, 502, 520, 521, 522, 525]:
error = RequestError
elif http_status_code in [422]:
error = RequestError
elif http_status_code in [400, 403, 405, 503, 530]:
# special case to detect ddos protection
error = RequestError
if response:
ddos_protection = re.search('(cloudflare|incapsula)', response, flags=re.IGNORECASE)
if ddos_protection:
error = DDoSProtection
elif http_status_code in [408, 504]:
error = RequestTimeout
elif http_status_code in [401, 511]:
error = RequestError
if error:
self.raise_error(error, url, method, exception if exception else http_status_code, response)
def handle_rest_response(self, response, url, method='GET', headers=None, body=None):
try:
if self.parseJsonResponse:
self.last_json_response = json.loads(response) if len(response) > 1 else None
return self.last_json_response
else:
return response
except ValueError as e: # ValueError == JsonDecodeError
ddos_protection = re.search('(cloudflare|incapsula|overload|ddos)', response, flags=re.IGNORECASE)
exchange_not_available = re.search(
'(offline|busy|retry|wait|unavailable|maintain|maintenance|maintenancing)', response,
flags=re.IGNORECASE)
if ddos_protection:
self.raise_error(DDoSProtection, method, url, None, response)
if exchange_not_available:
message = response + ' exchange downtime, exchange closed for maintenance or offline, DDoS protection or rate-limiting in effect'
self.raise_error(RequestError, method, url, None, message)
self.raise_error(RequestError, method, url, e, response)
def throttle(self):
now = float(self.milliseconds())
elapsed = now - self.lastRestRequestTimestamp
if elapsed < self.rateLimit:
delay = self.rateLimit - elapsed
time.sleep(delay / 1000.0)
@staticmethod
def seconds():
return int(time.time())
@staticmethod
def milliseconds():
return int(time.time() * 1000)
@staticmethod
def microseconds():
return int(time.time() * 1000000)
@staticmethod
def format_tag(tag):
return tag.text.strip().replace('\n', '').replace(' ', '')
@staticmethod
def deep_extend(*args):
result = None
for arg in args:
if isinstance(arg, dict):
if not isinstance(result, dict):
result = {}
for key in arg:
result[key] = RealEstate.deep_extend(result[key] if key in result else None, arg[key])
else:
result = arg
return result
def describe(self):
return {}
<file_sep>#!/usr/bin/env python
# _*_ coding:utf-8 _*_
'''
@author: yerik
@contact: <EMAIL>
@time: 2019/5/31 10:30
@desc:
'''
from base.realestate import RealEstate
from bs4 import BeautifulSoup
class lianjia(RealEstate):
def describe(self):
return self.deep_extend(super(lianjia, self).describe(), {
'id': 'lianjia',
'name': '链家',
'spelling': False, # True为全拼,False为缩写
'has': {
'fetchNewHouse': False,
'fetchSecondHandHouse': True,
'fetchRentalLinks': True
},
'urls': {
'new_house_url': '',
'second_hand_url': '',
'rental_url': ''
}
})
def fetch_new_hourse_links(self, city):
if self.has['fetchNewHouse'] == False:
return None
url = self.urls['new_house_url'] % city
def analysis_new_house_page(self, link):
if self.has['fetchNewHouse'] == False:
return None
pass
def fetch_rental_links(self, city):
if self.has['fetchRentalLinks'] == False:
return None
pass
def analysis_rental_page(self, link):
if self.has['fetchRentalLinks'] == False:
return None
pass
def fetch_second_hand_links(self, city):
if self.has['fetchSecondHandHouse'] == False:
return None
pass
def analysis_second_hand_page(self, link):
if self.has['fetchSecondHandHouse'] == False:
return None
pass
<file_sep># realty-crawler
房地产网站爬虫
中国房地产网站:
1. 58:https://sz.58.com/
2. 安居客:https://guangzhou.anjuke.com/
3. 搜房网:http://www.sofang.com/
4. 房天下:https://www.fang.com/
5. 链家网:https://sz.lianjia.com/
6. 我爱我家:https://bj.5i5j.com/
7. 麦田房产:http://bj.maitian.cn/Index.html
8. Q房网:https://www.qfang.com/index.html
9. 中原地产:https://sz.centanet.com/
10. 贝壳找房:https://sz.ke.com/
11. 居理新房:https://www.julive.com/
12. 乐有家:https://shenzhen.leyoujia.com/<file_sep># !/usr/bin/env python
# _*_ coding:utf-8 _*_
'''
@author: yerik
@contact: <EMAIL>
@time: 2019/5/31 10:35
@desc:
'''
from base.realestate import RealEstate
from bs4 import BeautifulSoup
from bs4.element import Tag
class leyoujia(RealEstate):
def describe(self):
return self.deep_extend(super(leyoujia, self).describe(), {
'id': 'leyoujia',
'name': '乐有家',
'spelling': True, # True为全拼,False为缩写
'has': {
'fetchNewHouse': True,
'fetchSecondHandHouse': True,
'fetchRentalLinks': True
},
'urls': {
'new_house_url': 'https://%s.leyoujia.com/ysl/',
'second_hand_url': 'https://%s.leyoujia.com/esf/',
'rental_url': 'https://%s.leyoujia.com/zf/'
}
})
def base_fetch_links(self, url, base_url):
wb_data = self.fetch(url)
soup = BeautifulSoup(wb_data, 'lxml')
items = soup.select('p.tit > a')
links = []
for i in items:
link = i.get('href')
links.append(base_url + link)
return links
def fetch_new_hourse_links(self, city):
if self.has['fetchNewHouse'] == False:
return None
url = self.urls['new_house_url'] % city
base_url = 'https://%s.leyoujia.com' % city
return self.base_fetch_links(url, base_url)
def analysis_new_house_page(self, link):
if self.has['fetchNewHouse'] == False:
return None
try:
wb_data = self.fetch(link)
soup = BeautifulSoup(wb_data, 'lxml')
title_items = soup.select('div.title > h1')
title = self.format_tag(title_items[0])
tags_items = soup.select('div.labs > span')
tags_str = ''
for i in tags_items:
tags_str += self.format_tag(i) + '|'
price_items = soup.select('div.price-box > p')
price_items = price_items[0].contents
price = self.format_tag(price_items[3]) + ' ' + self.format_tag(price_items[4])
intro_list = soup.select('div.intro-list > p > span')
open_time = self.format_tag(intro_list[1])
completion_time = self.format_tag(intro_list[3])
door_model_items = intro_list[9].contents
door_model = ''
for i in door_model_items:
if type(i) == Tag:
door_model += self.format_tag(i) + '|'
door_model = door_model.replace('||', '')
address = self.format_tag(intro_list[5])
detail_item = soup.select('p.less')
detail = self.format_tag(detail_item[0])
detail = detail.replace('\r', '').replace('\t', '').replace('阅读全文', '')
return {
'title': title,
'tags': tags_str, # 标签
'price': price, # 单位价格
'open_time': open_time, # 开盘时间
'completion_time': completion_time, # 交房时间
'door_model': door_model, # 户型
'address': address, # 地址
'detail': detail, # 简介
'link': link
}
except Exception as e:
print('数据抓取失败:%s, url:%s' % (str(e), link))
def fetch_rental_links(self, city):
if self.has['fetchRentalLinks'] == False:
return None
url = self.urls['rental_url'] % city
base_url = 'https://%s.leyoujia.com' % city
return self.base_fetch_links(url, base_url)
def analysis_rental_page(self, link):
if self.has['fetchRentalLinks'] == False:
return None
try:
wb_data = self.fetch(link)
soup = BeautifulSoup(wb_data, 'lxml')
title_tag = soup.select('h1.tit-conno')
title = self.format_tag(title_tag[0])
intro_box1 = soup.select('div.intro-box1 > p')
price = self.format_tag(intro_box1[0])
rental_info = self.format_tag(intro_box1[1])
deposit_way = rental_info.split('|')[0]
lease_way = rental_info.split('|')[1]
intro_box2 = soup.select('div.intro-box2 > span')
house_type = self.format_tag(intro_box2[0])
intro_box3 = soup.select('div.intro-box3 > p > span')
address = self.format_tag(intro_box3[3]) + '-' + self.format_tag(intro_box3[1])
address = address.replace('\r', '').replace('\t', '')
cont_items = soup.select('div.cont > span')
area = self.format_tag(cont_items[0])
area = area.replace('建筑面积', '')
floor = self.format_tag(cont_items[2])
floor = floor.replace('所在楼层', '')
toward = self.format_tag(cont_items[3])
toward = toward.replace('房屋朝向', '')
build_time = self.format_tag(cont_items[4])
build_time = build_time.replace('建筑年代', '')
desc_items = soup.select('div.fy-box > div.cont > p')
desc = ''
for i in desc_items:
desc += self.format_tag(i)
return {
'title': title,
'price': price, # 月租
'deposit_way': deposit_way, # 押金方式:押二付一
'lease_way': lease_way, # 租借方式:整租/合租
'house_type': house_type, # 房屋类型
'toward': toward, # 朝向
'address': address, # 地址
'area': area,
'floor': floor,
'build_time': build_time,
'desc': desc, # 描述
'link': link
}
except Exception as e:
print('数据抓取失败:%s, url:%s' % (str(e), link))
def fetch_second_hand_links(self, city):
if self.has['fetchSecondHandHouse'] == False:
return None
url = self.urls['second_hand_url'] % city
base_url = 'https://%s.leyoujia.com' % city
return self.base_fetch_links(url, base_url)
def analysis_second_hand_page(self, link):
if self.has['fetchSecondHandHouse'] == False:
return None
try:
wb_data = self.fetch(link)
soup = BeautifulSoup(wb_data, 'lxml')
title_tag = soup.select('h1.tit-conno')
title = self.format_tag(title_tag[0])
base_span_items = soup.select('div.intro > div > span')
total_price = self.format_tag(base_span_items[0])
toward = self.format_tag(base_span_items[3])
area = self.format_tag(base_span_items[2])
door_model = self.format_tag(base_span_items[1])
floor = self.format_tag(base_span_items[4])
build_time = self.format_tag(base_span_items[6])
base_p_items = soup.select('div.intro-box3 > p > span')
community = self.format_tag(base_p_items[3])
community = community.replace('\r', '').replace('\t', '')
address = self.format_tag(base_p_items[5])
address = address.replace('\r', '').replace('\t', '')
price_per_item = soup.select('div.intro-box1 > div')
price_per = self.format_tag(price_per_item[0])
price_per = price_per.replace('单价', '')
cont_items = soup.select('p.mb10 > span')
house_type = self.format_tag(cont_items[6])
house_type = house_type.replace('用途', '')
equity_year = self.format_tag(cont_items[10])
equity_year = equity_year.replace('产权年限', '')
equity_type = self.format_tag(cont_items[8])
equity_type = equity_type.replace('产权性质', '')
fitment = self.format_tag(cont_items[12])
fitment = fitment.replace('装修', '')
return {
'title': title, # 标题
'total_price': total_price, # 总价
'price_per': price_per, # 房屋单价
'community': community, # 所属小区
'door_model': door_model, # 户型
'address': address, # 地址
'area': area, # 建筑面积
'build_time': build_time, # 建造年代
'toward': toward, # 朝向
'house_type': house_type, # 房屋类型
'floor': floor, # 所在楼层
'fitment': fitment, # 装修程度
'equity_year': equity_year, # 产权年限
'equity_type': equity_type, # 产权性质
'link': link # 链接地址
}
except Exception as e:
print('数据抓取失败:%s, url:%s' % (str(e), link))
<file_sep>#!/usr/bin/env python
# _*_ coding:utf-8 _*_
'''
@author: yerik
@contact: <EMAIL>
@time: 2019/5/10 21:18
@desc: https://cloud.tencent.com/developer/article/1151814
'''
import config
import pymongo
from bson.objectid import ObjectId
class MongoClient(object):
def __init__(self, db, collection):
self.client = pymongo.MongoClient(host=config.MONGO_HOST, port=config.MONGO_PORT)
self.db = self.client[db]
self.collection = self.db[collection]
def insert_one(self, obj):
result = self.collection.insert_one(obj)
return result
def insert_many(self, lists):
results = self.collection.insert_many(lists)
return results
def find_one(self, condition, id=None):
result = self.collection.find_one({'_id':ObjectId(id)}) if id else self.collection.find_one(condition)
return result
def find(self, conditions):
results = self.collection.find(conditions)
return results
def update(self, condition, new_obj):
result = self.collection.update(condition, new_obj)
return result
def remove(self, condition):
result = self.collection.remove(condition)
return result
<file_sep># !/usr/bin/env python
# _*_ coding:utf-8 _*_
'''
@author: yerik
@contact: <EMAIL>
@time: 2019/5/22 19:24
@desc:
'''
from base.realestate import RealEstate
from bs4 import BeautifulSoup
from fontTools.ttLib import TTFont
from io import BytesIO
import base64
import re
class tongcheng58(RealEstate):
def describe(self):
return self.deep_extend(super(tongcheng58, self).describe(), {
'id': 'tongcheng58',
'name': '58同城',
'spelling': False, # True为全拼,False为缩写
'has': {
'fetchNewHouse': False,
'fetchSecondHandHouse': True,
'fetchRentalLinks': True
},
'urls': {
'new_house_url': '',
'second_hand_url': 'https://%s.58.com/ershoufang/',
'rental_url': 'https://%s.58.com/chuzu/'
}
})
# 新房信息
def fetch_new_hourse_links(self, city):
if self.has['fetchNewHouse'] == False:
return None
# 安居客
pass
def analysis_new_house_page(self, link):
if self.has['fetchNewHouse'] == False:
return None
pass
# 租房信息
def fetch_rental_links(self, city):
if self.has['fetchRentalLinks'] == False:
return None
url = self.urls['rental_url'] % city
wb_datas = self.fetch(url)
soup = BeautifulSoup(wb_datas, 'lxml')
items = soup.select('ul.house-list > li > div.des > h2 > a')
links = []
for i in items:
link = i.get('href')
if 'e.58.com' in link:
continue
if link[:2] == '//':
link = 'https:' + link
links.append(link)
return links
def analysis_rental_page(self, link):
if self.has['fetchRentalLinks'] == False:
return None
try:
wb_data = self.fetch(link)
bs64_str = re.findall("charset=utf-8;base64,(.*?)'\)", wb_data)[0]
soup = BeautifulSoup(wb_data, 'lxml')
title = soup.select('div.house-title > h1')[0].text.strip()
title = self.show_real_numb(title, bs64_str)
pay_way = soup.select('div.house-pay-way > span')
price = pay_way[0].text.strip()
price = self.show_real_numb(price, bs64_str)
deposit_way = pay_way[1].text.strip()
base_desc = soup.select('ul.f14 > li > span')
lease_way = self.format_tag(base_desc[1])
house_type = self.format_tag(base_desc[3])
house_type = house_type.replace('\xa0\xa0', ' ')
house_type = self.show_real_numb(house_type, bs64_str)
toward = self.format_tag(base_desc[5])
toward = toward.replace('\xa0\xa0', ' ')
toward = self.show_real_numb(toward, bs64_str)
address1 = self.format_tag(base_desc[7])
area = self.format_tag(base_desc[9])
address2 = self.format_tag(base_desc[11])
address = area + '_' + address2 + '_' + address1
address = address.replace('\xa0\xa0', ' ')
district_list_items = soup.select('ul.district-info-list > li > span')
build_time = self.format_tag(district_list_items[1])
floor = self.format_tag(district_list_items[2])
introduce_item = soup.select('ul.introduce-item > li')
desc = self.format_tag(introduce_item[1])
return {
'title': title,
'price': price, # 月租
'deposit_way': deposit_way, # 押金方式:押二付一
'lease_way': lease_way, # 租借方式:整租/合租
'house_type': house_type.split(' ')[0], # 房屋类型
'toward': toward, # 朝向
'address': address, # 地址
'area': house_type.split(' ')[1],
'floor': floor,
'build_time': build_time,
'desc': desc, # 描述
'link': link
}
except Exception as e:
print('数据抓取失败:%s, url:%s' % (str(e), link))
# 二手房信息
def fetch_second_hand_links(self, city):
if self.has['fetchSecondHandHouse'] == False:
return None
url = self.urls['second_hand_url'] % city
wb_datas = self.fetch(url)
soup = BeautifulSoup(wb_datas, 'lxml')
items = soup.select('h2.title > a')
links = []
for i in items:
link = i.get('href')
if link[:2] == '//':
link = 'https:' + link
links.append(link)
return links
def analysis_second_hand_page(self, link):
if self.has['fetchSecondHandHouse'] == False:
return None
try:
wb_data = self.fetch(link)
bs64_str = re.findall("charset=utf-8;base64,(.*?)'\)", wb_data)[0]
soup = BeautifulSoup(wb_data, 'lxml')
title = self.format_tag(soup.select('div.house-title > h1')[0])
basic_item1 = soup.select('p.house-basic-item1 > span')
total_price = self.show_real_numb(basic_item1[0].text.strip(), bs64_str)
price_per = self.show_real_numb(basic_item1[1].text.strip(), bs64_str)
price_per = price_per.replace('\xa0', ' ')
basic_item2 = soup.select('div.house-basic-item2 > p > span')
door_model = self.format_tag(basic_item2[0])
floor = self.format_tag(basic_item2[1])
area = self.format_tag(basic_item2[2])
fitment = self.format_tag(basic_item2[3])
toward = self.format_tag(basic_item2[4])
build_time = self.format_tag(basic_item2[5])
basic_item3 = soup.select('ul.house-basic-item3 > li > span')
community = self.format_tag(basic_item3[1])
address = self.format_tag(basic_item3[3])
general_item = soup.select('ul.general-item-right > li > span')
equity_year = self.format_tag(general_item[5])
return {
'title': title, # 标题
'total_price': total_price, # 总价
'price_per': price_per, # 房屋单价
'community': community, # 所属小区
'door_model': door_model, # 户型
'address': address, # 地址
'area': area, # 建筑面积
'build_time': build_time, # 建造年代
'toward': toward, # 朝向
'house_type': '普通住宅', # 房屋类型
'floor': floor, # 所在楼层
'fitment': fitment, # 装修程度
'equity_year': equity_year, # 产权年限
'equity_type': '商品房', # 产权性质
'link': link # 链接地址
}
except Exception as e:
print('数据抓取失败:%s' % str(e))
def show_real_numb(self, string, bs64_str):
font = TTFont(BytesIO(base64.decodebytes(bs64_str.encode())))
c = font['cmap'].tables[0].ttFont.tables['cmap'].tables[0].cmap
ret_list = []
for char in string:
decode_num = ord(char)
if decode_num in c:
num = c[decode_num]
num = int(num[-2:]) - 1
ret_list.append(num)
else:
ret_list.append(char)
ret_str_show = ''
for num in ret_list:
ret_str_show += str(num)
return ret_str_show<file_sep># !/usr/bin/env python
# _*_ coding:utf-8 _*_
'''
@author: yerik
@contact: <EMAIL>
@time: 2019/5/23 19:08
@desc:
'''
from base.realestate import RealEstate
from bs4 import BeautifulSoup
class anjuke(RealEstate):
def describe(self):
return self.deep_extend(super(anjuke, self).describe(), {
'id': 'anjuke',
'name': '安居客',
'spelling': False, # True为全拼,False为缩写
'has': {
'fetchNewHouse': True,
'fetchSecondHandHouse': True,
'fetchRentalLinks': True
},
'urls': {
'new_house_url': 'https://%s.fang.anjuke.com/',
'second_hand_url': 'https://%s.anjuke.com/sale/',
'rental_url': 'https://%s.zu.anjuke.com/'
}
})
# 新房信息
def fetch_new_hourse_links(self, city):
if self.has['fetchNewHouse'] == False:
return None
url = self.urls['new_house_url'] % city
wb_data = self.fetch(url)
soup = BeautifulSoup(wb_data, 'lxml')
items = soup.select('div.key-list > div.item-mod')
links = []
for i in items:
link = i.get('data-link')
links.append(link)
return links
def analysis_new_house_page(self, link):
if self.has['fetchNewHouse'] == False:
return None
try:
wb_data = self.fetch(link)
soup = BeautifulSoup(wb_data, 'lxml')
title = self.format_tag(soup.select('div.basic-info > h1')[0])
base_params = soup.select('dl.basic-parms > dd')
item0_lst = list(base_params[0].descendants)
item1_lst = list(base_params[1].descendants)
item2_lst = list(base_params[2].descendants)
item3_lst = list(base_params[3].descendants)
item4_lst = list(base_params[4].descendants)
tags = soup.select('div.tags > a')
tags_str = ''
for i in tags:
tags_str += self.format_tag(i) + '|'
price = item0_lst[4] + ' ' + item0_lst[6]
open_time = item1_lst[1]
completion_time = item2_lst[2]
door_model = item3_lst[4]
address = item4_lst[2]
detail = soup.select('div.louping-detail')[0].text.strip().replace('\n', '').replace(' ', '')
return {
'title': title,
'tags': tags_str, # 标签
'price': price, # 单位价格
'open_time': open_time, # 开盘时间
'completion_time': completion_time, # 交房时间
'door_model': door_model, # 户型
'address': address, # 地址
'detail': detail, # 简介
'link': link
}
except Exception as e:
print('数据抓取失败:%s, url:%s' % (str(e), link))
# 二手房信息
def fetch_second_hand_links(self, city):
if self.has['fetchSecondHandHouse'] == False:
return None
url = self.urls['second_hand_url'] % city
wb_data = self.fetch(url)
soup = BeautifulSoup(wb_data, 'lxml')
items = soup.select('div.house-title > a')
links = []
for i in items:
link = i.get('href')
links.append(link)
return links
def analysis_second_hand_page(self, link):
if self.has['fetchSecondHandHouse'] == False:
return None
try:
wb_data = self.fetch(link)
soup = BeautifulSoup(wb_data, 'lxml')
title = soup.select('h3.long-title')[0].text.strip().replace('\n', '').replace(' ', '')
base_infos = soup.select('div.houseInfo-wrap > ul > li > div.houseInfo-content')
community = self.format_tag(base_infos[0])
door_model = self.format_tag(base_infos[1])
door_model = door_model.replace('\t', '')
price_per = self.format_tag(base_infos[2])
address = self.format_tag(base_infos[3])
address = address.replace('\ue003', '')
area = self.format_tag(base_infos[4])
build_time = self.format_tag(base_infos[6])
toward = self.format_tag(base_infos[7])
house_type = self.format_tag(base_infos[9])
floor = self.format_tag(base_infos[10])
fitment = self.format_tag(base_infos[11])
equity_year = self.format_tag(base_infos[12])
equity_type = self.format_tag(base_infos[15])
simple_infos = soup.select('div.basic-info > span')
total_price = self.format_tag(simple_infos[0])
return {
'title': title, # 标题
'total_price': total_price, # 总价
'price_per': price_per, # 房屋单价
'community': community, # 所属小区
'door_model': door_model, # 户型
'address': address, # 地址
'area': area, # 建筑面积
'build_time': build_time, # 建造年代
'toward': toward, # 朝向
'house_type': house_type, # 房屋类型
'floor': floor, # 所在楼层
'fitment': fitment, # 装修程度
'equity_year': equity_year, # 产权年限
'equity_type': equity_type, # 产权性质
'link': link # 链接地址
}
except Exception as e:
print('数据抓取失败:%s, url:%s' % (str(e), link))
# 租房信息
def fetch_rental_links(self, city):
if self.has['fetchRentalLinks'] == False:
return None
url = self.urls['rental_url'] % city
wb_data = self.fetch(url)
soup = BeautifulSoup(wb_data, 'lxml')
items = soup.select('div.zu-itemmod')
links = []
for i in items:
link = i.get('link')
links.append(link)
return links
def analysis_rental_page(self, link):
if self.has['fetchRentalLinks'] == False:
return None
try:
wb_data = self.fetch(link)
soup = BeautifulSoup(wb_data, 'lxml')
title = soup.select('h3.house-title')
title = self.format_tag(title[0])
simple_infos = soup.select('ul.title-label > li')
lease_way = self.format_tag(simple_infos[0])
toward = self.format_tag(simple_infos[1])
basic_infos = soup.select('ul.house-info-zufang > li')
item0_lst = basic_infos[0].contents
item2_lst = basic_infos[2].contents
item4_lst = basic_infos[4].contents
item6_lst = basic_infos[6].contents
price = self.format_tag(item0_lst[1])
deposit_way = self.format_tag(item0_lst[3])
house_type = self.format_tag(item6_lst[3])
address = self.format_tag(basic_infos[7])
address = address.split(':')[1].replace('\xa0', '')
floor = self.format_tag(item4_lst[3])
area = self.format_tag(item2_lst[3])
desc = self.format_tag(soup.select('div.auto-general')[0])
return {
'title': title,
'price': price, # 月租
'deposit_way': deposit_way, # 押金方式:押二付一
'lease_way': lease_way, # 租借方式:整租/合租
'house_type': house_type, # 房屋类型
'toward': toward, # 朝向
'address': address, # 地址
'area': area,
'floor': floor,
'build_time': None,
'desc': desc, # 描述
'link': link
}
except Exception as e:
print('数据抓取失败:%s, url:%s' % (str(e), link))
<file_sep># !/usr/bin/env python
# _*_ coding:utf-8 _*_
'''
@author: yerik
@contact: <EMAIL>
@time: 2019/5/23 19:19
@desc:
'''
from base import errors
from base import realestate
from base.errors import BaseError
from base.errors import NetworkError
from base.errors import DDoSProtection
from base.errors import RequestError
from base.errors import RequestTimeout
__all__ = realestate.__all__ + errors.__all__
<file_sep>#!/usr/bin/env python
# _*_ coding:utf-8 _*_
'''
@author: yerik
@contact: <EMAIL>
@time: 2019/5/31 10:32
@desc:
'''
from base.realestate import RealEstate
from bs4 import BeautifulSoup
class qfang(RealEstate):
def describe(self):
return self.deep_extend(super(qfang, self).describe(), {
'id': 'qfang',
'name': 'Q房网',
'spelling': True, # True为全拼,False为缩写
'has': {
'fetchNewHouse': True,
'fetchSecondHandHouse': True,
'fetchRentalLinks': True
},
'urls': {
'new_house_url': 'https://%s.qfang.com/newhouse/list',
'second_hand_url': 'https://%s.qfang.com/sale',
'rental_url': 'https://%s.qfang.com/rent'
}
})
def fetch_new_hourse_links(self, city):
if self.has['fetchNewHouse'] == False:
return None
url = self.urls['new_house_url'] % city
wb_data = self.fetch(url)
soup = BeautifulSoup(wb_data, 'lxml')
items = soup.select('div.house-title > a')
links = []
for i in items:
link = i.get('href')
links.append(link)
return links
def analysis_new_house_page(self, link):
if self.has['fetchNewHouse'] == False:
return None
try:
wb_data = self.fetch(link)
soup = BeautifulSoup(wb_data, 'lxml')
title = self.format_tag(soup.select('div.left-con > h2')[0])
tag_items = soup.select('div.left-con > div > div')
tags = []
for item in tag_items:
tags.append(self.format_tag(item))
basic_info_items = soup.select('div.basic-info > ul > li.clearfix > p')
price = self.format_tag(basic_info_items[4])
open_time = self.format_tag(basic_info_items[12])
completion_time = self.format_tag(basic_info_items[14])
# TODO
door_model = None
address = self.format_tag(basic_info_items[-2])
detail = None
return {
'title': title,
'tags': ','.join(tags), # 标签
'price': price, # 单位价格
'open_time': open_time, # 开盘时间
'completion_time': completion_time, # 交房时间
'door_model': door_model, # 户型
'address': address, # 地址
'detail': detail, # 简介
'link': link
}
except Exception as e:
print('数据抓取失败:%s, url:%s' % (str(e), link))
def fetch_rental_links(self, city):
if self.has['fetchSecondHandHouse'] == False:
return None
url = self.urls['second_hand_url'] % city
wb_data = self.fetch(url)
soup = BeautifulSoup(wb_data, 'lxml')
items = soup.select('p.house-title > a')
links = []
for i in items:
link = i.get('href')
links.append(link)
return links
def analysis_rental_page(self, link):
pass
def fetch_second_hand_links(self, city):
pass
def analysis_second_hand_page(self, link):
pass
f = qfang()
print(f.fetch_rental_links('shenzhen')) | 32cb5caba2a82d41534e3dc746b5e5391e0f989e | [
"Markdown",
"Python"
] | 14 | Python | xiangzz159/realty-crawler | d52391f4fa7439dd385d1f621965a84fb99a1726 | ce6288d5f4a3609a73fc8e0d4b84838803275ba0 |
refs/heads/master | <repo_name>kajong0007/freecell<file_sep>/README.md
freecell
========
The card game FreeCell<file_sep>/Makefile
CC = clang
all:
$(CC) src/cards.c -o bin/cards
<file_sep>/src/cards.c
#include <stdio.h>
#include <string.h>
#define ACE 1
#define JACK 11
#define QUEEN 12
#define KING 13
/* This is the new deck order of a Bicycle Deck.
* I am taking liberties with the card order in these suits.
* In a new deck, it's in the order below (when face up),
* ACE through KING for the first two, but KING through
* ACE for the last two (with the "kissing kings" in the center).
* I have coded this to have the deck ACE through KING all the way through.
*/
#define SPADES 0
#define DIAMONDS 1
#define CLUBS 2
#define HEARTS 3
struct CARD {
unsigned int suit:2;
unsigned int val:4;
};
struct SUIT {
unsigned int suit:2;
struct CARD cards[13];
};
struct DECK {
struct CARD cards[52];
};
int valToChar (struct CARD inputCard);
int sameSuit (struct CARD oneCard, struct CARD otherCard);
int sameColor (struct CARD oneCard, struct CARD otherCard);
int
main (void)
{
/* Defining every card is going to take a long time... */
struct SUIT shovel;
shovel.suit = SPADES;
struct CARD aceS;
struct CARD twoS;
struct CARD thrS;
struct CARD fouS;
struct CARD fivS;
struct CARD sixS;
struct CARD sevS;
struct CARD eigS;
struct CARD ninS;
struct CARD tenS;
struct CARD jakS;
struct CARD queS;
struct CARD kinS;
shovel.cards[0] = aceS;
shovel.cards[1] = twoS;
shovel.cards[2] = thrS;
shovel.cards[3] = fouS;
shovel.cards[4] = fivS;
shovel.cards[5] = sixS;
shovel.cards[6] = sevS;
shovel.cards[7] = eigS;
shovel.cards[8] = ninS;
shovel.cards[9] = tenS;
shovel.cards[10] = jakS;
shovel.cards[11] = queS;
shovel.cards[12] = kinS;
struct SUIT stone;
stone.suit = DIAMONDS;
struct CARD aceD;
struct CARD twoD;
struct CARD thrD;
struct CARD fouD;
struct CARD fivD;
struct CARD sixD;
struct CARD sevD;
struct CARD eigD;
struct CARD ninD;
struct CARD tenD;
struct CARD jakD;
struct CARD queD;
struct CARD kinD;
stone.cards[0] = aceD;
stone.cards[1] = twoD;
stone.cards[2] = thrD;
stone.cards[3] = fouD;
stone.cards[4] = fivD;
stone.cards[5] = sixD;
stone.cards[6] = sevD;
stone.cards[7] = eigD;
stone.cards[8] = ninD;
stone.cards[9] = tenD;
stone.cards[10] = jakD;
stone.cards[11] = queD;
stone.cards[12] = kinD;
struct SUIT stick;
stick.suit = CLUBS;
struct CARD aceC;
struct CARD twoC;
struct CARD thrC;
struct CARD fouC;
struct CARD fivC;
struct CARD sixC;
struct CARD sevC;
struct CARD eigC;
struct CARD ninC;
struct CARD tenC;
struct CARD jakC;
struct CARD queC;
struct CARD kinC;
stick.cards[0] = aceC;
stick.cards[1] = twoC;
stick.cards[2] = thrC;
stick.cards[3] = fouC;
stick.cards[4] = fivC;
stick.cards[5] = sixC;
stick.cards[6] = sevC;
stick.cards[7] = eigC;
stick.cards[8] = ninC;
stick.cards[9] = tenC;
stick.cards[10] = jakC;
stick.cards[11] = queC;
stick.cards[12] = kinC;
struct SUIT soul;
soul.suit = HEARTS;
struct CARD aceH;
struct CARD twoH;
struct CARD thrH;
struct CARD fouH;
struct CARD fivH;
struct CARD sixH;
struct CARD sevH;
struct CARD eigH;
struct CARD ninH;
struct CARD tenH;
struct CARD jakH;
struct CARD queH;
struct CARD kinH;
soul.cards[0] = aceH;
soul.cards[1] = twoH;
soul.cards[2] = thrH;
soul.cards[3] = fouH;
soul.cards[4] = fivH;
soul.cards[5] = sixH;
soul.cards[6] = sevH;
soul.cards[7] = eigH;
soul.cards[8] = ninH;
soul.cards[9] = tenH;
soul.cards[10] = jakH;
soul.cards[11] = queH;
soul.cards[12] = kinH;
int i;
int j;
for (i = 0; i < 4; i++){
for (j = 0; j < 13; j++){
switch (i){
case 0:
shovel.cards[j].val = j;
shovel.cards[j].suit = i;
break;
case 1:
stone.cards[j].val = j;
stone.cards[j].suit = i;
break;
case 2:
stick.cards[j].val = j;
stick.cards[j].suit = i;
break;
case 3:
soul.cards[j].val = j;
soul.cards[j].suit = i;
break;
}
}
}
}
int
valToChar (struct CARD inputCard)
{
int output;
if ((inputCard.val > 1) && (inputCard.val <= 10)) {
output = inputCard.val + 48;
} else {
switch ( inputCard.val ){
case ACE:
output = 'A';
break;
case JACK:
output = 'J';
break;
case QUEEN:
output = 'Q';
break;
case KING:
output = 'K';
break;
default:
output = '?';
break;
}
}
return (output);
}
int
sameSuit (struct CARD oneCard, struct CARD otherCard)
{
int same = 0;
if (!((oneCard.suit & otherCard.suit) == 0)){
same = 1;
}
return (same);
}
int
sameColor (struct CARD oneCard, struct CARD otherCard)
{
int same = 0;
if (oneCard.suit == otherCard.suit){
same = 1;
}
return (same);
}
| 2915dbcaae01b5061635f3250547217c5ce912be | [
"Markdown",
"C",
"Makefile"
] | 3 | Markdown | kajong0007/freecell | 84b9987730611efb7da25373fffbdb1859f0a6e6 | df1430976b218d0f1ea9197f4e5ad1014d57cc70 |
refs/heads/master | <file_sep>package de.nunoit.networking.protocol.packets;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import de.nunoit.networking.PacketHandler;
import de.nunoit.networking.protocol.Packet;
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class TaskCancel extends Packet {
private int taskId;
@Override
public void handle(PacketHandler handler) throws Exception {
handler.handle(this);
}
@Override
public void write(ByteBuf buf) {
buf.writeInt(taskId);
}
@Override
public void read(ByteBuf buf) {
taskId = buf.readInt();
}
}
<file_sep>package de.nunoit.networking.protocol.packets;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import de.nunoit.networking.PacketHandler;
import de.nunoit.networking.protocol.Packet;
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class Connect extends Packet {
private String uuid;
@Override
public void handle(PacketHandler handler) throws Exception {
handler.handle(this);
}
@Override
public void write(ByteBuf buf) {
writeString(buf, uuid);
}
@Override
public void read(ByteBuf buf) {
uuid = readString(buf);
}
}
<file_sep>package de.nunoit.networking.protocol.packets;
import io.netty.buffer.ByteBuf;
import de.nunoit.networking.PacketHandler;
import de.nunoit.networking.protocol.Packet;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class ImageRequest extends Packet {
@Override
public void handle(PacketHandler handler) throws Exception {
handler.handle(this);
}
@Override
public void write(ByteBuf buf) {
}
@Override
public void read(ByteBuf buf) {
}
}
| cc5ddee7db5dd5c8d377672e30dcc8a8cc71b77b | [
"Java"
] | 3 | Java | nunoit/nunoit-networking | b9110ea12863dcbed1bba78a7ef490245a4938dc | 954631debb9911bfbff1b46287a0eec04584e142 |
refs/heads/master | <file_sep>mean <- function(l) {
sum <- 0
for (i in l) {
sum <- sum + i
}
return(sum / length(l))
}
median <- function(l) {
#order the list accending
l[order(l)]
if (is.even(length(l))) {
#if even, return the average of (n/2) and (n/2 + 1)
average <- (l[ length(l) / 2 ] + l[ (length(l) / 2) + 1]) / 2
return (average)
} else {
#if odd, return ((n+1)/2)
return(l[ (length(l) + 1) / 2 ])
}
}
mode <- function(l) {
l[order(l)]
#initialize the first item as the max to skip the first
max <- 1
char <- l[1]
#the list of modes
sameList = list()
sameList[[1]] = char;
curLen <- 1
i <- 2
while( i <= length(l) ) {
if (l[i] != l[i-1]) {
if (curLen > max) {
max <- curLen
char <- l[i - 1]
sameList <- list(char)
} else if (curLen == max) {
sameList[[1]][[length(sameList[[1]]) + 1]] <- l[i-1]
}
curLen <- 1
} else {
curLen <- curLen + 1
}
i <- i + 1
}
if (curLen > max) {
max <- curLen
char <- l[i - 1]
sameList <- list(char)
} else if (curLen == max) {
#sameList <- c(sameList, l[[i-1]])
sameList[[1]][[length(sameList[[1]]) + 1]] <- l[i-1]
}
return(sameList[[1]])
}
variance <- function(l) {
listAverage <- mean(l)
sum <- 0
for (i in l) {
partial <- ((i - listAverage) ^ 2)
sum <- sum + partial
}
return(sum / (length(l) - 1))
}
standardDeviation <- function(l) {
return(sqrt(variance(l)))
}<file_sep>test.probabilityGiven <- function() {
#checkEquals( probability.given() )
}<file_sep>RLib
====
A set of R functions for Statistics 301
<file_sep>test.combinations <- function () {
checkEquals( combination(10, 3), 120, "Basic Combination")
}
test.permutations <- function () {
checkEquals( permutations(10, 3), 720, "Basic Permutations")
}<file_sep>drv.expected <- function(pm) {
sum <- 0
i <- 1
while( i <= ncol(pm)) {
sum <- sum + (pm[1, i] * pm[2, i])
i <- i + 1
}
return(sum)
}
drv.variance <- function(pm) {
sum <- 0
i <- 1
while( i <= ncol(pm)) {
sum <- sum + (((pm[1, i] - drv.expected(pm))^2) * pm[2, i])
i <- i + 1
}
}<file_sep>is.even <- function(x) {
return ( x %% 2 == 0)
}<file_sep>fileToMatrix <- function(fileName, tempHeader=FALSE, tempSep = "") {
return(as.matrix(read.delim(fileName, header=tempHeader, colClasses = "numeric", sep = tempSep)))
}<file_sep>combination <- function(n,k) {
top <- factorial(n)
bottom <- factorial(k) * factorial(n - k)
return (top / bottom)
}
permutations <- function(n, k) {
top <- factorial(n)
bottom <- factorial(n - k)
return (top / bottom)
}<file_sep>library('RUnit')
source("./src/inputs.r")
source("./src/utils.r")
source('./src/average.r')
source('./src/counting.r')
test.suite <- defineTestSuite("Basic Stats",
dirs = file.path("tests"),
testFileRegexp = '*.test.r')
test.result <- runTestSuite(test.suite)
printTextProtocol(test.result)<file_sep>probability.given <- function(a, b) {
return( (a * b) / b);
}<file_sep>test.mean <- function() {
checkTrue( mean(c(1,2,3,4)) == 2.5, 'Mean works')
}
test.median <- function() {
checkTrue( median(c(1,2,3,4,5)) == 3, 'Median works with odd data set')
checkTrue( median(c(1,2,3,4)) == 2.5, 'Median works with odd data set')
}
test.mode <- function() {
checkTrue( mode(c(1,2,2)) == c(2), "One mode test")
checkEquals(mode(c(1,1,2,2,3,3)), c(1,2,3), "Multi mode works")
checkEquals(mode(c(1,1,2,2,3,3,2)), c(1,2,3), "mode out of order")
}
test.variance <- function() {
checkEquals(variance(c(.684, 2.540, .924, 3.130, 1.038, .598, .483, 3.520, 1.285, 2.650, 1.497)), 1.19358, "example from boot table 1.3; example 1.15")
}
test.deactivation <- function() {
DEACTIVATED('Deactivating this test function')
} | 2c26caec1814fbd64dfd7c56a70d655d92bfaf4b | [
"Markdown",
"R"
] | 11 | R | otternq/RLib | 4cc9be9711f72af9907fb6e5eed1faa676d95d38 | 562b7768d57e4566fb0f06f29761a45da1b96164 |
refs/heads/master | <repo_name>jessi1998/proyectotap<file_sep>/src/main/java/com/example/proyectoM5A/Servicio/AsignaturaService.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.proyectoM5A.Servicio;
import com.example.proyectoM5A.Modelo.Asignatura;
import com.example.proyectoM5A.Repository.AsignaturaRepository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* @author <NAME>
*/
@Service
public class AsignaturaService {
@Autowired
AsignaturaRepository asignaturarespository;
public Asignatura crearAsignatura(Asignatura asignatura){
return asignaturarespository.save(asignatura);
}
public List<Asignatura> ListarAsignatura(){
return asignaturarespository.findAll();
}
}
<file_sep>/src/main/java/com/example/proyectoM5A/Controller/AsignaturaController.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.proyectoM5A.Controller;
import com.example.proyectoM5A.Modelo.Asignatura;
import com.example.proyectoM5A.Servicio.AsignaturaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
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.RestController;
/**
*
* @author <NAME>
*/
@RestController
@RequestMapping("/asignatura")
@CrossOrigin(origins="*")
public class AsignaturaController {
@Autowired
AsignaturaService asignaturaservice;
@PostMapping
public ResponseEntity saveAsignatura(@RequestBody Asignatura asignatura){
return ResponseEntity.ok(asignaturaservice.crearAsignatura(asignatura));
}
@GetMapping(path= "/list")
public ResponseEntity listAsignatura(){
return ResponseEntity.ok(asignaturaservice.ListarAsignatura());
}
}
| c0c263f74417be329b95815875b60382ecae79c0 | [
"Java"
] | 2 | Java | jessi1998/proyectotap | 08a5150723d72056d3e1e5f19c25ec16fbdb954b | 230b8c72890a7314c27db78425b039d504104a13 |
refs/heads/master | <repo_name>lszwedxx/ReactVideos<file_sep>/src/context/ThemeProvider.js
import { React, useState } from 'react';
import ThemeContext from './ThemeContext';
const ThemeProvider = ({ children }) => {
const dark = {
name: 'dark',
primary: 'dark-primary',
secondary: 'dark-secondary',
background: 'dark-bg',
color: 'dark-text-primary',
colorSecondary: 'text-secondary',
};
const light = {
name: 'light',
primary: 'light-primary',
secondary: 'light-secondary',
background: 'light-bg',
color: 'light-text-primary',
colorSecondary: 'text-secondary',
};
const [mode, setMode] = useState(dark);
const changeMode = () => {
setMode((prevMode) => (prevMode.name === 'dark' ? light : dark));
};
const theme = {
mode,
changeMode,
};
return (
<ThemeContext.Provider value={theme}>{children}</ThemeContext.Provider>
);
};
export default ThemeProvider;
<file_sep>/src/components/VideosList.js
import { React, useContext } from 'react';
import { Button, Row, Col } from 'reactstrap';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
faThumbsUp,
faThumbsDown,
faPlus,
faTimes,
} from '@fortawesome/free-solid-svg-icons';
import ThemeContext from '../context/ThemeContext';
const VideosList = ({
videos,
handleClick,
toggleFavorite,
favorite,
favVideos,
}) => {
const { mode } = useContext(ThemeContext);
const { secondary, colorSecondary } = mode;
const videosList = favorite ? favVideos : videos;
return (
<div className="container-fluid ">
{videosList.length > 0 ? (
<ul className="container-fluid list-unstyled p-4 m-0">
<Row className="justify-content-around" md="2">
{videosList.map((video) => (
<li key={video.id}>
<Col>
<iframe
title="video"
width="100%"
height="300px"
src={`https://youtube.com/embed/${video.id}`}
/>
<h2>{video.title}</h2>
<div
style={{ fontSize: 15 }}
className={`text-${colorSecondary} d-flex p-1`}
>
<div className="d-flex flex-grow-1">
<p className="p-1 m-0">{`${video.viewCount} views`}</p>
<p className="p-1 m-0">{video.date}</p>
</div>
<div className="d-flex flex-grow-2">
<FontAwesomeIcon
className="fs-2 py-2"
icon={faThumbsUp}
/>
<p className="py-1 m-0">{video.likeCount}</p>
</div>
<div className="d-flex flex-grow-2">
<FontAwesomeIcon
className="fs-2 py-2"
icon={faThumbsDown}
/>
<p className="py-1 m-0">{video.dislikeCount}</p>
</div>
<Button
onClick={() => toggleFavorite(video.id)}
className={`btn-${secondary} mx-3 ${
video.favorite === true ? `text-success` : null
}`}
>
<FontAwesomeIcon icon={faPlus} />
</Button>
<Button
onClick={() => handleClick(video.id)}
className={`btn-danger text-${colorSecondary} mx-3`}
>
<FontAwesomeIcon icon={faTimes} />
</Button>
</div>
</Col>
</li>
))}
</Row>
</ul>
) : (
<h1 className="m-0 text-center">Nothing to watch</h1>
)}
</div>
);
};
export default VideosList;
<file_sep>/src/App.js
import React from 'react';
import Main from './components/Main';
import ThemeProvider from './context/ThemeProvider';
function App() {
return (
<div className="App">
<ThemeProvider>
<Main />
</ThemeProvider>
</div>
);
}
export default App;
<file_sep>/src/components/Header.js
import { React, useContext } from 'react';
import { Form, FormGroup, Button, Input, Row, Col } from 'reactstrap';
import ThemeContext from '../context/ThemeContext';
const Header = ({ input, handleChange, handleClick, handleToggle }) => {
const { changeMode, mode } = useContext(ThemeContext);
const { name, primary, secondary } = mode;
return (
<header className={`bg-${primary}`}>
<h1 className="text-center">My Favorite Videos</h1>
<Button
onClick={changeMode}
className={`btn-${secondary} position-absolute top-0 end-0 m-3`}
>
{name === 'dark' ? 'Light' : 'Dark'}
</Button>
<Form className="p-5">
<FormGroup>
<Row className="justify-content-center">
<Col xs="12" sm="6" md="5" lg="4">
<Input
placeholder="Add Video"
value={input}
onChange={handleChange}
/>
</Col>
<Col xs="auto">
<Button onClick={handleClick} className={`btn-${secondary}`}>
Add
</Button>
</Col>
<Col xs="auto">
<Input
onChange={handleToggle}
className={`btn-${secondary}`}
type="select"
>
<option>All</option>
<option>Favorites</option>
</Input>
</Col>
</Row>
</FormGroup>
</Form>
</header>
);
};
export default Header;
| d06bde7814268cc92384fa5ba5c4858ebf560c2d | [
"JavaScript"
] | 4 | JavaScript | lszwedxx/ReactVideos | 06acc1a166fafe959b973bd061285c82367eef89 | 18649e2dfb0ffeb84dbf12974cb642ab5ea761a4 |
refs/heads/main | <repo_name>Ferch42/PyDSRL<file_sep>/agents/SymbolicAgentv2.py
import random
from collections import namedtuple
from collections import deque
import pickle
import pygame
import numpy as np
# namedtuple definitions
EntityType = namedtuple('EntityType', ['activation_spectra', 'type_number'])
Entity = namedtuple('Entity', ['position', 'entity_type'])
Interaction = namedtuple('Interaction', ['entity_type1', 'entity_type2', 'x_dist', 'y_dist'])
# Auxiliary_functions
euclidean = lambda x, y: np.sqrt(np.sum(np.square(np.subtract(x,y))))
class SymbolicAgentv2:
def __init__(self, action_size: int):
self.action_size = action_size
# RL
self.gamma = 0.99
self.lr = 0.001
self.epsilon = 1
self.epsilon_decay = 0.999995
# Auxiliary data structures
self.entity_types = [EntityType(None, 0), EntityType('agent', 1), \
EntityType('cross', 2), EntityType('circle', 3)] # Initializes with null-type
self.interactions_Q_functions = {}
self.states_dict = {}
## max distances
self.interaction_max_distance = 40
self.viewer = None
self.experience_replay_buffer = deque(maxlen = 1_000)
self.batch_size = 32
def act(self, state, random_act = True):
Q_values = self.get_Q_total(self.get_state_representation(state))
#print(Q_values)
if random_act:
if np.random.random() < self.epsilon:
return np.random.choice(range(self.action_size))
Q_max = Q_values.max()
Q_max_indexes = [j for j in range(self.action_size) if Q_values[j]==Q_max]
return np.random.choice(Q_max_indexes)
def get_q_value_function(self, i: Interaction):
if i not in self.interactions_Q_functions.keys():
self.interactions_Q_functions[i] = np.zeros(self.action_size)
return self.interactions_Q_functions[i]
def get_state_representation(self, state):
state_string = str(state)
if state_string not in self.states_dict.keys():
self.states_dict[state_string] = self.build_state_representation(state)
return self.states_dict[state_string]
def get_Q_total(self, interactions):
Q_values = np.zeros(self.action_size)
for i in interactions:
Q_values += self.get_q_value_function(i)
return Q_values
def update(self, state, action, reward, next_state, done):
self.experience_replay_buffer.append((state,action, reward, next_state, done))
if len(self.experience_replay_buffer)> self.batch_size:
batch = random.sample(self.experience_replay_buffer, self.batch_size)
for experience in batch:
self.remember(*experience)
self.epsilon = max(0.1, self.epsilon*self.epsilon_decay)
def remember(self, state, action, reward, next_state, done):
interactions_before = self.get_state_representation(state)
interactions_after = self.get_state_representation(next_state)
Q_before = self.get_Q_total(interactions_before)
Q_after = self.get_Q_total(interactions_after)
td = reward + Q_after.max()- Q_before[action]
for ib in interactions_before:
# Interactions
Q_int = self.get_q_value_function(ib)
Q_int[action] = Q_int[action] + self.lr* td
def extract_entities(self, state):
agent_type = self.entity_types[1]
cross_type = self.entity_types[2]
circle_type = self.entity_types[3]
agent_pos_x, agent_pos_y = int(state['agent'].left), int(state['agent'].top)
detected_entities = [Entity(np.array([agent_pos_x, agent_pos_y]), agent_type)]
for cross in state['entities']['cross']:
if cross.alive:
cross_x, cross_y = int(cross.left), int(cross.top)
detected_entities.append(Entity(np.array([cross_x, cross_y]), cross_type))
for circle in state['entities']['circle']:
if circle.alive:
circle_x, circle_y = int(circle.left), int(circle.top)
detected_entities.append(Entity(np.array([circle_x, circle_y]), circle_type))
return detected_entities
def build_state_representation(self, state, only_agent_interactions = True):
"""
Builds the state representation
input:
state: np.array
return:
interactions: [Interaction]
"""
detected_entities = self.extract_entities(state)
n_entities = len(detected_entities)
interactions = set()
for i in range(n_entities-1):
for j in range(i+1, n_entities):
e1 = detected_entities[i]
e2 = detected_entities[j]
if only_agent_interactions and not (e1.entity_type.type_number == 1 or e2.entity_type.type_number == 1):
continue
if euclidean(e1.position, e2.position) < self.interaction_max_distance:
# Valid interaction
# Sorting entities by their type in order to mantain consistency
se1, se2 = sorted([e1, e2], key = lambda x: x.entity_type.type_number)
x_dist, y_dist = se1.position - se2.position
interactions.add(Interaction(se1.entity_type.type_number, \
se2.entity_type.type_number, x_dist, y_dist))
#print(interactions)
return interactions
def reset(self):
pygame.display.quit()
def save(self, path):
pickle.dump(self.interactions_Q_functions, open(path, "wb+") )
def load(self, path):
self.interactions_Q_functions = pickle.load(open(path, 'rb'))
<file_sep>/utils.py
import os
import gym
import numpy as np
import pickle
from sklearn.model_selection import train_test_split
from tqdm import tqdm
from components.autoencoder import SymbolAutoencoder
def make_autoencoder_train_data(num, min_entities=1, max_entities=30):
'''
Make training images for the autoencoder
env_parameters: (dict) dictionary that specifies the properties of the environment
num: (int) number of samples the data should consist of
min_entities, max_entities: (int) min/max number of entities that can appear \
in a single environment frame
return: (np.array) BxWxHxC dataset of environment images
'''
temp_env = gym.make('CrossCircle-MixedRand-v0')
temp_env.seed(0)
states = []
print('generating samples')
for i in tqdm(range(num)):
state = temp_env.make_random_state(min_entities, max_entities)
if len(state)==0:
continue
states.append(state)
#args.logger.info(f'Final number of states collected in the current configuration {len(states)}')
if (len(states)/num)<0.8:
raise Exception('With the current environment configuration entities do /'
'not fit onto the grid without overlapping too much')
return np.asarray(states)
def prepare_training(args):
'''
(1) Creates environment
(2) Checks whether training images for the autoencoder exist, if not creates them
(3) Creates the autoencoder
(4) Trains or loads the weights of the autoencoder
return: trained autoencoder, environment
'''
# Create the environment
env_parameters = {'entity_size': args.entity_size,
'min_entities': args.n_entities,
'max_entities': args.n_entities,
'step_size': args.step_size,
'overlap_factor': args.overlap_factor}
env = gym.make(args.env_id, **env_parameters)
seed = env.seed(1)[0]
# Load or create images
if args.colour_state:
GRAY = 'colour'
else:
GRAY = 'gray'
TRAIN_IMAGES_FILE = f'train_images_{GRAY}.pkl'
print(os.path.join(args.image_dir,TRAIN_IMAGES_FILE))
if not os.path.exists(os.path.join(args.image_dir,TRAIN_IMAGES_FILE)) or args.new_images:
args.logger.info('Making test images...')
images = make_autoencoder_train_data(env_parameters, 5000, args, max_entities=20)
with open(os.path.join(args.image_dir,TRAIN_IMAGES_FILE), 'wb') as f:
pickle.dump(images, f)
else:
args.logger.info('Loading test images...')
with open(os.path.join(args.image_dir,TRAIN_IMAGES_FILE), 'rb') as f:
images = pickle.load(f)
# Create the autoencoder
input_shape = images[0].shape
if args.load:
autoencoder = SymbolAutoencoder.from_saved(args.load,
input_shape,
args.filter_size,
neighbor_radius=args.neighborhood_size)
else:
autoencoder = SymbolAutoencoder(input_shape, args.filter_size, neighbor_radius=args.neighborhood_size)
# Train or load autoencoder
if args.load_train or args.visualize or not args.load:
args.logger.info('Splitting sets...')
X_train, X_test = train_test_split(images, test_size=0.2, random_state=seed)
X_train, X_val = train_test_split(X_train, test_size=0.2, random_state=seed)
if args.load_train or not args.load:
args.logger.info('Training...')
autoencoder.train(X_train, epochs=10, validation=X_val,tensorboard=args.tensorboard)
if args.visualize:
# Visualize autoencoder
vis_imgs = X_test[:10]
autoencoder.visualize(vis_imgs)
if args.save:
autoencoder.save_weights(os.path.join(args.save, f'{GRAY}_{args.entity_size}_model.h5'))
# Visualize the results of the autoencoder
if args.play:
# Visualize your own moves for 10 steps
state = env.reset()
for i in range(20):
state = np.reshape(state, (1,) + input_shape)
autoencoder.visualize(state,show=True)
action = int(input('Next action: '))
state, reward, _, _ = env.step(action)
print(f'The overall reward is {reward}')
return autoencoder, env
<file_sep>/mamamamamain.py
import argparse
import os
from collections import deque
from datetime import datetime
import numpy as np
import tensorflow as tf
import tqdm
import cross_circle_gym
from agents import DQNAgent, SymbolicAgent, SymbolicAgentv2, SymbolicAgentDQN, SymbolicAgentDQNv2, SymbolicAgentExact
from utils import make_autoencoder_train_data
import gym
parser = argparse.ArgumentParser(description=None)
# Experiment variables
parser.add_argument('--episodes', '-e', type=int, default=10_000,
help='number of DQN training episodes')
parser.add_argument('--evaluation_frequency', type=int, default=100,
help='How often to evaluate the agent')
parser.add_argument('--agent', type = str, default = 'symbdqn',
help='What agent do you want to evaluate (dqn or symb)')
# Saving and logging config
parser.add_argument('--experiment_name', type=str, default='default', help='Name of the experiment')
parser.add_argument('--logdir',type=str,default='./logs', help='Log directory')
parser.add_argument('--name',type=str,default='exp', help='name')
parser.add_argument('--agent_load_path',type=str,default='', help='Path to the agent configuration')
parser.add_argument('--rand',action='store_true', default=False)
args = parser.parse_args()
args.logdir = os.path.join(args.logdir,args.experiment_name,args.agent, args.name)
if not args.rand:
print("FIXED ENVIRONMENT")
env = gym.make("CrossCircle-MixedGrid-v0")
else:
print('RANDOM ENVIRONMENT')
env = gym.make("CrossCircle-MixedRand-v0")
action_size = env.action_space.n
evaluation_flag = args.experiment_name == 'eval'
symbv2flag = args.agent =='symbv2' or 'symbdqn' in args.agent
state_dim = None
if not symbv2flag:
state_dim = env.reset().shape
agent = None
if args.agent=='dqn':
agent = DQNAgent(state_dim, action_size)
elif args.agent=='symb':
agent = SymbolicAgent(state_dim, action_size, make_autoencoder_train_data(5000))
elif args.agent=='symbv2':
agent = SymbolicAgentv2(action_size)
elif args.agent=='symbdqn':
agent = SymbolicAgentDQN(action_size)
elif args.agent=='symbdqnv2':
agent = SymbolicAgentDQNv2(action_size)
elif args.agent== 'symbexact':
agent = SymbolicAgentExact(action_size)
else:
raise Exception('agent type not found')
if evaluation_flag:
agent.load(args.agent_load_path)
print('LOADED AGENT CONFIGURATION')
number_of_evaluations = 0
time_steps = 100
buffered_rewards = deque(maxlen=200)
summary_writer = tf.summary.create_file_writer(args.logdir)
for e in tqdm.tqdm(range(args.episodes)):
#state_builder.restart()
state = env.reset()
agent.reset()
#state = state_builder.build_state(*autoencoder.get_entities(state))
total_reward = 0
captured_entities = {'positive': 0, 'negative': 0}
for t in range(time_steps):
#env.render()
action = agent.act(state, random_act = (not evaluation_flag))
#print(action)
next_state, reward, done, _ = env.step(action)
if reward ==1:
captured_entities['positive'] +=1
elif reward== -1:
captured_entities['negative'] += 1
total_reward += reward
if not evaluation_flag:
agent.update(state, action, reward, next_state, done)
state = next_state
if done:
break
env.close()
buffered_rewards.append(total_reward)
captured_positive = 0.5
if captured_entities['positive'] + captured_entities['negative'] ==0:
captured_positive = 0.5
else:
captured_positive = captured_entities['positive']/(captured_entities['positive'] + captured_entities['negative'])
with summary_writer.as_default():
tf.summary.scalar('Averaged Reward',np.mean(buffered_rewards),e)
tf.summary.scalar('Epsilon',agent.epsilon,e)
tf.summary.scalar('Captured Positive', captured_positive, e)
if e%args.evaluation_frequency ==0:
agent.save(os.path.join(args.logdir,'agent'))
"""
if e % args.evaluation_frequency == 0:
number_of_evaluations += 1
agent.save(os.path.join(args.logdir,'dqn_agent.h5'))
evaluation_reward = []
with summary_writer.as_default():
for i in range(1):
done = False
#state_builder.restart()
image = env.reset()
agent.reset()
#state = state_builder.build_state(*autoencoder.get_entities(image))
total_reward = 0
for t in range(time_steps):
action = agent.act(image,random_act=False)
#env.render()
next_image, reward, done, _ = env.step(action)
if i==0:
tf.summary.image(f'Agent Behaviour {number_of_evaluations}',np.reshape(image,(1,)+image.shape),t)
total_reward += reward
#next_state = state_builder.build_state(*autoencoder.get_entities(next_image))
#state = next_image
image = next_image
evaluation_reward.append(total_reward)
env.close()
tf.summary.scalar('Evaluation Reward',np.mean(evaluation_reward),number_of_evaluations)
"""<file_sep>/agents/SymbolicAgentDQN.py
import random
from collections import namedtuple
from collections import deque
import gc
import pickle
import pygame
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.models import Model
from tensorflow.keras.losses import MeanSquaredError
# namedtuple definitions
EntityType = namedtuple('EntityType', ['activation_spectra', 'type_number'])
Entity = namedtuple('Entity', ['position', 'entity_type'])
Interaction = namedtuple('Interaction', ['entity_type1', 'entity_type2', 'x_dist', 'y_dist'])
# Auxiliary_functions
euclidean = lambda x, y: np.sqrt(np.sum(np.square(np.subtract(x,y))))
class SymbolicAgentDQN:
def __init__(self, action_size: int):
self.action_size = action_size
# RL
self.gamma = 0.99
self.lr = 0.001
self.epsilon = 1
self.epsilon_min = 0.1
self.epsilon_decay = 0.999995
# Auxiliary data structures
self.entity_types = [EntityType(None, 0), EntityType('agent', 1), \
EntityType('cross', 2), EntityType('circle', 3)] # Initializes with null-type
self.interactions_Q_functions = {}
self.states_dict = {}
## max distances
self.interaction_max_distance = 40
self.viewer = None
self.experience_replay_buffer = deque(maxlen = 1_000)
self.batch_size = 32
self.max_number_of_interactions = 10
# DQN
self.memory = deque(maxlen=1_000)
self.update_frequency = 4
self.model = self._build_model()
self.target_model = self._build_model()
self.update_target_model()
self.step = 0
self.C = 10_000
self.batch_size = 32
self.loss_function = MeanSquaredError()
self.optimizer = Adam(learning_rate=0.00025, clipnorm=1.0)
def _build_model(self):
# Neural Net for Deep-Q learning Model
state_input = Input(shape = (self.max_number_of_interactions *4,))
dense1 = Dense(128, activation = 'relu')(state_input)
action_output = Dense(self.action_size, activation='linear')(dense1)
model = Model(inputs = state_input, outputs = action_output)
return model
def update_target_model(self):
# copy weights from model to target_model
self.target_model.set_weights(self.model.get_weights())
def act(self, state,random_act=True):
s = self.get_state_representation(state)
if random_act:
if np.random.rand() <= self.epsilon:
return random.randrange(self.action_size)
act_values = self.model.predict(np.array([s]))
return np.argmax(act_values[0]) # returns action
def get_state_representation(self, state):
state_string = str(state)
if state_string not in self.states_dict.keys():
self.states_dict[state_string] = self.build_state_representation(state)
return self.states_dict[state_string]
def replay(self, batch_size):
minibatch = random.sample(self.memory, batch_size)
states, rewards, next_states, actions, dones = [], [], [], [], []
for s, a, r, ns, d in minibatch:
states.append(s)
actions.append(a)
rewards.append(r)
next_states.append(ns)
dones.append(int(d))
states, next_states = np.array(states), np.array(next_states)
rewards = np.array(rewards)
dones = np.array(dones)
future_rewards = self.target_model.predict(next_states)
updated_q_values = rewards + (1-dones) * (self.gamma* np.max(future_rewards, axis = 1))
action_masks = tf.one_hot(actions, self.action_size)
with tf.GradientTape() as tape:
q_values = self.model(states)
q_action = tf.reduce_sum(tf.multiply(q_values, action_masks), axis=1)
loss = self.loss_function(updated_q_values, q_action)
grads = tape.gradient(loss, self.model.trainable_variables)
self.optimizer.apply_gradients(zip(grads, self.model.trainable_variables))
gc.collect()
def update(self, state, action, reward, next_state, done):
self.remember(self.get_state_representation(state), action, reward, self.get_state_representation(next_state), done)
if len(self.memory) > self.batch_size and self.step % self.update_frequency==0:
self.replay(self.batch_size)
self.step +=1
if self.epsilon > self.epsilon_min:
self.epsilon *= self.epsilon_decay
if self.step%self.C == 0:
self.update_target_model()
def remember(self, state, action, reward, next_state, done):
self.memory.append((state, action, reward, next_state, done))
def extract_entities(self, state):
agent_type = self.entity_types[1]
cross_type = self.entity_types[2]
circle_type = self.entity_types[3]
agent_pos_x, agent_pos_y = int(state['agent'].left), int(state['agent'].top)
detected_entities = [Entity(np.array([agent_pos_x, agent_pos_y]), agent_type)]
for cross in state['entities']['cross']:
if cross.alive:
cross_x, cross_y = int(cross.left), int(cross.top)
detected_entities.append(Entity(np.array([cross_x, cross_y]), cross_type))
for circle in state['entities']['circle']:
if circle.alive:
circle_x, circle_y = int(circle.left), int(circle.top)
detected_entities.append(Entity(np.array([circle_x, circle_y]), circle_type))
return detected_entities
def build_state_representation(self, state):
"""
Builds the state representation
input:
state: np.array
return:
interactions: [Interaction]
"""
detected_entities = self.extract_entities(state)
n_entities = len(detected_entities)
interactions = set()
for i in range(n_entities-1):
for j in range(i+1, n_entities):
e1 = detected_entities[i]
e2 = detected_entities[j]
if not (e1.entity_type.type_number == 1 or e2.entity_type.type_number == 1):
continue
if euclidean(e1.position, e2.position) < self.interaction_max_distance:
# Valid interaction
# Sorting entities by their type in order to mantain consistency
se1, se2 = sorted([e1, e2], key = lambda x: x.entity_type.type_number)
x_dist, y_dist = se1.position - se2.position
interactions.add(Interaction(se1.entity_type.type_number, \
se2.entity_type.type_number, x_dist, y_dist))
#print(interactions)
return self.create_vector_representation(interactions)
def create_vector_representation(self, interactions):
vector_representation = []
sorted_interactions = sorted(interactions, key = lambda x: abs(x.x_dist) + abs(x.y_dist))
count = 0
for si in sorted_interactions:
if si.entity_type2 == 2:
vector_representation += [1,0]
elif si.entity_type2 == 3:
vector_representation += [0,1]
else:
raise Exception("invalid format")
vector_representation += [si.x_dist/self.interaction_max_distance, si.y_dist/self.interaction_max_distance]
count+=1
if count == self.max_number_of_interactions:
break
if count!= self.max_number_of_interactions:
number_of_remaining_zeros = [0]* (self.max_number_of_interactions- count) *4
vector_representation += number_of_remaining_zeros
#print(vector_representation)
assert(len(vector_representation) == self.max_number_of_interactions*4)
return np.array(vector_representation)
def reset(self):
pygame.display.quit()
def save(self, path):
self.model.save_weights(path+ '.h5')
def load(self, path):
self.model.load_weights(path + 'h5')
<file_sep>/agents/DQNAgent.py
'''
MIT License
Copyright (c) 2017 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
SOURCE: https://github.com/keon/deep-q-learning/blob/master/ddqn.py
SOURCE: https://keras.io/examples/rl/deep_q_network_breakout/
'''
import pickle
import random
from collections import deque
import sys
import gc
from scipy import sparse
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import Input, Dense, Conv2D, MaxPooling2D, Flatten
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.models import Model
from tensorflow.keras.losses import MeanSquaredError
class DQNAgent:
def __init__(self, state_dim, action_size, memory_size = 1_000,
gamma = 0.99, init_epsilon = 1.0, final_epsilon = 0.1, epsilon_decay = 0.999995,
lr = 0.00025, update_frequency = 4, batch_size = 32, C = 10_000):
self.state_dim = state_dim
self.action_size = action_size
self.gamma = gamma # discount rate
self.epsilon = init_epsilon # exploration rate
self.epsilon_min = final_epsilon
self.epsilon_decay = epsilon_decay #0.99998
# DQN
self.memory = deque(maxlen=memory_size)
self.learning_rate = lr
self.update_frequency = update_frequency
self.model = self._build_model()
self.target_model = self._build_model()
self.update_target_model()
self.step = 0
self.C = C
self.batch_size = batch_size
self.loss_function = MeanSquaredError()
self.optimizer = Adam(learning_rate=0.00025, clipnorm=1.0)
self.states_table = dict()
print(self.model.summary())
def _build_model(self):
# Neural Net for Deep-Q learning Model
state_input = Input(shape = self.state_dim)
conv1 = Conv2D(8, (5,5), activation = 'relu')(state_input)
conv2 = Conv2D(8 , (3,3), activation = 'relu') (conv1)
max_pool = MaxPooling2D((2,2))(conv2)
flatten = Flatten()(max_pool)
dense1 = Dense(32, activation = 'relu')(flatten)
action_output = Dense(self.action_size, activation='linear')(dense1)
model = Model(inputs = state_input, outputs = action_output)
return model
def update_target_model(self):
# copy weights from model to target_model
self.target_model.set_weights(self.model.get_weights())
def remember(self, state, action, reward, next_state, done):
self.memory.append((state, action, reward, next_state, done))
def act(self, state,random_act=True):
if random_act:
if np.random.rand() <= self.epsilon:
return random.randrange(self.action_size)
act_values = self.model.predict(np.array([state]))
else:
act_values = self.model.predict(np.array([state]))
return np.argmax(act_values[0]) # returns action
def replay(self, batch_size):
minibatch = random.sample(self.memory, batch_size)
states, rewards, next_states, actions, dones = [], [], [], [], []
for s, a, r, ns, d in minibatch:
states.append(s)
actions.append(a)
rewards.append(r)
next_states.append(ns)
dones.append(int(d))
states, next_states = np.array(states), np.array(next_states)
rewards = np.array(rewards)
dones = np.array(dones)
future_rewards = self.target_model.predict(next_states)
updated_q_values = rewards + (1-dones) * (self.gamma* np.max(future_rewards, axis = 1))
action_masks = tf.one_hot(actions, self.action_size)
with tf.GradientTape() as tape:
q_values = self.model(states)
q_action = tf.reduce_sum(tf.multiply(q_values, action_masks), axis=1)
loss = self.loss_function(updated_q_values, q_action)
grads = tape.gradient(loss, self.model.trainable_variables)
self.optimizer.apply_gradients(zip(grads, self.model.trainable_variables))
gc.collect()
def update(self, state, action, reward, next_state, done):
self.remember(state, action, reward, next_state, done)
if len(self.memory) > self.batch_size and self.step % self.update_frequency==0:
self.replay(self.batch_size)
self.step +=1
if self.epsilon > self.epsilon_min:
self.epsilon *= self.epsilon_decay
if self.step%self.C == 0:
self.update_target_model()
def load(self, name):
self.model.load_weights(name + '.h5')
def save(self, name):
self.model.save_weights(name+ '.h5')
def reset(self):
pass<file_sep>/README.md
# PyDSRL
Fork of the work of https://github.com/ivegner/PyDSRL
Faithful Python implementation of the paper "Towards Deep Symbolic Reinforcement Learning" by Garnelo et al.
*Work in progress, please feel free to contribute.*
## Instructions
Confirmed to work with Python 3.8.5.
```
pip install -r requirements.txt
```
or
```pip install -r requirements.freeze```
Run with `python main.py`.
## Issues:
* Object tracking occasionally messes up, and relations get jumbled. Cause unknown.
* Agent breaks upon encountering a cross during an episode
<file_sep>/scripts/training.sh
#! /bin/bash
experiment_name='default'
load='../autoencoder_models/gray_10_model.h5' # If pretrained autoencoder exist here is the file-path of the model
image_dir='../'
logdir='../logs'
log_level='info' # info, warn
evaluation_frequency=50
# Environment
n_entities=16
entity_size=10
neighborhood_size=10
step_size=2.0
overlap_factor=0.01
# Training parameters
alpha=0.01
epsilon_decay=0.99999
# Autoencdoer
filter_size=7
python ../main.py --experiment_name $experiment_name \
--load $load \
--logdir $logdir \
--image_dir $image_dir \
--log_level $log_level \
--evaluation_frequency $evaluation_frequency \
--n_entities $n_entities \
--entity_size $entity_size \
--neighborhood_size $neighborhood_size \
--step_size $step_size \
--overlap_factor $overlap_factor \
--alpha $alpha \
--epsilon_decay $epsilon_decay \
--filter_size $filter_size\
<file_sep>/agents/__init__.py
from agents.DQNAgent import DQNAgent
from agents.SymbolicAgent import SymbolicAgent
from agents.SymbolicAgentv2 import SymbolicAgentv2
from agents.SymbolicAgentDQN import SymbolicAgentDQN
from agents.SymbolicAgentExact import SymbolicAgentExact
from agents.SymbolicAgentDQNv2 import SymbolicAgentDQNv2<file_sep>/agents/SymbolicAgent.py
import random
from collections import namedtuple
from collections import deque
#from scipy.spatial.distance import euclidean
import pygame
from skimage.transform import resize, rescale
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D, Conv2DTranspose
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.models import Model
from tensorflow.keras.losses import MeanSquaredError
from sklearn.model_selection import train_test_split
from sklearn.metrics import pairwise
from tqdm import tqdm
# namedtuple definitions
EntityType = namedtuple('EntityType', ['activation_spectra', 'type_number'])
Entity = namedtuple('Entity', ['position', 'entity_type'])
Interaction = namedtuple('Interaction', ['entity_type1', 'entity_type2', 'x_dist', 'y_dist'])
# Auxiliary_functions
euclidean = lambda x, y: np.sqrt(np.sum(np.square(np.subtract(x,y))))
np.set_printoptions(threshold=np.inf)
def duplicate_matrix(mat):
mat_i, mat_j = mat.shape
dup_mat = np.zeros(shape = (mat_i*2, mat_j*2))
for i in range(mat_i):
for j in range(mat_j):
dup_mat[2*i][2*j] = mat[i][j]
dup_mat[2*i+1][2*j] = mat[i][j]
dup_mat[2*i][2*j+1] = mat[i][j]
dup_mat[2*i+1][2*j+1] = mat[i][j]
return dup_mat
class SymbolicAgent:
def __init__(self, state_dim: tuple, action_size: int, pre_training_images: np.array):
self.state_dim = state_dim
self.action_size = action_size
# Number of convolutions
self.number_of_convolutions = 8
# RL
self.gamma = 0.99
self.lr = 0.00001
self.epsilon = 1
self.epsilon_decay = 0.999995
self.batch_size = 32
# Auxiliary data structures
self.entity_types = [EntityType(np.full(self.number_of_convolutions , np.inf), 0)] # Initializes with null-type
self.interactions_Q_functions = {}
self.states_dict = {}
self.experience_replay_buffer = deque(maxlen = 1_000)
# Entity tracking
## thresholds
self.activation_threshold = 0
self.type_distance_threshold = 1
## max distances
self.interaction_max_distance = 20
# Autoencoder
self.build_autoencoder()
self.train_autoencoder(pre_training_images)
self.viewer = None
def build_autoencoder(self):
"""
Builds the model for the autoencoder
"""
input_state = Input(shape = self.state_dim)
conv = Conv2D(self.number_of_convolutions, (5,5), activation = 'relu')(input_state)
max_pool = MaxPooling2D((2,2))(conv)
#max_pool2 = MaxPooling2D((2,2))(max_pool)
#up_sample2 = UpSampling2D((2,2))(max_pool2)
up_sample = UpSampling2D((2,2))(max_pool)
conv_trans = Conv2DTranspose(1, (5,5), activation = 'sigmoid')(up_sample)
self.encoder = Model(input_state, max_pool)
self.autoencoder = Model(input_state, conv_trans)
self.autoencoder.compile(optimizer=Adam(learning_rate=0.0001, clipnorm=1.0), loss='binary_crossentropy', metrics=['accuracy'])
print(self.autoencoder.summary())
def train_autoencoder(self, pre_training_images: np.array):
"""
Trains the autoencoder given the pre_training_images
"""
print("Training autoencoder...")
train_data, validation_data = train_test_split(pre_training_images, test_size=0.1)
self.autoencoder.fit(train_data, train_data, validation_data=(validation_data, validation_data), verbose = 1, epochs=100, batch_size = 64)
# Using the validation data in order to estimate activation threshold
thresholds_estimate_list = []
for v in validation_data:
encoded_filters = self.encoder.predict(np.expand_dims(v, axis = 0))[0]
highest_activation_features = np.max(encoded_filters, axis = 2)
thresholds_estimate_list.append(np.percentile(highest_activation_features, 90))
self.activation_threshold = np.mean(thresholds_estimate_list)
def render_image(self, state):
#if self.viewer is None:
pygame.init()
self.viewer = pygame.display.set_mode((350, 350))
self.clock = pygame.time.Clock()
s = state
if len(state.shape)==3:
s = duplicate_matrix(duplicate_matrix(np.squeeze(state, axis = 2)))
else:
s = duplicate_matrix(duplicate_matrix(duplicate_matrix(s)))
squeezed_combined_state = s*255
surf = pygame.surfarray.make_surface(squeezed_combined_state).convert_alpha()
pygame.event.poll()
self.viewer.blit(surf, (0, 0))
self.clock.tick(60)
pygame.display.update()
def act(self, state, random_act = True):
Q_values = self.get_Q_total(self.get_state_representation(state))
#print(Q_values)
if random_act:
if np.random.random() < self.epsilon:
return np.random.choice(range(self.action_size))
Q_max = Q_values.max()
Q_max_indexes = [j for j in range(self.action_size) if Q_values[j]==Q_max]
return np.random.choice(Q_max_indexes)
def get_q_value_function(self, i: Interaction):
if i not in self.interactions_Q_functions.keys():
self.interactions_Q_functions[i] = np.zeros(self.action_size)
return self.interactions_Q_functions[i]
def get_state_representation(self, state):
state_string = str(state)
if state_string not in self.states_dict.keys():
self.states_dict[state_string] = self.build_state_representation(state)
return self.states_dict[state_string]
def build_state_representation(self, state):
"""
Builds the state representation
input:
state: np.array
return:
interactions: [Interaction]
"""
detected_entities = self.extract_entities(state)
print('detected ent', len(detected_entities))
n_entities = len(detected_entities)
interactions = set()
for i in range(n_entities-1):
for j in range(i+1, n_entities):
e1 = detected_entities[i]
e2 = detected_entities[j]
if euclidean(e1.position, e2.position) < self.interaction_max_distance:
# Valid interaction
# Sorting entities by their type in order to mantain consistency
se1, se2 = sorted([e1, e2], key = lambda x: x.entity_type.type_number)
x_dist, y_dist = se1.position - se2.position
interactions.add(Interaction(se1.entity_type.type_number, \
se2.entity_type.type_number, x_dist, y_dist))
print('interactions', len(interactions))
return interactions
def get_Q_total(self, interactions):
Q_values = np.zeros(self.action_size)
for i in interactions:
Q_values += self.get_q_value_function(i)
return Q_values
def update(self, state, action, reward, next_state, done):
self.experience_replay_buffer.append((state,action, reward, next_state, done))
if len(self.experience_replay_buffer)> self.batch_size:
batch = random.sample(self.experience_replay_buffer, self.batch_size)
for experience in batch:
self.remember(*experience)
self.epsilon = max(0.1, self.epsilon*self.epsilon_decay)
def remember(self, state, action, reward, next_state, done):
interactions_before = self.get_state_representation(state)
interactions_after = self.get_state_representation(next_state)
Q_before = self.get_Q_total(interactions_before)
Q_after = self.get_Q_total(interactions_after)
td = reward + Q_after.max()- Q_before[action]
for ib in interactions_before:
# Interactions
Q_int = self.get_q_value_function(ib)
Q_int[action] = Q_int[action] + self.lr* td
def extract_entities(self, state: np.array, render_extracted = False):
"""
Extracts the entities and their locations
input:
state: np.array
return:
entities = [Entities]
"""
# Predict Encoded latent spaces
encoded_filters = self.encoder.predict(np.expand_dims(state, axis = 0))[0]
highest_activation_features = np.max(encoded_filters, axis = 2)
#self.activation_threshold = (np.percentile(highest_activation_features, 80) +self.activation_threshold)/2
sufficient_salient_positions = np.argwhere(highest_activation_features > self.activation_threshold)
detected_entities = []
for position in sufficient_salient_positions:
x, y = position
activation_spectra = encoded_filters[x, y, :]
new_entity_type_flag = True
for entity_type in self.entity_types:
if euclidean(entity_type.activation_spectra, activation_spectra) < self.type_distance_threshold:
detected_entities.append(Entity(position, entity_type))
new_entity_type_flag = False
break
if new_entity_type_flag:
# New Entity type detected
new_entity_type = EntityType(activation_spectra , len(self.entity_types))
self.entity_types.append(new_entity_type)
detected_entities.append(Entity(position, new_entity_type))
detected_entities_img = np.zeros(shape = (highest_activation_features.shape))
if render_extracted:
print('original state')
self.render_image(state)
input()
for de in detected_entities:
x,y = de.position
detected_entities_img[x][y] = de.entity_type.type_number* 0.1
print('enitites')
self.render_image(detected_entities_img)
input()
p = self.autoencoder.predict(np.array([state]))[0]
print('reconstructed image')
self.render_image(p)
input()
return detected_entities
def reset(self):
pygame.display.quit()
def save(self, path):
pickle.dump(self.interactions_Q_functions, open(path + '_Q_values', "wb+"))
pickle.dump(self.entity_types, open(path + '_Entity_types', "wb+"))
self.autoencoder.save_weights(path + '_nn_weights')
<file_sep>/components/agent.py
'''
MIT License
Copyright (c) 2017 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
SOURCE: https://github.com/keon/deep-q-learning/blob/master/ddqn.py
'''
import pickle
import random
from collections import deque
import sys
import gc
from scipy import sparse
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import Input, Dense, Conv2D, MaxPooling2D, Flatten
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.models import Model
from tensorflow.keras.losses import MeanSquaredError
class DQNAgent:
def __init__(self, state_dim, action_size, memory_size = 1_000,
gamma = 0.99, init_epsilon = 1.5, final_epsilon = 0.1, epsilon_decay = 0.99999,
lr = 0.00025, update_frequency = 4, batch_size = 32, C = 10_000):
self.state_dim = state_dim
self.action_size = action_size
self.memory = deque(maxlen=memory_size)
self.gamma = gamma # discount rate
self.epsilon = init_epsilon # exploration rate
self.epsilon_min = final_epsilon
self.epsilon_decay = epsilon_decay #0.99998
self.learning_rate = lr
self.update_frequency = update_frequency
self.model = self._build_model()
self.target_model = self._build_model()
self.update_target_model()
self.step = 0
self.C = C
self.batch_size = batch_size
self.loss_function = MeanSquaredError()
self.optimizer = Adam(learning_rate=0.00025, clipnorm=1.0)
self.states_table = dict()
print(self.model.summary())
def _build_model(self):
# Neural Net for Deep-Q learning Model
state_input = Input(shape = self.state_dim)
conv1 = Conv2D(8, (5,5), activation = 'relu')(state_input)
conv2 = Conv2D(8 , (3,3), activation = 'relu') (conv1)
max_pool = MaxPooling2D((2,2))(conv2)
flatten = Flatten()(max_pool)
dense1 = Dense(32, activation = 'relu')(flatten)
"""
dense2 = Dense(128 , activation = 'relu')(state_input)
dense3 = Dense(128, activation = 'relu')(dense2)
dense4 = Dense(128, activation = 'relu')(dense3)
"""
action_output = Dense(self.action_size, activation='linear')(dense1)
model = Model(inputs = state_input, outputs = action_output)
return model
def update_target_model(self):
# copy weights from model to target_model
self.target_model.set_weights(self.model.get_weights())
def remember(self, state, action, reward, next_state, done):
self.memory.append((state, action, reward, next_state, done))
def act(self, state,random_act=True):
if random_act:
if np.random.rand() <= self.epsilon:
return random.randrange(self.action_size)
act_values = self.model.predict(np.array([state]))
else:
act_values = self.model.predict(np.array([state]))
return np.argmax(act_values[0]) # returns action
def replay(self, batch_size):
minibatch = random.sample(self.memory, batch_size)
states, rewards, next_states, actions, dones = [], [], [], [], []
for s, a, r, ns, d in minibatch:
states.append(s)
actions.append(a)
rewards.append(r)
next_states.append(ns)
dones.append(int(d))
states, next_states = np.array(states), np.array(next_states)
rewards = np.array(rewards)
dones = np.array(dones)
future_rewards = self.target_model.predict(next_states)
updated_q_values = rewards + (1-dones) * (self.gamma* np.max(future_rewards, axis = 1))
action_masks = tf.one_hot(actions, self.action_size)
with tf.GradientTape() as tape:
q_values = self.model(states)
q_action = tf.reduce_sum(tf.multiply(q_values, action_masks), axis=1)
loss = self.loss_function(updated_q_values, q_action)
grads = tape.gradient(loss, self.model.trainable_variables)
self.optimizer.apply_gradients(zip(grads, self.model.trainable_variables))
gc.collect()
def update(self, state, action, reward, next_state, done):
self.remember(state, action, reward, next_state, done)
if len(self.memory) > self.batch_size and self.step % self.update_frequency==0:
self.replay(self.batch_size)
self.step +=1
if self.epsilon > self.epsilon_min:
self.epsilon *= self.epsilon_decay
if self.step%self.C == 0:
self.update_target_model()
def load(self, name):
self.model.load_weights(name)
def save(self, name):
self.model.save_weights(name)
class TabularAgent:
'''RL agent as described in the DSRL paper'''
def __init__(self, action_size,alpha,epsilon_decay,neighbor_radius=25):
self.action_size = action_size
self.alpha = alpha
self.epsilon = 1
self.epsilon_decay = epsilon_decay
self.epsilon_min = 0.1
self.gamma = 0.95
self.neighbor_radius=neighbor_radius
self.offset = neighbor_radius*2
self.tables = {}
def act(self, state,random_act=True):
'''
Determines action to take based on given state
State: Array of interactions
(entities in each interaction are presorted by type for consistency)
Returns: action to take, chosen e-greedily
'''
if not random_act:
return np.argmax(self._total_rewards(state))
if np.random.rand() <= self.epsilon:
#print('random action, e:', self.epsilon)
if self.epsilon > self.epsilon_min:
self.epsilon *= self.epsilon_decay
return random.randrange(self.action_size)
if self.epsilon > self.epsilon_min:
self.epsilon *= self.epsilon_decay
return np.argmax(self._total_rewards(state)) # returns action
def update(self, state, action, reward, next_state, done):
'''Update tables based on reward and action taken'''
for interaction in state:
type_1, type_2 = interaction['types_after'] # TODO resolve: should this too be types_before?
table = self.tables.setdefault(type_1, {}).setdefault(type_2, self._make_table())
id1,id2 = interaction['interaction']
interaction_next_state = [inter for inter in next_state if inter['interaction']==(id1,id2)]
if len(interaction_next_state)==0:
continue
elif len(interaction_next_state)>1:
raise ValueError('This should not happen')
else:
#print('Now we should update the Q-values')
#print(f'The current reward is {reward}')
interaction_next_state = interaction_next_state[0]
interaction['loc_difference'] = (interaction['loc_difference'][0]+self.offset,interaction['loc_difference'][1]+self.offset)
interaction_next_state['loc_difference'] = (interaction_next_state['loc_difference'][0]+self.offset,interaction_next_state['loc_difference'][1]+self.offset)
#print(interaction_next_state['loc_difference'])
#print(interaction['loc_difference'])
next_action_value = table[interaction_next_state['loc_difference']]
#print(f'The next action value {next_action_value}')
if done:
table[interaction['loc_difference']][action] = reward
else:
#print(f'Q-value before update {table[interaction["loc_difference"]][action]}')
#print(f'Location {interaction["loc_difference"]}')
#print(f"The new value should be {table[interaction['loc_difference']][action] + self.alpha*(reward + self.gamma * np.max(next_action_value) - table[interaction['loc_difference']][action])}")
#print(interaction['loc_difference'])
table[interaction['loc_difference']][action] = table[interaction['loc_difference']][action] + self.alpha*(reward + self.gamma * np.max(next_action_value) - table[interaction['loc_difference']][action])
#print(f'Q-value after update {table[interaction["loc_difference"]][action]}')
def _total_rewards(self, interactions):
action_rewards = np.zeros(self.action_size)
for interaction in interactions:
type_1, type_2 = interaction['types_before']
table = self.tables.setdefault(type_1, {}).setdefault(type_2, self._make_table())
action_rewards += table[interaction['loc_difference']] # add q-value arrays
return action_rewards
def _make_table(self):
'''
Makes table for q-learning
3-D table: rows = loc_difference_x, cols = loc_difference_y, z = q-values for actions
Rows and cols added to as needed
'''
return np.zeros((self.neighbor_radius * 8, self.neighbor_radius * 8, self.action_size),
dtype=float)
def save(self, filename):
'''Save agent's tables'''
with open(filename, 'wb') as f_p:
pickle.dump(self.tables, f_p)
@staticmethod
def from_saved(filename, action_size):
'''Load agent from filename'''
with open(filename, 'rb') as f_p:
tables = pickle.load(f_p)
ret = TabularAgent(action_size)
assert len(tables.values()[0].values()[0][0, 0]) == action_size, \
'Action size given to from_saved doesn\'t match the one in the tables'
ret.tables = tables
return ret
<file_sep>/cross_circle_gym/envs/__init__.py
from cross_circle_gym.envs.cross_circle_neg_grid import CrossCircleNegGrid
from cross_circle_gym.envs.cross_circle_mixed_grid import CrossCircleMixedGrid
from cross_circle_gym.envs.cross_circle_neg_rand import CrossCircleNegRand
from cross_circle_gym.envs.cross_circle_mixed_rand import CrossCircleMixedRand
<file_sep>/testing_envs.py
import gym
import cross_circle_gym
from components.agent import DQNAgent
import numpy as np
from tqdm import tqdm
from matplotlib import pyplot as plt
env = gym.make("CartPole-v1")
s = env.reset()
agent = DQNAgent(s.shape, env.action_space.n)
rewards = []
epsilons = []
total_rewards = 0
for i in tqdm(range(1_000_000)):
a = agent.act(s)
ns, r, d, info = env.step(a)
#env.render()
total_rewards+= r
agent.update(s,a,r,ns,d)
s = ns
epsilons.append(agent.epsilon)
if i%10_000 == 0:
plt.title('rewards')
plt.plot(rewards)
plt.show()
plt.title('episilons')
plt.plot(epsilons)
plt.show()
if d:
rewards.append(total_rewards)
total_rewards = 0
s = env.reset()<file_sep>/agents/SymbolicAgentExact.py
import random
from collections import namedtuple
from collections import deque
#from scipy.spatial.distance import euclidean
import pickle
import pygame
import numpy as np
from tqdm import tqdm
# namedtuple definitions
EntityType = namedtuple('EntityType', ['activation_spectra', 'type_number'])
Entity = namedtuple('Entity', ['position', 'entity_type'])
Interaction = namedtuple('Interaction', ['entity_type1', 'entity_type2', 'x_dist', 'y_dist'])
# Auxiliary_functions
euclidean = lambda x, y: np.sqrt(np.sum(np.square(np.subtract(x,y))))
np.set_printoptions(threshold=np.inf)
class SymbolicAgentExact:
def __init__(self,action_size: int):
self.action_size = action_size
# RL
self.gamma = 0.99
self.lr = 0.001
self.epsilon = 1
self.epsilon_decay = 0.999995
self.batch_size = 32
# Auxiliary data structures
self.state_Q_functions = {}
self.experience_replay_buffer = deque(maxlen = 1_000)
self.viewer = None
def act(self, state, random_act = True):
Q_values = self.get_q_value_function(self.get_state_representation(state))
#print(Q_values)
if random_act:
if np.random.random() < self.epsilon:
return np.random.choice(range(self.action_size))
Q_max = Q_values.max()
Q_max_indexes = [j for j in range(self.action_size) if Q_values[j]==Q_max]
return np.random.choice(Q_max_indexes)
def get_q_value_function(self, i: str):
if i not in self.state_Q_functions.keys():
self.state_Q_functions[i] = np.zeros(self.action_size)
return self.state_Q_functions[i]
def get_state_representation(self, state):
state_string = hash(str(state))
return state_string
def update(self, state, action, reward, next_state, done):
self.experience_replay_buffer.append((self.get_state_representation(state),action, reward, self.get_state_representation(next_state), done))
if len(self.experience_replay_buffer)> self.batch_size:
batch = random.sample(self.experience_replay_buffer, self.batch_size)
for experience in batch:
self.remember(*experience)
self.epsilon = max(0.1, self.epsilon*self.epsilon_decay)
def remember(self, state, action, reward, next_state, done):
Q_before = self.get_q_value_function(state)
Q_after = self.get_q_value_function(next_state)
td = reward + Q_after.max()- Q_before[action]
Q_before[action] = Q_before[action] + self.lr* td
def reset(self):
pygame.display.quit()
def save(self, path):
pickle.dump(self.state_Q_functions, open(path + '_Q_values', "wb+"))
<file_sep>/dqn_main.py
'''Main module for the paper's algorithm'''
import argparse
import os
from collections import deque
from datetime import datetime
import numpy as np
import tensorflow as tf
import tqdm
from gym import logger
import cross_circle_gym
from components.state_builder import StateRepresentationBuilder
from components.agent import TabularAgent, DQNAgent
from utils import prepare_training
# Experiment Parameters
parser = argparse.ArgumentParser(description=None)
parser.add_argument('--experiment_name', type=str, default='default', help='Name of the experiment')
parser.add_argument('--load', type=str, help='load existing model from filename provided')
parser.add_argument('--image_dir', type=str, help='laod images from directory provided')
parser.add_argument('--episodes', '-e', type=int, default=1000,
help='number of DQN training episodes')
parser.add_argument('--load-train', action='store_true',
help='load existing model from filename provided and keep training')
parser.add_argument('--new-images', action='store_true', help='make new set of training images')
parser.add_argument('--enhancements', action='store_true',
help='activate own improvements over original paper')
parser.add_argument('--visualize', '--vis', action='store_true',
help='plot autoencoder input & output')
parser.add_argument('--save', type=str, help='save model to directory provided')
parser.add_argument('--logdir',type=str,default='./logs', help='Log directory')
parser.add_argument('--log_level',type=str,default='warn',help='Detail of logging output')
parser.add_argument('--evaluation_frequency', type=int, default=100,
help='How often to evaluate the agent')
parser.add_argument('--tensorboard', action='store_true', default=False,
help='Switch on tensorboard for the autoencoder training')
parser.add_argument('--play', action='store_true', default=False,
help='Choose the agents action for 20 timesteps to see what the autoencoder does')
# Environment
parser.add_argument('--random', action='store_true', default=False,
help='Should the position of the entities be random')
parser.add_argument('--double', action='store_true', default=False,
help='Only negative objects (circles) or also positive ones (cross)')
parser.add_argument('--n_entities', type=int, default=16,
help='Number of entities in the environment')
parser.add_argument('--entity_size', type=int, default=10, help='Size of the entities')
parser.add_argument('--neighborhood_size', type=int, default=10,
help='Size of the neighborhood')
parser.add_argument('--step_size', type=float, default=1.0, help='Step-Size')
parser.add_argument('--overlap_factor', type=float, default=0.01,
help='How much must an gent overlap with an entitiy to collect it')
parser.add_argument('--colour_state', action='store_true', default=False,
help='Whether to use the colour image as a state or a one-channel black and white image')
# Training parameters
parser.add_argument('--alpha', type=float, default=0.01, help='Learning Rate')
parser.add_argument('--epsilon_decay', type=float, default=0.99995,
help='Decay rate of epsilon')
parser.add_argument('--timesteps', type=int, default=100, help='Length of a training episode')
# Autoencdoer
parser.add_argument('--filter_size', default=10, type=int, help='Size of the filter')
args = parser.parse_args()
now = datetime.now().strftime("%d_%m_%Y_%H_%M_%S")
args.logdir = os.path.join(args.logdir,args.experiment_name,now)
# Choose environment
if args.random and args.double:
env_id = 'CrossCircle-MixedRand-v0'
elif args.random and not args.double:
env_id = 'CrossCircle-NegRand-v0'
elif not args.random and args.double:
env_id = 'CrossCircle-MixedGrid-v0'
else:
env_id = 'CrossCircle-NegGrid-v0'
args.env_id = env_id
# Set logger
if args.log_level=='warn':
logger.setLevel(logger.WARN)
elif args.log_level=='info':
logger.setLevel(logger.INFO)
else:
raise NotImplementedError('Log-level not implemented')
args.logger = logger
_ ,env = prepare_training(args)
#state_builder = StateRepresentationBuilder(neighbor_radius=args.neighborhood_size)
action_size = env.action_space.n
state_dim = env.reset().shape
agent = DQNAgent(state_dim, action_size)
done = False
time_steps = args.timesteps
number_of_evaluations = 0
buffered_rewards = deque(maxlen=200)
summary_writer = tf.summary.create_file_writer(args.logdir)
for e in tqdm.tqdm(range(args.episodes)):
#state_builder.restart()
state = env.reset()
#state = state_builder.build_state(*autoencoder.get_entities(state))
total_reward = 0
for t in range(time_steps):
action = agent.act(state)
next_state, reward, done, _ = env.step(action)
total_reward += reward
#next_state = state_builder.build_state(*autoencoder.get_entities(next_state))
agent.update(state, action, reward, next_state, done)
state = next_state
if done:
break
env.close()
buffered_rewards.append(total_reward)
with summary_writer.as_default():
tf.summary.scalar('Averaged Reward',np.mean(buffered_rewards),e)
tf.summary.scalar('Epsilon',agent.epsilon,e)
if e % args.evaluation_frequency == 0:
number_of_evaluations += 1
agent.save(os.path.join(args.logdir,'dqn_agent.h5'))
evaluation_reward = []
with summary_writer.as_default():
for i in range(10):
done = False
#state_builder.restart()
image = env.reset()
#state = state_builder.build_state(*autoencoder.get_entities(image))
total_reward = 0
for t in range(time_steps):
action = agent.act(state,random_act=False)
env.render()
next_image, reward, done, _ = env.step(action)
if i==0:
tf.summary.image(f'Agent Behaviour {number_of_evaluations}',np.reshape(image,(1,)+image.shape),t)
total_reward += reward
#next_state = state_builder.build_state(*autoencoder.get_entities(next_image))
state = next_image
image = next_image
evaluation_reward.append(total_reward)
env.close()
tf.summary.scalar('Evaluation Reward',np.mean(evaluation_reward),number_of_evaluations)
<file_sep>/requirements.txt
numpy
gym
sklearn
scipy
keras
matplotlib
pandas
imageio
scikit-image
tensorflowtqdm
| d2e23269e81477e7ff3702321ff84c48eca770cd | [
"Markdown",
"Python",
"Text",
"Shell"
] | 15 | Python | Ferch42/PyDSRL | bd9ea3e739c837db0db5052f7db23476fa21c472 | 14cb5fafc6b0247da432120bcb477e1620838a12 |
refs/heads/master | <file_sep>def square(x):
# define the square function here
return x * x
# remember indentation here
<file_sep>def square(x):
# define the square function here
return x * x
# remember indentation here
for i in range(10):
print(f"The square of {i} is {square(i)}")
# run loop 10 times with a different sqaure value of i using the defined square function
<file_sep><!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>My Website!</title>
</head>
<body>
<h1>More Skyrim</h1>
<p>
The Elder Scrolls V: Skyrim, the 2011 Game of the Year, is the next chapter in the highly anticipated Elder Scrolls saga. Developed by Bethesda Game Studios, the 2011 Studio of the Year, that brought you Oblivion and Fallout 3. Skyrim reimagines and revolutionizes the open-world fantasy epic, bringing to life a complete virtual world open for you to explore any way you choose.
</p>
<p>
The Vampire Lord Harkon has returned to power. By using the Elder Scrolls, he seeks to do the unthinkable - to end the sun itself. Will you join the ancient order of the Dawnguard and stop him? Or will you become a Vampire Lord? In Dawnguard, the ultimate choice will be yours.
</p>
<p>
With this official add-on for The Elder Scrolls V: Skyrim, journey off the coast of Morrowind, to the island of Solstheim. Encounter new towns, dungeons, and quests, as you traverse the ash wastes and glacial valleys of this new land. Become more powerful with shouts that bend the will of your enemies and even tame dragons. Your fate, and the fate of Solstheim, hangs in the balance as you face off against your deadliest adversary – the first Dragonborn.
</p>
<a href="{{ url_for('index') }}">Go back</a>
<!-- url_for is a Jinja function -->
<!-- go back to the url of the index function in the app.py file-->
</body>
</html>
<file_sep># Create an empty set
# A set is a collection where no item appears twice
s = set()
#Add elements to the set
s.add(1)
s.add(2)
s.add(3)
s.add(4)
s.add(3)
print(s)
# even though 3 is added twice, the output is always {1,2,3,4}
# no element can appear twice in a set - mathematical definition
s.remove(2)
#remove an element from a set
print(s)
print(f"The set as {len(s)} elements")
#calculate the length of the set called s
<file_sep>i = 28
# variable i now an integer
print (f"i is {i}")
f = 2.8
# variable f now an float
print (f"f is {f}")
b = False
# variable b now a Bool (Boolean). This has to have Caps (True, False)
print (f"b is {b}")
n = None
# variable n now a None type, i.e to say the variable has not value
print (f"n is {n}")
# so Python doesn't need us to define the type of the variables
<file_sep>from flask import Flask, render_template
# import flask from the Flask module
# import render template
app = Flask(__name__)
# create new web application of type Flask
@app.route("/")
# / means the default page, so when user goes to the default page, the function below is what should run
def index():
# render the index.html file which is inside the templates folder
return render_template("index.html")
<file_sep>name = input("Name: ")
print("Hello, "+ name)
# above is the usual old way of concatenating a variable. Below is a newer way.
print(f"Hello, {name}")
# the f is for formatted strings. Then the name variable is appended in the string in curly braces
<file_sep>names = ["Harry","Ron","Hermoine","Ginny"]
print(names[0])
names.append("Draco")
#add new list element
names.sort()
# existing sort method to sort the values alphabetically, probably can do numbers and decimals as well
print(names)
<file_sep>from flask import Flask
# import flask from the Flask module
app = Flask(__name__)
# create new web application of type Flask
# __name__ means that this current file represents the web application
@app.route("/")
# Flask is designed in terms of routes
# / means the default page, so when user goes to the default page, the function below is what should run
def index():
# this index function just returns the text Hello world
return "Hello, world!"
<file_sep>people = [
# define a people List
# and inside the list we have 3 dictionaries
# python allows us to nest data structures inside other data structures
{"name": "Harry", "house": "Gryffindor"},
{"name": "Cho", "house": "Ravenclaw"},
{"name": "Draco", "house": "Slytherin"}
]
def f(person):
# define a function that takes a person variable as input and then returns that persons name
return person["name"]
# this will help to sort persons by name
# return person["house"] - can help to sort persons by their house
# this function takes any variable passed and returns a dict object name
# if we make it return person("name"), then we get error TypeError: 'dict' object is not callable
people.sort(key=f)
# people.sort() will give this error: TypeError: '<' not supported between instances of 'dict' and 'dict'
# that means python does not know how to sort these dictionaries by default
# so we need to tell the sort function how to sort these dictionaries by defining a function f defined above
# then we can sort by saying people.sort(key=f), i.e. by running the f function
# so we seem to be passing the people list to the function f as the person variable
# then function f will return the person variable (people list) name
# then the sort function will sort the people list+dictionary based on that returned name
people.sort(key=lambda person: person["name"])
# we can define the sort function like this as well
# a lambda is considered as a function
# so this lambda takes a person and returns a person's name
# person is the input of the function and person:["name"] is the output
# to get the above lambda to run, comment out the above f function and the people.sort(key=f)
print(people)
<file_sep>from flask import Flask
# import flask from the Flask module
app = Flask(__name__)
# create new web application of type Flask
# __name__ means that this current file represents the web application
@app.route("/")
# Flask is designed in terms of routes
# / means the default page, so when user goes to the default page, the function below is what should run
def index():
# this index function just returns the text Hello world
return "Hello, world!"
@app.route("/Chamara")
def Chamara():
return "Hello, Chamara!"
# now once we run do flask run
# http://127.0.0.1:5000/Chamara going to this path will call the def Chamara() function
# similarly we can add another route, run flask run and then navigate to that url route
@app.route("/Riah")
def Riah():
return "Hello, Riah!"
<file_sep>import sys
# import the sys library to use the exit method
try:
x = int(input("x: "))
y = int(input("y: "))
except ValueError:
# this is to handle ValueError: invalid literal for int() with base 10, non numeric values
print("Error: Invalid input")
sys.exit(1)
try:
result = x / y
except ZeroDivisionError:
# this is to handle ZeroDivisionError: division by zero
# if we divide a value by zero then we get the above exception
# we will handle this sxception and then print a message and exit
# to exit we use a method from the sys library in python called sys.exit
print("Error: Cannot divide by 0.")
sys.exit(1)
# exit the program with a status code of 1
# status code 1 means something went wrong
print(f"{x} / {y} = {result}")
<file_sep>for i in [0,1,2,3,4,5]:
# this is a for loop in python
print(i)
# remember indentation means the print is part if the for loop
for i in range(6):
# the range method will get a range of 6 numbers
print(i)
names = ["Harry", "Ron", "Hermoine"]
for name in names:
print(name)
oneName = "Harry"
for character in oneName:
print(character)
<file_sep>houses = {"Harry":"Griffindor", "Draco":"Slytherin"}
# dictionary houses is defined as above
# dictionaries can be used to map values to other values; so mapping values like user to info about them, people to houses they live in etc.
# then we can look up the key Harry to get the value Griffindor
print(houses["Harry"])
houses["Hermoine"] = "Griffindor"
# add values to the dictionary
print(houses["Hermoine"])
ages = {"Alice": 22, "Bob": 27}
# dictionary to keep track of ages of people.
# Dictionaries map keyes to values
ages ["Charlie"] = 30
# add name charlie to the dictionary and set the age
ages ["Alice"] += 1
# edit the age of Alice to be incremented by one
# the longer way to write: ages ["Alice"] = ages["Alice"] + 1
print(ages)
<file_sep>class Flight ():
def __init__(self, capacity):
self.capacity = capacity
# we say self.capacity will store the capacity variable value
self.passengers = []
# we say self.passengers will store the list of passengers. The List is empty curently
def add_passenger(self,name):
# we define a new method under the Flight class to add passengers. Note the indentation.
if not self.open_seats():
# if there are no open seats. Its the same as if self.open_seats()==0:
return False
# return false if there are no open seats.
self.passengers.append(name)
# self.passengers has the empty passenger list. We append the value in name variable to that list.
return True
# retuen true if there are open seats.
def open_seats(self):
# we define a new method under Flight class to count open seats. It does not need arguments, so only self is there
return self.capacity-len(self.passengers)
# we subtract the length of the passengers list from the capacity value
flight = Flight(3)
# object flight of type Flight has a capacity of 3
people = ["Harry", "Ron", "Hermoine", "Ginny"]
for person in people:
# loop over every person or x in that people list
success = flight.add_passenger(person)
# for each person do flight.add_passenger(person) and save the result (True/False) in the variable called success
if success:
# this one not sure...?
# apparently it means if success = True
# I think its because True is returned only if self.passengers.append(name) is run
# also we can remove the line success = flight.add_passenger(person)
# and we can just say if flight.add_passenger(person) to make the code optimized
print(f"Added {person} to flight successfully.")
else:
# apparently this means if success = False
# because False is returned only if not self.open_seats() is run
print(f"No available seats for {person}.")
<file_sep>class Point():
# remember a class is a template for a type of object
def __init__(self, input1, input2):
# __init__ is called a magic method
# it will be called each time we try to create a Point object
# the very first argument self represents the object Point we try to create
self.x = input1
# we say self.x to say store the x and y values inside of itself
self.y = input2
# the 2 input values are going to be stored inside self in properties x and y
p = Point(2,8)
# create object p of type Point
# the self argument will be provided automatically, we dont need to specifically state it
print(p.x)
print(p.y)
# we say to prin the x and y values inside the self of the Point object
<file_sep>from functions import square
# import functions
# we can import just functions and the call functions.square
# from functions.py file import the square function
for i in range(10):
print(f"The square of {i} is {square(i)}")
#print(f"The square of {i} is {functions.square(i)}")
# need to call functions.square if we only import functions
# run loop 10 times with a different sqaure value of i using the defined square function
<file_sep>n = int(input("Number: "))
# input by default will return a string, so n = input("Number: ") wont work
# we need to use int function and have the input inside it
if n > 0:
print("n is positive")
# python requires indentation to say its inside the if statement block
elif n < 0:
print("n is negative")
# python uses elif instead of saying elseif
else:
print("n is zero")
<file_sep>from flask import Flask, render_template
# import flask from the Flask module
# import render template
app = Flask(__name__)
# create new web application of type Flask
@app.route("/")
# / means the default page, so when user goes to the default page, the function below is what should run
def index():
headline = "Hello, world!"
# render the index.html file which is inside the templates folder
# also passed an additional argument to the render template function
# this will
return render_template("index.html", headline=headline)
@app.route("/bye")
def bye():
headline = "Goodbye!"
return render_template("index.html", headline=headline)
@app.route("/welcome")
def welcome():
headline = "Welcome!"
return render_template("index.html", headline=headline)
<file_sep>from flask import Flask
# import flask from the Flask module
app = Flask(__name__)
# create new web application of type Flask
# __name__ means that this current file represents the web application
@app.route("/")
# Flask is designed in terms of routes
# / means the default page, so when user goes to the default page, the function below is what should run
def index():
# this index function just returns the text Hello world
return "Hello, world!"
@app.route("/<string:name>")
# when a user goes to a / any name, it will call the hello function
# then pass the name value that the user typed in from the url
def hello(name):
name = name.capitalize()
# this funtion will capitalize the name that we type in the url
return f"<h1>Hello, {name}!<h1>"
<file_sep># python decorators are a way to take a function and modify that function.
# a decorator takes a function as input and returns a modified version of that function as output
# this is possible because pyhton considers functions a just another value, this is called functional programmining paradigm
def announce(f):
# this announce function is going to take a function f as input
def wrapper():
# this function will take function f and wrap it up with some additional behavoir. Therefore thay are ususally called wrapper functions
print("About to run the function...")
# wrapper will print the above line
f()
# then actually run function f
print("Done with the function")
# then print something else
return wrapper
@announce
# this adds the decorator to the hello world function
def hello():
print("Hello, world!")
hello()
# we call hello and that will run the decorator as well
<file_sep>import datetime
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
now = datetime.datetime.now()
# the all_saints variable is a boolean so it returns true or false
# check if month is November and the day is 1st
all_saints = now.month == 11 and now.day == 1
return render_template("index.html", all_saints = all_saints)
<file_sep>name = "Harry"
print(name[0])
print(name[1])
# as shown above we can index into a string
names = ["Harry", "Ron", "Hermoine"]
print(names)
print(names[0])
# we can also index into a list. Lists are mutable
coordinate = (10.0,20.0)
# tuple is a pair of values, we can use these two values as a different humanity
# a tuple is immutable, cannot add values to it
print(coordinate[0])
| aad28826ebae79fad5e4237be0a7282397f648bb | [
"Python",
"HTML"
] | 23 | Python | cgayaan/gitlecture2b | d98730d300d0df9039551b5bfba06857eed2cfd7 | 8317eece5ef18100fbb2ac80e9cee6aca0e7773e |
refs/heads/master | <repo_name>SiriusRU/Unity-2D-Pathfinding-Grid-ECS-Job<file_sep>/README.md
# Pure ECS Burst Job 2D Grid A* Pathfinding

My goal was to create an easy to use high performant example for myself, as well as other people to incorporate into their 2D projects.
[Forum discussion post](https://forum.unity.com/threads/planning-a-2d-grid-pure-ecs-job-burst-pathfinding.724211)
## Why Pure ECS?
The current project I was working on had performance issues, I resolved some by converting my targeting system to pure ECS.
After I made this change I couldn't believe how amazing the performance was, so I wanted to push things to the limit.
My previous pathfinding system was the cause for +70% of the CPU strain, so I was bottlenecked by having too many Agents or too large a Map.
## Why Not use Navmesh?
Unity has not shown any love to 2D in the form of navigation, and until that changes I would rather use something that I can quickly adjust
at runtime without having to do work-arounds or hacks to make compatible.
There are other resources for doing so here: [NavMesh+](https://unitylist.com/p/hqq/Nav-Mesh-Plus)
<file_sep>/Assets/Scripts/TextFade.cs
using UnityEngine;
using UnityEngine.UI;
namespace UnityTemplateProjects
{
[RequireComponent(typeof(Text))]
public class TextFade : UnityEngine.MonoBehaviour
{
public float speed = 0.25f;
public float wait = 3f;
[Space(10)]
public bool fadeIn = false;
public bool fadeOut = false;
[Space(5)]
public bool destroyAfterwards = false;
private Color initialColor;
private Text text;
private CurrentStage currentStage;
private enum CurrentStage
{
fadeIn,
wait,
fadeOut
}
private float waitedAlready = 0;
private void OnEnable()
{
text = GetComponent<Text>();
initialColor = text.color;
if (fadeOut) { currentStage = CurrentStage.fadeOut; }
if (fadeIn)
{
var temp = text.color;
temp.a = 0;
text.color = temp;
currentStage = CurrentStage.fadeIn;
}
}
private void Update()
{
var currentColor = text.color;
if (currentStage == CurrentStage.wait)
{
waitedAlready += Time.deltaTime;
if (waitedAlready >= wait)
{
currentStage = CurrentStage.fadeOut;
}
else
{
return;
}
}
if (fadeIn && currentStage == CurrentStage.fadeIn)
{
var targetAlpha = initialColor.a;
currentColor.a += speed * Time.deltaTime;
text.color = currentColor;
if (currentColor.a >= initialColor.a)
{
if (fadeOut)
{
if(wait <= 0) { currentStage = CurrentStage.fadeOut; }
else { currentStage = CurrentStage.wait; }
return;
}
else
{
Final();
}
}
}
if (fadeOut && currentStage == CurrentStage.fadeOut)
{
if (currentColor.a > 0)
{
currentColor.a -= speed * Time.deltaTime;
text.color = currentColor;
}
else
{
Final();
}
}
}
private void Final()
{
waitedAlready = 0;
if (destroyAfterwards)
{
Destroy(this.gameObject);
}
else
{
text.color = initialColor;
this.gameObject.SetActive(false);
}
}
public void Hide()
{
waitedAlready = wait;
}
}
}<file_sep>/Assets/Scripts/PathfindingSystem.cs
using Unity.Jobs;
using Unity.Transforms;
using Unity.Mathematics;
using Unity.Collections;
using Unity.Entities;
using Unity.Burst;
namespace Pathfinding
{
public class PathfindingSystem : JobComponentSystem
{
NativeArray<Neighbour> neighbours;
EntityQuery pathRequests;
public int IterationLimit = 1000;
public int2 worldSize;
public bool canMoveDiag;
public int numberOfRequests = 0;
protected override void OnCreate()
{
pathRequests = GetEntityQuery(typeof(Waypoint), ComponentType.ReadOnly<PathRequest>(), ComponentType.ReadOnly<Translation>(), ComponentType.ReadOnly<NavigationCapabilities>());
pathRequests.SetFilterChanged(typeof(PathRequest));
if (canMoveDiag)
{
neighbours = new NativeArray<Neighbour>(8, Allocator.Persistent)
{
[0] = new Neighbour(-1, -1), // Bottom left
[1] = new Neighbour(0, -1), // Bottom
[2] = new Neighbour(1, -1), // Bottom Right
[3] = new Neighbour(-1, 0), // Left
[4] = new Neighbour(1, 0), // Right
[5] = new Neighbour(-1, 1), // Top Left
[6] = new Neighbour(0, 1), // Top
[7] = new Neighbour(1, 1), // Top Right
};
}
else
{
neighbours = new NativeArray<Neighbour>(4, Allocator.Persistent)
{
[0] = new Neighbour(0, -1), // Bottom
[1] = new Neighbour(-1, 0), // Left
[2] = new Neighbour(1, 0), // Right
[3] = new Neighbour(0, 1), // Top
};
}
}
protected override void OnDestroy()
{
neighbours.Dispose();
}
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
numberOfRequests = pathRequests.CalculateChunkCount();
if (numberOfRequests == 0) return inputDeps;
//Schedule the findPath to build <Waypoints> Job
FindPathJobChunk findPathJob = new FindPathJobChunk()
{
WaypointChunkBuffer = GetArchetypeChunkBufferType<Waypoint>(false),
PathRequestsChunkComponent = GetArchetypeChunkComponentType<PathRequest>(true),
CellArray = RequiredExtensions.nodes,
TranslationsChunkComponent = GetArchetypeChunkComponentType<Translation>(true),
NavigationCapabilitiesChunkComponent = GetArchetypeChunkComponentType<NavigationCapabilities>(true),
Neighbors = neighbours,
DimY = worldSize.y,
DimX = worldSize.x,
Iterations = IterationLimit,
NeighborCount = neighbours.Length
};
JobHandle jobHandle = findPathJob.Schedule(pathRequests, inputDeps);
return jobHandle;
}
[BurstCompile(FloatPrecision.Low, FloatMode.Fast)]
struct FindPathJobChunk : IJobChunk
{
[ReadOnly] public int DimX;
[ReadOnly] public int DimY;
[ReadOnly] public int Iterations;
[ReadOnly] public int NeighborCount;
[ReadOnly] public NativeArray<Node> CellArray;
[WriteOnly] public ArchetypeChunkBufferType<Waypoint> WaypointChunkBuffer;
[ReadOnly] public ArchetypeChunkComponentType<PathRequest> PathRequestsChunkComponent;
[ReadOnly] public NativeArray<Neighbour> Neighbors;
[ReadOnly] public ArchetypeChunkComponentType<Translation> TranslationsChunkComponent;
[ReadOnly] public ArchetypeChunkComponentType<NavigationCapabilities> NavigationCapabilitiesChunkComponent;
public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
{
int size = DimX * DimY;
BufferAccessor<Waypoint> Waypoints = chunk.GetBufferAccessor(WaypointChunkBuffer);
NativeArray<PathRequest> PathRequests = chunk.GetNativeArray(PathRequestsChunkComponent);
NativeArray<Translation> Translations = chunk.GetNativeArray(TranslationsChunkComponent);
NativeArray<NavigationCapabilities> NavigationCapabilities = chunk.GetNativeArray(NavigationCapabilitiesChunkComponent);
NativeArray<float> CostSoFar = new NativeArray<float>(size * chunk.Count, Allocator.Temp);
NativeArray<int2> CameFrom = new NativeArray<int2>(size * chunk.Count, Allocator.Temp);
NativeMinHeap OpenSet = new NativeMinHeap((Iterations + 1) * Neighbors.Length * chunk.Count, Allocator.Temp);
for (int i = chunkIndex; i < chunk.Count; i++)
{
NativeSlice<float> costSoFar = CostSoFar.Slice(i * size, size);
NativeSlice<int2> cameFrom = CameFrom.Slice(i * size, size);
int openSetSize = (Iterations + 1) * NeighborCount;
NativeMinHeap openSet = OpenSet.Slice(i * openSetSize, openSetSize);
PathRequest request = PathRequests[i];
Translation currentPosition = Translations[i];
NavigationCapabilities capability = NavigationCapabilities[i];
// cache these as they're used a lot
int2 start = currentPosition.Value.xy.FloorToInt();
int2 goal = request.end;
DynamicBuffer<float3> waypoints = Waypoints[i].Reinterpret<float3>();
waypoints.Clear();
// Special case when the start is the same point as the goal
if (start.Equals(goal))
{
// We just set the destination as the goal, but need to get the correct height
int gridIndex = this.GetIndex(goal);
Node node = CellArray[gridIndex];
float3 point = new float3(request.Destination.x, request.Destination.y, node.Height);
waypoints.Add(point);
continue;
}
var stash = new InstanceStash
{
Grid = CellArray,
CameFrom = cameFrom,
CostSoFar = costSoFar,
OpenSet = openSet,
Request = request,
Capability = capability,
CurrentPosition = currentPosition,
Start = start,
Goal = goal,
Waypoints = waypoints,
};
if (this.ProcessPath(ref stash))
this.ReconstructPath(stash);
}
CostSoFar.Dispose();
CameFrom.Dispose();
OpenSet.Dispose();
}
static float H(float2 p0, float2 p1)
{
float dx = p0.x - p1.x;
float dy = p0.y - p1.y;
float sqr = (dx * dx) + (dy * dy);
return math.sqrt(sqr);
}
bool ProcessPath(ref InstanceStash stash)
{
// Push the start to NativeMinHeap openSet
float hh = H(stash.Start, stash.Goal);
MinHeapNode head = new MinHeapNode(stash.Start, hh, hh);
stash.OpenSet.Push(head);
int iterations = this.Iterations;
MinHeapNode closest = head;
// While we still have potential nodes to explore
while (stash.OpenSet.HasNext())
{
MinHeapNode current = stash.OpenSet.Pop();
if (current.DistanceToGoal < closest.DistanceToGoal)
closest = current;
// Found our goal
if (current.Position.Equals(stash.Goal))
return true;
// Path might still be obtainable but we've run out of allowed iterations
if (iterations == 0)
{
if (stash.Request.NavigateToBestIfIncomplete)
{
// Return the best result we've found so far
// Need to update goal so we can reconstruct the shorter path
stash.Goal = closest.Position;
return true;
}
return false;
}
iterations--;
var initialCost = stash.CostSoFar[this.GetIndex(current.Position)];
var fromIndex = this.GetIndex(current.Position);
// Loop our potential cells - generally neighbours but could include portals
for (var i = 0; i < this.Neighbors.Length; i++)
{
var neighbour = this.Neighbors[i];
var position = current.Position + neighbour.Offset;
// Make sure the node isn't outside our grid
if (position.x < 0 || position.x >= this.DimX || position.y < 0 || position.y >= this.DimY)
continue;
var index = this.GetIndex(position);
// Get the cost of going to this cell
var cellCost = this.GetCellCost(stash.Grid, stash.Capability, fromIndex, index, neighbour, true);
// Infinity means the cell is un-walkable, skip it
if (float.IsInfinity(cellCost))
continue;
var newCost = initialCost + (neighbour.Distance * cellCost);
var oldCost = stash.CostSoFar[index];
// If we've explored this cell before and it was a better path, ignore this route
if (!(oldCost <= 0) && !(newCost < oldCost))
continue;
// Update the costing and best path
stash.CostSoFar[index] = newCost;
stash.CameFrom[index] = current.Position;
// Push the node onto our heap
var h = H(position, stash.Goal);
var expectedCost = newCost + h;
stash.OpenSet.Push(new MinHeapNode(position, expectedCost, h));
}
}
if (stash.Request.NavigateToNearestIfBlocked)
{
stash.Goal = closest.Position;
return true;
}
// All routes have been explored without finding a route to destination
return false;
}
void ReconstructPath(InstanceStash stash)
{
var current = stash.CameFrom[this.GetIndex(stash.Goal)];
var from = this.GetPosition(stash.Grid, current);
stash.Waypoints.Add(from);
var next = this.GetPosition(stash.Grid, current);
while (!current.Equals(stash.Start))
{
current = stash.CameFrom[this.GetIndex(current)];
var tmp = next;
next = this.GetPosition(stash.Grid, current);
if (!this.IsWalkable(stash.Grid, from.xy, next.xy))
{
// skip
stash.Waypoints.Add(tmp);
from = tmp;
}
}
stash.Waypoints.Reverse();
stash.Request.fufilled = true;
}
bool IsWalkable(NativeArray<Node> buffer, float2 from, float2 to)
{
const float step = 0.25f;
var vector = to - from;
var length = math.length(vector);
var unit = vector / length;
var iterations = length / step;
var currentCell = buffer[this.GetIndex(from.FloorToInt())];
for (var i = 0; i < iterations; i++)
{
var point = (i * step * unit) + from;
var index = this.GetIndex(point.FloorToInt());
var cell = buffer[index];
if (cell.Obstacle)
return false;
if (cell.Height != currentCell.Height)
return false;
}
return true;
}
float GetCellCost(NativeArray<Node> grid, NavigationCapabilities capabilities, int fromIndex, int toIndex, Neighbour neighbour, bool areNeighbours)
{
var target = grid[toIndex];
if (target.Obstacle)
return float.PositiveInfinity;
// If we're not neighbours, then we're a portal and can just go straight there
if (!areNeighbours)
return 1;
var from = grid[fromIndex];
var heightDiff = target.Height - from.Height;
var absDiff = math.abs(heightDiff);
// TODO Should precompute this
var dropHeight = 0;
var climbHeight = 0;
if (heightDiff > 0)
climbHeight = absDiff;
else
dropHeight = absDiff;
var slope = math.degrees(math.atan(absDiff / neighbour.Distance));
// TODO End precompute
if ((capabilities.MaxClimbHeight < climbHeight || capabilities.MaxDropHeight < dropHeight)
&& capabilities.MaxSlopeAngle < slope)
return float.PositiveInfinity;
return 1;
}
float3 GetPosition(NativeArray<Node> grid, int2 point)
{
var index = this.GetIndex(point);
var cell = grid[index];
var fPoint = point + new float2(0.5f, 0.5f);
return new float3(fPoint.x, fPoint.y, cell.Height);
}
int GetIndex(int2 i)
{
if (DimY >= DimX)
return (i.x * DimY) + i.y;
else
return (i.y * DimX) + i.x;
}
struct InstanceStash
{
public Translation CurrentPosition;
public PathRequest Request;
public NavigationCapabilities Capability;
public DynamicBuffer<float3> Waypoints;
public int2 Start;
public int2 Goal;
public NativeArray<Node> Grid;
public NativeSlice<float> CostSoFar;
public NativeSlice<int2> CameFrom;
public NativeMinHeap OpenSet;
}
}
}
}<file_sep>/Assets/Scripts/Editor/PathfindingManagerEditor.cs
using UnityEngine;
using UnityEditor;
namespace Pathfinding
{
[CustomEditor(typeof(PathfindingManager))]
//[CanEditMultipleObjects]
public class InitializerEditor : Editor
{
PathfindingManager PathfindingManager => (PathfindingManager)target;
SerializedProperty numberOfRandomPaths => serializedObject.FindProperty("randomPathsCount");
SerializedProperty startManualPath => serializedObject.FindProperty("start");
SerializedProperty endManualPath => serializedObject.FindProperty("end");
SerializedProperty numberOfBlocksToAdd => serializedObject.FindProperty("randomObstaclesCount");
SerializedProperty manualBlockNode => serializedObject.FindProperty("obstacleNode");
SerializedProperty size;
SerializedProperty cellMaterial => serializedObject.FindProperty("nodeMaterial");
SerializedProperty cellBlockedMaterial => serializedObject.FindProperty("obstacleMaterial");
SerializedProperty instancedMeshWalkable => serializedObject.FindProperty("walkableMesh");
SerializedProperty instancedMeshBlocked => serializedObject.FindProperty("obstacleMesh");
SerializedProperty instancedSpacing => serializedObject.FindProperty("gridSpacing");
SerializedProperty instancedScale => serializedObject.FindProperty("gridScale");
SerializedProperty noiseLevel => serializedObject.FindProperty("noiseLevel");
SerializedProperty noiseScale => serializedObject.FindProperty("noiseScale");
SerializedProperty gizmoPathColor => serializedObject.FindProperty("gizmoPathColor");
SerializedProperty visualMode => serializedObject.FindProperty("visualMode");
bool showBlocked;
bool showPathTesting;
bool showInstancing;
bool showGizmo;
private GUIStyle title;
private GUIStyle foldout;
private void OnEnable()
{
title = new GUIStyle(GUIStyle.none);
title.fontStyle = FontStyle.Bold;
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
EditorGUILayout.Space();
showBlocked = EditorGUILayout.Foldout(showBlocked, "Obstacles");
if (showBlocked)
ShowBlockedNodes();
showPathTesting = EditorGUILayout.Foldout(showPathTesting, "Path Testing");
if (showPathTesting)
ShowPathTesting();
EditorGUILayout.Space();
int mode = visualMode.intValue;
if (mode != 1)
{
showGizmo = EditorGUILayout.Foldout(showGizmo, "Display (Gizmo)");
if (showGizmo)
ShowGizmoSettings();
}
if (mode != 0)
{
showInstancing = EditorGUILayout.Foldout(showInstancing, "Display (Instancing)");
if (showInstancing)
ShowInstancingSettings();
}
}
void ShowBlockedNodes()
{
EditorGUILayout.LabelField("Additional Obstacles", title);
EditorGUILayout.PropertyField(numberOfBlocksToAdd, new GUIContent("Count"));
if (GUILayout.Button($"Add Random Obstacles ({numberOfBlocksToAdd.intValue})")) PathfindingManager.SetRandomObstacles();
EditorGUILayout.Space();
EditorGUILayout.LabelField("Single Obstacle At Position", title);
EditorGUILayout.PropertyField(manualBlockNode, new GUIContent("Position"));
if (GUILayout.Button("Add Obstacle"))
PathfindingManager.AddObstacleManually();
EditorGUILayout.Space();
EditorGUILayout.LabelField("Perlin Noise", title);
EditorGUILayout.PropertyField(noiseLevel, new GUIContent("Noise Level"));
EditorGUILayout.PropertyField(noiseScale, new GUIContent("Noise Scale"));
if (GUILayout.Button("Generate")) PathfindingManager.GenerateObstaclesWithPerlinNoise();
if (GUILayout.Button("Clear Obstacles Map")) PathfindingManager.ClearObstaclesMap();
serializedObject.ApplyModifiedProperties();
}
void ShowPathTesting()
{
EditorGUILayout.LabelField("Random Paths", title);
EditorGUILayout.PropertyField(numberOfRandomPaths, new GUIContent("Count"));
if (GUILayout.Button($"Add Additional Paths ({numberOfRandomPaths.intValue})")) PathfindingManager.AddRandomPaths();
EditorGUILayout.Space();
EditorGUILayout.LabelField("Custom Path", title);
EditorGUILayout.PropertyField(startManualPath, new GUIContent("Start Node"));
EditorGUILayout.PropertyField(endManualPath, new GUIContent("End Node"));
if (GUILayout.Button("Add Path Manually")) PathfindingManager.AddPathManually();
serializedObject.ApplyModifiedProperties();
}
void ShowInstancingSettings()
{
EditorGUILayout.LabelField("Materials", title);
EditorGUILayout.PropertyField(cellMaterial, new GUIContent("Walkable Cells"));
EditorGUILayout.PropertyField(cellBlockedMaterial, new GUIContent("Blocked Cells"));
EditorGUILayout.Space();
EditorGUILayout.LabelField("Geometry", title);
EditorGUILayout.PropertyField(instancedMeshWalkable, new GUIContent("Cell Mesh"));
EditorGUILayout.PropertyField(instancedMeshBlocked, new GUIContent("Obstacle Mesh"));
EditorGUILayout.Space();
EditorGUILayout.LabelField("Position", title);
EditorGUILayout.PropertyField(instancedScale, new GUIContent("Scale"));
EditorGUILayout.PropertyField(instancedSpacing, new GUIContent("Spacing"));
EditorGUILayout.Space();
if (GUILayout.Button("Apply Scale and Spacing"))
{
PathfindingManager.UpdateMatrices();
PathfindingManager.UpdatePathsDisplay();
}
if (GUILayout.Button("Update Paths Display"))
PathfindingManager.UpdatePathsDisplay();
serializedObject.ApplyModifiedProperties();
}
void ShowGizmoSettings()
{
EditorGUILayout.PropertyField(gizmoPathColor, new GUIContent("Gizmo Path Color"));
serializedObject.ApplyModifiedProperties();
}
}
}<file_sep>/Assets/Scripts/NativeMinHeap.cs
namespace Pathfinding
{
using System;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Mathematics;
[NativeContainerSupportsDeallocateOnJobCompletion]
[NativeContainer]
public unsafe struct NativeMinHeap : IDisposable
{
private readonly Allocator allocator;
[NativeDisableUnsafePtrRestriction]
private void* buffer;
private int capacity;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
private AtomicSafetyHandle m_Safety;
[NativeSetClassTypeToNullOnSchedule]
private DisposeSentinel m_DisposeSentinel;
#endif
private int head;
private int length;
/// <summary>
/// Initializes a new instance of the <see cref="NativeMinHeap"/> struct.
/// </summary>
/// <param name="capacity"> The capacity of the min heap. </param>
/// <param name="allocator"> The allocator. </param>
/// <exception cref="ArgumentOutOfRangeException"> Thrown if allocator not set, capacity is negative or the size > maximum integer value. </exception>
public NativeMinHeap(int capacity, Allocator allocator)
{
var size = (long)UnsafeUtility.SizeOf<MinHeapNode>() * capacity;
if (allocator <= Allocator.None)
{
throw new ArgumentException("Allocator must be Temp, TempJob or Persistent", nameof(allocator));
}
if (capacity < 0)
{
throw new ArgumentOutOfRangeException(nameof(capacity), "Length must be >= 0");
}
if (size > int.MaxValue)
{
throw new ArgumentOutOfRangeException(
nameof(capacity),
$"Length * sizeof(T) cannot exceed {int.MaxValue} bytes");
}
this.buffer = UnsafeUtility.Malloc(size, UnsafeUtility.AlignOf<MinHeapNode>(), allocator);
this.capacity = capacity;
this.allocator = allocator;
this.head = -1;
this.length = 0;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
DisposeSentinel.Create(out this.m_Safety, out this.m_DisposeSentinel, 1, allocator);
#endif
}
/// <summary>
/// Does the heap still have remaining nodes.
/// </summary>
/// <returns>
/// True if the min heap still has at least one remaining node, otherwise false.
/// </returns>
public bool HasNext()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(this.m_Safety);
#endif
return this.head >= 0;
}
/// <summary>
/// Add a node to the heap which will be sorted.
/// </summary>
/// <param name="node"> The node to add. </param>
/// <exception cref="IndexOutOfRangeException"> Throws if capacity reached. </exception>
public void Push(MinHeapNode node)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (this.length == this.capacity)
{
throw new IndexOutOfRangeException("Capacity Reached");
}
AtomicSafetyHandle.CheckReadAndThrow(this.m_Safety);
#endif
if (this.head < 0)
{
this.head = this.length;
}
else if (node.ExpectedCost < this.Get(this.head).ExpectedCost)
{
node.Next = this.head;
this.head = this.length;
}
else
{
var currentPtr = this.head;
var current = this.Get(currentPtr);
while (current.Next >= 0 && this.Get(current.Next).ExpectedCost <= node.ExpectedCost)
{
currentPtr = current.Next;
current = this.Get(current.Next);
}
node.Next = current.Next;
current.Next = this.length;
UnsafeUtility.WriteArrayElement(this.buffer, currentPtr, current);
}
UnsafeUtility.WriteArrayElement(this.buffer, this.length, node);
this.length += 1;
}
/// <summary>
/// Take the top node off the heap.
/// </summary>
/// <returns>The current node of the heap.</returns>
public MinHeapNode Pop()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndThrow(this.m_Safety);
#endif
var result = this.head;
this.head = this.Get(this.head).Next;
return this.Get(result);
}
/// <summary>
/// Clear the heap by resetting the head and length.
/// </summary>
/// <remarks>Does not clear memory.</remarks>
public void Clear()
{
this.head = -1;
this.length = 0;
}
/// <summary>
/// Dispose of the heap by freeing up memory.
/// </summary>
/// <exception cref="InvalidOperationException"> Memory hasn't been allocated. </exception>
public void Dispose()
{
if (!UnsafeUtility.IsValidAllocator(this.allocator))
{
return;
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
DisposeSentinel.Dispose(ref this.m_Safety, ref this.m_DisposeSentinel);
#endif
UnsafeUtility.Free(this.buffer, this.allocator);
this.buffer = null;
this.capacity = 0;
}
public NativeMinHeap Slice(int start, int length)
{
var stride = UnsafeUtility.SizeOf<MinHeapNode>();
return new NativeMinHeap()
{
buffer = (byte*)((IntPtr)this.buffer + stride * start),
capacity = length,
length = 0,
head = -1,
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = this.m_Safety,
#endif
};
}
private MinHeapNode Get(int index)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (index < 0 || index >= this.length)
{
this.FailOutOfRangeError(index);
}
AtomicSafetyHandle.CheckReadAndThrow(this.m_Safety);
#endif
return UnsafeUtility.ReadArrayElement<MinHeapNode>(this.buffer, index);
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
private void FailOutOfRangeError(int index)
{
throw new IndexOutOfRangeException($"Index {index} is out of range of '{this.capacity}' Length.");
}
#endif
}
/// <summary>
/// The min heap node.
/// </summary>
public struct MinHeapNode
{
/// <summary>
/// Initializes a new instance of the <see cref="MinHeapNode"/> struct.
/// </summary>
/// <param name="position"> The position. </param>
/// <param name="expectedCost"> The expected cost. </param>
/// <param name="distanceToGoal">Remaining distance to the goal</param>
public MinHeapNode(int2 position, float expectedCost, float distanceToGoal)
{
this.Position = position;
this.ExpectedCost = expectedCost;
this.DistanceToGoal = distanceToGoal;
this.Next = -1;
}
/// <summary>
/// Gets the position.
/// </summary>
public int2 Position { get; }
/// <summary>
/// Gets the expected cost.
/// </summary>
public float ExpectedCost { get; }
/// <summary>
/// Gets the expected cost.
/// </summary>
public float DistanceToGoal { get; }
/// <summary>
/// Gets or sets the next node in the heap.
/// </summary>
public int Next { get; set; }
}
}<file_sep>/Assets/Scripts/PathfindingManager.cs
using System;
using System.IO;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
using UnityEngine.Rendering;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using Random = UnityEngine.Random;
namespace Pathfinding
{
[RequireComponent(typeof(PathRenderer))]
public class PathfindingManager : MonoBehaviour
{
public VisualMode visualMode;
[Range(0, 2500)] public int iterationLimit = 1000; //How long path could be calculated. Higher values might affect performance.
public int2 size;
[Space(5)]
public bool showGrid;
public bool showPaths;
public bool canMoveDiag;
[HideInInspector] public Color gizmoPathColor;
//Manual Path
[HideInInspector] public Vector2Int start;
[HideInInspector] public Vector2Int end;
//Random Path
[HideInInspector] public int randomPathsCount;
//Manual obstacles creation.
List<int2> obstacleNodes = new List<int2>();
[HideInInspector] public Vector2Int obstacleNode;
private List<Vector3> obstaclesToAdd = new List<Vector3>();
//Purely random obstacles.
[HideInInspector] public int randomObstaclesCount = 200;
//Instancing settings.
[HideInInspector] public Material nodeMaterial;
[HideInInspector] public Material obstacleMaterial;
[HideInInspector] public Mesh walkableMesh;
[HideInInspector] public Mesh obstacleMesh;
[HideInInspector] public float gridSpacing = 1.1f;
[HideInInspector] public float gridScale = 1;
//Perlin noise settings.
[HideInInspector] public float noiseLevel = 0.35f;
[HideInInspector] public float noiseScale = 10;
private const int instancesLimit = 1023; //DrawMeshInstanced can only draw a maximum of 1023 instances at once.
private Matrix4x4[][] matricesWalkable;
private Matrix4x4[][] matricesObstacles;
private PathRenderer pathRenderer; //Pool with LineRenderers.
private EntityManager entityManager;
private PathfindingSystem pathfindingSystem;
private bool pathfindingNow = false; //Equal to true when pathfinding happening and allows pathRenderer to update when becoming false.
private int previousSize; //Last obstacles map size.
private void OnEnable()
{
pathRenderer = GetComponent<PathRenderer>();
pathfindingSystem = World.Active.GetExistingSystem<PathfindingSystem>();
entityManager = World.Active.EntityManager;
pathfindingSystem.canMoveDiag = canMoveDiag;
CreateGrid();
GenerateObstaclesWithPerlinNoise();
}
private void Update()
{
//Instancing.
if (visualMode == VisualMode.Instancing || visualMode == VisualMode.Both)
{
if (showGrid) DisplayGrid();
}
//Check if pathfinding is happening.
if (pathfindingSystem.numberOfRequests > 0)
{
pathfindingNow = true;
}
else if (pathfindingNow)
{
pathfindingNow = false;
UpdatePathsDisplay();
}
}
private void OnValidate()
{
if (Application.isPlaying == false || pathfindingSystem == null)
return;
pathfindingSystem.IterationLimit = iterationLimit;
if(size.x * size.y != previousSize)
{
CreateGrid();
}
if(!showPaths) pathRenderer.Clear();
}
private void OnDisable()
{
RequiredExtensions.nodes.Dispose();
}
//Display grid info with instancing.
private void DisplayGrid()
{
//Walkable nodes might be replaced with single large quad.
for (int i = 0; i < matricesWalkable.Length; i++)
{
Graphics.DrawMeshInstanced(walkableMesh, 0, nodeMaterial,
matricesWalkable[i], matricesWalkable[i].Length, null, ShadowCastingMode.Off);
}
for (int i = 0; i < matricesObstacles.Length; i++)
{
Graphics.DrawMeshInstanced(obstacleMesh, 0, obstacleMaterial,
matricesObstacles[i], matricesObstacles[i].Length);
}
}
//Update transform data for instances and split it. Must be called every time grid is changed.
public void UpdateMatrices()
{
var nodes = RequiredExtensions.nodes;
//Initially it's unknown how much of blocked nodes there is, so let's just count them,
//so we could render them separately later.
List<Queue<Matrix4x4>> queueMatricesWalkable = new List<Queue<Matrix4x4>>();
List<Queue<Matrix4x4>> queueMatricesObstacles = new List<Queue<Matrix4x4>>();
int walkableCount = 0;
int walkableListIndex = 0;
int obstaclesCount = 0;
int obstaclesListIndex = 0;
queueMatricesWalkable.Add(new Queue<Matrix4x4>());
queueMatricesObstacles.Add(new Queue<Matrix4x4>());
Vector3 position = new Vector3(0, 0, 0);
Vector3 scale = new Vector3(gridScale, gridScale, gridScale);
float spacing = (gridSpacing * gridScale); //Make node spacing relative to established in inspector scale.
for (int x = 0; x < size.x; x++)
for (int y = 0; y < size.y; y++)
{
position.x = x * spacing;
position.y = y * spacing;
position.z = 0;
var obstacle = nodes[GetIndex(new int2(x, y))].Obstacle;
//Add a matrix to the queue at corresponding list, since nodes are use different materials marking it's type.
if (!obstacle)
{
queueMatricesWalkable[walkableListIndex].Enqueue(Matrix4x4.TRS(position, Quaternion.identity, scale));
walkableCount++;
//If we get to the limit, then add and use next queue.
if (walkableCount >= instancesLimit)
{
walkableCount = 0;
walkableListIndex++;
queueMatricesWalkable.Add(new Queue<Matrix4x4>());
}
}
else
{
queueMatricesObstacles[obstaclesListIndex].Enqueue(Matrix4x4.TRS(position, Quaternion.identity, scale));
obstaclesCount++;
if (obstaclesCount >= instancesLimit)
{
obstaclesCount = 0;
obstaclesListIndex++;
queueMatricesObstacles.Add(new Queue<Matrix4x4>());
}
}
}
//Finally convert everything to the array of arrays.
walkableListIndex++;
obstaclesListIndex++;
matricesWalkable = new Matrix4x4[walkableListIndex][];
matricesObstacles = new Matrix4x4[obstaclesListIndex][];
for (int i = 0; i < walkableListIndex; i++) matricesWalkable[i] = queueMatricesWalkable[i].ToArray();
for (int i = 0; i < obstaclesListIndex; i++) matricesObstacles[i] = queueMatricesObstacles[i].ToArray();
}
public void UpdatePathsDisplay()
{
if (showPaths)
{
DisplayPaths();
}
else
{
pathRenderer.Clear();
}
}
public void SetNodeWalkable(int2 position)
{
var nodes = RequiredExtensions.nodes;
nodes[GetIndex(position)] = new Node { obstacle = Convert.ToByte(false), Height = 0 };
}
public void SetObstacle(int2 position)
{
var nodes = RequiredExtensions.nodes;
nodes[GetIndex(position)] = new Node {obstacle = Convert.ToByte(true), Height = 0};
obstacleNodes.Clear();
UpdateMatrices();
}
public void GenerateObstaclesWithPerlinNoise()
{
//Clear existing map and pathdinding.
ClearPathfinders();
ClearObstaclesMap(updateMatrices: false);
float randomization = Random.value * 10000; //Offset perlin noise with this value to give it different look each time.
var nodes = RequiredExtensions.nodes;
float2 scale = (new float2(1f / size.x, 1f / size.y) * noiseScale);
for (int y = 0; y < size.y; y++)
for (int x = 0; x < size.x; x++)
{
bool obstacle = Mathf.PerlinNoise((scale.x * x) + randomization, (scale.y * y)) <= noiseLevel;
nodes[GetIndex(new int2(x, y))] = new Node { obstacle = Convert.ToByte(obstacle), Height = 0 };
}
UpdateMatrices();
}
public void ClearObstaclesMap(bool updateMatrices = true)
{
var nodes = RequiredExtensions.nodes;
for (int y = 0; y < size.y; y++)
for (int x = 0; x < size.x; x++)
{
nodes[GetIndex(new int2(x, y))] = new Node { obstacle = Convert.ToByte(false), Height = 0 };
}
if(updateMatrices) UpdateMatrices();
}
public void SetRandomObstacles()
{
var nodes = RequiredExtensions.nodes;
for (int i = 0; i < randomObstaclesCount; i++)
{
int2 targetNode = new int2(Random.Range(0, size.x), Random.Range(0, size.y));
int randomNode = GetIndex(targetNode);
nodes[randomNode] = new Node { obstacle = Convert.ToByte(true), Height = 0 };
}
UpdateMatrices();
}
public void ClearPathfinders()
{
var query = entityManager.CreateEntityQuery(ComponentType.ReadOnly<Waypoint>());
entityManager.DestroyEntity(query);
pathRenderer.Clear();
}
//Display existing paths with provided line renderer.
private void DisplayPaths()
{
var query = entityManager.CreateEntityQuery(ComponentType.ReadOnly<Waypoint>());
if (query.CalculateEntityCount() > 0)
{
var actualGroup = query.ToEntityArray(Unity.Collections.Allocator.TempJob);
pathRenderer.Clear();
float spacing = (gridSpacing * gridScale); //Make node spacing relative to established in inspector scale.
float3 offset = new Vector3(spacing * .5f, spacing * .5f, 0); //Ground path at the center of nodes.
foreach (Entity entity in actualGroup)
{
var pathRequest = entityManager.GetComponentData<PathRequest>(entity);
var buffer = entityManager.GetBuffer<Waypoint>(entity);
var lineRenderer = pathRenderer.GetLineRenderer();
Queue<Vector3> positions = new Queue<Vector3>();
float3 start = (new float3(pathRequest.start.x, pathRequest.start.y, 0) * spacing);
float3 end = (new float3(pathRequest.end.x, pathRequest.end.y, 0) * spacing) - offset;
positions.Enqueue(start);
if (buffer.Length > 0)
{
for (int i = 0; i < buffer.Length; i++)
{
positions.Enqueue(((buffer[i].waypoints) * spacing) - offset);
}
}
lineRenderer.positionCount = positions.Count;
lineRenderer.SetPositions(positions.ToArray());
}
actualGroup.Dispose();
}
}
public void CreateSearcher(int2 start, int2 end)
{
var pathSearcher = entityManager.CreateEntity(typeof(PathRequest), typeof(Translation), typeof(NavigationCapabilities));
var translation = entityManager.GetComponentData<Translation>(pathSearcher);
translation.Value = new float3(start.x, start.y, 0);
entityManager.SetComponentData<Translation>(pathSearcher, translation);
entityManager.AddBuffer<Waypoint>(pathSearcher);
PathRequest pathRequest = new PathRequest
{
Entity = pathSearcher,
start = start,
end = end,
Destination = NodeToWorldPosition(end),
NavigateToBestIfIncomplete = true,
NavigateToNearestIfBlocked = true
};
entityManager.SetComponentData(pathSearcher, pathRequest);
}
public void CreateGrid()
{
if(RequiredExtensions.nodes.IsCreated)
RequiredExtensions.nodes.Dispose();
RequiredExtensions.nodes = new Unity.Collections.NativeArray<Node>(size.x * size.y, Unity.Collections.Allocator.Persistent);
previousSize = size.x * size.y;
for (int y = 0; y < size.y; y++)
for (int x = 0; x < size.x; x++)
{
Node node = new Node
{
obstacle = Convert.ToByte(obstacleNodes.Contains(new int2(x, y)))
};
RequiredExtensions.nodes[GetIndex(new int2(x, y))] = node;
}
World.Active.GetExistingSystem<PathfindingSystem>().worldSize = size;
UpdateMatrices();
}
public void SaveToFile()
{
string path = Application.dataPath + "/PathfindingSave";
var nodes = RequiredExtensions.nodes;
BinaryFormatter serializer = new BinaryFormatter();
var fileStream = File.Create(Application.dataPath + "/PathfindingSave");
int count = nodes.Length;
SaveData saveData = new SaveData()
{
iterationLimit = iterationLimit,
start = new SerializableInt2(start.x, start.y),
end = new SerializableInt2(end.x, end.y),
size = new SerializableInt2(size.x, size.y),
nodes = new byte[count]
};
for (int i = 0; i < count; i++)
saveData.nodes[i] = nodes[i].obstacle;
serializer.Serialize(fileStream, saveData);
fileStream.Close();
Debug.Log("Saved to " + path);
}
public void LoadFromFile()
{
string path = Application.dataPath + "/PathfindingSave";
if (File.Exists(path))
{
BinaryFormatter serializer = new BinaryFormatter();
var fileStream = File.Open(path, FileMode.Open);
SaveData saveData = (SaveData) serializer.Deserialize(fileStream);
fileStream.Close();
iterationLimit = saveData.iterationLimit;
start = new Vector2Int(saveData.start.x, saveData.start.y);
end = new Vector2Int(saveData.end.x, saveData.end.y);
size = new int2(saveData.size.x, saveData.size.y);
CreateGrid();
var nodes = RequiredExtensions.nodes;
int count = saveData.nodes.Length;
for (int i = 0; i < count; i++)
nodes[i] = new Node { Height = 0, obstacle = saveData.nodes[i] };
ClearPathfinders();
UpdateMatrices();
Debug.Log("Loaded.");
}
}
public void AddObstacleManually()
{
SetObstacle(new int2(obstacleNode.x, obstacleNode.y));
}
public void AddPathManually()
{
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
{
for (int i = 0; i < randomPathsCount; i++)
{
CreateSearcher(new int2(start.x, start.y), new int2(end.x, end.y));
}
}
else
{
CreateSearcher(new int2(start.x, start.y), new int2(end.x, end.y));
}
}
public void AddRandomPaths()
{
var nodes = RequiredExtensions.nodes;
for (int i = 0; i < randomPathsCount; i++)
{
int2 startPosition = new int2(Random.Range(0, size.x), Random.Range(0, size.y));
if (nodes[GetIndex(startPosition)].Obstacle) continue;
int2 endPosition = new int2(Random.Range(0, size.x), Random.Range(0, size.y));
CreateSearcher(startPosition, endPosition);
}
}
void OnDrawGizmos()
{
if ((visualMode == VisualMode.Instancing) || (!showGrid && !showPaths)) return;
if (Application.isPlaying)
{
if (showGrid && size.x * size.y == previousSize)
{
var nodes = RequiredExtensions.nodes;
for (int y = 0; y < size.y; y++)
for (int x = 0; x < size.x; x++)
{
Gizmos.color = nodes[GetIndex(new int2(x, y))].Obstacle ? Color.grey : Color.white;
Gizmos.DrawCube(NodeToWorldPosition(new int2(x, y)), new Vector3(.90f, .90f));
}
}
if (showPaths)
{
var query = entityManager.CreateEntityQuery(ComponentType.ReadOnly<Waypoint>());
if (query.CalculateEntityCount() > 0)
{
var actualGroup = query.ToEntityArray(Unity.Collections.Allocator.TempJob);
foreach (Entity entity in actualGroup)
{
var buffer = entityManager.GetBuffer<Waypoint>(entity);
if (buffer.Length > 0)
{
Gizmos.color = gizmoPathColor;
for (int i = 0; i < buffer.Length - 1; i++)
{
Gizmos.DrawLine(buffer[i].waypoints - .5f, buffer[i + 1].waypoints - .5f);
}
}
}
actualGroup.Dispose();
}
}
}
}
[Serializable]
private struct SaveData
{
public int iterationLimit;
public SerializableInt2 start;
public SerializableInt2 end;
public SerializableInt2 size;
public byte[] nodes;
}
[Serializable]
private struct SerializableInt2
{
public int x;
public int y;
public SerializableInt2(int x, int y)
{
this.x = x;
this.y = y;
}
}
//Display method.
public enum VisualMode { Gizmo, Instancing, Both };
public float3 NodeToWorldPosition(int2 i) => new float3(i.x, i.y, 0);
//Job system uses only linear arrays, but we can convert two-dimensional index to linear one like that.
int GetIndex(int2 i)
{
if (size.y >= size.x)
return (i.x * size.y) + i.y;
else
return (i.y * size.x) + i.x;
}
int GetIndex(int x, int y)
{
if (size.y >= size.x)
return (x * size.y) + y;
else
return (y * size.x) + x;
}
}
}
//Making better testing workflow.
//Research
//TODO Check deadlock at high obstacles density and with negative values in path positions.
//TODO Check for simulation of multiple grids at once.
<file_sep>/Assets/Scripts/RequiredExtensions.cs
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
namespace Pathfinding
{
public static class RequiredExtensions
{
public static NativeArray<Node> nodes;
public static void Reverse<T>(this DynamicBuffer<T> buffer)
where T : struct
{
var length = buffer.Length;
var index1 = 0;
for (var index2 = length - 1; index1 < index2; --index2)
{
var obj = buffer[index1];
buffer[index1] = buffer[index2];
buffer[index2] = obj;
++index1;
}
}
public static int2 FloorToInt(this float2 f2) => (int2)math.floor(f2);
}
}<file_sep>/Assets/Scripts/Components.cs
using UnityEngine;
using UnityEditor;
using Unity.Entities;
using Unity.Mathematics;
using System;
namespace Pathfinding
{
public struct PathRequest : IComponentData
{
public Entity Entity;
public int2 start;
public int2 end;
public float3 Destination;
public bool NavigateToNearestIfBlocked;
public bool NavigateToBestIfIncomplete;
public bool fufilled;
}
public struct Neighbour
{
public readonly float Distance;
public readonly int2 Offset;
public Neighbour(int x, int y)
{
if (x < -1 || x > 1)
{
throw new ArgumentOutOfRangeException(
nameof(x),
$"Parameter {nameof(x)} cannot have a magnitude larger than one");
}
if (y < -1 || y > 1)
{
throw new ArgumentOutOfRangeException(
nameof(y),
$"Parameter {nameof(y)} cannot have a magnitude larger than one");
}
if (x == 0 && y == 0)
{
throw new ArgumentException(
nameof(y),
$"Paramters {nameof(x)} and {nameof(y)} cannot both be zero");
}
this.Offset = new int2(x, y);
// Penalize diagonal movement
this.Distance = x != 0 && y != 0 ? 1.41421f : 1;
}
}
[Serializable]
public struct NavigationCapabilities : IComponentData
{
public float MaxSlopeAngle;
public float MaxClimbHeight;
public float MaxDropHeight;
}
public struct Waypoint : IBufferElementData
{
public float3 waypoints;
}
public struct Node
{
public bool Obstacle
{
get { return Convert.ToBoolean(obstacle); }
}
public int Height;
public byte obstacle;
}
}
<file_sep>/Assets/Scripts/SimpleCameraController.cs
using UnityEngine;
using Pathfinding;
using Unity.Mathematics;
using UnityEngine.Serialization;
namespace UnityTemplateProjects
{
public class SimpleCameraController : MonoBehaviour
{
public float speed = 50f;
public float ShiftAcceleration = 4f;
public Vector2 zoomMinMax = new Vector2(5, 100);
public Material cursorMaterial, startPointMaterial, endPointMaterial;
public TextFade help;
static Plane XZPlane = new Plane(Vector3.forward, Vector3.zero);
private Camera main;
private Transform tf;
private Vector3 lastMousePosition = Vector3.negativeInfinity;
private PathfindingManager pathfindingManager;
void OnEnable()
{
tf = GetComponent<Transform>();
main = GetComponent<Camera>();
pathfindingManager = FindObjectOfType<PathfindingManager>();
}
Vector3 GetInputTranslationDirection()
{
Vector3 direction = new Vector3();
if (Input.GetKey(KeyCode.W))
{
direction += Vector3.up;
}
if (Input.GetKey(KeyCode.S))
{
direction += Vector3.down;
}
if (Input.GetKey(KeyCode.A))
{
direction += Vector3.left;
}
if (Input.GetKey(KeyCode.D))
{
direction += Vector3.right;
}
return direction;
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.F1))
{
if(!help.gameObject.activeSelf) { help.gameObject.SetActive(true); }
else
{
help.Hide();
}
}
//Zoom
var mouseWheel = Input.mouseScrollDelta.y;
if (mouseWheel != 0)
{
var size = Mathf.Clamp(main.orthographicSize - (mouseWheel * 3), zoomMinMax.x, zoomMinMax.y);
main.orthographicSize = size;
}
//Quit
if (Input.GetKey(KeyCode.Escape))
{
Application.Quit();
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#endif
}
// Translation
var translation = GetInputTranslationDirection();
// Speed up movement when shift key held
if (Input.GetKey(KeyCode.LeftShift))
{
translation *= ShiftAcceleration;
}
var temp = tf.position;
temp += ((translation * speed) * Time.smoothDeltaTime);
tf.position = temp;
DrawObstacles();
}
//Use mouse to draw some obstacles
private void DrawObstacles()
{
if (pathfindingManager.visualMode != PathfindingManager.VisualMode.Gizmo)
{
float spacing = pathfindingManager.gridScale * pathfindingManager.gridSpacing;
Vector3 mousePosition = GetMousePositionOnXZPlane();
mousePosition.x = Mathf.Round(mousePosition.x / spacing) * spacing;
mousePosition.y = Mathf.Round(mousePosition.y / spacing) * spacing;
Matrix4x4 trs = Matrix4x4.TRS(mousePosition, Quaternion.identity, new Vector3(spacing, spacing, spacing));
Graphics.DrawMesh(pathfindingManager.obstacleMesh, trs, cursorMaterial, 0);
trs.m03 = pathfindingManager.start.x * spacing;
trs.m13 = pathfindingManager.start.y * spacing;
Graphics.DrawMesh(pathfindingManager.obstacleMesh, trs, startPointMaterial, 0);
trs.m03 = pathfindingManager.end.x * spacing;
trs.m13 = pathfindingManager.end.y * spacing;
Graphics.DrawMesh(pathfindingManager.obstacleMesh, trs, endPointMaterial, 0);
if (Input.GetMouseButton(0)) //LMB draw
{
if (mousePosition == lastMousePosition) return;
lastMousePosition = mousePosition;
mousePosition /= spacing;
pathfindingManager.SetObstacle(new int2((int) mousePosition.x, (int) mousePosition.y));
pathfindingManager.UpdateMatrices();
}
if (Input.GetMouseButton(1)) //RMB erase
{
if (mousePosition == lastMousePosition) return;
lastMousePosition = mousePosition;
mousePosition /= spacing;
pathfindingManager.SetNodeWalkable(new int2((int) mousePosition.x, (int) mousePosition.y));
pathfindingManager.UpdateMatrices();
}
//Set start&end nodes for custom path.
if (Input.GetMouseButtonDown(2))
{
lastMousePosition = mousePosition;
mousePosition /= spacing;
pathfindingManager.SetNodeWalkable(new int2((int) mousePosition.x, (int) mousePosition.y));
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
{
pathfindingManager.start = new Vector2Int((int) mousePosition.x, (int) mousePosition.y);
}
else
{
pathfindingManager.end = new Vector2Int((int) mousePosition.x, (int) mousePosition.y);
}
pathfindingManager.UpdateMatrices();
}
//Use start&end node to create custom path.
if (Input.GetKeyDown(KeyCode.KeypadEnter) || Input.GetKeyDown(KeyCode.Return))
{
pathfindingManager.AddPathManually();
}
//Clear pathfinding and obstacles map.
if (Input.GetKeyDown(KeyCode.Delete))
{
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
{
pathfindingManager.ClearObstaclesMap();
pathfindingManager.ClearPathfinders();
}
else
{
pathfindingManager.ClearPathfinders();
}
}
//Generate obstacles with perlin noise.
if (Input.GetKeyDown(KeyCode.F2))
{
pathfindingManager.GenerateObstaclesWithPerlinNoise();
}
//Save
if (Input.GetKeyDown(KeyCode.F5))
{
pathfindingManager.SaveToFile();
} //Load
else if (Input.GetKeyDown(KeyCode.F9))
{
pathfindingManager.LoadFromFile();
}
}
}
private Vector3 GetMousePositionOnXZPlane()
{
float distance;
var ray = main.ScreenPointToRay(Input.mousePosition);
if(XZPlane.Raycast (ray, out distance))
{
Vector3 hitPoint = ray.GetPoint(distance);
hitPoint.z = 0;
return hitPoint;
}
return Vector3.zero;
}
}
}<file_sep>/Assets/Scripts/PathRenderer.cs
using UnityEngine;
using System.Collections.Generic;
namespace Pathfinding
{
//Basically just a pool of LineRenderers.
public class PathRenderer : MonoBehaviour
{
public int poolSize = 50;
public GameObject lineRendererPrefab;
private Queue<LineRenderer> pool = new Queue<LineRenderer>();
private Queue<LineRenderer> used = new Queue<LineRenderer>();
private void Awake()
{
InstantiateSome(count: poolSize);
}
//Will return one object out of pool and create new one if there is not enough.
public LineRenderer GetLineRenderer()
{
if (pool.Count <= 0) InstantiateSome();
var temp = pool.Dequeue();
temp.SetPositions(new Vector3[1]{ new Vector3() });
temp.gameObject.SetActive(true);
used.Enqueue(temp);
return temp;
}
private void InstantiateSome(int count = 1)
{
var tf = GetComponent<Transform>();
for (int i = 0; i < count; i++)
{
var temp = Instantiate(lineRendererPrefab, tf);
pool.Enqueue(temp.GetComponent<LineRenderer>());
temp.SetActive(false);
}
}
//Return all used objects to pool.
public void Clear()
{
int count = used.Count;
for (int i = 0; i < count; i++)
{
var temp = used.Dequeue();
temp.gameObject.SetActive(false);
pool.Enqueue(temp);
}
}
}
}
| c65d4f4c6c53b709d32b1ba68aa6941cfc082b1f | [
"Markdown",
"C#"
] | 10 | Markdown | SiriusRU/Unity-2D-Pathfinding-Grid-ECS-Job | 80a328956851a4245c07e11103b40f70088f115c | 962ea14e6bdb570b4a43097e880171467f97c820 |
refs/heads/master | <file_sep>import React, { Component } from 'react'
import '../Gem.css';
//Not sure what to do here
class Gem extends Component {
render(){
return (
<div>
<br/>
<table className="Gem-table">
<tr>
<td className="Gem-td">10 GP Gem</td>
<td className="Gem-td">50 GP Gem</td>
<td className="Gem-td">100 GP Gem</td>
<td className="Gem-td">500 GP Gem</td>
<td className="Gem-td">1000 GP Gem</td>
<td className="Gem-td">5000 GP Gem</td>
<td className="Gem-td">Total Value of Gems</td>
</tr>
<tr>
<td className="Gem-td" id="10">{this.props.gemTotal[0]}</td>
<td className="Gem-td" id="50">{this.props.gemTotal[1]}</td>
<td className="Gem-td" id="100">{this.props.gemTotal[2]}</td>
<td className="Gem-td" id="500">{this.props.gemTotal[3]}</td>
<td className="Gem-td" id="1000">{this.props.gemTotal[4]}</td>
<td className="Gem-td" id="5000">{this.props.gemTotal[5]}</td>
<td className="Gem-td" id="total-gem-value">{this.props.gemValue}</td>
</tr>
</table>
<br/>
<button onClick={this.props.rollGems.bind(this, 1)}>1</button>
<button onClick={this.props.rollGems.bind(this, 2)}>2</button>
<button onClick={this.props.rollGems.bind(this, 3)}>3</button>
<button onClick={this.props.rollGems.bind(this, 4)}>4</button>
<button onClick={this.props.rollGems.bind(this, 5)}>5</button>
<button onClick={this.props.rollGems.bind(this, 6)}>6</button>
<button onClick={this.props.rollGems.bind(this, 7)}>7</button>
<button onClick={this.props.rollGems.bind(this, 8)}>8</button>
<button onClick={this.props.rollGems.bind(this, 9)}>9</button>
<button onClick={this.props.rollGems.bind(this, 10)}>10</button>
<button onClick={this.props.rollGems.bind(this, 20)}>20</button>
<button onClick={this.props.rollGems.bind(this, 50)}>50</button>
<button onClick={this.props.rollGems.bind(this, 100)}>100</button>
</div>)
}
}
export default Gem;<file_sep>import React, { Component } from 'react';
import Gem from '../component/Gem.js';
import GemPrice from '../data/GemPrice.js';
class GemContainer extends Component {
constructor(props, context) {
super(props, context);
this.handleGemChange = this.handleGemChange.bind(this);
this.state = {
gemTotal: [0, 0, 0, 0, 0, 0],
gemValue: 0,
}
}
handleGemChange(newGemTotal){
var tempGemValue = 0; //temporarily stores total gem value
for (var i = 0; i <= 5; i++) {
tempGemValue += newGemTotal[i] * GemPrice[i];
}
this.setState({gemTotal: newGemTotal, gemValue: tempGemValue})
};
rollGems(gemAmount){ //rolls gem value/type for 1-100 gems, one at a time, and tracks the total number of each type
function randomize(min,max){ //generates a number between min and max (inclusive); always an integer
return Math.floor(Math.random()*(max-min+1)+min);
};
function rollGemType(){ //rolls to determine the value/type of an individual gem
var dieRoll = randomize(1, 100);
var gemType = 0
if (dieRoll < 1){
gemType = 0;
}
else if (dieRoll <= 25){
gemType = 0; //ornamental
}
else if (dieRoll <= 50){
gemType = 1; //semi-precious
}
else if (dieRoll <= 70){
gemType = 2; //fancy
}
else if (dieRoll <= 90){
gemType = 3; //valuable
}
else if (dieRoll <= 99){
gemType = 4; //highly valuable
}
else{
gemType = 5; //extremely valuable
}
return gemType;
};
var gemCounter = [0, 0, 0, 0, 0, 0]; //temporarily stores gem values
if (gemAmount < 1){
alert("Minimum gem amount is 1, changing to 1");
gemAmount = 1;
};
if (gemAmount > 100){
alert("Maximum gem amount is 100, changing to 1");
gemAmount = 1;
};
for (var i = 1; i <= gemAmount; i++){
var gemType = rollGemType();
gemCounter[gemType] += 1;
};
this.props.handleGemChange(gemCounter) //Using "props" here doesn't look right, but it's the only way Gem.js can understand this, so it works for now
};
render() {
return (
<Gem rollGems={this.rollGems} gemTotal={this.state.gemTotal} gemValue={this.state.gemValue} handleGemChange={this.handleGemChange} />
);
}
}
export default GemContainer | 662a8e2e482d9d28ceed42dcd07567243f89bf2a | [
"JavaScript"
] | 2 | JavaScript | EmilyBrumfield/2e-treasure-roller | d56685f72eae1562ac004c3f5a3e44c6cff1483e | 6a363b86bcd775cc4a21a77d9e83f43a3dc5054c |
refs/heads/master | <file_sep>Vorgurakendused
i244
<NAME>
<file_sep>/*old method
window.onload = function reverseAll(){
var beads = document.getElementsByClassName("bead");
for (var i = 0; i < beads.length; i++) {
var s = getComputedStyle(beads[i], null);
if (s.cssFloat=="left"){
beads[i].style.cssFloat="right";
}else {
beads[i].style.cssFloat="left";
}
}
}
*/
function eventListener(event) {
var nmb = parseInt(event.target.textContent);
var beads = document.getElementsByClassName("bead");
var index =0;
for (var i = 0; i < beads.length; i++) {if(event.target==beads[i]){index=i;}}
if (event.target.classList.contains("bead")) {
if (event.target.style.cssFloat == "left") {
for (var i = 0; i < 6-nmb; i++) {
beads[index].style.cssFloat = "right";
index++;
}
} else {
for (var i = 0; i < 6-nmb; i++) {
beads[index].style.cssFloat = "left";
index++;
}
}
}
}
<file_sep><?php require_once('head.html'); ?>
<div id="wrap">
<h3>Valiku tulemus</h3>
<p>
<?php
$dir = 'pildid/';
$images = glob($dir . '*.jpg');
$imgList = array();
foreach($images as $img){
$imgList[]=$img;
}
if(!empty($_GET)){
error_reporting(0);
$nr = intval($_GET['pilt'])-1;
if(in_array($images[intval($_GET['pilt'])-1], $imgList)) {
echo "<p>Thank you! Your vote counts! The picture number ".$_GET['pilt']." is my favorite too. </p>";
} else {
echo "<p>Your vote is not in the list, sorry.</p>";
}
} else {
echo "<p>Go back and vote, this is your obligation.</p>";
}
?>
</p>
</div>
<?php require_once('foot.html'); ?>
<file_sep><div id="wrap">
<h3>Vali oma lemmik :)</h3>
<form action="tulemus.php" method="GET">
<?php
$dir = 'pildid/';
$images = glob($dir . '*.jpg');
$nr=1;
foreach ($images as $i) {
echo("<p><label for='p".$nr."'><img src='".$i."' alt='nimetu ".$nr."' height='100' /></label><input type='radio' value='".$nr."' id='p".$nr."' name='pilt'/></p>");
}
?>
<br/>
<input type="submit" value="Valin!"/>
</form>
</div>
<file_sep><h2>Network Applications I: Client-Server Systems</h2>
<h5><em>i244 - Võrgurakendused I: klient-server süsteemide ehitamine</em></h5>
<b>Kodune ülesanne - 1. nädal</b><br>
http://enos.itcollege.ee/~alikhach/Vorgurakendused1/kt1/kt1.html
<b>Kodune ülesanne - 2. nädal</b><br>
http://enos.itcollege.ee/~alikhach/Vorgurakendused1/kt2/kt2-iframe.html
<b>Kodune ülesanne - 3. nädal</b><br>
http://enos.itcollege.ee/~alikhach/Vorgurakendused1/kt3/kt3-selektorite-%C3%BClesanne.htm <b>(selektorid)</b><br>
http://enos.itcollege.ee/~alikhach/Vorgurakendused1/kt3/kt3-stiilid.htm <b>(stiilid)</b><br>
http://enos.itcollege.ee/~alikhach/Vorgurakendused1/kt3/kt3-kt1.html <b>(3-4)</b> <br>
<b>Kodune ülesanne - 4. nädal</b><br>
http://enos.itcollege.ee/~alikhach/Vorgurakendused1/kt4/kt4-1.html <b>Duck hunt - target</b><br>
http://enos.itcollege.ee/~alikhach/Vorgurakendused1/kt4/kt4-2.html <b>Abakus beads</b> <br>
<b>Kodune ülesanne - 5. nädal</b><br>
http://enos.itcollege.ee/~alikhach/Vorgurakendused1/kt5/kt4-1.html <b>Duck hunt - interactive</b><br>
http://enos.itcollege.ee/~alikhach/Vorgurakendused1/kt5/kt4-2.html <b>Abakus beads - inverted</b> <br>
<b>Kodune ülesanne - 6. nädal</b><br>
http://enos.itcollege.ee/~alikhach/Vorgurakendused1/kt6/loop.htm <b>Loop</b><br>
<b>Kodune ülesanne - 7. nädal</b><br>
http://enos.itcollege.ee/~alikhach/Vorgurakendused1/kt7/myphp.php <b>1st</b><br>
http://enos.itcollege.ee/~alikhach/Vorgurakendused1/kt7/suurAlgus.php <b>2nd</b><br>
http://enos.itcollege.ee/~alikhach/Vorgurakendused1/kt7/myphp2.php <b>3rd</b><br>
http://enos.itcollege.ee/~alikhach/Vorgurakendused1/kt7/dogs.html <b>3rd</b><br>
<b>Kodune ülesanne - 8. nädal</b><br>
http://enos.itcollege.ee/~alikhach/Vorgurakendused1/kt8/form_style.php <b>Form style post</b><br>
http://enos.itcollege.ee/~alikhach/Vorgurakendused1/kt8/nr2.php <b>nr2</b><br>
<b>Kodune ülesanne - 9. nädal</b><br>
http://enos.itcollege.ee/~alikhach/Vorgurakendused1/kt9/multipage/pealeht.php <b>Multipage</b><br>
http://enos.itcollege.ee/~alikhach/Vorgurakendused1/kt9/controller/controller.php <b>Controller</b><br>
<b>Kodune ülesanne - 10. nädal</b><br>
http://enos.itcollege.ee/~alikhach/Vorgurakendused1/kt10/nr1.php <b>nr1</b><br>
http://enos.itcollege.ee/~alikhach/Vorgurakendused1/kt10/controller/controller.php <b>nr2</b><br>
<b>Kodune ülesanne - 11. nädal</b><br>
http://enos.itcollege.ee/~alikhach/Vorgurakendused1/kt11/zoo.php <b>zoo</b><br>
<b>Kodune ülesanne - 12. nädal</b><br>
http://enos.itcollege.ee/~alikhach/Vorgurakendused1/kt12/loomaaed.php <b>loomaaed</b><br>
<b>Kodune ülesanne - 13. nädal</b><br>
http://enos.itcollege.ee/~alikhach/Vorgurakendused1/kt13/loomaaed.php <b>loomaaed</b><br>
<NAME><br>
<b>Enos link:</b> http://enos.itcollege.ee/~alikhach/
<file_sep><?php
require_once("functions.php");
$mode="";
if (!empty($_GET["mode"])) {
$mode=$_GET["mode"];
}
switch($mode){
case "ok":
include("ok.php");
break;
case "kontroll":
kontrolli_vormi();
include("pealeht.php");
break;
default:
include("pealeht.php");
break;
}
?><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Homework №8</title>
</head>
<body>
<?php
$text_area = "Enter your text here";
$bg_color = "#ffffff";
$txt_color = "#ffffff";
$brd_width = 0;
$brd_style = "solid";
$brd_color = "#ffffff";
$brd_radius = 0;
if (isset($_POST['txtarea']) && $_POST['txtarea']!="Enter your text here" && $_POST['txtarea']!="") {
$text_area=htmlspecialchars($_POST['txtarea']);
}
if (isset($_POST['bg_col']) && $_POST['bg_col']!="") {
$bg_color=htmlspecialchars($_POST['bg_col']);
}
if (isset($_POST['txt_col']) && $_POST['txt_col']!="") {
$txt_color=htmlspecialchars($_POST['txt_col']);
}
if (isset($_POST['width']) && $_POST['width']!="") {
$brd_width=htmlspecialchars($_POST['width']);
}
if (isset($_POST['style']) && $_POST['style']!="") {
$brd_style=htmlspecialchars($_POST['style']);
}
if (isset($_POST['bcolor']) && $_POST['bcolor']!="") {
$brd_color=htmlspecialchars($_POST['bcolor']);
}
if (isset($_POST['radius']) && $_POST['radius']!="") {
$brd_radius=htmlspecialchars($_POST['radius']);
}
?>
<style scoped>
.result {
width: 400px;
height: 100px;
background-color: <?php echo $bg_color; ?>;
color: <?php echo $txt_color; ?>;
border-style: <?php echo $brd_style; ?>;
border-color: <?php echo $brd_color; ?>;
border-width: <?php echo $brd_width; ?>px;
border-radius: <?php echo $brd_radius; ?>px;
text-align: center;
font-size: 32px;
font-family: Helvetica, sans-serif;
padding-left: 15px;
padding-bottom: 15px;
padding-right: 15px;
padding-top: 15px;
margin-left: 15px;
margin-top: 15px;
}
form{
max-width: 350px;
}
ul {
list-style-type: none;
padding: 0;
border: 1px solid #ddd;
}
ul li {
padding: 8px 16px;
border-bottom: 1px solid #ddd;
}
ul li:last-child {
border-bottom: none
}
</style>
<p class="result">
<?php if (isset($_POST['txtarea'])&& $_POST['txtarea']!="Enter your text here") echo $text_area; ?>
</p>
<form method="post" action="form_style.php">
<ul>
<li><label>
<textarea name="txtarea" cols="30" rows="3"><?php echo $text_area; ?></textarea>
</label></li>
<li><label>
<input type="color" name="bg_col" value="<?php echo $bg_color; ?>">
</label> Background color</li>
<li><label>
<input type="color" name="txt_col" value="<?php echo $txt_color; ?>">
</label> Text color</li>
<li><label>
<input type="number" name="width" value="<?php echo $brd_width; ?>" min="0" max="20" step="1">
</label> Border width (0-20px)</li>
<li><label>
<select name="style">
<option
value="<?php if (isset($_POST['width']) && isset($_POST['style'])){echo $brd_style;} else echo "
select
"; ?>"><?php if (isset($_POST['style'])){echo $brd_style;} else echo "select";
?></option>
<option value="solid">solid</option>
<option value="dotted">dotted</option>
<option value="dashed">dashed</option>
<option value="outset">outset</option>
<option value="double">double</option>
<option value="inset">inset</option>
<option value="groove">groove</option>
<option value="ridge">ridge</option>
</select>
</label> Border style</li>
<li><label>
<input type="color" name="bcolor" value="<?php echo $brd_color; ?>">
</label> Border color</li>
<li><label>
<input type="number" name="radius" value="<?php echo $brd_radius; ?>" min="0" max="100" step="1">
</label> Border radius (0-100px)</li>
</ul>
<button type="submit">Show it</button>
</form>
<p>Validators:<br>
<a href="http://validator.w3.org/check?uri=referer">
<img src="http://www.w3.org/Icons/valid-xhtml10" alt="Valid XHTML 1.0 Strict" height="31" width="88" /></a>
<a href="http://jigsaw.w3.org/css-validator/check/referer">
<img src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!" /></a>
</p>
</body>
</html><file_sep><?php
// see on mudel
function kontrolli_vormi(){
if (!empty($_POST)){ // vorm esitati
$errors=array();
if(!empty($_POST["nimi"])) {
// tee infoga midagi
} else {
$errors[]="nimi puudu!";
}
if(!empty($_POST["vanus"])) {
// tee infoga midagi
} else {
$errors[]="vanus puudu!";
}
if(!empty($_POST["sugu"])) {
// tee infoga midagi
} else {
$errors[]="sugu puudu!";
}
if(!empty($_POST["kood"])) {
// tee infoga midagi
} else {
$errors[]="kood puudu!";
}
// kontroll läbi
if (empty($errors)) {
// kõik ok
// siin peaks infoga midagi tegema (andmebaas v sessioon)
header("Location: kontroller.php?mode=ok");
exit(0);
}
}
}
?><file_sep><?php
session_start();
session_unset();
session_destroy();
header ("Location: controller.php?page=vote");
?><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Homework 11</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<?php
$host="localhost";
$user="test";
$pass="<PASSWORD>";
$db="test";
$connection = mysqli_connect($host, $user, $pass, $db) or die("ei saa ühendust mootoriga");
mysqli_query($connection, "SET CHARACTER SET UTF8") or die("Ei saanud baasi utf-8-sse - ".mysqli_error($connection));
$selecttable = "SELECT * FROM alikhach_loomaaed";
$result = mysqli_query($connection, $selecttable);
if ($result->num_rows > 0) {
echo "<table border='1'><tr>";
echo "<th>id</th>";
echo "<th>nimi</th>";
echo "<th>vanus</th>";
echo "<th>liik</th>";
echo "<th>puur</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['nimi']."</td>";
echo "<td>".$row['vanus']."</td>";
echo "<td>".$row['liik']."</td>";
echo "<td>".$row['puur']."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "Table is empty";
}
echo "<p><b>Hankida kõigi mingis ühes kindlas puuris elavate loomade nimi ja puuri number</b></p>";
$q1 = mysqli_query($connection, "SELECT * FROM alikhach_loomaaed WHERE puur='1'");
echo "<p>Puuris number 1 elavad: </p>";
while($row = $q1->fetch_assoc()) {
echo $row['nimi']." ";
}
$q1 = mysqli_query($connection, "SELECT * FROM alikhach_loomaaed WHERE puur='3'");
echo "<p>Puuris number 3 elavad: </p>";
while($row = $q1->fetch_assoc()) {
echo $row['nimi']." ";
}
$q1 = mysqli_query($connection, "SELECT * FROM alikhach_loomaaed WHERE puur='6'");
echo "<p>Puuris number 6 elavad: </p>";
while($row = $q1->fetch_assoc()) {
echo $row['nimi']." ";
}
echo "<p><b>Hankida vanima ja noorima looma vanused</b></p>";
$q1=mysqlQuery("SELECT MAX(vanus) AS `max` FROM alikhach_loomaaed");
$q2=mysqlQuery("SELECT MIN(vanus) AS `min` FROM alikhach_loomaaed");
echo "<p>Vanim on ".$q1['max']."-aastane, ja noorim on ".$q2['min']."-aastane.</p>";
echo "<p><b>Hankida puuri number koos selles elavate loomade arvuga</b></p>";
$q1=mysqlQuery("SELECT COUNT(*) AS `count` FROM alikhach_loomaaed WHERE puur='1'");
echo "<p>Puuris number 1 loomade arv on : ".$q1['count']."</p>";
$q1=mysqlQuery("SELECT COUNT(*) AS `count` FROM alikhach_loomaaed WHERE puur='3'");
echo "<p>Puuris number 3 loomade arv on : ".$q1['count']."</p>";
$q1=mysqlQuery("SELECT COUNT(*) AS `count` FROM alikhach_loomaaed WHERE puur='6'");
echo "<p>Puuris number 6 loomade arv on : ".$q1['count']."</p>";
$q1=mysqlQuery("SELECT COUNT(*) AS `count` FROM alikhach_loomaaed WHERE puur='7'");
echo "<p>Puuris number 7 loomade arv on : ".$q1['count']."</p>";
$q1=mysqlQuery("SELECT COUNT(*) AS `count` FROM alikhach_loomaaed WHERE puur='11'");
echo "<p>Puuris number 11 loomade arv on : ".$q1['count']."</p>";
mysqli_close($connection);
function mysqlQuery($query) {
$result = mysqli_query($GLOBALS['connection'], $query);
return $result->fetch_assoc();
}
?>
<form method="post" action="refresh.php">
<button type="submit" formaction="refresh.php">Suurendada kõiki tabelis olevaid vanuseid 1 aasta võrra</button>
</form>
<form method="post" action="refresh2.php">
<button type="submit" formaction="refresh2.php">Vähendada kõiki tabelis olevaid vanuseid 1 aasta võrra</button>
</form>
</body>
</html>
<file_sep><?php
function connect_db(){
global $connection;
$host="localhost";
$user="test";
$pass="<PASSWORD>";
$db="test";
$connection = mysqli_connect($host, $user, $pass, $db) or die("ei saa ühendust mootoriga- ".mysqli_error());
mysqli_query($connection, "SET CHARACTER SET UTF8") or die("Ei saanud baasi utf-8-sse - ".mysqli_error($connection));
}
function logi(){
global $connection;
$errors = array();
if(isset($_SESSION["user"])){
header("Location: ?page=loomad");
}else{
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(empty($_POST["user"]) || empty($_POST["pass"])){
if(empty($_POST["user"])) {
array_push($errors, "Empty username field.");
}
if(empty($_POST["pass"])) {
array_push($errors, "Empty password field.");
}
}else{
$sql = "SELECT id FROM alikhach_kylastajad WHERE username='".mysqli_real_escape_string($connection, $_POST["user"])."' AND passw=SHA1('". mysqli_real_escape_string($connection, $_POST["pass"])."')";
$result = mysqli_num_rows(mysqli_query($connection, $sql));
if($result){
$_SESSION["user"] = $_POST["user"];
header("Location: ?page=loomad");
}else{
array_push($errors, "Wrong username / password");
}
}
}
}
include_once('views/login.html');
}
function logout(){
$_SESSION=array();
session_destroy();
header("Location: ?");
}
function kuva_puurid(){
global $connection;
$puurid = array();
if(isset($_SESSION["user"])) {
$distinct_puur = "SELECT DISTINCT puur FROM al1213_loomaaed ORDER BY puur ASC";
$result = mysqli_query($connection, $distinct_puur);
while ($row = $result->fetch_assoc()) {
$select_puur = "SELECT * FROM al1213_loomaaed WHERE puur=" . $row['puur'];
$result2 = mysqli_query($connection, $select_puur);
while ($row2 = $result2->fetch_assoc()) {
$puurid[$row['puur']][] = $row2;
}
}
} else {
header("Location: ?page=login");
}
include_once('views/puurid.html');
}
function lisa(){
global $connection;
$errors=array();
if(isset($_SESSION["user"])) {
if($_SERVER['REQUEST_METHOD'] == 'POST'){
try{$fileLocation = upload('liik');
}catch(Exception $e){}
if(empty($_POST["nimi"]) || empty($_POST["puur"]) || empty($fileLocation)){
if(empty($_POST["nimi"])) {
array_push($errors, "Empty name field.");
}
if(empty($_POST["puur"])) {
array_push($errors, "Empty cage field.");
}
if(empty($fileLocation)) {
array_push($errors, "Picture is missing");
}
}else{
$n = mysqli_real_escape_string ($connection, $_POST["nimi"]);
$p = mysqli_real_escape_string ($connection, $_POST["puur"]);
$l = mysqli_real_escape_string ($connection, "pildid/".$_FILES["liik"]["name"]);
$result = mysqli_query($connection, "INSERT INTO al1213_loomaaed (nimi, puur, liik) VALUES ('$n','$p','$l')");
$id = mysqli_insert_id($connection);
if($id>0){
header("Location: ?page=loomad");
}else{
array_push($errors, "Picture can't be loaded");
}
}
}
} else {
header("Location: ?page=login");
}
include_once('views/loomavorm.html');
}
function upload($name){
$allowedExts = array("jpg", "jpeg", "gif", "png");
$allowedTypes = array("image/gif", "image/jpeg", "image/png","image/pjpeg");
$extension = end(explode(".", $_FILES[$name]["name"]));
if ( in_array($_FILES[$name]["type"], $allowedTypes)
&& ($_FILES[$name]["size"] < 100000)
&& in_array($extension, $allowedExts)) {
// fail õiget tüüpi ja suurusega
if ($_FILES[$name]["error"] > 0) {
$_SESSION['notices'][]= "Return Code: " . $_FILES[$name]["error"];
return "";
} else {
// vigu ei ole
if (file_exists("pildid/" . $_FILES[$name]["name"])) {
// fail olemas ära uuesti lae, tagasta failinimi
$_SESSION['notices'][]= $_FILES[$name]["name"] . " juba eksisteerib. ";
return "pildid/" .$_FILES[$name]["name"];
} else {
// kõik ok, aseta pilt
move_uploaded_file($_FILES[$name]["tmp_name"], "pildid/" . $_FILES[$name]["name"]);
return "pildid/" .$_FILES[$name]["name"];
}
}
} else {
return "";
}
}
?><file_sep><?php require_once('head.html'); ?>
<div id="wrap">
<h3>Fotod</h3>
<div id="gallery">
<?php
$dir = 'pildid/';
$images = glob($dir . '*.jpg');
foreach ($images as $i) {
echo("<img src='".$i."' alt='".$i."' />");
}
?>
</div>
</div>
<?php require_once('foot.html'); ?><file_sep><?php
//ebaturvaline
if(!empty($_POST["q"])){
echo $_POST["q"]."<br>";
}
?>
<?php
//turvaline
if(!empty($_POST["q"])){
echo htmlspecialchars($_POST["q"]);
}
?>
<form action = "minuHTML.php" method="POST">
<textarea name="q"></textarea>
<input type="submit" name="s" value="esita" />
</form><file_sep> <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="stiil.css">
<script src="myscripts.js"></script>
<title>Title</title>
</head>
<body>
<h1>Võrgurakendused I esimene HTML lehekülg</h1>
<p>Paneme pildi ka</p>
<img src="http://images.clipartpanda.com/cute-tortoise-clipart-cute-safari-turtle-vector-illustration-9631748.jpg" alt="Turtle image" width="500" height="400">
<div id="clockdiv">
Days: <span class="days"></span><br>
Hours: <span class="hours"></span><br>
Minutes: <span class="minutes"></span><br>
Seconds: <span class="seconds"></span>
</div>
<?php
include("counter.php");
?>
</body>
</html>
<file_sep>
<?php
require_once('head.html');
$dir = 'pildid/';
$images = glob($dir . '*.jpg');
$imgList = array();
foreach($images as $img){
$imgList[]=$img;
}
if(!empty($_GET)){
$page=$_GET['page'];
} else {
$page="pealeht";
}
switch($page) {
case "pealeht":
require_once('pealeht.html');
break;
case "galerii":
require_once('galerii.html');
break;
case "vote":
require_once('vote.html');
break;
case "tulemus":
require_once('tulemus.html');
break;}
require_once('foot.html');
?>
<file_sep>
<?php
session_start();
require_once('head.html');
$dir = 'pildid/';
$images = glob($dir . '*.jpg');
$imgList = array();
foreach($images as $img){
$imgList[]=$img;
}
if(!empty($_GET)){
$page=$_GET['page'];
} else {
$page="pealeht";
}
switch($page) {
case "pealeht":
require_once('pealeht.html');
break;
case "galerii":
require_once('galerii.html');
break;
case "vote":
if (!isset($_SESSION['LAST_ACTIVITY'])){
require_once('vote.html');
}
else if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 86400)) {
session_unset();
session_destroy();
require_once('vote.html');
} else {
echo "<p style=\"color:red; text-align: center; font-weight: bold\">Sorry! You have voted for number ".$_SESSION['VOTED_FOR']." already. You can vote only once a day.</p>";
$_POST['pilt'] = $_SESSION['VOTED_FOR'];
require_once('tulemus.html');
}
break;
case "tulemus":
require_once('tulemus.html');
break;}
require_once('foot.html');
?>
<file_sep><?php
$file = 'count.txt';
// Open the file to get existing content
$current = file_get_contents($file);
//print $current;
$current = $current + 1;
//print $current;
// Write the contents back to the file
file_put_contents($file, $current);
echo "Lehe külastuse arv on: " . $current;
?>
<file_sep><?php
$host="localhost";
$user="test";
$pass="<PASSWORD>";
$db="test";
$connection = mysqli_connect($host, $user, $pass, $db) or die("ei saa ühendust mootoriga");
mysqli_query($connection, "SET CHARACTER SET UTF8") or die("Ei saanud baasi utf-8-sse - ".mysqli_error($connection));
mysqli_query($connection, "UPDATE alikhach_loomaaed SET vanus=vanus-1");
mysqli_close($connection);
header("Refresh:0; url=zoo.php");
?><file_sep><?php
$this->view('head.html');
//$this->view('content.php');
$this->view('foot.html');
?> | 88bec96cb5a3867b8b78e73b4b8febd3bd703609 | [
"Markdown",
"JavaScript",
"PHP"
] | 19 | Markdown | tyomhd/Vorgurakendused | 7a3bb24ab40ee74b0b1c9be0a7136559c4191d23 | c6c244f55f0776113e5a6ad0087075de01ea10a9 |
refs/heads/master | <repo_name>ketan-ryan/PopularMMOs-Mod-1.7.10<file_sep>/src/main/java/com/popularmmos/particles/EntityParticleFXPinkSparkle.java
package com.popularmmos.particles;
import net.minecraft.client.particle.EntitySmokeFX;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
public class EntityParticleFXPinkSparkle extends EntitySmokeFX
{
public static ResourceLocation texture = new ResourceLocation("popular:textures/PopularParticles.png");
public EntityParticleFXPinkSparkle(World p_i1209_1_, double p_i1209_2_, double p_i1209_4_, double p_i1209_6_, double p_i1209_8_, double p_i1209_10_, double p_i1209_12_)
{
super(p_i1209_1_, p_i1209_2_, p_i1209_4_, p_i1209_6_, p_i1209_8_, p_i1209_10_, p_i1209_12_);
this.particleMaxAge = 20;
this.particleRed = 1F;
this.particleGreen = 0.07F;
this.particleBlue = 0.57F;
this.setParticleTextureIndex(6);
this.noClip = true;
}
public void renderParticle(Tessellator p_70539_1_, float p_70539_2_, float p_70539_3_, float p_70539_4_, float p_70539_5_, float p_70539_6_, float p_70539_7_)
{
super.renderParticle(p_70539_1_, p_70539_2_, p_70539_3_, p_70539_4_, p_70539_5_, p_70539_6_, p_70539_7_);
}
}
<file_sep>/src/main/java/com/popularmmos/entities/jenboss/RenderJenBoss.java
package com.popularmmos.entities.jenboss;
import com.popularmmos.main.ClientProxy;
import net.minecraft.client.Minecraft;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.RenderLiving;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.boss.BossStatus;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
public class RenderJenBoss extends RenderLiving
{
private Minecraft mc;
private static final ResourceLocation mobTextures = new ResourceLocation("popular:textures/entities/JenBoss.png");
private static final ResourceLocation beamTextures = new ResourceLocation("popular:textures/entities/PinkBeam.png");
public ModelJenBoss jenBoss;
private EntityJenBoss entityJen;
public RenderJenBoss(ModelBase par1ModelBase, float par2) {
super(par1ModelBase, par2);
this.jenBoss = (ModelJenBoss)super.mainModel;
this.setRenderPassModel(this.jenBoss);
}
protected ResourceLocation getEntityTexture(EntityJenBoss entity)
{
return mobTextures;
}
protected ResourceLocation getEntityTexture(Entity entity)
{
return this.getEntityTexture((EntityJenBoss)entity);
}
protected void rotateCorpse(EntityJenBoss p_77043_1_, float p_77043_2_, float p_77043_3_, float p_77043_4_)
{
super.rotateCorpse(p_77043_1_, p_77043_2_, p_77043_3_, p_77043_4_);
GL11.glTranslatef(0F, .8F, 0F);
}
protected void rotateCorpse(EntityLivingBase p_77043_1_, float p_77043_2_, float p_77043_3_, float p_77043_4_)
{
this.rotateCorpse((EntityJenBoss) p_77043_1_, p_77043_2_, p_77043_3_, p_77043_4_);
}
public void doRender(EntityJenBoss p_76986_1_, double p_76986_2_, double p_76986_4_, double p_76986_6_, float p_76986_8_, float p_76986_9_)
{
BossStatus.setBossStatus(p_76986_1_, true);
super.doRender(p_76986_1_, p_76986_2_, p_76986_4_, p_76986_6_, p_76986_8_, p_76986_9_);
GL11.glAlphaFunc(GL11.GL_GREATER, 0.1F);
Tessellator tessellator = Tessellator.instance;
this.bindTexture(beamTextures);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, 10497.0F);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, 10497.0F);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_CULL_FACE);
GL11.glDisable(GL11.GL_BLEND);
GL11.glDepthMask(true);
OpenGlHelper.glBlendFunc(770, 1, 1, 0);
float f2 = (float)p_76986_1_.worldObj.getTotalWorldTime() + p_76986_8_;
float f3 = -f2 * 0.2F - (float) MathHelper.floor_float(-f2 * 0.1F);
byte b0 = 1;
double d3 = (double)f2 * 0.025D * (1.0D - (double)(b0 & 1) * 2.5D);
tessellator.startDrawingQuads();
tessellator.setColorRGBA(255, 255, 255, 32);
double d5 = (double)b0 * 0.2D;
double d7 = 0.5D + Math.cos(d3 + 2.356194490192345D) * d5;
double d9 = 0.5D + Math.sin(d3 + 2.356194490192345D) * d5;
double d11 = 0.5D + Math.cos(d3 + (Math.PI / 4D)) * d5;
double d13 = 0.5D + Math.sin(d3 + (Math.PI / 4D)) * d5;
double d15 = 0.5D + Math.cos(d3 + 3.9269908169872414D) * d5;
double d17 = 0.5D + Math.sin(d3 + 3.9269908169872414D) * d5;
double d19 = 0.5D + Math.cos(d3 + 5.497787143782138D) * d5;
double d21 = 0.5D + Math.sin(d3 + 5.497787143782138D) * d5;
double d23 = (double)(256.0F);
double d25 = 0.0D;
double d27 = 1.0D;
double d28 = (double)(-1.0F + f3);
double d29 = (double)(256.0F) * (0.5D / d5) + d28;
tessellator.addVertexWithUV(p_76986_2_ + d7, p_76986_4_ + d23, p_76986_6_ + d9, d27, d29);
tessellator.addVertexWithUV(p_76986_2_ + d7, p_76986_4_, p_76986_6_ + d9, d27, d28);
tessellator.addVertexWithUV(p_76986_2_ + d11, p_76986_4_, p_76986_6_ + d13, d25, d28);
tessellator.addVertexWithUV(p_76986_2_ + d11, p_76986_4_ + d23, p_76986_6_ + d13, d25, d29);
tessellator.addVertexWithUV(p_76986_2_ + d19, p_76986_4_ + d23, p_76986_6_ + d21, d27, d29);
tessellator.addVertexWithUV(p_76986_2_ + d19, p_76986_4_, p_76986_6_ + d21, d27, d28);
tessellator.addVertexWithUV(p_76986_2_ + d15, p_76986_4_, p_76986_6_ + d17, d25, d28);
tessellator.addVertexWithUV(p_76986_2_ + d15, p_76986_4_ + d23, p_76986_6_ + d17, d25, d29);
tessellator.addVertexWithUV(p_76986_2_ + d11, p_76986_4_ + d23, p_76986_6_ + d13, d27, d29);
tessellator.addVertexWithUV(p_76986_2_ + d11, p_76986_4_, p_76986_6_ + d13, d27, d28);
tessellator.addVertexWithUV(p_76986_2_ + d19, p_76986_4_, p_76986_6_ + d21, d25, d28);
tessellator.addVertexWithUV(p_76986_2_ + d19, p_76986_4_ + d23, p_76986_6_ + d21, d25, d29);
tessellator.addVertexWithUV(p_76986_2_ + d15, p_76986_4_ + d23, p_76986_6_ + d17, d27, d29);
tessellator.addVertexWithUV(p_76986_2_ + d15, p_76986_4_, p_76986_6_ + d17, d27, d28);
tessellator.addVertexWithUV(p_76986_2_ + d7, p_76986_4_, p_76986_6_ + d9, d25, d28);
tessellator.addVertexWithUV(p_76986_2_ + d7, p_76986_4_ + d23, p_76986_6_ + d9, d25, d29);
tessellator.draw();
GL11.glEnable(GL11.GL_BLEND);
OpenGlHelper.glBlendFunc(770, 771, 1, 0);
GL11.glDepthMask(false);
tessellator.startDrawingQuads();
tessellator.setColorRGBA(255, 255, 255, 32);
double d30 = 0.2D;
double d4 = 0.2D;
double d6 = 0.8D;
double d8 = 0.2D;
double d10 = 0.2D;
double d12 = 0.8D;
double d14 = 0.8D;
double d16 = 0.8D;
double d18 = (double)(256.0F);
double d20 = 0.0D;
double d22 = 1.0D;
double d24 = (double)(-1.0F + f3);
double d26 = (double)(256.0F) + d24;
tessellator.addVertexWithUV(p_76986_2_ + d30, p_76986_4_ + d18, p_76986_6_ + d4, d22, d26);
tessellator.addVertexWithUV(p_76986_2_ + d30, p_76986_4_, p_76986_6_ + d4, d22, d24);
tessellator.addVertexWithUV(p_76986_2_ + d6, p_76986_4_, p_76986_6_ + d8, d20, d24);
tessellator.addVertexWithUV(p_76986_2_ + d6, p_76986_4_ + d18, p_76986_6_ + d8, d20, d26);
tessellator.addVertexWithUV(p_76986_2_ + d14, p_76986_4_ + d18, p_76986_6_ + d16, d22, d26);
tessellator.addVertexWithUV(p_76986_2_ + d14, p_76986_4_, p_76986_6_ + d16, d22, d24);
tessellator.addVertexWithUV(p_76986_2_ + d10, p_76986_4_, p_76986_6_ + d12, d20, d24);
tessellator.addVertexWithUV(p_76986_2_ + d10, p_76986_4_ + d18, p_76986_6_ + d12, d20, d26);
tessellator.addVertexWithUV(p_76986_2_ + d6, p_76986_4_ + d18, p_76986_6_ + d8, d22, d26);
tessellator.addVertexWithUV(p_76986_2_ + d6, p_76986_4_, p_76986_6_ + d8, d22, d24);
tessellator.addVertexWithUV(p_76986_2_ + d14, p_76986_4_, p_76986_6_ + d16, d20, d24);
tessellator.addVertexWithUV(p_76986_2_ + d14, p_76986_4_ + d18, p_76986_6_ + d16, d20, d26);
tessellator.addVertexWithUV(p_76986_2_ + d10, p_76986_4_ + d18, p_76986_6_ + d12, d22, d26);
tessellator.addVertexWithUV(p_76986_2_ + d10, p_76986_4_, p_76986_6_ + d12, d22, d24);
tessellator.addVertexWithUV(p_76986_2_ + d30, p_76986_4_, p_76986_6_ + d4, d20, d24);
tessellator.addVertexWithUV(p_76986_2_ + d30, p_76986_4_ + d18, p_76986_6_ + d4, d20, d26);
tessellator.draw();
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glDepthMask(true);
}
protected void passSpecialRender(EntityLivingBase parEntity, double parX, double parY, double parZ)
{
super.passSpecialRender(parEntity, parX, parY, parZ);
if(parEntity instanceof EntityJenBoss)
{
EntityJenBoss jen = (EntityJenBoss)parEntity;
if(jen.getShield())
{
GL11.glPushMatrix();
GL11.glTranslated(parX, parY + parEntity.height / 2, parZ);
GL11.glScalef(9.0F, 9.0F, 9.0F);
GL11.glEnable(GL11.GL_BLEND);
GL11.glDepthMask(false);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glColor4f(1.000F, 0.412F, 0.706F, 0.7F);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glCallList(ClientProxy.sphereIdOutside);
GL11.glCallList(ClientProxy.sphereIdInside);
GL11.glPopMatrix();
}
}
}
/**
* Actually renders the given argument. This is a synthetic bridge method, always casting down its argument and then
* handing it off to a worker function which does the actual work. In all probability, the class Render is generic
* (Render<T extends Entity) and this method has signature public void func_76986_a(T entity, double d, double d1,
* double d2, float f, float f1). But JAD is pre 1.5 so doesn't do that.
*/
public void doRender(EntityLiving p_76986_1_, double p_76986_2_, double p_76986_4_, double p_76986_6_, float p_76986_8_, float p_76986_9_)
{
this.doRender((EntityJenBoss)p_76986_1_, p_76986_2_, p_76986_4_, p_76986_6_, p_76986_8_, p_76986_9_);
}
/**
* Actually renders the given argument. This is a synthetic bridge method, always casting down its argument and then
* handing it off to a worker function which does the actual work. In all probability, the class Render is generic
* (Render<T extends Entity) and this method has signature public void func_76986_a(T entity, double d, double d1,
* double d2, float f, float f1). But JAD is pre 1.5 so doesn't do that.
*/
public void doRender(EntityLivingBase p_76986_1_, double p_76986_2_, double p_76986_4_, double p_76986_6_, float p_76986_8_, float p_76986_9_)
{
this.doRender((EntityJenBoss)p_76986_1_, p_76986_2_, p_76986_4_, p_76986_6_, p_76986_8_, p_76986_9_);
}
/**
* Actually renders the given argument. This is a synthetic bridge method, always casting down its argument and then
* handing it off to a worker function which does the actual work. In all probability, the class Render is generic
* (Render<T extends Entity) and this method has signature public void func_76986_a(T entity, double d, double d1,
* double d2, float f, float f1). But JAD is pre 1.5 so doesn't do that.
*/
public void doRender(Entity p_76986_1_, double p_76986_2_, double p_76986_4_, double p_76986_6_, float p_76986_8_, float p_76986_9_)
{
this.doRender((EntityJenBoss)p_76986_1_, p_76986_2_, p_76986_4_, p_76986_6_, p_76986_8_, p_76986_9_);
}
}
<file_sep>/src/main/java/com/popularmmos/explosions/EntityPinkTNTPrimed.java
package com.popularmmos.explosions;
import com.popularmmos.main.MMOs;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityTNTPrimed;
import net.minecraft.world.World;
public class EntityPinkTNTPrimed extends EntityTNTPrimed
{
private EntityLivingBase tntPlacedBy;
public EntityPinkTNTPrimed(World p_i1729_1_)
{
super(p_i1729_1_);
this.preventEntitySpawning = true;
this.setSize(0.98F, 0.98F);
this.yOffset = this.height / 2.0F;
}
public EntityPinkTNTPrimed(World p_i1730_1_, double p_i1730_2_, double p_i1730_4_, double p_i1730_6_, EntityLivingBase p_i1730_8_)
{
this(p_i1730_1_);
this.setPosition(p_i1730_2_, p_i1730_4_, p_i1730_6_);
float f = (float)(Math.random() * Math.PI * 2.0D);
this.motionX = (double)(-((float)Math.sin((double)f)) * 0.02F);
this.motionY = 0.40000000298023224D;
this.motionZ = (double)(-((float)Math.cos((double)f)) * 0.02F);
this.fuse = 40;
this.prevPosX = p_i1730_2_;
this.prevPosY = p_i1730_4_;
this.prevPosZ = p_i1730_6_;
this.tntPlacedBy = p_i1730_8_;
}
/**
* Called to update the entity's position/logic.
*/
@Override
public void onUpdate()
{
this.prevPosX = this.posX;
this.prevPosY = this.posY;
this.prevPosZ = this.posZ;
this.motionY -= 0.03999999910593033D;
this.moveEntity(this.motionX, this.motionY, this.motionZ);
this.motionX *= 0.9800000190734863D;
this.motionY *= 0.9800000190734863D;
this.motionZ *= 0.9800000190734863D;
if (this.onGround)
{
this.motionX *= 0.699999988079071D;
this.motionZ *= 0.699999988079071D;
this.motionY *= -0.5D;
}
if (this.fuse-- <= 0)
{
this.setDead();
if (!this.worldObj.isRemote)
{
this.explode();
}
}
else
{
MMOs.proxy.generatePinkParticles(this);
}
}
private void explode()
{
float f = 2.0F;
this.worldObj.newExplosion(this, this.posX, this.posY, this.posZ, f, true, true);
}
}
<file_sep>/src/main/java/com/popularmmos/blocks/DecorationBlock.java
package com.popularmmos.blocks;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
public class DecorationBlock extends Block
{
public DecorationBlock(Material material)
{
super(material);
}
}
<file_sep>/src/main/java/com/popularmmos/items/smallWeight/ItemSmallWeight.java
package com.popularmmos.items.smallWeight;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemSword;
import net.minecraft.world.World;
public class ItemSmallWeight extends ItemSword {
public ItemSmallWeight(ToolMaterial tm)
{
super(tm);
}
@SideOnly(Side.CLIENT)
public boolean isFull3D()
{
return true;
}
/**
* Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer
*/
public ItemStack onItemRightClick(ItemStack p_77659_1_, World p_77659_2_, EntityPlayer p_77659_3_)
{
if (!p_77659_3_.capabilities.isCreativeMode)
{
--p_77659_1_.stackSize;
}
p_77659_2_.playSoundAtEntity(p_77659_3_, "random.bow", 0.5F, 0.4F / (itemRand.nextFloat() * 0.4F + 0.8F));
return p_77659_1_;
}
}
<file_sep>/src/main/java/com/popularmmos/main/PopularBlocks.java
package com.popularmmos.main;
import com.popularmmos.explosions.BlockPinkTNT;
import com.popularmmos.blocks.DecorationBlock;
import com.popularmmos.blocks.PinkOre;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
public class PopularBlocks
{
public static void Popular()
{
initThings();
registerThings();
}
public static Block pinkOre;
public static Block patFace;
public static Block pinkTNT;
public static void initThings(){
pinkOre = new PinkOre(Material.rock).setBlockName("pinkOre").setBlockTextureName("popular:pinkOre").setCreativeTab(PopularItems.popularTab).setHardness(3F);
patFace = new DecorationBlock(Material.rock).setBlockName("patFace").setBlockTextureName("popular:patFace").setCreativeTab(PopularItems.popularTab).setHardness(2);
pinkTNT = new BlockPinkTNT().setBlockName("pinkTNT").setCreativeTab(PopularItems.popularTab).setBlockTextureName("pinktnt");
}
public static void registerThings(){
GameRegistry.registerBlock(pinkOre, "pinkOre");
GameRegistry.registerBlock(patFace, "patFace");
GameRegistry.registerBlock(pinkTNT, "pinkTNT");
}
}
<file_sep>/src/main/java/com/popularmmos/items/largeWeight/RenderItemLargeWeight.java
package com.popularmmos.items.largeWeight;
import com.popularmmos.entities.pat.largeweight.ModelLargeWeight;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiContainerCreative;
import net.minecraft.client.gui.inventory.GuiInventory;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.IItemRenderer;
import org.lwjgl.opengl.GL11;
public class RenderItemLargeWeight implements IItemRenderer{
private ModelLargeWeight modelWeight;
public static ResourceLocation texture = new ResourceLocation("popular:textures/models/largeWeight.png");
public RenderItemLargeWeight()
{
modelWeight = new ModelLargeWeight();
}
@Override
public boolean handleRenderType(ItemStack item, ItemRenderType type) {
switch(type)
{
case EQUIPPED: return true;
case EQUIPPED_FIRST_PERSON: return true;
case ENTITY: return true;
default: return false;
}
}
@Override
public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper)
{
return false;
}
@Override
public void renderItem(ItemRenderType type, ItemStack item, Object... data)
{
switch(type)
{
case EQUIPPED:
{
GL11.glPushMatrix();
Minecraft.getMinecraft().renderEngine.bindTexture(texture);
GL11.glRotatef(120F, 0.0f, 0.0f, 1.0f);
GL11.glTranslatef(-.4F, -1.5F, 0F);
this.modelWeight.render((Entity)data[1], 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, .0650F);
GL11.glPopMatrix();
break;
}
case EQUIPPED_FIRST_PERSON:
{
GL11.glPushMatrix();
Minecraft.getMinecraft().renderEngine.bindTexture(texture);
GL11.glRotatef(120F, 0.0f, 0.0f, 1.0f);
GL11.glTranslatef(-.4F, -1.5F, 0F);
boolean isFirstPerson = false;
if(data[1] != null && data[1] instanceof EntityPlayer)
{
if(!((EntityPlayer)data[1] == Minecraft.getMinecraft().renderViewEntity && Minecraft.getMinecraft().gameSettings.thirdPersonView == 0 && !((Minecraft.getMinecraft().currentScreen instanceof GuiInventory || Minecraft.getMinecraft().currentScreen instanceof GuiContainerCreative) && RenderManager.instance.playerViewY == 180.0F)))
{
// GL11.glTranslatef(-.6F, -.4F, 0F);
}
else
{
isFirstPerson = true;
// GL11.glTranslatef(-.6F, -.4F, 0F);
}
}
else
{
GL11.glTranslatef(-.4F, -1.5F, 0F);
GL11.glRotatef(90F, 0F, 0F, 1F);
}
this.modelWeight.render((Entity)data[1], 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0650F);
GL11.glPopMatrix();
break;
}
case ENTITY:
{
GL11.glPushMatrix();
Minecraft.getMinecraft().renderEngine.bindTexture(texture);
GL11.glRotatef(180F, 0.0f, 0.0f, 1.0f);
GL11.glTranslatef(-.8F, -1.55F, 0F);
this.modelWeight.render(0.0750F);
GL11.glPopMatrix();
break;
}
default:
break;
}
}
}
<file_sep>/src/main/java/com/popularmmos/generation/PopularStructureGen.java
package com.popularmmos.generation;
import cpw.mods.fml.common.IWorldGenerator;
import net.minecraft.world.World;
import net.minecraft.world.chunk.IChunkProvider;
import scala.concurrent.forkjoin.ThreadLocalRandom;
import java.util.Random;
public class PopularStructureGen implements IWorldGenerator
{
@Override
public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider)
{
int Xcoord = chunkX * 20 + random.nextInt(15);
int Ycoord = ThreadLocalRandom.current().nextInt(0, 256);
int Zcoord = chunkZ * 20 + random.nextInt(15);
new Gym().generate(world, random, Xcoord, Ycoord, Zcoord);
}
}
<file_sep>/src/main/java/com/popularmmos/generation/Gym.java
//Schematic to java Structure by jajo_11 | inspired by "MITHION'S .SCHEMATIC TO JAVA CONVERTINGTOOL"
package com.popularmmos.generation;
import com.popularmmos.entities.pat.EntityPat;
import com.popularmmos.main.PopularItems;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.tileentity.TileEntityChest;
import net.minecraft.util.WeightedRandomChestContent;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.gen.feature.WorldGenerator;
import java.util.Random;
import static com.popularmmos.generation.PopularChestGenHooks.POPULAR;
public class Gym extends WorldGenerator
{
/** List of Chest contents to be generated in the Structure chests. */
public static final WeightedRandomChestContent[] popularChestContents = new WeightedRandomChestContent[] {new WeightedRandomChestContent(PopularItems.furiousEssence, 1, 4, 14, 5),
new WeightedRandomChestContent(Items.apple, 2, 5, 10, 20), new WeightedRandomChestContent(Items.gold_ingot, 1, 4, 14, 30),
new WeightedRandomChestContent(Items.iron_ingot, 4, 4, 14, 30)};
protected Block[] GetValidSpawnBlocks()
{
return new Block[]
{
Blocks.grass,
Blocks.sand,
};
}
public boolean LocationIsValidSpawn(World world, int x, int y, int z)
{
Block checkBlock = world.getBlock(x, y - 1, z);
Block blockAbove = world.getBlock(x, y , z);
Block blockBelow = world.getBlock(x, y - 2, z);
for (Block i : GetValidSpawnBlocks())
{
if (blockAbove != Blocks.air)
{
return false;
}
if (checkBlock == i)
{
return true;
}
if(world.getBiomeGenForCoords(x, z) != BiomeGenBase.desert || world.getBiomeGenForCoords(x, z) != BiomeGenBase.extremeHills || world.getBiomeGenForCoords(x, z) != BiomeGenBase.plains)
{
return false;
}
else if (checkBlock == Blocks.snow_layer && blockBelow == i)
{
return true;
}
else if (checkBlock.getMaterial() == Material.plants && blockBelow == i)
{
return true;
}
}
return false;
}
public boolean generate(World world, Random rand, int x, int y, int z)
{
int i = rand.nextInt(1);
if(i == 0)
{
generate_r0(world, rand, x, y, z);
}
return true;
}
public boolean generate_r0(World world, Random rand, int x, int y, int z)
{
if(!LocationIsValidSpawn(world, x + 11, y, z + 12))
{
return true;
}
world.setBlock(x + 0, y + 0, z + 0, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 0, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 0, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 0, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 0, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 0, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 0, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 0, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 0, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 0, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 0, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 0, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 0, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 0, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 0, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 0, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 0, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 0, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 0, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 0, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 0, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 0, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 1, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 1, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 1, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 1, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 1, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 1, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 1, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 1, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 1, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 1, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 1, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 1, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 1, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 1, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 1, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 1, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 1, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 1, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 1, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 1, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 1, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 1, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 2, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 2, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 2, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 2, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 2, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 2, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 2, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 2, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 2, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 2, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 2, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 2, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 2, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 2, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 2, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 2, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 2, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 2, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 2, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 2, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 2, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 2, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 3, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 3, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 3, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 3, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 3, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 3, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 3, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 3, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 3, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 3, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 3, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 3, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 3, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 3, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 3, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 3, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 3, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 3, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 3, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 3, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 3, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 3, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 4, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 4, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 4, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 4, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 4, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 4, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 4, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 4, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 4, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 4, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 4, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 4, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 4, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 4, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 4, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 4, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 4, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 4, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 4, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 4, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 4, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 4, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 5, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 5, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 5, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 5, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 5, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 5, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 5, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 5, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 5, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 5, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 5, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 5, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 5, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 5, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 5, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 5, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 5, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 5, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 5, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 5, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 5, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 5, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 6, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 6, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 6, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 6, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 6, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 6, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 6, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 6, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 6, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 6, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 6, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 6, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 6, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 6, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 6, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 6, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 6, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 6, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 6, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 6, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 6, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 6, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 7, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 7, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 7, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 7, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 7, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 7, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 7, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 7, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 7, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 7, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 7, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 7, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 7, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 7, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 7, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 7, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 7, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 7, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 7, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 7, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 7, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 7, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 8, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 8, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 8, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 8, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 8, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 8, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 8, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 8, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 8, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 8, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 8, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 8, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 8, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 8, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 8, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 8, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 8, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 8, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 8, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 8, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 8, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 8, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 9, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 9, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 9, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 9, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 9, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 9, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 9, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 9, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 9, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 9, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 9, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 9, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 9, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 9, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 9, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 9, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 9, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 9, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 9, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 9, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 9, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 9, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 10, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 10, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 10, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 10, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 10, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 10, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 10, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 10, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 10, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 10, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 10, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 10, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 10, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 10, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 10, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 10, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 10, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 10, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 10, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 10, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 10, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 10, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 11, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 11, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 11, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 11, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 11, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 11, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 11, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 11, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 11, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 11, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 11, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 11, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 11, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 11, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 11, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 11, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 11, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 11, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 11, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 11, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 11, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 11, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 12, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 12, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 12, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 12, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 12, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 12, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 12, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 12, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 12, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 12, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 12, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 12, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 12, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 12, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 12, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 12, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 12, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 12, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 12, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 12, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 12, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 12, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 13, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 13, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 13, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 13, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 13, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 13, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 13, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 13, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 13, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 13, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 13, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 13, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 13, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 13, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 13, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 13, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 13, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 13, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 13, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 13, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 13, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 13, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 14, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 14, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 14, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 14, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 14, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 14, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 14, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 14, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 14, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 14, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 14, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 14, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 14, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 14, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 14, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 14, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 14, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 14, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 14, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 14, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 14, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 14, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 15, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 15, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 15, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 15, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 15, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 15, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 15, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 15, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 15, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 15, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 15, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 15, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 15, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 15, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 15, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 15, Blocks.planks, 0, 3);
EntityPat entityPat = new EntityPat(world);
entityPat.setLocationAndAngles(x + 15, y + 1, z + 15, 0, 0);
world.spawnEntityInWorld(entityPat);
world.setBlock(x + 16, y + 0, z + 15, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 15, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 15, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 15, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 15, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 15, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 16, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 16, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 16, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 16, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 16, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 16, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 16, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 16, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 16, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 16, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 16, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 16, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 16, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 16, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 16, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 16, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 16, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 16, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 16, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 16, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 16, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 16, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 17, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 17, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 17, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 17, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 17, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 17, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 17, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 17, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 17, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 17, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 17, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 17, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 17, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 17, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 17, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 17, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 17, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 17, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 17, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 17, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 17, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 17, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 18, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 18, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 18, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 18, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 18, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 18, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 18, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 18, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 18, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 18, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 18, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 18, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 18, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 18, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 18, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 18, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 18, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 18, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 18, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 18, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 18, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 18, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 19, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 19, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 19, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 19, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 19, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 19, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 19, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 19, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 19, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 19, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 19, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 19, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 19, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 19, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 19, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 19, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 19, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 19, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 19, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 19, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 19, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 19, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 20, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 20, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 20, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 20, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 20, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 20, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 20, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 20, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 20, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 20, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 20, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 20, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 20, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 20, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 20, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 20, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 20, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 20, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 20, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 20, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 20, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 20, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 21, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 21, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 21, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 21, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 21, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 21, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 21, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 21, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 21, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 21, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 21, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 21, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 21, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 21, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 21, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 21, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 21, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 21, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 21, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 21, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 21, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 21, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 22, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 22, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 22, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 22, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 22, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 22, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 22, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 22, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 22, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 22, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 22, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 22, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 22, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 22, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 22, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 22, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 22, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 22, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 22, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 22, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 22, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 22, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 23, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 23, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 23, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 23, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 23, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 23, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 23, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 23, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 23, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 23, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 23, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 23, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 23, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 23, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 23, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 23, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 23, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 23, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 23, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 23, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 23, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 23, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 0, z + 24, Blocks.planks, 0, 3);
world.setBlock(x + 1, y + 0, z + 24, Blocks.planks, 0, 3);
world.setBlock(x + 2, y + 0, z + 24, Blocks.planks, 0, 3);
world.setBlock(x + 3, y + 0, z + 24, Blocks.planks, 0, 3);
world.setBlock(x + 4, y + 0, z + 24, Blocks.planks, 0, 3);
world.setBlock(x + 5, y + 0, z + 24, Blocks.planks, 0, 3);
world.setBlock(x + 6, y + 0, z + 24, Blocks.planks, 0, 3);
world.setBlock(x + 7, y + 0, z + 24, Blocks.planks, 0, 3);
world.setBlock(x + 8, y + 0, z + 24, Blocks.planks, 0, 3);
world.setBlock(x + 9, y + 0, z + 24, Blocks.planks, 0, 3);
world.setBlock(x + 10, y + 0, z + 24, Blocks.planks, 0, 3);
world.setBlock(x + 11, y + 0, z + 24, Blocks.planks, 0, 3);
world.setBlock(x + 12, y + 0, z + 24, Blocks.planks, 0, 3);
world.setBlock(x + 13, y + 0, z + 24, Blocks.planks, 0, 3);
world.setBlock(x + 14, y + 0, z + 24, Blocks.planks, 0, 3);
world.setBlock(x + 15, y + 0, z + 24, Blocks.planks, 0, 3);
world.setBlock(x + 16, y + 0, z + 24, Blocks.planks, 0, 3);
world.setBlock(x + 17, y + 0, z + 24, Blocks.planks, 0, 3);
world.setBlock(x + 18, y + 0, z + 24, Blocks.planks, 0, 3);
world.setBlock(x + 19, y + 0, z + 24, Blocks.planks, 0, 3);
world.setBlock(x + 20, y + 0, z + 24, Blocks.planks, 0, 3);
world.setBlock(x + 21, y + 0, z + 24, Blocks.planks, 0, 3);
world.setBlock(x + 0, y + 1, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 2, y + 1, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 3, y + 1, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 4, y + 1, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 5, y + 1, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 6, y + 1, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 7, y + 1, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 8, y + 1, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 9, y + 1, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 10, y + 1, z + 0, Blocks.iron_door, 1, 3);
world.setBlock(x + 11, y + 1, z + 0, Blocks.iron_door, 1, 3);
world.setBlock(x + 12, y + 1, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 13, y + 1, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 14, y + 1, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 15, y + 1, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 16, y + 1, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 17, y + 1, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 18, y + 1, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 19, y + 1, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 20, y + 1, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 21, y + 1, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 1, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 1, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 1, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 1, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 1, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 1, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 1, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 1, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 1, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 1, z + 1, Blocks.heavy_weighted_pressure_plate, 0, 3);
world.setBlock(x + 11, y + 1, z + 1, Blocks.heavy_weighted_pressure_plate, 0, 3);
world.setBlock(x + 12, y + 1, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 1, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 1, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 1, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 1, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 1, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 1, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 1, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 1, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 1, z + 1, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 2, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 1, z + 2, Blocks.fence, 0, 3);
world.setBlock(x + 3, y + 1, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 1, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 1, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 1, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 1, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 1, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 1, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 1, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 1, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 1, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 1, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 1, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 1, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 1, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 1, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 1, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 1, z + 2, Blocks.fence, 0, 3);
world.setBlock(x + 20, y + 1, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 1, z + 2, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 3, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 1, z + 3, Blocks.stone_slab, 0, 3);
world.setBlock(x + 3, y + 1, z + 3, Blocks.stone_slab, 0, 3);
world.setBlock(x + 4, y + 1, z + 3, Blocks.stone_slab, 0, 3);
world.setBlock(x + 5, y + 1, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 1, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 1, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 1, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 1, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 1, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 1, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 1, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 1, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 1, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 1, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 1, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 1, z + 3, Blocks.stone_slab, 0, 3);
world.setBlock(x + 18, y + 1, z + 3, Blocks.stone_slab, 0, 3);
world.setBlock(x + 19, y + 1, z + 3, Blocks.stone_slab, 0, 3);
world.setBlock(x + 20, y + 1, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 1, z + 3, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 4, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 1, z + 4, Blocks.fence, 0, 3);
world.setBlock(x + 3, y + 1, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 1, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 1, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 1, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 1, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 1, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 1, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 1, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 1, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 1, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 1, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 1, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 1, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 1, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 1, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 1, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 1, z + 4, Blocks.fence, 0, 3);
world.setBlock(x + 20, y + 1, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 1, z + 4, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 5, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 1, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 1, z + 5, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 1, z + 5, Blocks.stone_slab, 0, 3);
world.setBlock(x + 5, y + 1, z + 5, Blocks.fence_gate, 7, 3);
world.setBlock(x + 6, y + 1, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 1, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 1, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 1, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 1, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 1, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 1, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 1, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 1, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 1, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 1, z + 5, Blocks.fence_gate, 5, 3);
world.setBlock(x + 17, y + 1, z + 5, Blocks.stone_slab, 0, 3);
world.setBlock(x + 18, y + 1, z + 5, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 1, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 1, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 1, z + 5, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 6, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 1, z + 6, Blocks.fence, 0, 3);
world.setBlock(x + 3, y + 1, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 1, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 1, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 1, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 1, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 1, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 1, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 1, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 1, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 1, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 1, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 1, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 1, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 1, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 1, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 1, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 1, z + 6, Blocks.fence, 0, 3);
world.setBlock(x + 20, y + 1, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 1, z + 6, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 7, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 1, z + 7, Blocks.stone_slab, 0, 3);
world.setBlock(x + 3, y + 1, z + 7, Blocks.stone_slab, 0, 3);
world.setBlock(x + 4, y + 1, z + 7, Blocks.stone_slab, 0, 3);
world.setBlock(x + 5, y + 1, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 1, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 1, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 1, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 1, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 1, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 1, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 1, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 1, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 1, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 1, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 1, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 1, z + 7, Blocks.stone_slab, 0, 3);
world.setBlock(x + 18, y + 1, z + 7, Blocks.stone_slab, 0, 3);
world.setBlock(x + 19, y + 1, z + 7, Blocks.stone_slab, 0, 3);
world.setBlock(x + 20, y + 1, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 1, z + 7, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 8, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 1, z + 8, Blocks.fence, 0, 3);
world.setBlock(x + 3, y + 1, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 1, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 1, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 1, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 1, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 1, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 1, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 1, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 1, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 1, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 1, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 1, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 1, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 1, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 1, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 1, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 1, z + 8, Blocks.fence, 0, 3);
world.setBlock(x + 20, y + 1, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 1, z + 8, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 9, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 1, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 1, z + 9, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 1, z + 9, Blocks.stone_slab, 0, 3);
world.setBlock(x + 5, y + 1, z + 9, Blocks.fence_gate, 7, 3);
world.setBlock(x + 6, y + 1, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 1, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 1, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 1, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 1, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 1, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 1, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 1, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 1, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 1, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 1, z + 9, Blocks.fence_gate, 5, 3);
world.setBlock(x + 17, y + 1, z + 9, Blocks.stone_slab, 0, 3);
world.setBlock(x + 18, y + 1, z + 9, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 1, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 1, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 1, z + 9, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 10, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 1, z + 10, Blocks.fence, 0, 3);
world.setBlock(x + 3, y + 1, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 1, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 1, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 1, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 1, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 1, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 1, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 1, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 1, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 1, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 1, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 1, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 1, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 1, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 1, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 1, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 1, z + 10, Blocks.fence, 0, 3);
world.setBlock(x + 20, y + 1, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 1, z + 10, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 11, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 1, z + 11, Blocks.stone_slab, 0, 3);
world.setBlock(x + 3, y + 1, z + 11, Blocks.stone_slab, 0, 3);
world.setBlock(x + 4, y + 1, z + 11, Blocks.stone_slab, 0, 3);
world.setBlock(x + 5, y + 1, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 1, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 1, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 1, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 1, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 1, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 1, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 1, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 1, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 1, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 1, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 1, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 1, z + 11, Blocks.stone_slab, 0, 3);
world.setBlock(x + 18, y + 1, z + 11, Blocks.stone_slab, 0, 3);
world.setBlock(x + 19, y + 1, z + 11, Blocks.stone_slab, 0, 3);
world.setBlock(x + 20, y + 1, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 1, z + 11, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 12, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 1, z + 12, Blocks.fence, 0, 3);
world.setBlock(x + 3, y + 1, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 1, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 1, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 1, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 1, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 1, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 1, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 1, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 1, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 1, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 1, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 1, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 1, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 1, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 1, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 1, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 1, z + 12, Blocks.fence, 0, 3);
world.setBlock(x + 20, y + 1, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 1, z + 12, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 13, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 1, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 1, z + 13, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 1, z + 13, Blocks.stone_slab, 0, 3);
world.setBlock(x + 5, y + 1, z + 13, Blocks.fence_gate, 7, 3);
world.setBlock(x + 6, y + 1, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 1, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 1, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 1, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 1, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 1, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 1, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 1, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 1, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 1, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 1, z + 13, Blocks.fence_gate, 5, 3);
world.setBlock(x + 17, y + 1, z + 13, Blocks.stone_slab, 0, 3);
world.setBlock(x + 18, y + 1, z + 13, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 1, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 1, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 1, z + 13, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 14, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 1, z + 14, Blocks.fence, 0, 3);
world.setBlock(x + 3, y + 1, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 1, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 1, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 1, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 1, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 1, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 1, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 1, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 1, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 1, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 1, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 1, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 1, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 1, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 1, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 1, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 1, z + 14, Blocks.fence, 0, 3);
world.setBlock(x + 20, y + 1, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 1, z + 14, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 15, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 1, z + 15, Blocks.stone_slab, 0, 3);
world.setBlock(x + 3, y + 1, z + 15, Blocks.stone_slab, 0, 3);
world.setBlock(x + 4, y + 1, z + 15, Blocks.stone_slab, 0, 3);
world.setBlock(x + 5, y + 1, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 1, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 1, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 1, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 1, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 1, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 1, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 1, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 1, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 1, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 1, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 1, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 1, z + 15, Blocks.stone_slab, 0, 3);
world.setBlock(x + 18, y + 1, z + 15, Blocks.stone_slab, 0, 3);
world.setBlock(x + 19, y + 1, z + 15, Blocks.stone_slab, 0, 3);
world.setBlock(x + 20, y + 1, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 1, z + 15, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 16, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 1, z + 16, Blocks.fence, 0, 3);
world.setBlock(x + 3, y + 1, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 1, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 1, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 1, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 1, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 1, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 1, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 1, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 1, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 1, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 1, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 1, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 1, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 1, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 1, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 1, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 1, z + 16, Blocks.fence, 0, 3);
world.setBlock(x + 20, y + 1, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 1, z + 16, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 17, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 1, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 1, z + 17, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 1, z + 17, Blocks.stone_slab, 0, 3);
world.setBlock(x + 5, y + 1, z + 17, Blocks.fence_gate, 7, 3);
world.setBlock(x + 6, y + 1, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 1, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 1, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 1, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 1, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 1, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 1, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 1, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 1, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 1, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 1, z + 17, Blocks.fence_gate, 5, 3);
world.setBlock(x + 17, y + 1, z + 17, Blocks.stone_slab, 0, 3);
world.setBlock(x + 18, y + 1, z + 17, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 1, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 1, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 1, z + 17, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 18, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 1, z + 18, Blocks.fence, 0, 3);
world.setBlock(x + 3, y + 1, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 1, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 1, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 1, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 1, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 1, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 1, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 1, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 1, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 1, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 1, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 1, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 1, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 1, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 1, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 1, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 1, z + 18, Blocks.fence, 0, 3);
world.setBlock(x + 20, y + 1, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 1, z + 18, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 19, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 1, z + 19, Blocks.stone_slab, 0, 3);
world.setBlock(x + 3, y + 1, z + 19, Blocks.stone_slab, 0, 3);
world.setBlock(x + 4, y + 1, z + 19, Blocks.stone_slab, 0, 3);
world.setBlock(x + 5, y + 1, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 1, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 1, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 1, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 1, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 1, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 1, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 1, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 1, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 1, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 1, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 1, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 1, z + 19, Blocks.stone_slab, 0, 3);
world.setBlock(x + 18, y + 1, z + 19, Blocks.stone_slab, 0, 3);
world.setBlock(x + 19, y + 1, z + 19, Blocks.stone_slab, 0, 3);
world.setBlock(x + 20, y + 1, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 1, z + 19, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 20, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 1, z + 20, Blocks.fence, 0, 3);
world.setBlock(x + 3, y + 1, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 1, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 1, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 1, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 1, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 1, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 1, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 1, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 1, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 1, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 1, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 1, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 1, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 1, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 1, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 1, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 1, z + 20, Blocks.fence, 0, 3);
world.setBlock(x + 20, y + 1, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 1, z + 20, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 21, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 1, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 1, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 1, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 1, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 1, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 1, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 1, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 1, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 1, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 1, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 1, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 1, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 1, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 1, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 1, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 1, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 1, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 1, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 1, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 1, z + 21, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 22, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 1, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 1, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 1, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 1, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 1, z + 22, Blocks.wool, 12, 3);
world.setBlock(x + 7, y + 1, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 1, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 1, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 1, z + 22, Blocks.wool, 12, 3);
world.setBlock(x + 11, y + 1, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 1, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 1, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 1, z + 22, Blocks.wool, 12, 3);
world.setBlock(x + 15, y + 1, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 1, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 1, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 1, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 1, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 1, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 1, z + 22, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 23, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 1, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 1, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 1, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 1, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 1, z + 23, Blocks.fence, 0, 3);
world.setBlock(x + 7, y + 1, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 1, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 1, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 1, z + 23, Blocks.fence, 0, 3);
world.setBlock(x + 11, y + 1, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 1, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 1, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 1, z + 23, Blocks.fence, 0, 3);
world.setBlock(x + 15, y + 1, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 1, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 1, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 1, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 1, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 1, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 1, z + 23, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 1, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 1, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 2, y + 1, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 3, y + 1, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 4, y + 1, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 5, y + 1, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 6, y + 1, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 7, y + 1, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 8, y + 1, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 9, y + 1, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 10, y + 1, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 11, y + 1, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 12, y + 1, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 13, y + 1, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 14, y + 1, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 15, y + 1, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 16, y + 1, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 17, y + 1, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 18, y + 1, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 19, y + 1, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 20, y + 1, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 21, y + 1, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 2, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 2, z + 0, Blocks.stained_glass, 15, 3);
world.setBlock(x + 2, y + 2, z + 0, Blocks.stained_glass, 15, 3);
world.setBlock(x + 3, y + 2, z + 0, Blocks.stained_glass, 15, 3);
world.setBlock(x + 4, y + 2, z + 0, Blocks.stained_glass, 15, 3);
world.setBlock(x + 5, y + 2, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 6, y + 2, z + 0, Blocks.stained_glass, 15, 3);
world.setBlock(x + 7, y + 2, z + 0, Blocks.stained_glass, 15, 3);
world.setBlock(x + 8, y + 2, z + 0, Blocks.stained_glass, 15, 3);
world.setBlock(x + 9, y + 2, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 10, y + 2, z + 0, Blocks.iron_door, 9, 3);
world.setBlock(x + 11, y + 2, z + 0, Blocks.iron_door, 8, 3);
world.setBlock(x + 12, y + 2, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 13, y + 2, z + 0, Blocks.stained_glass, 15, 3);
world.setBlock(x + 14, y + 2, z + 0, Blocks.stained_glass, 15, 3);
world.setBlock(x + 15, y + 2, z + 0, Blocks.stained_glass, 15, 3);
world.setBlock(x + 16, y + 2, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 17, y + 2, z + 0, Blocks.stained_glass, 15, 3);
world.setBlock(x + 18, y + 2, z + 0, Blocks.stained_glass, 15, 3);
world.setBlock(x + 19, y + 2, z + 0, Blocks.stained_glass, 15, 3);
world.setBlock(x + 20, y + 2, z + 0, Blocks.stained_glass, 15, 3);
world.setBlock(x + 21, y + 2, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 2, z + 1, Blocks.stained_glass, 15, 3);
world.setBlock(x + 1, y + 2, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 2, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 2, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 2, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 2, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 2, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 2, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 2, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 2, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 2, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 2, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 2, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 2, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 2, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 2, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 2, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 2, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 2, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 2, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 2, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 2, z + 1, Blocks.stained_glass, 15, 3);
world.setBlock(x + 0, y + 2, z + 2, Blocks.stained_glass, 15, 3);
world.setBlock(x + 1, y + 2, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 2, z + 2, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 2, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 2, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 2, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 2, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 2, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 2, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 2, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 2, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 2, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 2, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 2, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 2, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 2, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 2, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 2, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 2, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 2, z + 2, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 2, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 2, z + 2, Blocks.stained_glass, 15, 3);
world.setBlock(x + 0, y + 2, z + 3, Blocks.stained_glass, 15, 3);
world.setBlock(x + 1, y + 2, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 2, z + 3, Blocks.iron_bars, 0, 3);
world.setBlock(x + 3, y + 2, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 2, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 2, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 2, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 2, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 2, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 2, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 2, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 2, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 2, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 2, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 2, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 2, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 2, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 2, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 2, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 2, z + 3, Blocks.iron_bars, 0, 3);
world.setBlock(x + 20, y + 2, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 2, z + 3, Blocks.stained_glass, 15, 3);
world.setBlock(x + 0, y + 2, z + 4, Blocks.stained_glass, 15, 3);
world.setBlock(x + 1, y + 2, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 2, z + 4, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 2, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 2, z + 4, Blocks.fence, 0, 3);
world.setBlock(x + 5, y + 2, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 2, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 2, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 2, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 2, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 2, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 2, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 2, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 2, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 2, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 2, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 2, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 2, z + 4, Blocks.fence, 0, 3);
world.setBlock(x + 18, y + 2, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 2, z + 4, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 2, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 2, z + 4, Blocks.stained_glass, 15, 3);
world.setBlock(x + 0, y + 2, z + 5, Blocks.stained_glass, 15, 3);
world.setBlock(x + 1, y + 2, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 2, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 2, z + 5, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 2, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 2, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 2, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 2, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 2, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 2, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 2, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 2, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 2, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 2, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 2, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 2, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 2, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 2, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 2, z + 5, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 2, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 2, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 2, z + 5, Blocks.stained_glass, 15, 3);
world.setBlock(x + 0, y + 2, z + 6, Blocks.stained_glass, 15, 3);
world.setBlock(x + 1, y + 2, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 2, z + 6, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 2, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 2, z + 6, Blocks.fence, 0, 3);
world.setBlock(x + 5, y + 2, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 2, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 2, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 2, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 2, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 2, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 2, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 2, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 2, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 2, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 2, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 2, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 2, z + 6, Blocks.fence, 0, 3);
world.setBlock(x + 18, y + 2, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 2, z + 6, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 2, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 2, z + 6, Blocks.stained_glass, 15, 3);
world.setBlock(x + 0, y + 2, z + 7, Blocks.stained_glass, 15, 3);
world.setBlock(x + 1, y + 2, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 2, z + 7, Blocks.iron_bars, 0, 3);
world.setBlock(x + 3, y + 2, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 2, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 2, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 2, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 2, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 2, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 2, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 2, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 2, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 2, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 2, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 2, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 2, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 2, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 2, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 2, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 2, z + 7, Blocks.iron_bars, 0, 3);
world.setBlock(x + 20, y + 2, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 2, z + 7, Blocks.stained_glass, 15, 3);
world.setBlock(x + 0, y + 2, z + 8, Blocks.stained_glass, 15, 3);
world.setBlock(x + 1, y + 2, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 2, z + 8, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 2, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 2, z + 8, Blocks.fence, 0, 3);
world.setBlock(x + 5, y + 2, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 2, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 2, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 2, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 2, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 2, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 2, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 2, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 2, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 2, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 2, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 2, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 2, z + 8, Blocks.fence, 0, 3);
world.setBlock(x + 18, y + 2, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 2, z + 8, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 2, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 2, z + 8, Blocks.stained_glass, 15, 3);
world.setBlock(x + 0, y + 2, z + 9, Blocks.stained_glass, 15, 3);
world.setBlock(x + 1, y + 2, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 2, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 2, z + 9, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 2, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 2, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 2, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 2, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 2, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 2, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 2, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 2, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 2, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 2, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 2, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 2, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 2, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 2, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 2, z + 9, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 2, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 2, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 2, z + 9, Blocks.stained_glass, 15, 3);
world.setBlock(x + 0, y + 2, z + 10, Blocks.stained_glass, 15, 3);
world.setBlock(x + 1, y + 2, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 2, z + 10, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 2, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 2, z + 10, Blocks.fence, 0, 3);
world.setBlock(x + 5, y + 2, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 2, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 2, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 2, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 2, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 2, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 2, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 2, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 2, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 2, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 2, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 2, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 2, z + 10, Blocks.fence, 0, 3);
world.setBlock(x + 18, y + 2, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 2, z + 10, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 2, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 2, z + 10, Blocks.stained_glass, 15, 3);
world.setBlock(x + 0, y + 2, z + 11, Blocks.stained_glass, 15, 3);
world.setBlock(x + 1, y + 2, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 2, z + 11, Blocks.iron_bars, 0, 3);
world.setBlock(x + 3, y + 2, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 2, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 2, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 2, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 2, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 2, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 2, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 2, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 2, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 2, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 2, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 2, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 2, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 2, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 2, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 2, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 2, z + 11, Blocks.iron_bars, 0, 3);
world.setBlock(x + 20, y + 2, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 2, z + 11, Blocks.stained_glass, 15, 3);
world.setBlock(x + 0, y + 2, z + 12, Blocks.stained_glass, 15, 3);
world.setBlock(x + 1, y + 2, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 2, z + 12, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 2, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 2, z + 12, Blocks.fence, 0, 3);
world.setBlock(x + 5, y + 2, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 2, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 2, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 2, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 2, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 2, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 2, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 2, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 2, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 2, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 2, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 2, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 2, z + 12, Blocks.fence, 0, 3);
world.setBlock(x + 18, y + 2, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 2, z + 12, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 2, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 2, z + 12, Blocks.stained_glass, 15, 3);
world.setBlock(x + 0, y + 2, z + 13, Blocks.stained_glass, 15, 3);
world.setBlock(x + 1, y + 2, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 2, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 2, z + 13, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 2, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 2, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 2, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 2, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 2, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 2, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 2, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 2, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 2, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 2, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 2, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 2, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 2, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 2, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 2, z + 13, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 2, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 2, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 2, z + 13, Blocks.stained_glass, 15, 3);
world.setBlock(x + 0, y + 2, z + 14, Blocks.stained_glass, 15, 3);
world.setBlock(x + 1, y + 2, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 2, z + 14, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 2, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 2, z + 14, Blocks.fence, 0, 3);
world.setBlock(x + 5, y + 2, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 2, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 2, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 2, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 2, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 2, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 2, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 2, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 2, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 2, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 2, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 2, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 2, z + 14, Blocks.fence, 0, 3);
world.setBlock(x + 18, y + 2, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 2, z + 14, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 2, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 2, z + 14, Blocks.stained_glass, 15, 3);
world.setBlock(x + 0, y + 2, z + 15, Blocks.stained_glass, 15, 3);
world.setBlock(x + 1, y + 2, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 2, z + 15, Blocks.iron_bars, 0, 3);
world.setBlock(x + 3, y + 2, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 2, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 2, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 2, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 2, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 2, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 2, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 2, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 2, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 2, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 2, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 2, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 2, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 2, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 2, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 2, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 2, z + 15, Blocks.iron_bars, 0, 3);
world.setBlock(x + 20, y + 2, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 2, z + 15, Blocks.stained_glass, 15, 3);
world.setBlock(x + 0, y + 2, z + 16, Blocks.stained_glass, 15, 3);
world.setBlock(x + 1, y + 2, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 2, z + 16, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 2, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 2, z + 16, Blocks.fence, 0, 3);
world.setBlock(x + 5, y + 2, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 2, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 2, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 2, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 2, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 2, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 2, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 2, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 2, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 2, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 2, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 2, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 2, z + 16, Blocks.fence, 0, 3);
world.setBlock(x + 18, y + 2, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 2, z + 16, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 2, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 2, z + 16, Blocks.stained_glass, 15, 3);
world.setBlock(x + 0, y + 2, z + 17, Blocks.stained_glass, 15, 3);
world.setBlock(x + 1, y + 2, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 2, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 2, z + 17, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 2, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 2, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 2, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 2, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 2, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 2, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 2, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 2, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 2, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 2, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 2, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 2, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 2, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 2, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 2, z + 17, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 2, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 2, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 2, z + 17, Blocks.stained_glass, 15, 3);
world.setBlock(x + 0, y + 2, z + 18, Blocks.stained_glass, 15, 3);
world.setBlock(x + 1, y + 2, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 2, z + 18, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 2, z + 18, Blocks.air, 0, 3);
generate_r02(world, rand, x, y, z);
return true;
}
public boolean generate_r02(World world, Random rand, int x, int y, int z)
{
world.setBlock(x + 4, y + 2, z + 18, Blocks.fence, 0, 3);
world.setBlock(x + 5, y + 2, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 2, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 2, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 2, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 2, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 2, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 2, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 2, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 2, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 2, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 2, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 2, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 2, z + 18, Blocks.fence, 0, 3);
world.setBlock(x + 18, y + 2, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 2, z + 18, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 2, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 2, z + 18, Blocks.stained_glass, 15, 3);
world.setBlock(x + 0, y + 2, z + 19, Blocks.stained_glass, 15, 3);
world.setBlock(x + 1, y + 2, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 2, z + 19, Blocks.iron_bars, 0, 3);
world.setBlock(x + 3, y + 2, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 2, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 2, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 2, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 2, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 2, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 2, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 2, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 2, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 2, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 2, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 2, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 2, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 2, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 2, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 2, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 2, z + 19, Blocks.iron_bars, 0, 3);
world.setBlock(x + 20, y + 2, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 2, z + 19, Blocks.stained_glass, 15, 3);
world.setBlock(x + 0, y + 2, z + 20, Blocks.stained_glass, 15, 3);
world.setBlock(x + 1, y + 2, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 2, z + 20, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 2, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 2, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 2, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 2, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 2, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 2, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 2, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 2, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 2, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 2, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 2, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 2, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 2, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 2, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 2, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 2, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 2, z + 20, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 2, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 2, z + 20, Blocks.stained_glass, 15, 3);
world.setBlock(x + 0, y + 2, z + 21, Blocks.stained_glass, 15, 3);
world.setBlock(x + 1, y + 2, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 2, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 2, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 2, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 2, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 2, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 2, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 2, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 2, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 2, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 2, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 2, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 2, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 2, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 2, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 2, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 2, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 2, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 2, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 2, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 2, z + 21, Blocks.stained_glass, 15, 3);
world.setBlock(x + 0, y + 2, z + 22, Blocks.stained_glass, 15, 3);
world.setBlock(x + 1, y + 2, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 2, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 2, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 2, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 2, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 2, z + 22, Blocks.wool, 12, 3);
world.setBlock(x + 7, y + 2, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 2, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 2, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 2, z + 22, Blocks.wool, 12, 3);
world.setBlock(x + 11, y + 2, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 2, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 2, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 2, z + 22, Blocks.wool, 12, 3);
world.setBlock(x + 15, y + 2, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 2, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 2, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 2, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 2, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 2, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 2, z + 22, Blocks.stained_glass, 15, 3);
world.setBlock(x + 0, y + 2, z + 23, Blocks.stained_glass, 15, 3);
world.setBlock(x + 1, y + 2, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 2, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 2, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 2, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 2, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 2, z + 23, Blocks.fence, 0, 3);
world.setBlock(x + 7, y + 2, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 2, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 2, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 2, z + 23, Blocks.fence, 0, 3);
world.setBlock(x + 11, y + 2, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 2, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 2, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 2, z + 23, Blocks.fence, 0, 3);
world.setBlock(x + 15, y + 2, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 2, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 2, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 2, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 2, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 2, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 2, z + 23, Blocks.stained_glass, 15, 3);
world.setBlock(x + 0, y + 2, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 2, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 2, y + 2, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 3, y + 2, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 4, y + 2, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 5, y + 2, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 6, y + 2, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 7, y + 2, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 8, y + 2, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 9, y + 2, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 10, y + 2, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 11, y + 2, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 12, y + 2, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 13, y + 2, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 14, y + 2, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 15, y + 2, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 16, y + 2, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 17, y + 2, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 18, y + 2, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 19, y + 2, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 20, y + 2, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 21, y + 2, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 2, y + 3, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 3, y + 3, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 4, y + 3, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 5, y + 3, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 6, y + 3, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 7, y + 3, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 8, y + 3, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 9, y + 3, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 10, y + 3, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 11, y + 3, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 12, y + 3, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 13, y + 3, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 14, y + 3, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 15, y + 3, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 16, y + 3, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 17, y + 3, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 18, y + 3, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 19, y + 3, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 20, y + 3, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 21, y + 3, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 1, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 1, Blocks.iron_bars, 0, 3);
world.setBlock(x + 2, y + 3, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 3, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 3, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 3, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 3, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 3, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 3, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 3, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 3, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 3, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 3, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 3, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 3, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 3, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 3, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 3, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 3, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 3, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 3, z + 1, Blocks.iron_bars, 0, 3);
world.setBlock(x + 21, y + 3, z + 1, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 2, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 3, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 3, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 3, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 3, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 3, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 3, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 3, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 3, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 3, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 3, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 3, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 3, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 3, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 3, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 3, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 3, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 3, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 3, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 3, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 3, z + 2, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 3, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 3, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 3, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 3, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 3, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 3, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 3, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 3, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 3, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 3, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 3, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 3, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 3, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 3, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 3, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 3, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 3, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 3, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 3, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 3, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 3, z + 3, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 4, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 3, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 3, z + 4, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 3, z + 4, Blocks.iron_bars, 0, 3);
world.setBlock(x + 5, y + 3, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 3, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 3, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 3, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 3, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 3, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 3, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 3, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 3, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 3, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 3, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 3, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 3, z + 4, Blocks.iron_bars, 0, 3);
world.setBlock(x + 18, y + 3, z + 4, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 3, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 3, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 3, z + 4, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 5, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 3, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 3, z + 5, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 3, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 3, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 3, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 3, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 3, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 3, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 3, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 3, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 3, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 3, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 3, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 3, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 3, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 3, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 3, z + 5, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 3, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 3, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 3, z + 5, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 6, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 3, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 3, z + 6, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 3, z + 6, Blocks.iron_bars, 0, 3);
world.setBlock(x + 5, y + 3, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 3, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 3, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 3, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 3, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 3, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 3, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 3, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 3, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 3, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 3, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 3, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 3, z + 6, Blocks.iron_bars, 0, 3);
world.setBlock(x + 18, y + 3, z + 6, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 3, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 3, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 3, z + 6, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 7, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 3, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 3, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 3, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 3, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 3, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 3, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 3, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 3, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 3, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 3, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 3, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 3, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 3, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 3, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 3, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 3, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 3, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 3, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 3, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 3, z + 7, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 8, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 3, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 3, z + 8, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 3, z + 8, Blocks.iron_bars, 0, 3);
world.setBlock(x + 5, y + 3, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 3, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 3, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 3, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 3, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 3, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 3, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 3, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 3, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 3, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 3, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 3, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 3, z + 8, Blocks.iron_bars, 0, 3);
world.setBlock(x + 18, y + 3, z + 8, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 3, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 3, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 3, z + 8, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 9, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 3, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 3, z + 9, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 3, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 3, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 3, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 3, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 3, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 3, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 3, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 3, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 3, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 3, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 3, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 3, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 3, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 3, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 3, z + 9, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 3, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 3, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 3, z + 9, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 10, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 3, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 3, z + 10, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 3, z + 10, Blocks.iron_bars, 0, 3);
world.setBlock(x + 5, y + 3, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 3, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 3, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 3, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 3, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 3, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 3, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 3, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 3, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 3, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 3, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 3, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 3, z + 10, Blocks.iron_bars, 0, 3);
world.setBlock(x + 18, y + 3, z + 10, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 3, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 3, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 3, z + 10, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 11, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 3, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 3, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 3, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 3, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 3, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 3, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 3, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 3, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 3, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 3, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 3, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 3, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 3, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 3, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 3, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 3, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 3, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 3, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 3, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 3, z + 11, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 12, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 3, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 3, z + 12, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 3, z + 12, Blocks.iron_bars, 0, 3);
world.setBlock(x + 5, y + 3, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 3, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 3, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 3, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 3, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 3, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 3, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 3, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 3, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 3, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 3, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 3, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 3, z + 12, Blocks.iron_bars, 0, 3);
world.setBlock(x + 18, y + 3, z + 12, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 3, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 3, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 3, z + 12, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 13, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 13, Blocks.iron_bars, 0, 3);
world.setBlock(x + 2, y + 3, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 3, z + 13, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 3, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 3, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 3, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 3, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 3, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 3, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 3, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 3, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 3, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 3, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 3, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 3, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 3, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 3, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 3, z + 13, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 3, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 3, z + 13, Blocks.iron_bars, 0, 3);
world.setBlock(x + 21, y + 3, z + 13, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 14, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 3, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 3, z + 14, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 3, z + 14, Blocks.iron_bars, 0, 3);
world.setBlock(x + 5, y + 3, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 3, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 3, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 3, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 3, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 3, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 3, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 3, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 3, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 3, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 3, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 3, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 3, z + 14, Blocks.iron_bars, 0, 3);
world.setBlock(x + 18, y + 3, z + 14, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 3, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 3, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 3, z + 14, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 15, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 3, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 3, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 3, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 3, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 3, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 3, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 3, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 3, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 3, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 3, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 3, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 3, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 3, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 3, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 3, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 3, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 3, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 3, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 3, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 3, z + 15, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 16, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 3, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 3, z + 16, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 3, z + 16, Blocks.iron_bars, 0, 3);
world.setBlock(x + 5, y + 3, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 3, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 3, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 3, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 3, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 3, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 3, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 3, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 3, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 3, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 3, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 3, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 3, z + 16, Blocks.iron_bars, 0, 3);
world.setBlock(x + 18, y + 3, z + 16, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 3, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 3, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 3, z + 16, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 17, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 3, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 3, z + 17, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 3, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 3, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 3, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 3, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 3, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 3, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 3, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 3, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 3, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 3, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 3, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 3, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 3, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 3, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 3, z + 17, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 3, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 3, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 3, z + 17, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 18, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 3, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 3, z + 18, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 3, z + 18, Blocks.iron_bars, 0, 3);
world.setBlock(x + 5, y + 3, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 3, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 3, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 3, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 3, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 3, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 3, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 3, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 3, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 3, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 3, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 3, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 3, z + 18, Blocks.iron_bars, 0, 3);
world.setBlock(x + 18, y + 3, z + 18, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 3, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 3, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 3, z + 18, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 19, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 3, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 3, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 3, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 3, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 3, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 3, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 3, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 3, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 3, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 3, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 3, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 3, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 3, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 3, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 3, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 3, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 3, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 3, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 3, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 3, z + 19, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 20, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 3, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 3, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 3, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 3, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 3, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 3, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 3, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 3, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 3, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 3, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 3, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 3, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 3, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 3, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 3, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 3, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 3, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 3, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 3, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 3, z + 20, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 21, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 3, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 3, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 3, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 3, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 3, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 3, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 3, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 3, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 3, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 3, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 3, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 3, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 3, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 3, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 3, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 3, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 3, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 3, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 3, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 3, z + 21, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 22, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 3, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 3, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 3, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 3, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 3, z + 22, Blocks.fence, 0, 3);
world.setBlock(x + 7, y + 3, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 3, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 3, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 3, z + 22, Blocks.fence, 0, 3);
world.setBlock(x + 11, y + 3, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 3, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 3, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 3, z + 22, Blocks.fence, 0, 3);
world.setBlock(x + 15, y + 3, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 3, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 3, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 3, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 3, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 3, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 3, z + 22, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 23, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 23, Blocks.iron_bars, 0, 3);
world.setBlock(x + 2, y + 3, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 3, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 3, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 3, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 3, z + 23, Blocks.fence, 0, 3);
world.setBlock(x + 7, y + 3, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 3, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 3, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 3, z + 23, Blocks.fence, 0, 3);
world.setBlock(x + 11, y + 3, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 3, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 3, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 3, z + 23, Blocks.fence, 0, 3);
world.setBlock(x + 15, y + 3, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 3, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 3, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 3, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 3, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 3, z + 23, Blocks.iron_bars, 0, 3);
world.setBlock(x + 21, y + 3, z + 23, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 3, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 3, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 2, y + 3, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 3, y + 3, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 4, y + 3, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 5, y + 3, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 6, y + 3, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 7, y + 3, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 8, y + 3, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 9, y + 3, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 10, y + 3, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 11, y + 3, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 12, y + 3, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 13, y + 3, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 14, y + 3, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 15, y + 3, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 16, y + 3, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 17, y + 3, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 18, y + 3, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 19, y + 3, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 20, y + 3, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 21, y + 3, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 2, y + 4, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 3, y + 4, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 4, y + 4, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 5, y + 4, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 6, y + 4, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 7, y + 4, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 8, y + 4, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 9, y + 4, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 10, y + 4, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 11, y + 4, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 12, y + 4, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 13, y + 4, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 14, y + 4, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 15, y + 4, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 16, y + 4, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 17, y + 4, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 18, y + 4, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 19, y + 4, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 20, y + 4, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 21, y + 4, z + 0, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 1, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 1, Blocks.glowstone, 0, 3);
world.setBlock(x + 2, y + 4, z + 1, Blocks.iron_bars, 0, 3);
world.setBlock(x + 3, y + 4, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 4, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 4, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 4, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 4, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 4, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 4, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 4, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 4, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 4, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 4, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 4, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 4, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 4, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 4, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 4, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 4, z + 1, Blocks.iron_bars, 0, 3);
world.setBlock(x + 20, y + 4, z + 1, Blocks.glowstone, 0, 3);
world.setBlock(x + 21, y + 4, z + 1, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 2, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 2, Blocks.iron_bars, 0, 3);
world.setBlock(x + 2, y + 4, z + 2, Blocks.iron_bars, 0, 3);
world.setBlock(x + 3, y + 4, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 4, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 4, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 4, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 4, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 4, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 4, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 4, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 4, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 4, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 4, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 4, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 4, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 4, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 4, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 4, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 4, z + 2, Blocks.iron_bars, 0, 3);
world.setBlock(x + 20, y + 4, z + 2, Blocks.iron_bars, 0, 3);
world.setBlock(x + 21, y + 4, z + 2, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 3, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 4, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 4, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 4, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 4, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 4, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 4, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 4, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 4, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 4, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 4, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 4, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 4, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 4, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 4, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 4, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 4, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 4, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 4, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 4, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 4, z + 3, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 4, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 4, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 4, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 4, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 4, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 4, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 4, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 4, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 4, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 4, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 4, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 4, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 4, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 4, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 4, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 4, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 4, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 4, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 4, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 4, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 4, z + 4, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 5, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 4, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 4, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 4, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 4, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 4, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 4, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 4, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 4, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 4, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 4, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 4, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 4, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 4, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 4, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 4, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 4, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 4, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 4, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 4, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 4, z + 5, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 6, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 4, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 4, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 4, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 4, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 4, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 4, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 4, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 4, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 4, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 4, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 4, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 4, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 4, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 4, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 4, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 4, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 4, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 4, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 4, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 4, z + 6, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 7, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 4, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 4, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 4, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 4, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 4, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 4, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 4, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 4, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 4, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 4, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 4, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 4, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 4, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 4, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 4, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 4, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 4, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 4, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 4, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 4, z + 7, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 8, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 4, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 4, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 4, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 4, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 4, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 4, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 4, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 4, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 4, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 4, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 4, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 4, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 4, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 4, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 4, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 4, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 4, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 4, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 4, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 4, z + 8, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 9, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 4, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 4, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 4, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 4, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 4, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 4, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 4, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 4, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 4, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 4, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 4, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 4, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 4, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 4, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 4, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 4, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 4, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 4, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 4, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 4, z + 9, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 10, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 4, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 4, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 4, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 4, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 4, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 4, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 4, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 4, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 4, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 4, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 4, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 4, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 4, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 4, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 4, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 4, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 4, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 4, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 4, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 4, z + 10, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 11, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 4, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 4, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 4, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 4, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 4, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 4, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 4, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 4, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 4, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 4, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 4, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 4, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 4, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 4, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 4, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 4, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 4, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 4, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 4, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 4, z + 11, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 12, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 12, Blocks.iron_bars, 0, 3);
world.setBlock(x + 2, y + 4, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 4, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 4, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 4, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 4, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 4, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 4, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 4, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 4, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 4, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 4, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 4, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 4, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 4, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 4, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 4, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 4, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 4, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 4, z + 12, Blocks.iron_bars, 0, 3);
world.setBlock(x + 21, y + 4, z + 12, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 13, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 13, Blocks.glowstone, 0, 3);
world.setBlock(x + 2, y + 4, z + 13, Blocks.iron_bars, 0, 3);
world.setBlock(x + 3, y + 4, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 4, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 4, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 4, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 4, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 4, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 4, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 4, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 4, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 4, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 4, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 4, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 4, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 4, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 4, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 4, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 4, z + 13, Blocks.iron_bars, 0, 3);
world.setBlock(x + 20, y + 4, z + 13, Blocks.glowstone, 0, 3);
world.setBlock(x + 21, y + 4, z + 13, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 14, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 14, Blocks.iron_bars, 0, 3);
world.setBlock(x + 2, y + 4, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 4, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 4, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 4, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 4, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 4, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 4, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 4, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 4, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 4, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 4, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 4, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 4, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 4, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 4, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 4, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 4, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 4, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 4, z + 14, Blocks.iron_bars, 0, 3);
world.setBlock(x + 21, y + 4, z + 14, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 15, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 4, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 4, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 4, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 4, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 4, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 4, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 4, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 4, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 4, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 4, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 4, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 4, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 4, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 4, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 4, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 4, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 4, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 4, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 4, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 4, z + 15, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 16, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 4, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 4, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 4, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 4, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 4, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 4, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 4, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 4, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 4, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 4, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 4, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 4, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 4, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 4, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 4, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 4, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 4, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 4, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 4, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 4, z + 16, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 17, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 4, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 4, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 4, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 4, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 4, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 4, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 4, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 4, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 4, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 4, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 4, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 4, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 4, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 4, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 4, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 4, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 4, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 4, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 4, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 4, z + 17, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 18, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 4, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 4, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 4, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 4, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 4, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 4, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 4, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 4, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 4, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 4, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 4, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 4, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 4, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 4, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 4, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 4, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 4, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 4, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 4, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 4, z + 18, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 19, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 4, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 4, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 4, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 4, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 4, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 4, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 4, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 4, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 4, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 4, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 4, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 4, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 4, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 4, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 4, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 4, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 4, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 4, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 4, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 4, z + 19, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 20, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 4, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 4, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 4, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 4, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 4, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 4, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 4, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 4, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 4, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 4, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 4, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 4, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 4, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 4, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 4, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 4, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 4, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 4, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 4, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 4, z + 20, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 21, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 4, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 4, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 4, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 4, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 4, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 4, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 4, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 4, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 4, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 4, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 4, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 4, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 4, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 4, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 4, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 4, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 4, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 4, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 4, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 4, z + 21, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 22, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 22, Blocks.iron_bars, 0, 3);
world.setBlock(x + 2, y + 4, z + 22, Blocks.iron_bars, 0, 3);
world.setBlock(x + 3, y + 4, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 4, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 4, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 4, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 4, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 4, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 4, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 4, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 4, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 4, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 4, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 4, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 4, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 4, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 4, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 4, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 4, z + 22, Blocks.iron_bars, 0, 3);
world.setBlock(x + 20, y + 4, z + 22, Blocks.iron_bars, 0, 3);
world.setBlock(x + 21, y + 4, z + 22, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 23, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 23, Blocks.glowstone, 0, 3);
world.setBlock(x + 2, y + 4, z + 23, Blocks.iron_bars, 0, 3);
world.setBlock(x + 3, y + 4, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 4, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 4, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 4, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 4, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 4, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 4, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 4, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 4, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 4, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 4, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 4, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 4, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 4, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 4, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 4, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 4, z + 23, Blocks.iron_bars, 0, 3);
world.setBlock(x + 20, y + 4, z + 23, Blocks.glowstone, 0, 3);
world.setBlock(x + 21, y + 4, z + 23, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 4, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 1, y + 4, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 2, y + 4, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 3, y + 4, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 4, y + 4, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 5, y + 4, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 6, y + 4, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 7, y + 4, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 8, y + 4, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 9, y + 4, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 10, y + 4, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 11, y + 4, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 12, y + 4, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 13, y + 4, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 14, y + 4, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 15, y + 4, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 16, y + 4, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 17, y + 4, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 18, y + 4, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 19, y + 4, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 20, y + 4, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 21, y + 4, z + 24, Blocks.stone, 0, 3);
world.setBlock(x + 0, y + 5, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 5, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 5, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 5, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 5, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 5, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 5, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 5, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 5, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 5, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 5, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 5, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 5, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 5, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 5, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 5, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 5, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 5, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 5, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 5, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 5, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 1, Blocks.wool, 15, 3);
world.setBlock(x + 2, y + 5, z + 1, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 5, z + 1, Blocks.wool, 15, 3);
world.setBlock(x + 4, y + 5, z + 1, Blocks.wool, 15, 3);
world.setBlock(x + 5, y + 5, z + 1, Blocks.wool, 15, 3);
world.setBlock(x + 6, y + 5, z + 1, Blocks.wool, 15, 3);
world.setBlock(x + 7, y + 5, z + 1, Blocks.wool, 15, 3);
world.setBlock(x + 8, y + 5, z + 1, Blocks.wool, 15, 3);
world.setBlock(x + 9, y + 5, z + 1, Blocks.wool, 15, 3);
world.setBlock(x + 10, y + 5, z + 1, Blocks.wool, 15, 3);
world.setBlock(x + 11, y + 5, z + 1, Blocks.wool, 15, 3);
world.setBlock(x + 12, y + 5, z + 1, Blocks.wool, 15, 3);
world.setBlock(x + 13, y + 5, z + 1, Blocks.wool, 15, 3);
world.setBlock(x + 14, y + 5, z + 1, Blocks.wool, 15, 3);
world.setBlock(x + 15, y + 5, z + 1, Blocks.wool, 15, 3);
world.setBlock(x + 16, y + 5, z + 1, Blocks.wool, 15, 3);
world.setBlock(x + 17, y + 5, z + 1, Blocks.wool, 15, 3);
world.setBlock(x + 18, y + 5, z + 1, Blocks.wool, 15, 3);
world.setBlock(x + 19, y + 5, z + 1, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 5, z + 1, Blocks.wool, 15, 3);
world.setBlock(x + 21, y + 5, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 2, Blocks.wool, 15, 3);
world.setBlock(x + 2, y + 5, z + 2, Blocks.glowstone, 0, 3);
world.setBlock(x + 3, y + 5, z + 2, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 5, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 5, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 5, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 5, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 5, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 5, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 5, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 5, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 5, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 5, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 5, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 5, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 5, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 5, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 5, z + 2, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 5, z + 2, Blocks.glowstone, 0, 3);
world.setBlock(x + 20, y + 5, z + 2, Blocks.wool, 15, 3);
world.setBlock(x + 21, y + 5, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 3, Blocks.wool, 15, 3);
world.setBlock(x + 2, y + 5, z + 3, Blocks.iron_bars, 0, 3);
world.setBlock(x + 3, y + 5, z + 3, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 5, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 5, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 5, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 5, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 5, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 5, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 5, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 5, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 5, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 5, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 5, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 5, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 5, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 5, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 5, z + 3, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 5, z + 3, Blocks.iron_bars, 0, 3);
world.setBlock(x + 20, y + 5, z + 3, Blocks.wool, 15, 3);
world.setBlock(x + 21, y + 5, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 4, Blocks.wool, 15, 3);
world.setBlock(x + 2, y + 5, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 5, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 5, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 5, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 5, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 5, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 5, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 5, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 5, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 5, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 5, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 5, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 5, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 5, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 5, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 5, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 5, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 5, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 5, z + 4, Blocks.wool, 15, 3);
world.setBlock(x + 21, y + 5, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 5, Blocks.wool, 15, 3);
world.setBlock(x + 2, y + 5, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 5, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 5, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 5, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 5, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 5, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 5, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 5, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 5, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 5, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 5, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 5, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 5, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 5, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 5, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 5, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 5, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 5, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 5, z + 5, Blocks.wool, 15, 3);
world.setBlock(x + 21, y + 5, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 6, Blocks.wool, 15, 3);
world.setBlock(x + 2, y + 5, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 5, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 5, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 5, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 5, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 5, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 5, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 5, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 5, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 5, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 5, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 5, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 5, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 5, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 5, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 5, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 5, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 5, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 5, z + 6, Blocks.wool, 15, 3);
world.setBlock(x + 21, y + 5, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 7, Blocks.wool, 15, 3);
world.setBlock(x + 2, y + 5, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 5, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 5, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 5, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 5, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 5, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 5, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 5, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 5, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 5, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 5, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 5, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 5, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 5, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 5, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 5, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 5, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 5, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 5, z + 7, Blocks.wool, 15, 3);
world.setBlock(x + 21, y + 5, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 8, Blocks.wool, 15, 3);
world.setBlock(x + 2, y + 5, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 5, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 5, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 5, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 5, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 5, z + 8, Blocks.chest, 2, 3);
TileEntityChest tileentitychest = (TileEntityChest)world.getTileEntity(x + 7, y + 5, z + 8);
if (tileentitychest != null)
WeightedRandomChestContent.generateChestContents(rand, PopularChestGenHooks.getItems(POPULAR, rand), tileentitychest, PopularChestGenHooks.getCount(POPULAR, rand));
world.setBlock(x + 8, y + 5, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 5, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 5, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 5, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 5, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 5, z + 8, Blocks.chest, 2, 3);
TileEntityChest tileentitychest1 = (TileEntityChest)world.getTileEntity(x + 13, y + 5, z + 8);
if (tileentitychest1 != null)
WeightedRandomChestContent.generateChestContents(rand, PopularChestGenHooks.getItems(POPULAR, rand), tileentitychest1, PopularChestGenHooks.getCount(POPULAR, rand));
world.setBlock(x + 14, y + 5, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 5, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 5, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 5, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 5, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 5, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 5, z + 8, Blocks.wool, 15, 3);
world.setBlock(x + 21, y + 5, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 9, Blocks.wool, 15, 3);
world.setBlock(x + 2, y + 5, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 5, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 5, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 5, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 5, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 5, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 5, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 5, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 5, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 5, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 5, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 5, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 5, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 5, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 5, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 5, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 5, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 5, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 5, z + 9, Blocks.wool, 15, 3);
world.setBlock(x + 21, y + 5, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 10, Blocks.wool, 15, 3);
world.setBlock(x + 2, y + 5, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 5, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 5, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 5, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 5, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 5, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 5, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 5, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 5, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 5, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 5, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 5, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 5, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 5, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 5, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 5, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 5, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 5, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 5, z + 10, Blocks.wool, 15, 3);
world.setBlock(x + 21, y + 5, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 11, Blocks.wool, 15, 3);
world.setBlock(x + 2, y + 5, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 5, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 5, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 5, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 5, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 5, z + 11, Blocks.air, 0, 3);
generate_r03(world, rand, x, y, z);
return true;
}
public boolean generate_r03(World world, Random rand, int x, int y, int z)
{
world.setBlock(x + 8, y + 5, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 5, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 5, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 5, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 5, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 5, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 5, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 5, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 5, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 5, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 5, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 5, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 5, z + 11, Blocks.wool, 15, 3);
world.setBlock(x + 21, y + 5, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 12, Blocks.wool, 15, 3);
world.setBlock(x + 2, y + 5, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 5, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 5, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 5, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 5, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 5, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 5, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 5, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 5, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 5, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 5, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 5, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 5, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 5, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 5, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 5, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 5, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 5, z + 12, Blocks.iron_bars, 0, 3);
world.setBlock(x + 20, y + 5, z + 12, Blocks.wool, 15, 3);
world.setBlock(x + 21, y + 5, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 13, Blocks.wool, 15, 3);
world.setBlock(x + 2, y + 5, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 5, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 5, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 5, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 5, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 5, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 5, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 5, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 5, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 5, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 5, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 5, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 5, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 5, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 5, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 5, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 5, z + 13, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 5, z + 13, Blocks.glowstone, 0, 3);
world.setBlock(x + 20, y + 5, z + 13, Blocks.wool, 15, 3);
world.setBlock(x + 21, y + 5, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 14, Blocks.wool, 15, 3);
world.setBlock(x + 2, y + 5, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 5, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 5, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 5, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 5, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 5, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 5, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 5, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 5, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 5, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 5, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 5, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 5, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 5, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 5, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 5, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 5, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 5, z + 14, Blocks.iron_bars, 0, 3);
world.setBlock(x + 20, y + 5, z + 14, Blocks.wool, 15, 3);
world.setBlock(x + 21, y + 5, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 15, Blocks.wool, 15, 3);
world.setBlock(x + 2, y + 5, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 5, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 5, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 5, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 5, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 5, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 5, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 5, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 5, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 5, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 5, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 5, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 5, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 5, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 5, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 5, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 5, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 5, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 5, z + 15, Blocks.wool, 15, 3);
world.setBlock(x + 21, y + 5, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 16, Blocks.wool, 15, 3);
world.setBlock(x + 2, y + 5, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 5, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 5, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 5, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 5, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 5, z + 16, Blocks.chest, 2, 3);
TileEntityChest tileentitychest2 = (TileEntityChest)world.getTileEntity(x + 7, y + 5, z + 16);
if (tileentitychest2 != null)
WeightedRandomChestContent.generateChestContents(rand, PopularChestGenHooks.getItems(POPULAR, rand), tileentitychest2, PopularChestGenHooks.getCount(POPULAR, rand));
world.setBlock(x + 8, y + 5, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 5, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 5, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 5, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 5, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 5, z + 16, Blocks.chest, 2, 3);
TileEntityChest tileentitychest3 = (TileEntityChest)world.getTileEntity(x + 13, y + 5, z + 16);
if (tileentitychest3 != null)
WeightedRandomChestContent.generateChestContents(rand, PopularChestGenHooks.getItems(POPULAR, rand), tileentitychest3, PopularChestGenHooks.getCount(POPULAR, rand));
world.setBlock(x + 14, y + 5, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 5, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 5, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 5, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 5, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 5, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 5, z + 16, Blocks.wool, 15, 3);
world.setBlock(x + 21, y + 5, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 17, Blocks.wool, 15, 3);
world.setBlock(x + 2, y + 5, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 5, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 5, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 5, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 5, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 5, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 5, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 5, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 5, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 5, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 5, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 5, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 5, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 5, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 5, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 5, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 5, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 5, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 5, z + 17, Blocks.wool, 15, 3);
world.setBlock(x + 21, y + 5, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 18, Blocks.wool, 15, 3);
world.setBlock(x + 2, y + 5, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 5, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 5, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 5, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 5, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 5, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 5, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 5, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 5, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 5, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 5, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 5, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 5, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 5, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 5, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 5, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 5, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 5, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 5, z + 18, Blocks.wool, 15, 3);
world.setBlock(x + 21, y + 5, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 19, Blocks.wool, 15, 3);
world.setBlock(x + 2, y + 5, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 5, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 5, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 5, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 5, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 5, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 5, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 5, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 5, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 5, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 5, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 5, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 5, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 5, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 5, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 5, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 5, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 5, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 5, z + 19, Blocks.wool, 15, 3);
world.setBlock(x + 21, y + 5, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 20, Blocks.wool, 15, 3);
world.setBlock(x + 2, y + 5, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 5, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 5, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 5, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 5, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 5, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 5, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 5, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 5, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 5, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 5, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 5, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 5, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 5, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 5, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 5, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 5, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 5, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 5, z + 20, Blocks.wool, 15, 3);
world.setBlock(x + 21, y + 5, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 21, Blocks.wool, 15, 3);
world.setBlock(x + 2, y + 5, z + 21, Blocks.iron_bars, 0, 3);
world.setBlock(x + 3, y + 5, z + 21, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 5, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 5, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 5, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 5, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 5, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 5, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 5, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 5, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 5, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 5, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 5, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 5, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 5, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 5, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 5, z + 21, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 5, z + 21, Blocks.iron_bars, 0, 3);
world.setBlock(x + 20, y + 5, z + 21, Blocks.wool, 15, 3);
world.setBlock(x + 21, y + 5, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 22, Blocks.wool, 15, 3);
world.setBlock(x + 2, y + 5, z + 22, Blocks.glowstone, 0, 3);
world.setBlock(x + 3, y + 5, z + 22, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 5, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 5, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 5, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 5, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 5, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 5, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 5, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 5, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 5, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 5, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 5, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 5, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 5, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 5, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 5, z + 22, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 5, z + 22, Blocks.glowstone, 0, 3);
world.setBlock(x + 20, y + 5, z + 22, Blocks.wool, 15, 3);
world.setBlock(x + 21, y + 5, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 23, Blocks.wool, 15, 3);
world.setBlock(x + 2, y + 5, z + 23, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 5, z + 23, Blocks.wool, 15, 3);
world.setBlock(x + 4, y + 5, z + 23, Blocks.wool, 15, 3);
world.setBlock(x + 5, y + 5, z + 23, Blocks.wool, 15, 3);
world.setBlock(x + 6, y + 5, z + 23, Blocks.wool, 15, 3);
world.setBlock(x + 7, y + 5, z + 23, Blocks.wool, 15, 3);
world.setBlock(x + 8, y + 5, z + 23, Blocks.wool, 15, 3);
world.setBlock(x + 9, y + 5, z + 23, Blocks.wool, 15, 3);
world.setBlock(x + 10, y + 5, z + 23, Blocks.wool, 15, 3);
world.setBlock(x + 11, y + 5, z + 23, Blocks.wool, 15, 3);
world.setBlock(x + 12, y + 5, z + 23, Blocks.wool, 15, 3);
world.setBlock(x + 13, y + 5, z + 23, Blocks.wool, 15, 3);
world.setBlock(x + 14, y + 5, z + 23, Blocks.wool, 15, 3);
world.setBlock(x + 15, y + 5, z + 23, Blocks.wool, 15, 3);
world.setBlock(x + 16, y + 5, z + 23, Blocks.wool, 15, 3);
world.setBlock(x + 17, y + 5, z + 23, Blocks.wool, 15, 3);
world.setBlock(x + 18, y + 5, z + 23, Blocks.wool, 15, 3);
world.setBlock(x + 19, y + 5, z + 23, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 5, z + 23, Blocks.wool, 15, 3);
world.setBlock(x + 21, y + 5, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 5, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 5, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 5, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 5, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 5, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 5, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 5, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 5, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 5, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 5, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 5, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 5, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 5, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 5, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 5, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 5, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 5, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 5, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 5, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 5, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 5, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 5, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 6, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 6, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 6, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 6, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 6, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 6, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 6, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 6, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 6, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 6, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 6, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 6, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 6, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 6, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 6, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 6, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 6, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 6, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 6, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 6, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 6, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 6, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 6, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 6, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 6, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 6, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 6, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 6, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 6, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 6, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 6, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 6, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 6, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 6, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 6, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 6, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 2, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 6, z + 2, Blocks.wool, 15, 3);
world.setBlock(x + 4, y + 6, z + 2, Blocks.wool, 15, 3);
world.setBlock(x + 5, y + 6, z + 2, Blocks.wool, 15, 3);
world.setBlock(x + 6, y + 6, z + 2, Blocks.wool, 15, 3);
world.setBlock(x + 7, y + 6, z + 2, Blocks.wool, 15, 3);
world.setBlock(x + 8, y + 6, z + 2, Blocks.wool, 15, 3);
world.setBlock(x + 9, y + 6, z + 2, Blocks.wool, 15, 3);
world.setBlock(x + 10, y + 6, z + 2, Blocks.wool, 15, 3);
world.setBlock(x + 11, y + 6, z + 2, Blocks.wool, 15, 3);
world.setBlock(x + 12, y + 6, z + 2, Blocks.wool, 15, 3);
world.setBlock(x + 13, y + 6, z + 2, Blocks.wool, 15, 3);
world.setBlock(x + 14, y + 6, z + 2, Blocks.wool, 15, 3);
world.setBlock(x + 15, y + 6, z + 2, Blocks.wool, 15, 3);
world.setBlock(x + 16, y + 6, z + 2, Blocks.wool, 15, 3);
world.setBlock(x + 17, y + 6, z + 2, Blocks.wool, 15, 3);
world.setBlock(x + 18, y + 6, z + 2, Blocks.wool, 15, 3);
world.setBlock(x + 19, y + 6, z + 2, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 6, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 3, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 6, z + 3, Blocks.glowstone, 0, 3);
world.setBlock(x + 4, y + 6, z + 3, Blocks.iron_bars, 0, 3);
world.setBlock(x + 5, y + 6, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 6, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 6, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 6, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 6, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 6, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 6, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 6, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 6, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 6, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 6, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 6, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 6, z + 3, Blocks.iron_bars, 0, 3);
world.setBlock(x + 18, y + 6, z + 3, Blocks.glowstone, 0, 3);
world.setBlock(x + 19, y + 6, z + 3, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 6, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 4, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 6, z + 4, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 6, z + 4, Blocks.iron_bars, 0, 3);
world.setBlock(x + 5, y + 6, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 6, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 6, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 6, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 6, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 6, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 6, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 6, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 6, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 6, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 6, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 6, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 6, z + 4, Blocks.iron_bars, 0, 3);
world.setBlock(x + 18, y + 6, z + 4, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 6, z + 4, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 6, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 5, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 6, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 6, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 6, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 6, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 6, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 6, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 6, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 6, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 6, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 6, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 6, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 6, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 6, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 6, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 6, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 6, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 6, z + 5, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 6, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 6, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 6, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 6, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 6, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 6, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 6, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 6, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 6, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 6, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 6, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 6, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 6, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 6, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 6, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 6, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 6, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 6, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 6, z + 6, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 6, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 7, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 6, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 6, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 6, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 6, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 6, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 6, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 6, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 6, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 6, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 6, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 6, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 6, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 6, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 6, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 6, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 6, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 6, z + 7, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 6, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 8, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 6, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 6, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 6, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 6, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 6, z + 8, Blocks.iron_bars, 0, 3);
world.setBlock(x + 8, y + 6, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 6, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 6, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 6, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 6, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 6, z + 8, Blocks.iron_bars, 0, 3);
world.setBlock(x + 14, y + 6, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 6, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 6, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 6, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 6, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 6, z + 8, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 6, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 9, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 6, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 6, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 6, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 6, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 6, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 6, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 6, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 6, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 6, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 6, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 6, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 6, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 6, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 6, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 6, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 6, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 6, z + 9, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 6, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 10, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 6, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 6, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 6, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 6, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 6, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 6, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 6, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 6, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 6, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 6, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 6, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 6, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 6, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 6, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 6, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 6, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 6, z + 10, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 6, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 11, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 6, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 6, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 6, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 6, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 6, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 6, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 6, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 6, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 6, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 6, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 6, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 6, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 6, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 6, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 6, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 6, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 6, z + 11, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 6, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 12, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 6, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 6, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 6, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 6, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 6, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 6, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 6, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 6, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 6, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 6, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 6, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 6, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 6, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 6, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 6, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 6, z + 12, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 6, z + 12, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 6, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 13, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 6, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 6, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 6, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 6, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 6, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 6, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 6, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 6, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 6, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 6, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 6, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 6, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 6, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 6, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 6, z + 13, Blocks.iron_bars, 0, 3);
world.setBlock(x + 18, y + 6, z + 13, Blocks.glowstone, 0, 3);
world.setBlock(x + 19, y + 6, z + 13, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 6, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 14, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 6, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 6, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 6, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 6, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 6, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 6, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 6, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 6, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 6, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 6, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 6, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 6, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 6, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 6, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 6, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 6, z + 14, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 6, z + 14, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 6, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 15, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 6, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 6, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 6, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 6, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 6, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 6, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 6, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 6, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 6, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 6, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 6, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 6, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 6, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 6, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 6, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 6, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 6, z + 15, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 6, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 16, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 6, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 6, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 6, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 6, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 6, z + 16, Blocks.iron_bars, 0, 3);
world.setBlock(x + 8, y + 6, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 6, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 6, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 6, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 6, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 6, z + 16, Blocks.iron_bars, 0, 3);
world.setBlock(x + 14, y + 6, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 6, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 6, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 6, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 6, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 6, z + 16, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 6, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 17, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 6, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 6, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 6, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 6, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 6, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 6, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 6, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 6, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 6, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 6, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 6, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 6, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 6, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 6, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 6, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 6, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 6, z + 17, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 6, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 18, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 6, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 6, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 6, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 6, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 6, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 6, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 6, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 6, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 6, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 6, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 6, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 6, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 6, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 6, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 6, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 6, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 6, z + 18, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 6, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 19, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 6, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 6, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 6, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 6, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 6, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 6, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 6, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 6, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 6, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 6, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 6, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 6, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 6, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 6, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 6, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 6, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 6, z + 19, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 6, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 20, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 6, z + 20, Blocks.iron_bars, 0, 3);
world.setBlock(x + 4, y + 6, z + 20, Blocks.iron_bars, 0, 3);
world.setBlock(x + 5, y + 6, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 6, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 6, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 6, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 6, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 6, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 6, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 6, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 6, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 6, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 6, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 6, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 6, z + 20, Blocks.iron_bars, 0, 3);
world.setBlock(x + 18, y + 6, z + 20, Blocks.iron_bars, 0, 3);
world.setBlock(x + 19, y + 6, z + 20, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 6, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 21, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 6, z + 21, Blocks.glowstone, 0, 3);
world.setBlock(x + 4, y + 6, z + 21, Blocks.iron_bars, 0, 3);
world.setBlock(x + 5, y + 6, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 6, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 6, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 6, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 6, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 6, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 6, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 6, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 6, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 6, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 6, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 6, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 6, z + 21, Blocks.iron_bars, 0, 3);
world.setBlock(x + 18, y + 6, z + 21, Blocks.glowstone, 0, 3);
world.setBlock(x + 19, y + 6, z + 21, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 6, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 22, Blocks.wool, 15, 3);
world.setBlock(x + 3, y + 6, z + 22, Blocks.wool, 15, 3);
world.setBlock(x + 4, y + 6, z + 22, Blocks.wool, 15, 3);
world.setBlock(x + 5, y + 6, z + 22, Blocks.wool, 15, 3);
world.setBlock(x + 6, y + 6, z + 22, Blocks.wool, 15, 3);
world.setBlock(x + 7, y + 6, z + 22, Blocks.wool, 15, 3);
world.setBlock(x + 8, y + 6, z + 22, Blocks.wool, 15, 3);
world.setBlock(x + 9, y + 6, z + 22, Blocks.wool, 15, 3);
world.setBlock(x + 10, y + 6, z + 22, Blocks.wool, 15, 3);
world.setBlock(x + 11, y + 6, z + 22, Blocks.wool, 15, 3);
world.setBlock(x + 12, y + 6, z + 22, Blocks.wool, 15, 3);
world.setBlock(x + 13, y + 6, z + 22, Blocks.wool, 15, 3);
world.setBlock(x + 14, y + 6, z + 22, Blocks.wool, 15, 3);
world.setBlock(x + 15, y + 6, z + 22, Blocks.wool, 15, 3);
world.setBlock(x + 16, y + 6, z + 22, Blocks.wool, 15, 3);
world.setBlock(x + 17, y + 6, z + 22, Blocks.wool, 15, 3);
world.setBlock(x + 18, y + 6, z + 22, Blocks.wool, 15, 3);
world.setBlock(x + 19, y + 6, z + 22, Blocks.wool, 15, 3);
world.setBlock(x + 20, y + 6, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 6, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 6, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 6, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 6, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 6, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 6, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 6, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 6, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 6, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 6, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 6, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 6, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 6, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 6, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 6, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 6, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 6, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 6, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 6, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 6, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 6, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 6, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 6, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 6, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 6, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 6, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 6, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 6, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 6, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 6, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 6, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 6, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 6, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 6, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 6, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 6, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 6, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 6, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 6, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 6, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 7, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 7, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 7, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 7, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 7, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 7, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 7, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 7, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 7, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 7, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 7, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 7, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 7, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 7, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 7, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 7, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 7, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 7, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 7, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 7, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 7, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 7, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 7, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 7, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 7, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 7, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 7, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 7, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 7, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 7, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 7, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 7, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 7, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 7, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 7, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 7, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 7, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 7, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 7, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 7, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 7, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 7, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 7, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 7, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 7, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 7, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 7, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 7, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 3, Blocks.wool, 15, 3);
world.setBlock(x + 4, y + 7, z + 3, Blocks.wool, 15, 3);
world.setBlock(x + 5, y + 7, z + 3, Blocks.wool, 15, 3);
world.setBlock(x + 6, y + 7, z + 3, Blocks.wool, 15, 3);
world.setBlock(x + 7, y + 7, z + 3, Blocks.wool, 15, 3);
world.setBlock(x + 8, y + 7, z + 3, Blocks.wool, 15, 3);
world.setBlock(x + 9, y + 7, z + 3, Blocks.wool, 15, 3);
world.setBlock(x + 10, y + 7, z + 3, Blocks.wool, 15, 3);
world.setBlock(x + 11, y + 7, z + 3, Blocks.wool, 15, 3);
world.setBlock(x + 12, y + 7, z + 3, Blocks.wool, 15, 3);
world.setBlock(x + 13, y + 7, z + 3, Blocks.wool, 15, 3);
world.setBlock(x + 14, y + 7, z + 3, Blocks.wool, 15, 3);
world.setBlock(x + 15, y + 7, z + 3, Blocks.wool, 15, 3);
world.setBlock(x + 16, y + 7, z + 3, Blocks.wool, 15, 3);
world.setBlock(x + 17, y + 7, z + 3, Blocks.wool, 15, 3);
world.setBlock(x + 18, y + 7, z + 3, Blocks.wool, 15, 3);
world.setBlock(x + 19, y + 7, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 4, Blocks.wool, 15, 3);
world.setBlock(x + 4, y + 7, z + 4, Blocks.glowstone, 0, 3);
world.setBlock(x + 5, y + 7, z + 4, Blocks.iron_bars, 0, 3);
world.setBlock(x + 6, y + 7, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 7, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 7, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 7, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 7, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 7, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 7, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 7, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 7, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 7, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 7, z + 4, Blocks.iron_bars, 0, 3);
world.setBlock(x + 17, y + 7, z + 4, Blocks.glowstone, 0, 3);
world.setBlock(x + 18, y + 7, z + 4, Blocks.wool, 15, 3);
world.setBlock(x + 19, y + 7, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 5, Blocks.wool, 15, 3);
world.setBlock(x + 4, y + 7, z + 5, Blocks.iron_bars, 0, 3);
world.setBlock(x + 5, y + 7, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 7, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 7, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 7, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 7, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 7, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 7, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 7, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 7, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 7, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 7, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 7, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 7, z + 5, Blocks.iron_bars, 0, 3);
world.setBlock(x + 18, y + 7, z + 5, Blocks.wool, 15, 3);
world.setBlock(x + 19, y + 7, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 6, Blocks.wool, 15, 3);
world.setBlock(x + 4, y + 7, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 7, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 7, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 7, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 7, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 7, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 7, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 7, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 7, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 7, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 7, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 7, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 7, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 7, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 7, z + 6, Blocks.wool, 15, 3);
world.setBlock(x + 19, y + 7, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 7, Blocks.wool, 15, 3);
world.setBlock(x + 4, y + 7, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 7, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 7, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 7, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 7, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 7, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 7, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 7, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 7, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 7, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 7, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 7, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 7, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 7, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 7, z + 7, Blocks.wool, 15, 3);
world.setBlock(x + 19, y + 7, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 8, Blocks.wool, 15, 3);
world.setBlock(x + 4, y + 7, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 7, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 7, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 7, z + 8, Blocks.iron_bars, 0, 3);
world.setBlock(x + 8, y + 7, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 7, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 7, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 7, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 7, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 7, z + 8, Blocks.iron_bars, 0, 3);
world.setBlock(x + 14, y + 7, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 7, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 7, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 7, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 7, z + 8, Blocks.wool, 15, 3);
world.setBlock(x + 19, y + 7, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 9, Blocks.wool, 15, 3);
world.setBlock(x + 4, y + 7, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 7, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 7, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 7, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 7, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 7, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 7, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 7, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 7, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 7, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 7, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 7, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 7, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 7, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 7, z + 9, Blocks.wool, 15, 3);
world.setBlock(x + 19, y + 7, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 10, Blocks.wool, 15, 3);
world.setBlock(x + 4, y + 7, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 7, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 7, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 7, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 7, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 7, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 7, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 7, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 7, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 7, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 7, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 7, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 7, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 7, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 7, z + 10, Blocks.wool, 15, 3);
world.setBlock(x + 19, y + 7, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 11, Blocks.wool, 15, 3);
world.setBlock(x + 4, y + 7, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 7, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 7, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 7, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 7, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 7, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 7, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 7, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 7, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 7, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 7, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 7, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 7, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 7, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 7, z + 11, Blocks.wool, 15, 3);
world.setBlock(x + 19, y + 7, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 12, Blocks.wool, 15, 3);
world.setBlock(x + 4, y + 7, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 7, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 7, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 7, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 7, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 7, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 7, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 7, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 7, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 7, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 7, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 7, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 7, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 7, z + 12, Blocks.iron_bars, 0, 3);
world.setBlock(x + 18, y + 7, z + 12, Blocks.wool, 15, 3);
world.setBlock(x + 19, y + 7, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 13, Blocks.wool, 15, 3);
world.setBlock(x + 4, y + 7, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 7, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 7, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 7, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 7, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 7, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 7, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 7, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 7, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 7, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 7, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 7, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 7, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 7, z + 13, Blocks.glowstone, 0, 3);
world.setBlock(x + 18, y + 7, z + 13, Blocks.wool, 15, 3);
world.setBlock(x + 19, y + 7, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 14, Blocks.wool, 15, 3);
world.setBlock(x + 4, y + 7, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 7, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 7, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 7, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 7, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 7, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 7, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 7, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 7, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 7, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 7, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 7, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 7, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 7, z + 14, Blocks.iron_bars, 0, 3);
world.setBlock(x + 18, y + 7, z + 14, Blocks.wool, 15, 3);
world.setBlock(x + 19, y + 7, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 15, Blocks.wool, 15, 3);
world.setBlock(x + 4, y + 7, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 7, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 7, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 7, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 7, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 7, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 7, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 7, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 7, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 7, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 7, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 7, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 7, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 7, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 7, z + 15, Blocks.wool, 15, 3);
world.setBlock(x + 19, y + 7, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 16, Blocks.wool, 15, 3);
world.setBlock(x + 4, y + 7, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 7, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 7, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 7, z + 16, Blocks.iron_bars, 0, 3);
world.setBlock(x + 8, y + 7, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 7, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 7, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 7, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 7, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 7, z + 16, Blocks.iron_bars, 0, 3);
world.setBlock(x + 14, y + 7, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 7, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 7, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 7, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 7, z + 16, Blocks.wool, 15, 3);
world.setBlock(x + 19, y + 7, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 17, Blocks.wool, 15, 3);
world.setBlock(x + 4, y + 7, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 7, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 7, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 7, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 7, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 7, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 7, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 7, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 7, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 7, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 7, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 7, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 7, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 7, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 7, z + 17, Blocks.wool, 15, 3);
world.setBlock(x + 19, y + 7, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 18, Blocks.wool, 15, 3);
world.setBlock(x + 4, y + 7, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 7, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 7, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 7, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 7, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 7, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 7, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 7, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 7, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 7, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 7, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 7, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 7, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 7, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 7, z + 18, Blocks.wool, 15, 3);
world.setBlock(x + 19, y + 7, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 19, Blocks.wool, 15, 3);
world.setBlock(x + 4, y + 7, z + 19, Blocks.iron_bars, 0, 3);
world.setBlock(x + 5, y + 7, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 7, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 7, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 7, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 7, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 7, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 7, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 7, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 7, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 7, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 7, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 7, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 7, z + 19, Blocks.iron_bars, 0, 3);
world.setBlock(x + 18, y + 7, z + 19, Blocks.wool, 15, 3);
world.setBlock(x + 19, y + 7, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 20, Blocks.wool, 15, 3);
world.setBlock(x + 4, y + 7, z + 20, Blocks.glowstone, 0, 3);
world.setBlock(x + 5, y + 7, z + 20, Blocks.iron_bars, 0, 3);
world.setBlock(x + 6, y + 7, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 7, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 7, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 7, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 7, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 7, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 7, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 7, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 7, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 7, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 7, z + 20, Blocks.iron_bars, 0, 3);
world.setBlock(x + 17, y + 7, z + 20, Blocks.glowstone, 0, 3);
world.setBlock(x + 18, y + 7, z + 20, Blocks.wool, 15, 3);
world.setBlock(x + 19, y + 7, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 21, Blocks.wool, 15, 3);
world.setBlock(x + 4, y + 7, z + 21, Blocks.wool, 15, 3);
world.setBlock(x + 5, y + 7, z + 21, Blocks.wool, 15, 3);
world.setBlock(x + 6, y + 7, z + 21, Blocks.wool, 15, 3);
world.setBlock(x + 7, y + 7, z + 21, Blocks.wool, 15, 3);
world.setBlock(x + 8, y + 7, z + 21, Blocks.wool, 15, 3);
world.setBlock(x + 9, y + 7, z + 21, Blocks.wool, 15, 3);
world.setBlock(x + 10, y + 7, z + 21, Blocks.wool, 15, 3);
world.setBlock(x + 11, y + 7, z + 21, Blocks.wool, 15, 3);
world.setBlock(x + 12, y + 7, z + 21, Blocks.wool, 15, 3);
world.setBlock(x + 13, y + 7, z + 21, Blocks.wool, 15, 3);
world.setBlock(x + 14, y + 7, z + 21, Blocks.wool, 15, 3);
world.setBlock(x + 15, y + 7, z + 21, Blocks.wool, 15, 3);
world.setBlock(x + 16, y + 7, z + 21, Blocks.wool, 15, 3);
world.setBlock(x + 17, y + 7, z + 21, Blocks.wool, 15, 3);
world.setBlock(x + 18, y + 7, z + 21, Blocks.wool, 15, 3);
world.setBlock(x + 19, y + 7, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 7, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 7, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 7, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 7, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 7, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 7, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 7, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 7, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 7, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 7, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 7, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 7, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 7, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 7, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 7, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 7, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 7, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 7, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 7, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 7, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 7, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 7, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 7, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 7, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 7, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 7, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 7, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 7, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 7, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 7, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 7, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 7, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 7, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 7, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 7, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 7, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 7, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 7, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 7, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 7, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 7, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 7, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 7, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 7, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 7, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 7, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 7, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 7, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 7, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 7, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 7, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 7, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 7, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 7, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 8, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 8, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 8, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 8, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 8, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 8, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 8, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 8, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 8, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 8, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 8, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 8, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 8, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 8, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 8, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 8, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 8, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 8, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 8, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 8, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 8, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 8, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 8, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 8, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 8, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 8, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 8, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 8, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 8, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 8, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 8, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 8, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 8, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 8, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 8, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 8, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 8, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 8, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 8, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 8, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 8, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 8, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 8, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 8, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 8, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 8, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 8, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 8, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 8, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 8, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 8, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 8, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 8, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 8, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 8, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 8, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 4, Blocks.wool, 15, 3);
world.setBlock(x + 5, y + 8, z + 4, Blocks.wool, 15, 3);
world.setBlock(x + 6, y + 8, z + 4, Blocks.wool, 15, 3);
world.setBlock(x + 7, y + 8, z + 4, Blocks.wool, 15, 3);
world.setBlock(x + 8, y + 8, z + 4, Blocks.wool, 15, 3);
world.setBlock(x + 9, y + 8, z + 4, Blocks.wool, 15, 3);
world.setBlock(x + 10, y + 8, z + 4, Blocks.wool, 15, 3);
world.setBlock(x + 11, y + 8, z + 4, Blocks.wool, 15, 3);
generate_r04(world, rand, x, y, z);
return true;
}
public boolean generate_r04(World world, Random rand, int x, int y, int z)
{
world.setBlock(x + 12, y + 8, z + 4, Blocks.wool, 15, 3);
world.setBlock(x + 13, y + 8, z + 4, Blocks.wool, 15, 3);
world.setBlock(x + 14, y + 8, z + 4, Blocks.wool, 15, 3);
world.setBlock(x + 15, y + 8, z + 4, Blocks.wool, 15, 3);
world.setBlock(x + 16, y + 8, z + 4, Blocks.wool, 15, 3);
world.setBlock(x + 17, y + 8, z + 4, Blocks.wool, 15, 3);
world.setBlock(x + 18, y + 8, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 5, Blocks.wool, 15, 3);
world.setBlock(x + 5, y + 8, z + 5, Blocks.wool, 15, 3);
world.setBlock(x + 6, y + 8, z + 5, Blocks.wool, 15, 3);
world.setBlock(x + 7, y + 8, z + 5, Blocks.wool, 15, 3);
world.setBlock(x + 8, y + 8, z + 5, Blocks.wool, 15, 3);
world.setBlock(x + 9, y + 8, z + 5, Blocks.wool, 15, 3);
world.setBlock(x + 10, y + 8, z + 5, Blocks.wool, 15, 3);
world.setBlock(x + 11, y + 8, z + 5, Blocks.wool, 15, 3);
world.setBlock(x + 12, y + 8, z + 5, Blocks.wool, 15, 3);
world.setBlock(x + 13, y + 8, z + 5, Blocks.wool, 15, 3);
world.setBlock(x + 14, y + 8, z + 5, Blocks.wool, 15, 3);
world.setBlock(x + 15, y + 8, z + 5, Blocks.wool, 15, 3);
world.setBlock(x + 16, y + 8, z + 5, Blocks.wool, 15, 3);
world.setBlock(x + 17, y + 8, z + 5, Blocks.wool, 15, 3);
world.setBlock(x + 18, y + 8, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 6, Blocks.wool, 15, 3);
world.setBlock(x + 5, y + 8, z + 6, Blocks.wool, 15, 3);
world.setBlock(x + 6, y + 8, z + 6, Blocks.glowstone, 0, 3);
world.setBlock(x + 7, y + 8, z + 6, Blocks.glowstone, 0, 3);
world.setBlock(x + 8, y + 8, z + 6, Blocks.glowstone, 0, 3);
world.setBlock(x + 9, y + 8, z + 6, Blocks.glowstone, 0, 3);
world.setBlock(x + 10, y + 8, z + 6, Blocks.glowstone, 0, 3);
world.setBlock(x + 11, y + 8, z + 6, Blocks.glowstone, 0, 3);
world.setBlock(x + 12, y + 8, z + 6, Blocks.glowstone, 0, 3);
world.setBlock(x + 13, y + 8, z + 6, Blocks.glowstone, 0, 3);
world.setBlock(x + 14, y + 8, z + 6, Blocks.glowstone, 0, 3);
world.setBlock(x + 15, y + 8, z + 6, Blocks.glowstone, 0, 3);
world.setBlock(x + 16, y + 8, z + 6, Blocks.wool, 15, 3);
world.setBlock(x + 17, y + 8, z + 6, Blocks.wool, 15, 3);
world.setBlock(x + 18, y + 8, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 7, Blocks.wool, 15, 3);
world.setBlock(x + 5, y + 8, z + 7, Blocks.wool, 15, 3);
world.setBlock(x + 6, y + 8, z + 7, Blocks.glowstone, 0, 3);
world.setBlock(x + 7, y + 8, z + 7, Blocks.glowstone, 0, 3);
world.setBlock(x + 8, y + 8, z + 7, Blocks.glowstone, 0, 3);
world.setBlock(x + 9, y + 8, z + 7, Blocks.glowstone, 0, 3);
world.setBlock(x + 10, y + 8, z + 7, Blocks.glowstone, 0, 3);
world.setBlock(x + 11, y + 8, z + 7, Blocks.glowstone, 0, 3);
world.setBlock(x + 12, y + 8, z + 7, Blocks.glowstone, 0, 3);
world.setBlock(x + 13, y + 8, z + 7, Blocks.glowstone, 0, 3);
world.setBlock(x + 14, y + 8, z + 7, Blocks.glowstone, 0, 3);
world.setBlock(x + 15, y + 8, z + 7, Blocks.glowstone, 0, 3);
world.setBlock(x + 16, y + 8, z + 7, Blocks.wool, 15, 3);
world.setBlock(x + 17, y + 8, z + 7, Blocks.wool, 15, 3);
world.setBlock(x + 18, y + 8, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 8, Blocks.wool, 15, 3);
world.setBlock(x + 5, y + 8, z + 8, Blocks.wool, 15, 3);
world.setBlock(x + 6, y + 8, z + 8, Blocks.glowstone, 0, 3);
world.setBlock(x + 7, y + 8, z + 8, Blocks.glowstone, 0, 3);
world.setBlock(x + 8, y + 8, z + 8, Blocks.glowstone, 0, 3);
world.setBlock(x + 9, y + 8, z + 8, Blocks.glowstone, 0, 3);
world.setBlock(x + 10, y + 8, z + 8, Blocks.glowstone, 0, 3);
world.setBlock(x + 11, y + 8, z + 8, Blocks.glowstone, 0, 3);
world.setBlock(x + 12, y + 8, z + 8, Blocks.glowstone, 0, 3);
world.setBlock(x + 13, y + 8, z + 8, Blocks.glowstone, 0, 3);
world.setBlock(x + 14, y + 8, z + 8, Blocks.glowstone, 0, 3);
world.setBlock(x + 15, y + 8, z + 8, Blocks.glowstone, 0, 3);
world.setBlock(x + 16, y + 8, z + 8, Blocks.wool, 15, 3);
world.setBlock(x + 17, y + 8, z + 8, Blocks.wool, 15, 3);
world.setBlock(x + 18, y + 8, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 9, Blocks.wool, 15, 3);
world.setBlock(x + 5, y + 8, z + 9, Blocks.wool, 15, 3);
world.setBlock(x + 6, y + 8, z + 9, Blocks.glowstone, 0, 3);
world.setBlock(x + 7, y + 8, z + 9, Blocks.glowstone, 0, 3);
world.setBlock(x + 8, y + 8, z + 9, Blocks.glowstone, 0, 3);
world.setBlock(x + 9, y + 8, z + 9, Blocks.glowstone, 0, 3);
world.setBlock(x + 10, y + 8, z + 9, Blocks.glowstone, 0, 3);
world.setBlock(x + 11, y + 8, z + 9, Blocks.glowstone, 0, 3);
world.setBlock(x + 12, y + 8, z + 9, Blocks.glowstone, 0, 3);
world.setBlock(x + 13, y + 8, z + 9, Blocks.glowstone, 0, 3);
world.setBlock(x + 14, y + 8, z + 9, Blocks.glowstone, 0, 3);
world.setBlock(x + 15, y + 8, z + 9, Blocks.glowstone, 0, 3);
world.setBlock(x + 16, y + 8, z + 9, Blocks.wool, 15, 3);
world.setBlock(x + 17, y + 8, z + 9, Blocks.wool, 15, 3);
world.setBlock(x + 18, y + 8, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 10, Blocks.wool, 15, 3);
world.setBlock(x + 5, y + 8, z + 10, Blocks.wool, 15, 3);
world.setBlock(x + 6, y + 8, z + 10, Blocks.glowstone, 0, 3);
world.setBlock(x + 7, y + 8, z + 10, Blocks.glowstone, 0, 3);
world.setBlock(x + 8, y + 8, z + 10, Blocks.glowstone, 0, 3);
world.setBlock(x + 9, y + 8, z + 10, Blocks.glowstone, 0, 3);
world.setBlock(x + 10, y + 8, z + 10, Blocks.glowstone, 0, 3);
world.setBlock(x + 11, y + 8, z + 10, Blocks.glowstone, 0, 3);
world.setBlock(x + 12, y + 8, z + 10, Blocks.glowstone, 0, 3);
world.setBlock(x + 13, y + 8, z + 10, Blocks.glowstone, 0, 3);
world.setBlock(x + 14, y + 8, z + 10, Blocks.glowstone, 0, 3);
world.setBlock(x + 15, y + 8, z + 10, Blocks.glowstone, 0, 3);
world.setBlock(x + 16, y + 8, z + 10, Blocks.wool, 15, 3);
world.setBlock(x + 17, y + 8, z + 10, Blocks.wool, 15, 3);
world.setBlock(x + 18, y + 8, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 11, Blocks.wool, 15, 3);
world.setBlock(x + 5, y + 8, z + 11, Blocks.wool, 15, 3);
world.setBlock(x + 6, y + 8, z + 11, Blocks.glowstone, 0, 3);
world.setBlock(x + 7, y + 8, z + 11, Blocks.glowstone, 0, 3);
world.setBlock(x + 8, y + 8, z + 11, Blocks.glowstone, 0, 3);
world.setBlock(x + 9, y + 8, z + 11, Blocks.glowstone, 0, 3);
world.setBlock(x + 10, y + 8, z + 11, Blocks.glowstone, 0, 3);
world.setBlock(x + 11, y + 8, z + 11, Blocks.glowstone, 0, 3);
world.setBlock(x + 12, y + 8, z + 11, Blocks.glowstone, 0, 3);
world.setBlock(x + 13, y + 8, z + 11, Blocks.glowstone, 0, 3);
world.setBlock(x + 14, y + 8, z + 11, Blocks.glowstone, 0, 3);
world.setBlock(x + 15, y + 8, z + 11, Blocks.glowstone, 0, 3);
world.setBlock(x + 16, y + 8, z + 11, Blocks.wool, 15, 3);
world.setBlock(x + 17, y + 8, z + 11, Blocks.wool, 15, 3);
world.setBlock(x + 18, y + 8, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 12, Blocks.wool, 15, 3);
world.setBlock(x + 5, y + 8, z + 12, Blocks.wool, 15, 3);
world.setBlock(x + 6, y + 8, z + 12, Blocks.glowstone, 0, 3);
world.setBlock(x + 7, y + 8, z + 12, Blocks.glowstone, 0, 3);
world.setBlock(x + 8, y + 8, z + 12, Blocks.glowstone, 0, 3);
world.setBlock(x + 9, y + 8, z + 12, Blocks.glowstone, 0, 3);
world.setBlock(x + 10, y + 8, z + 12, Blocks.glowstone, 0, 3);
world.setBlock(x + 11, y + 8, z + 12, Blocks.glowstone, 0, 3);
world.setBlock(x + 12, y + 8, z + 12, Blocks.glowstone, 0, 3);
world.setBlock(x + 13, y + 8, z + 12, Blocks.glowstone, 0, 3);
world.setBlock(x + 14, y + 8, z + 12, Blocks.glowstone, 0, 3);
world.setBlock(x + 15, y + 8, z + 12, Blocks.glowstone, 0, 3);
world.setBlock(x + 16, y + 8, z + 12, Blocks.wool, 15, 3);
world.setBlock(x + 17, y + 8, z + 12, Blocks.wool, 15, 3);
world.setBlock(x + 18, y + 8, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 13, Blocks.wool, 15, 3);
world.setBlock(x + 5, y + 8, z + 13, Blocks.wool, 15, 3);
world.setBlock(x + 6, y + 8, z + 13, Blocks.glowstone, 0, 3);
world.setBlock(x + 7, y + 8, z + 13, Blocks.glowstone, 0, 3);
world.setBlock(x + 8, y + 8, z + 13, Blocks.glowstone, 0, 3);
world.setBlock(x + 9, y + 8, z + 13, Blocks.glowstone, 0, 3);
world.setBlock(x + 10, y + 8, z + 13, Blocks.glowstone, 0, 3);
world.setBlock(x + 11, y + 8, z + 13, Blocks.glowstone, 0, 3);
world.setBlock(x + 12, y + 8, z + 13, Blocks.glowstone, 0, 3);
world.setBlock(x + 13, y + 8, z + 13, Blocks.glowstone, 0, 3);
world.setBlock(x + 14, y + 8, z + 13, Blocks.glowstone, 0, 3);
world.setBlock(x + 15, y + 8, z + 13, Blocks.glowstone, 0, 3);
world.setBlock(x + 16, y + 8, z + 13, Blocks.wool, 15, 3);
world.setBlock(x + 17, y + 8, z + 13, Blocks.wool, 15, 3);
world.setBlock(x + 18, y + 8, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 14, Blocks.wool, 15, 3);
world.setBlock(x + 5, y + 8, z + 14, Blocks.wool, 15, 3);
world.setBlock(x + 6, y + 8, z + 14, Blocks.glowstone, 0, 3);
world.setBlock(x + 7, y + 8, z + 14, Blocks.glowstone, 0, 3);
world.setBlock(x + 8, y + 8, z + 14, Blocks.glowstone, 0, 3);
world.setBlock(x + 9, y + 8, z + 14, Blocks.glowstone, 0, 3);
world.setBlock(x + 10, y + 8, z + 14, Blocks.glowstone, 0, 3);
world.setBlock(x + 11, y + 8, z + 14, Blocks.glowstone, 0, 3);
world.setBlock(x + 12, y + 8, z + 14, Blocks.glowstone, 0, 3);
world.setBlock(x + 13, y + 8, z + 14, Blocks.glowstone, 0, 3);
world.setBlock(x + 14, y + 8, z + 14, Blocks.glowstone, 0, 3);
world.setBlock(x + 15, y + 8, z + 14, Blocks.glowstone, 0, 3);
world.setBlock(x + 16, y + 8, z + 14, Blocks.wool, 15, 3);
world.setBlock(x + 17, y + 8, z + 14, Blocks.wool, 15, 3);
world.setBlock(x + 18, y + 8, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 15, Blocks.wool, 15, 3);
world.setBlock(x + 5, y + 8, z + 15, Blocks.wool, 15, 3);
world.setBlock(x + 6, y + 8, z + 15, Blocks.glowstone, 0, 3);
world.setBlock(x + 7, y + 8, z + 15, Blocks.glowstone, 0, 3);
world.setBlock(x + 8, y + 8, z + 15, Blocks.glowstone, 0, 3);
world.setBlock(x + 9, y + 8, z + 15, Blocks.glowstone, 0, 3);
world.setBlock(x + 10, y + 8, z + 15, Blocks.glowstone, 0, 3);
world.setBlock(x + 11, y + 8, z + 15, Blocks.glowstone, 0, 3);
world.setBlock(x + 12, y + 8, z + 15, Blocks.glowstone, 0, 3);
world.setBlock(x + 13, y + 8, z + 15, Blocks.glowstone, 0, 3);
world.setBlock(x + 14, y + 8, z + 15, Blocks.glowstone, 0, 3);
world.setBlock(x + 15, y + 8, z + 15, Blocks.glowstone, 0, 3);
world.setBlock(x + 16, y + 8, z + 15, Blocks.wool, 15, 3);
world.setBlock(x + 17, y + 8, z + 15, Blocks.wool, 15, 3);
world.setBlock(x + 18, y + 8, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 16, Blocks.wool, 15, 3);
world.setBlock(x + 5, y + 8, z + 16, Blocks.wool, 15, 3);
world.setBlock(x + 6, y + 8, z + 16, Blocks.glowstone, 0, 3);
world.setBlock(x + 7, y + 8, z + 16, Blocks.glowstone, 0, 3);
world.setBlock(x + 8, y + 8, z + 16, Blocks.glowstone, 0, 3);
world.setBlock(x + 9, y + 8, z + 16, Blocks.glowstone, 0, 3);
world.setBlock(x + 10, y + 8, z + 16, Blocks.glowstone, 0, 3);
world.setBlock(x + 11, y + 8, z + 16, Blocks.glowstone, 0, 3);
world.setBlock(x + 12, y + 8, z + 16, Blocks.glowstone, 0, 3);
world.setBlock(x + 13, y + 8, z + 16, Blocks.glowstone, 0, 3);
world.setBlock(x + 14, y + 8, z + 16, Blocks.glowstone, 0, 3);
world.setBlock(x + 15, y + 8, z + 16, Blocks.glowstone, 0, 3);
world.setBlock(x + 16, y + 8, z + 16, Blocks.wool, 15, 3);
world.setBlock(x + 17, y + 8, z + 16, Blocks.wool, 15, 3);
world.setBlock(x + 18, y + 8, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 17, Blocks.wool, 15, 3);
world.setBlock(x + 5, y + 8, z + 17, Blocks.wool, 15, 3);
world.setBlock(x + 6, y + 8, z + 17, Blocks.glowstone, 0, 3);
world.setBlock(x + 7, y + 8, z + 17, Blocks.glowstone, 0, 3);
world.setBlock(x + 8, y + 8, z + 17, Blocks.glowstone, 0, 3);
world.setBlock(x + 9, y + 8, z + 17, Blocks.glowstone, 0, 3);
world.setBlock(x + 10, y + 8, z + 17, Blocks.glowstone, 0, 3);
world.setBlock(x + 11, y + 8, z + 17, Blocks.glowstone, 0, 3);
world.setBlock(x + 12, y + 8, z + 17, Blocks.glowstone, 0, 3);
world.setBlock(x + 13, y + 8, z + 17, Blocks.glowstone, 0, 3);
world.setBlock(x + 14, y + 8, z + 17, Blocks.glowstone, 0, 3);
world.setBlock(x + 15, y + 8, z + 17, Blocks.glowstone, 0, 3);
world.setBlock(x + 16, y + 8, z + 17, Blocks.wool, 15, 3);
world.setBlock(x + 17, y + 8, z + 17, Blocks.wool, 15, 3);
world.setBlock(x + 18, y + 8, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 18, Blocks.wool, 15, 3);
world.setBlock(x + 5, y + 8, z + 18, Blocks.wool, 15, 3);
world.setBlock(x + 6, y + 8, z + 18, Blocks.glowstone, 0, 3);
world.setBlock(x + 7, y + 8, z + 18, Blocks.glowstone, 0, 3);
world.setBlock(x + 8, y + 8, z + 18, Blocks.glowstone, 0, 3);
world.setBlock(x + 9, y + 8, z + 18, Blocks.glowstone, 0, 3);
world.setBlock(x + 10, y + 8, z + 18, Blocks.glowstone, 0, 3);
world.setBlock(x + 11, y + 8, z + 18, Blocks.glowstone, 0, 3);
world.setBlock(x + 12, y + 8, z + 18, Blocks.glowstone, 0, 3);
world.setBlock(x + 13, y + 8, z + 18, Blocks.glowstone, 0, 3);
world.setBlock(x + 14, y + 8, z + 18, Blocks.glowstone, 0, 3);
world.setBlock(x + 15, y + 8, z + 18, Blocks.glowstone, 0, 3);
world.setBlock(x + 16, y + 8, z + 18, Blocks.wool, 15, 3);
world.setBlock(x + 17, y + 8, z + 18, Blocks.wool, 15, 3);
world.setBlock(x + 18, y + 8, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 19, Blocks.wool, 15, 3);
world.setBlock(x + 5, y + 8, z + 19, Blocks.wool, 15, 3);
world.setBlock(x + 6, y + 8, z + 19, Blocks.wool, 15, 3);
world.setBlock(x + 7, y + 8, z + 19, Blocks.wool, 15, 3);
world.setBlock(x + 8, y + 8, z + 19, Blocks.wool, 15, 3);
world.setBlock(x + 9, y + 8, z + 19, Blocks.wool, 15, 3);
world.setBlock(x + 10, y + 8, z + 19, Blocks.wool, 15, 3);
world.setBlock(x + 11, y + 8, z + 19, Blocks.wool, 15, 3);
world.setBlock(x + 12, y + 8, z + 19, Blocks.wool, 15, 3);
world.setBlock(x + 13, y + 8, z + 19, Blocks.wool, 15, 3);
world.setBlock(x + 14, y + 8, z + 19, Blocks.wool, 15, 3);
world.setBlock(x + 15, y + 8, z + 19, Blocks.wool, 15, 3);
world.setBlock(x + 16, y + 8, z + 19, Blocks.wool, 15, 3);
world.setBlock(x + 17, y + 8, z + 19, Blocks.wool, 15, 3);
world.setBlock(x + 18, y + 8, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 20, Blocks.wool, 15, 3);
world.setBlock(x + 5, y + 8, z + 20, Blocks.wool, 15, 3);
world.setBlock(x + 6, y + 8, z + 20, Blocks.wool, 15, 3);
world.setBlock(x + 7, y + 8, z + 20, Blocks.wool, 15, 3);
world.setBlock(x + 8, y + 8, z + 20, Blocks.wool, 15, 3);
world.setBlock(x + 9, y + 8, z + 20, Blocks.wool, 15, 3);
world.setBlock(x + 10, y + 8, z + 20, Blocks.wool, 15, 3);
world.setBlock(x + 11, y + 8, z + 20, Blocks.wool, 15, 3);
world.setBlock(x + 12, y + 8, z + 20, Blocks.wool, 15, 3);
world.setBlock(x + 13, y + 8, z + 20, Blocks.wool, 15, 3);
world.setBlock(x + 14, y + 8, z + 20, Blocks.wool, 15, 3);
world.setBlock(x + 15, y + 8, z + 20, Blocks.wool, 15, 3);
world.setBlock(x + 16, y + 8, z + 20, Blocks.wool, 15, 3);
world.setBlock(x + 17, y + 8, z + 20, Blocks.wool, 15, 3);
world.setBlock(x + 18, y + 8, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 8, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 8, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 8, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 8, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 8, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 8, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 8, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 8, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 8, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 8, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 8, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 8, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 8, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 8, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 8, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 8, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 8, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 8, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 8, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 8, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 8, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 8, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 8, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 8, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 8, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 8, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 8, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 8, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 8, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 8, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 8, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 8, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 8, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 8, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 8, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 8, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 8, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 8, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 8, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 8, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 8, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 8, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 8, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 8, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 8, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 8, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 8, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 8, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 8, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 8, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 8, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 8, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 8, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 8, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 8, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 8, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 8, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 8, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 8, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 8, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 8, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 8, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 8, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 8, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 9, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 9, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 9, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 9, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 9, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 9, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 9, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 9, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 9, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 9, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 9, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 9, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 9, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 9, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 9, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 9, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 9, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 9, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 9, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 9, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 9, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 9, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 9, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 9, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 9, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 9, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 9, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 9, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 9, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 9, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 9, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 9, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 9, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 9, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 9, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 9, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 9, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 9, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 9, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 9, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 9, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 9, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 9, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 9, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 9, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 9, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 9, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 9, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 9, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 9, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 9, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 9, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 9, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 9, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 9, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 9, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 9, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 9, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 9, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 9, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 6, Blocks.wool, 15, 3);
world.setBlock(x + 7, y + 9, z + 6, Blocks.wool, 15, 3);
world.setBlock(x + 8, y + 9, z + 6, Blocks.wool, 15, 3);
world.setBlock(x + 9, y + 9, z + 6, Blocks.wool, 15, 3);
world.setBlock(x + 10, y + 9, z + 6, Blocks.wool, 15, 3);
world.setBlock(x + 11, y + 9, z + 6, Blocks.wool, 15, 3);
world.setBlock(x + 12, y + 9, z + 6, Blocks.wool, 15, 3);
world.setBlock(x + 13, y + 9, z + 6, Blocks.wool, 15, 3);
world.setBlock(x + 14, y + 9, z + 6, Blocks.wool, 15, 3);
world.setBlock(x + 15, y + 9, z + 6, Blocks.wool, 15, 3);
world.setBlock(x + 16, y + 9, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 7, Blocks.wool, 15, 3);
world.setBlock(x + 7, y + 9, z + 7, Blocks.wool, 15, 3);
world.setBlock(x + 8, y + 9, z + 7, Blocks.wool, 15, 3);
world.setBlock(x + 9, y + 9, z + 7, Blocks.wool, 15, 3);
world.setBlock(x + 10, y + 9, z + 7, Blocks.wool, 15, 3);
world.setBlock(x + 11, y + 9, z + 7, Blocks.wool, 15, 3);
world.setBlock(x + 12, y + 9, z + 7, Blocks.wool, 15, 3);
world.setBlock(x + 13, y + 9, z + 7, Blocks.wool, 15, 3);
world.setBlock(x + 14, y + 9, z + 7, Blocks.wool, 15, 3);
world.setBlock(x + 15, y + 9, z + 7, Blocks.wool, 15, 3);
world.setBlock(x + 16, y + 9, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 8, Blocks.wool, 15, 3);
world.setBlock(x + 7, y + 9, z + 8, Blocks.wool, 15, 3);
world.setBlock(x + 8, y + 9, z + 8, Blocks.wool, 15, 3);
world.setBlock(x + 9, y + 9, z + 8, Blocks.wool, 15, 3);
world.setBlock(x + 10, y + 9, z + 8, Blocks.wool, 15, 3);
world.setBlock(x + 11, y + 9, z + 8, Blocks.wool, 15, 3);
world.setBlock(x + 12, y + 9, z + 8, Blocks.wool, 15, 3);
world.setBlock(x + 13, y + 9, z + 8, Blocks.wool, 15, 3);
world.setBlock(x + 14, y + 9, z + 8, Blocks.wool, 15, 3);
world.setBlock(x + 15, y + 9, z + 8, Blocks.wool, 15, 3);
world.setBlock(x + 16, y + 9, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 9, Blocks.wool, 15, 3);
world.setBlock(x + 7, y + 9, z + 9, Blocks.wool, 15, 3);
world.setBlock(x + 8, y + 9, z + 9, Blocks.wool, 15, 3);
world.setBlock(x + 9, y + 9, z + 9, Blocks.wool, 15, 3);
world.setBlock(x + 10, y + 9, z + 9, Blocks.wool, 15, 3);
world.setBlock(x + 11, y + 9, z + 9, Blocks.wool, 15, 3);
world.setBlock(x + 12, y + 9, z + 9, Blocks.wool, 15, 3);
world.setBlock(x + 13, y + 9, z + 9, Blocks.wool, 15, 3);
world.setBlock(x + 14, y + 9, z + 9, Blocks.wool, 15, 3);
world.setBlock(x + 15, y + 9, z + 9, Blocks.wool, 15, 3);
world.setBlock(x + 16, y + 9, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 10, Blocks.wool, 15, 3);
world.setBlock(x + 7, y + 9, z + 10, Blocks.wool, 15, 3);
world.setBlock(x + 8, y + 9, z + 10, Blocks.wool, 15, 3);
world.setBlock(x + 9, y + 9, z + 10, Blocks.wool, 15, 3);
world.setBlock(x + 10, y + 9, z + 10, Blocks.wool, 15, 3);
world.setBlock(x + 11, y + 9, z + 10, Blocks.wool, 15, 3);
world.setBlock(x + 12, y + 9, z + 10, Blocks.wool, 15, 3);
world.setBlock(x + 13, y + 9, z + 10, Blocks.wool, 15, 3);
world.setBlock(x + 14, y + 9, z + 10, Blocks.wool, 15, 3);
world.setBlock(x + 15, y + 9, z + 10, Blocks.wool, 15, 3);
world.setBlock(x + 16, y + 9, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 11, Blocks.wool, 15, 3);
world.setBlock(x + 7, y + 9, z + 11, Blocks.wool, 15, 3);
world.setBlock(x + 8, y + 9, z + 11, Blocks.wool, 15, 3);
world.setBlock(x + 9, y + 9, z + 11, Blocks.wool, 15, 3);
world.setBlock(x + 10, y + 9, z + 11, Blocks.wool, 15, 3);
world.setBlock(x + 11, y + 9, z + 11, Blocks.wool, 15, 3);
world.setBlock(x + 12, y + 9, z + 11, Blocks.wool, 15, 3);
world.setBlock(x + 13, y + 9, z + 11, Blocks.wool, 15, 3);
world.setBlock(x + 14, y + 9, z + 11, Blocks.wool, 15, 3);
world.setBlock(x + 15, y + 9, z + 11, Blocks.wool, 15, 3);
world.setBlock(x + 16, y + 9, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 12, Blocks.wool, 15, 3);
world.setBlock(x + 7, y + 9, z + 12, Blocks.wool, 15, 3);
world.setBlock(x + 8, y + 9, z + 12, Blocks.wool, 15, 3);
world.setBlock(x + 9, y + 9, z + 12, Blocks.wool, 15, 3);
world.setBlock(x + 10, y + 9, z + 12, Blocks.wool, 15, 3);
world.setBlock(x + 11, y + 9, z + 12, Blocks.wool, 15, 3);
world.setBlock(x + 12, y + 9, z + 12, Blocks.wool, 15, 3);
world.setBlock(x + 13, y + 9, z + 12, Blocks.wool, 15, 3);
world.setBlock(x + 14, y + 9, z + 12, Blocks.wool, 15, 3);
world.setBlock(x + 15, y + 9, z + 12, Blocks.wool, 15, 3);
world.setBlock(x + 16, y + 9, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 13, Blocks.wool, 15, 3);
world.setBlock(x + 7, y + 9, z + 13, Blocks.wool, 15, 3);
world.setBlock(x + 8, y + 9, z + 13, Blocks.wool, 15, 3);
world.setBlock(x + 9, y + 9, z + 13, Blocks.wool, 15, 3);
world.setBlock(x + 10, y + 9, z + 13, Blocks.wool, 15, 3);
world.setBlock(x + 11, y + 9, z + 13, Blocks.wool, 15, 3);
world.setBlock(x + 12, y + 9, z + 13, Blocks.wool, 15, 3);
world.setBlock(x + 13, y + 9, z + 13, Blocks.wool, 15, 3);
world.setBlock(x + 14, y + 9, z + 13, Blocks.wool, 15, 3);
world.setBlock(x + 15, y + 9, z + 13, Blocks.wool, 15, 3);
world.setBlock(x + 16, y + 9, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 14, Blocks.wool, 15, 3);
world.setBlock(x + 7, y + 9, z + 14, Blocks.wool, 15, 3);
world.setBlock(x + 8, y + 9, z + 14, Blocks.wool, 15, 3);
world.setBlock(x + 9, y + 9, z + 14, Blocks.wool, 15, 3);
world.setBlock(x + 10, y + 9, z + 14, Blocks.wool, 15, 3);
world.setBlock(x + 11, y + 9, z + 14, Blocks.wool, 15, 3);
world.setBlock(x + 12, y + 9, z + 14, Blocks.wool, 15, 3);
world.setBlock(x + 13, y + 9, z + 14, Blocks.wool, 15, 3);
world.setBlock(x + 14, y + 9, z + 14, Blocks.wool, 15, 3);
world.setBlock(x + 15, y + 9, z + 14, Blocks.wool, 15, 3);
world.setBlock(x + 16, y + 9, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 15, Blocks.wool, 15, 3);
world.setBlock(x + 7, y + 9, z + 15, Blocks.wool, 15, 3);
world.setBlock(x + 8, y + 9, z + 15, Blocks.wool, 15, 3);
world.setBlock(x + 9, y + 9, z + 15, Blocks.wool, 15, 3);
world.setBlock(x + 10, y + 9, z + 15, Blocks.wool, 15, 3);
world.setBlock(x + 11, y + 9, z + 15, Blocks.wool, 15, 3);
world.setBlock(x + 12, y + 9, z + 15, Blocks.wool, 15, 3);
world.setBlock(x + 13, y + 9, z + 15, Blocks.wool, 15, 3);
world.setBlock(x + 14, y + 9, z + 15, Blocks.wool, 15, 3);
world.setBlock(x + 15, y + 9, z + 15, Blocks.wool, 15, 3);
world.setBlock(x + 16, y + 9, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 16, Blocks.wool, 15, 3);
world.setBlock(x + 7, y + 9, z + 16, Blocks.wool, 15, 3);
world.setBlock(x + 8, y + 9, z + 16, Blocks.wool, 15, 3);
world.setBlock(x + 9, y + 9, z + 16, Blocks.wool, 15, 3);
world.setBlock(x + 10, y + 9, z + 16, Blocks.wool, 15, 3);
world.setBlock(x + 11, y + 9, z + 16, Blocks.wool, 15, 3);
world.setBlock(x + 12, y + 9, z + 16, Blocks.wool, 15, 3);
world.setBlock(x + 13, y + 9, z + 16, Blocks.wool, 15, 3);
world.setBlock(x + 14, y + 9, z + 16, Blocks.wool, 15, 3);
world.setBlock(x + 15, y + 9, z + 16, Blocks.wool, 15, 3);
world.setBlock(x + 16, y + 9, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 17, Blocks.wool, 15, 3);
world.setBlock(x + 7, y + 9, z + 17, Blocks.wool, 15, 3);
world.setBlock(x + 8, y + 9, z + 17, Blocks.wool, 15, 3);
world.setBlock(x + 9, y + 9, z + 17, Blocks.wool, 15, 3);
world.setBlock(x + 10, y + 9, z + 17, Blocks.wool, 15, 3);
world.setBlock(x + 11, y + 9, z + 17, Blocks.wool, 15, 3);
world.setBlock(x + 12, y + 9, z + 17, Blocks.wool, 15, 3);
world.setBlock(x + 13, y + 9, z + 17, Blocks.wool, 15, 3);
world.setBlock(x + 14, y + 9, z + 17, Blocks.wool, 15, 3);
world.setBlock(x + 15, y + 9, z + 17, Blocks.wool, 15, 3);
world.setBlock(x + 16, y + 9, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 18, Blocks.wool, 15, 3);
world.setBlock(x + 7, y + 9, z + 18, Blocks.wool, 15, 3);
world.setBlock(x + 8, y + 9, z + 18, Blocks.wool, 15, 3);
world.setBlock(x + 9, y + 9, z + 18, Blocks.wool, 15, 3);
world.setBlock(x + 10, y + 9, z + 18, Blocks.wool, 15, 3);
world.setBlock(x + 11, y + 9, z + 18, Blocks.wool, 15, 3);
world.setBlock(x + 12, y + 9, z + 18, Blocks.wool, 15, 3);
world.setBlock(x + 13, y + 9, z + 18, Blocks.wool, 15, 3);
world.setBlock(x + 14, y + 9, z + 18, Blocks.wool, 15, 3);
world.setBlock(x + 15, y + 9, z + 18, Blocks.wool, 15, 3);
world.setBlock(x + 16, y + 9, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 9, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 9, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 9, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 9, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 9, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 9, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 9, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 9, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 9, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 9, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 9, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 9, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 9, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 9, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 9, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 9, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 9, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 9, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 9, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 9, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 9, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 9, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 9, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 9, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 9, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 9, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 9, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 9, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 9, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 9, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 9, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 9, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 9, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 9, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 9, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 9, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 9, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 9, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 9, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 9, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 9, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 9, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 9, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 9, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 9, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 9, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 9, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 9, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 9, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 9, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 9, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 9, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 9, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 9, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 9, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 9, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 9, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 9, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 9, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 9, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 9, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 9, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 9, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 9, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 9, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 9, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 9, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 9, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 9, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 9, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 9, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 9, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 0, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 1, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 2, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 3, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 4, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 5, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 6, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 7, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 8, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 9, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 10, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 11, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 12, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 13, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 14, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 15, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 16, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 17, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 18, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 19, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 20, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 21, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 22, Blocks.air, 0, 3);
generate_r05(world, rand, x, y, z);
return true;
}
public boolean generate_r05(World world, Random rand, int x, int y, int z)
{
world.setBlock(x + 16, y + 10, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 22, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 23, Blocks.air, 0, 3);
world.setBlock(x + 0, y + 10, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 1, y + 10, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 2, y + 10, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 3, y + 10, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 4, y + 10, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 5, y + 10, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 6, y + 10, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 7, y + 10, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 8, y + 10, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 9, y + 10, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 10, y + 10, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 11, y + 10, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 12, y + 10, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 13, y + 10, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 14, y + 10, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 15, y + 10, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 16, y + 10, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 17, y + 10, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 18, y + 10, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 19, y + 10, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 20, y + 10, z + 24, Blocks.air, 0, 3);
world.setBlock(x + 21, y + 10, z + 24, Blocks.air, 0, 3);
return true;
}
}<file_sep>/src/main/java/com/popularmmos/armor/FuriousArmor.java
package com.popularmmos.armor;
import com.popularmmos.main.PopularItems;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.world.World;
public class FuriousArmor extends ItemArmor{
private String [] amourTypes = new String [] {"Helmfurious", "Chestfurious", "legsfurious", "bootsfurious"};
public FuriousArmor(ArmorMaterial armorMaterial, int renderIndex, int armourType) {
super(armorMaterial, renderIndex, armourType);
}
@Override
public String getArmorTexture(ItemStack stack, Entity entity, int slot, String layer){
if(stack.getItem().equals(PopularItems.furiousHelm)|| stack.getItem().equals(PopularItems.furiousChest) || stack.getItem().equals(PopularItems.furiousBoots)){
return "popular:textures/armor/furious_1.png";
}
if(stack.getItem().equals(PopularItems.furiousLegs)){
return "popular:textures/armor/furious_2.png";
}
else
return null;
}
@Override
public void registerIcons(IIconRegister reg){
if(this == PopularItems.furiousHelm)
this.itemIcon = reg.registerIcon("popular:furiousHelm");
if(this == PopularItems.furiousChest)
this.itemIcon = reg.registerIcon("popular:furiousChest");
if(this == PopularItems.furiousLegs)
this.itemIcon = reg.registerIcon("popular:furiousLegs");
if(this == PopularItems.furiousBoots)
this.itemIcon = reg.registerIcon("popular:furiousBoots");
}
private void effectPlayer(EntityPlayer player, Potion potion, int amplifier)
{
if (player.getActivePotionEffect(potion) == null || player.getActivePotionEffect(potion).getDuration() <= 1)
{
player.addPotionEffect(new PotionEffect(potion.id, 20, amplifier, true));
}
}
boolean isWearingFullSet(EntityPlayer player, Item Helm, Item Chest, Item Legs, Item boots)
{
return player.inventory.armorItemInSlot(3) != null && player.inventory.armorItemInSlot(3).getItem() == Helm
&& player.inventory.armorItemInSlot(2) != null && player.inventory.armorItemInSlot(2).getItem() == Chest
&& player.inventory.armorItemInSlot(1) != null && player.inventory.armorItemInSlot(1).getItem() == Legs
&& player.inventory.armorItemInSlot(0) != null && player.inventory.armorItemInSlot(0).getItem() == boots;
}
public void onArmorTick(World world, EntityPlayer player, ItemStack itemStack)
{
if (itemStack.getItem() == PopularItems.furiousChest)
{
this.effectPlayer(player, Potion.resistance, 1);
}
if (itemStack.getItem() == PopularItems.furiousLegs)
{
this.effectPlayer(player, Potion.jump, 1);
}
if (itemStack.getItem() == PopularItems.furiousBoots)
{
this.effectPlayer(player, Potion.moveSpeed, 1);
}
if (this.isWearingFullSet(player, PopularItems.furiousHelm, PopularItems.furiousChest, PopularItems.furiousLegs, PopularItems.furiousBoots))
{
this.effectPlayer(player, Potion.damageBoost, 1);
}
}
}<file_sep>/src/main/java/com/popularmmos/items/largeWeight/ItemLargeWeight.java
package com.popularmmos.items.largeWeight;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemSword;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.world.World;
public class ItemLargeWeight extends ItemSword {
public ItemLargeWeight(ToolMaterial tm)
{
super(tm);
}
private EntityPlayer player;
@SideOnly(Side.CLIENT)
public boolean isFull3D()
{
return true;
}
@Override
public void onUpdate(ItemStack itemStack, World world, Entity entity, int i, boolean b)
{
if(!world.isRemote)
{
if(entity instanceof EntityPlayer) {
player = (EntityPlayer) entity;
if (player.getCurrentEquippedItem() != null && player.getCurrentEquippedItem().getItem() instanceof ItemLargeWeight)
{
player.addPotionEffect(new PotionEffect(Potion.moveSlowdown.id, 1, 2));
}
}
}
}
}
<file_sep>/src/main/java/com/popularmmos/entities/pat/smallweight/ModelSmallWeight.java
package com.popularmmos.entities.pat.smallweight;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.entity.Entity;
/**
* ItemSmallWeight - Undefined
* Created using Tabula 5.1.0
*/
public class ModelSmallWeight extends ModelBase {
public ModelRenderer WeightBar;
public ModelRenderer WeightSideL;
public ModelRenderer WeightSideR;
public ModelSmallWeight() {
this.textureWidth = 64;
this.textureHeight = 32;
this.WeightSideL = new ModelRenderer(this, 0, 0);
this.WeightSideL.setRotationPoint(-6.0F, 1.6F, -6.0F);
this.WeightSideL.addBox(0.0F, 2.0F, -5.0F, 6, 8, 8, 0.0F);
this.setRotateAngle(WeightSideL, 0.742986662573986F, 0.0F, 0.0F);
this.WeightSideR = new ModelRenderer(this, 0, 0);
this.WeightSideR.setRotationPoint(20.0F, 1.0F, -5.8F);
this.WeightSideR.addBox(0.0F, 2.0F, -5.0F, 6, 8, 8, 0.0F);
this.setRotateAngle(WeightSideR, 0.7853981633974483F, 0.0F, 0.0F);
this.WeightBar = new ModelRenderer(this, 0, 22);
this.WeightBar.setRotationPoint(0.0F, 0.0F, 0.0F);
this.WeightBar.addBox(0.0F, 4.0F, -5.0F, 20, 5, 5, 0.0F);
this.WeightBar.addChild(this.WeightSideL);
this.WeightBar.addChild(this.WeightSideR);
}
@Override
public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) {
this.WeightBar.render(f5);
}
public void render(float f)
{
this.WeightBar.render(f);
}
/**
* This is a helper function from Tabula to set the rotation of model parts
*/
public void setRotateAngle(ModelRenderer modelRenderer, float x, float y, float z) {
modelRenderer.rotateAngleX = x;
modelRenderer.rotateAngleY = y;
modelRenderer.rotateAngleZ = z;
}
}
<file_sep>/src/main/java/com/popularmmos/explosions/BlockPinkTNT.java
package com.popularmmos.explosions;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.BlockTNT;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.util.IIcon;
import net.minecraft.world.Explosion;
import net.minecraft.world.World;
public class BlockPinkTNT extends BlockTNT
{
private IIcon icon;
private IIcon icon2;
@Override
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister p_149651_1_)
{
this.blockIcon = p_149651_1_.registerIcon("popular:textures/pinktnt_side.png");
this.icon = p_149651_1_.registerIcon("popular:textures/pinktnt_top.png");
this.icon2 = p_149651_1_.registerIcon("popular:textures/pinktnt_bottom.png");
}
@Override
public IIcon getIcon(int side, int meta)
{
return side == 0 ? this.icon2 : (side == 1 ? this.icon : this.blockIcon);
}
/**
* Called upon the block being destroyed by an explosion
*/
@Override
public void onBlockDestroyedByExplosion(World p_149723_1_, int p_149723_2_, int p_149723_3_, int p_149723_4_, Explosion p_149723_5_)
{
if (!p_149723_1_.isRemote)
{
EntityPinkTNTPrimed entitypinktntprimed = new EntityPinkTNTPrimed(p_149723_1_, (double)((float)p_149723_2_ + 0.5F), (double)((float)p_149723_3_ + 0.5F), (double)((float)p_149723_4_ + 0.5F), p_149723_5_.getExplosivePlacedBy());
entitypinktntprimed.fuse = p_149723_1_.rand.nextInt(entitypinktntprimed.fuse / 4) + entitypinktntprimed.fuse / 8;
p_149723_1_.spawnEntityInWorld(entitypinktntprimed);
}
}
}
<file_sep>/src/main/java/com/popularmmos/items/pinkSword/ItemPinkSword.java
package com.popularmmos.items.pinkSword;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.item.ItemSword;
public class ItemPinkSword extends ItemSword
{
public ItemPinkSword(ToolMaterial tm)
{
super(tm);
}
@SideOnly(Side.CLIENT)
public boolean isFull3D()
{
return true;
}
}
<file_sep>/src/main/java/com/popularmmos/entities/pat/EntityPat.java
package com.popularmmos.entities.pat;
import com.popularmmos.entities.pat.ai.AILargeThrow;
import com.popularmmos.entities.pat.ai.AISmallThrow;
import com.popularmmos.entities.pat.ai.AIUppercut;
import com.popularmmos.main.MMOs;
import com.popularmmos.main.PopularItems;
import io.netty.util.internal.ThreadLocalRandom;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.*;
import net.minecraft.entity.boss.IBossDisplayData;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.monster.IMob;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import thehippomaster.AnimationAPI.AnimationAPI;
import thehippomaster.AnimationAPI.IAnimatedEntity;
import java.util.Iterator;
public class EntityPat extends EntityMob implements IBossDisplayData, IAnimatedEntity, IMob
{
public static EntityLiving getAttackTarget;
public int animTick;
public int deathTicks;
private int animID;
private Minecraft mc;
public EntityPat(World world)
{
super(world);
this.setHealth(this.getMaxHealth());
this.setSize(2.8F, 6.5F);
this.isImmuneToFire = true;
tasks.addTask(1, new AIUppercut(this));
tasks.addTask(1, new AISmallThrow(this));
tasks.addTask(1, new AILargeThrow(this));
tasks.addTask(2, new EntityAISwimming(this));
tasks.addTask(3, new EntityAIWander(this, .8D));
tasks.addTask(4, new EntityAIWatchClosest(this, EntityPlayer.class, 6F));
tasks.addTask(5, new EntityAILookIdle(this));
targetTasks.addTask(6, new EntityAIHurtByTarget(this, false));
this.targetTasks.addTask(7, new EntityAINearestAttackableTarget(this, EntityPlayer.class, 64, true));
this.tasks.addTask(8, new EntityAIWatchClosest(this, EntityPlayer.class, 32F));
}
protected void applyEntityAttributes() {
super.applyEntityAttributes();
this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(500D);
this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.20000000298023224D);
this.getEntityAttribute(SharedMonsterAttributes.followRange).setBaseValue(40D);
}
public boolean isAIEnabled() {
return true;
}
public float getShadowSize() {
return this.height / 8F;
}
protected String getHurtSound() {
return "popular:PatGrunt";
}
protected String getDeathSound() {
return "popular:PatDeath";
}
public int getTotalArmorValue() {
return 2;
}
protected void dropFewItems(boolean b, int amt)
{
int essenceAmt;
essenceAmt = ThreadLocalRandom.current().nextInt(30, 35);
this.dropItem(PopularItems.largeWeight, 1);
this.dropItem(PopularItems.furiousEssence, essenceAmt);
if (!this.worldObj.isRemote)
{
Iterator iterator = this.worldObj.getEntitiesWithinAABB(EntityPlayer.class, this.boundingBox.expand(50.0D, 100.0D, 50.0D)).iterator();
while (iterator.hasNext())
{
EntityPlayer entityplayer = (EntityPlayer)iterator.next();
entityplayer.triggerAchievement(MMOs.popularmmos);
}
}
}
@Override
public void setAnimID(int id) {
animID = id;
}
@Override
public void setAnimTick(int tick) {
animTick = tick;
}
@Override
public int getAnimID() {
return animID;
}
@Override
public int getAnimTick() {
return animTick;
}
public void onUpdate() {
super.onUpdate();
if (animID != 0)
animTick++;
}
public void onLivingUpdate()
{
super.onLivingUpdate();
if(this.ticksExisted % 50 == 0)
{
this.heal(6F);
}
if(this.getAttackTarget() != null && this.animID == 0)
switch(this.rand.nextInt(3))
{
case 0:
this.setAnimID(1);
AnimationAPI.sendAnimPacket(this, 1);
break;
case 1:
this.setAnimID(2);
AnimationAPI.sendAnimPacket(this, 2);
break;
case 2:
this.setAnimID(3);
AnimationAPI.sendAnimPacket(this,3);
break;
default:
break;
}
if(this.getAttackTarget() != null)
{
this.getLookHelper().setLookPositionWithEntity(this.getAttackTarget(), 10F, 30F);
}
Entity entity = this.getAttackTarget();
if (entity != null)
{
double d0 = entity.posX - this.posX;
double d1 = entity.posZ - this.posZ;
double d3 = d0 * d0 + d1 * d1;
if ((d3 > 1.0D) && (this.animTick == 0))
{
double d5 = MathHelper.sqrt_double(d3);
this.motionX += d0 / d5 * 0.0625D - this.motionX;
this.motionZ += d1 / d5 * 0.0625D - this.motionZ;
}
}
this.renderYawOffset = this.rotationYaw = this.rotationYawHead;
if(this.ticksExisted == 1)
{
this.playSound("popular:PatSpawn", 10F, 10F);
}
}
public void onDeathUpdate()
{
deathTicks++;
if(deathTicks == 200)
{
this.setDead();
}
}
}
<file_sep>/src/main/java/com/popularmmos/entities/pat/ai/AISmallThrow.java
package com.popularmmos.entities.pat.ai;
import com.popularmmos.entities.pat.EntityPat;
import com.popularmmos.entities.pat.smallweight.EntitySmallWeight;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.MathHelper;
import thehippomaster.AnimationAPI.AIAnimation;
public class AISmallThrow extends AIAnimation {
private EntityPat entity;
private EntityLivingBase attackTarget;
public AISmallThrow(EntityPat pat)
{
super(pat);
entity = pat;
attackTarget = null;
}
public int getAnimID()
{
return 2;
}
public boolean isAutomatic()
{
return true;
}
public int getDuration()
{
return 50;
}
public boolean continueExecuting()
{
return entity.animTick > 50 ? false : super.continueExecuting();
}
public void startExecuting()
{
super.startExecuting();
attackTarget = entity.getAttackTarget();
}
public void updateTask()
{
if(entity.getAnimTick() < 14 && attackTarget != null)
entity.getLookHelper().setLookPositionWithEntity(attackTarget, 20F,20F);
if(entity.getAnimTick() == 45 && attackTarget != null)
{
EntitySmallWeight entitySmallWeight = new EntitySmallWeight(entity.worldObj, entity);
double d0 = attackTarget.posX - entity.posX;
double d1 = attackTarget.posY + (double)attackTarget.getEyeHeight() - 1.100000023841858D - entitySmallWeight.posY;
double d2 = attackTarget.posZ - entity.posZ;
float f1 = MathHelper.sqrt_double(d0 * d0 + d2 * d2) * 0.2F;
entitySmallWeight.setThrowableHeading(d0, d1 + (double)f1, d2, 1.6F, 12.0F);
entity.playSound("popular:PatWeightThrow", 1.0F, 1.0F / (entity.getRNG().nextFloat() * 0.4F + 0.8F));
entity.worldObj.spawnEntityInWorld(entitySmallWeight);
}
if(entity.getAnimTick() > 50)
entity.setAnimID(0);
}
}
<file_sep>/src/main/java/com/popularmmos/PopularDamageSources.java
package com.popularmmos;
import com.popularmmos.entities.pat.largeweight.EntityLargeWeight;
import com.popularmmos.entities.pat.smallweight.EntitySmallWeight;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EntityDamageSourceIndirect;
public class PopularDamageSources extends DamageSource{
public PopularDamageSources(String name)
{
super(name);
}
public static DamageSource upperCut = new PopularDamageSources("upperCut");
public static DamageSource swordSlice = new PopularDamageSources("swordSlice");
public static DamageSource downwardsSwordSlice = new PopularDamageSources("downwardsSwordSlice");
public static DamageSource beam = new PopularDamageSources("beam");
public static DamageSource smallWeight (EntitySmallWeight entitySmallWeight, EntityLivingBase thrower)
{
return (new EntityDamageSourceIndirect("smallWeight", entitySmallWeight, thrower)).setProjectile();
}
public static DamageSource largeWeight (EntityLargeWeight entityLargeWeight, EntityLivingBase thrower)
{
return (new EntityDamageSourceIndirect("largeWeight", entityLargeWeight, thrower)).setProjectile();
}
}
<file_sep>/src/main/java/com/popularmmos/main/CraftingManager.java
package com.popularmmos.main;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
public class CraftingManager
{
public static void Popular()
{
addCraftingRecipes();
addSmeltingRecipes();
}
public static void addCraftingRecipes()
{
GameRegistry.addShapedRecipe(new ItemStack(PopularItems.furiousHelm,1), new Object[] {"FFF", "F F", 'F', PopularItems.furiousEssence});
GameRegistry.addShapedRecipe(new ItemStack(PopularItems.furiousChest,1), new Object[] {"F F", "FFF", "FFF", 'F', PopularItems.furiousEssence});
GameRegistry.addShapedRecipe(new ItemStack(PopularItems.furiousLegs,1), new Object[] {"FFF", "F F", "F F", 'F', PopularItems.furiousEssence});
GameRegistry.addShapedRecipe(new ItemStack(PopularItems.furiousBoots,1), new Object[] {"F F", "F F", 'F', PopularItems.furiousEssence});
GameRegistry.addShapedRecipe(new ItemStack(PopularItems.pinkSword, 1), new Object[] {"P", "P", "S", 'P', PopularItems.pinkEssence, 'S', Items.nether_star});
GameRegistry.addShapedRecipe(new ItemStack(PopularItems.smallWeight, 1), new Object[]{"FSF", 'F', PopularItems.furiousEssence, 'S', Items.stick});
GameRegistry.addShapedRecipe(new ItemStack(PopularBlocks.patFace, 1), new Object[] {"FFF", "FFF", "FFF", 'F', PopularItems.furiousEssence});
}
public static void addSmeltingRecipes()
{
GameRegistry.addSmelting(PopularBlocks.pinkOre, new ItemStack(PopularItems.pinkEssence, 1), 10F);
}
}
<file_sep>/src/main/java/com/popularmmos/items/Essence.java
package com.popularmmos.items;
import net.minecraft.item.Item;
public class Essence extends Item
{
public Essence()
{
super();
this.setMaxStackSize(64);
}
}
| 20f922ac6ba7497b0076bbea3410f27c8ce3ee82 | [
"Java"
] | 19 | Java | ketan-ryan/PopularMMOs-Mod-1.7.10 | dc758e00af6a13dd308da85acde28dc12e7ccc86 | a9665fad61c289178295c7648b3bda9856186ffd |
refs/heads/master | <repo_name>HassanAhmed2020/urlshortner<file_sep>/config.js
var config = {};
config.db = {};
config.db.host = 'dbuser:<EMAIL>:41185';
config.db.name = 'hussurlshortner';
module.exports = config;
| a04a8729c43a38c2b72e17162b93a7e7bccf5f2d | [
"JavaScript"
] | 1 | JavaScript | HassanAhmed2020/urlshortner | 5ae6cd501ab656599e693fe43a65697b0711de86 | ce71f3a8fb0f29f9b0ec7216f94428354f3fbe56 |
refs/heads/master | <file_sep>import React from 'react';
import './App.scss';
const Product = props => {
const plus = () => {
// Call props.onVote to increase the vote count for this product
};
const minus = () => {
// Call props.onVote to decrease the vote count for this product
};
return (
<li>
<span>{/* Product name */}</span> - <span>votes: {/* Number of votes*/}</span>
<button onClick={plus}>+</button>{" "}
<button onClick={minus}>-</button>
</li>
);
};
export default Product;
<file_sep># Grocery App
## The exercise
1. You have an App class, which receives a list of products, each one with name and votes. The app should render an unordered list, with a list item for each product. Products can be upvoted or downvoted.
1. By appropriately using React state and props, implement the upvote/downvote logic. Keep the state in the topmost component (App), while the Product component should accept props.
#### Example
Passing the following array as products prop to the App `[{ name: "Oranges", votes: 0 }, { name: "Bananas", votes: 0 }]` and clicking the `+` button next to the Oranges should result in HTML like:
```
<div id="root">
<ul>
<li>
<span>Oranges</span> - <span>votes: 1</span><button>+</button> <button>-</button>
</li>
<li>
<span>Bananas</span> - <span>votes: 0</span><button>+</button> <button>-</button>
</li>
</ul>
</div>
```
## How to get started
1. Fork the repo - when it's forked the repo name will change to `{your username}/grocery-app_blank`
* (You might want to rename the repo at this point and remove the `_blank`)
1. Clone the repo
1. `cd` into the repo
1. run `npm install`
1. run `npm start` to run the app in the development mode. Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
## FYI
`npm run build` builds the app for production to the `build` folder. It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.
## Source
This exercise is Question #4 on <a href="https://www.testdome.com/d/react-js-interview-questions/304" target="_blank">Testdome: React Interview Questions</a>
| c24d499ab7aab359d6eb5aa6973b53c0a785fbef | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | aminakarl/grocery-app_blank | 71c57537dc7621dae344e7c6533072dca823bc72 | 9872f23a6e0d7345b4a86fc18c249aeb5074546e |
refs/heads/master | <repo_name>igorcferreira/ruby_page<file_sep>/app/controllers/sendgrid_controller.rb
require 'mail'
require 'pusher'
class SendgridController < ApplicationController
def index
msg = { :status => "ok", :message => "Success!", :parameters => params}
@from = params[:from];
unless @from.nil?
Mail.defaults do
delivery_method :smtp, { :address => "smtp.sendgrid.net",
:port => 587,
:domain => "pogamadores.com",
:user_name => ENV['SENDGRID_USER'],
:password => ENV['<PASSWORD>'],
:authentication => 'plain',
:enable_starttls_auto => true }
end
mail = Mail.new do
from 'POGAmadores <<EMAIL>>'
subject 'Sendgrid test with env'
text_part do
body msg.to_json()
end
html_part do
content_type 'text/html; charset=UTF-8'
body '<p>' + msg.to_json() + '</p>'
end
end
mail[:to] = params[:from]
mail.deliver!
end
Pusher.app_id = ENV['PUSH_APP_ID']
Pusher.key = ENV['PUSH_APP_KEY']
Pusher.secret = ENV['PUSH_APP_SECRET']
Pusher.host = "api-eu.pusher.com"
Pusher.encrypted = true
Pusher.default_client.sync_http_client.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_NONE
begin
Pusher.trigger('sendgrid_email_parser', 'received_email', msg)
render :json => msg.to_json, :status => 200 unless params[:format] != 'json'
render :xml => msg.to_xml(:root => 'response'), :status => 200 unless params[:format] != 'xml'
render :nothing => true, :status => 200 unless params[:format] != nil
rescue Pusher::Error => e
# (Pusher::AuthenticationError, Pusher::HTTPError, or Pusher::Error)
render :json => e.original_error.to_json, :status => 500 unless params[:format] != 'json'
render :xml => e.original_error.to_xml(:root => 'response'), :status => 500 unless params[:format] != 'xml'
render :nothing => true, :status => 500 unless params[:format] != nil
end
end
end<file_sep>/README.md
ruby_page
=========
Repository to hold tests and examples of ruby and ruby on rails development
<file_sep>/test/helpers/sendgrid_helper_test.rb
require 'test_helper'
class SendgridHelperTest < ActionView::TestCase
end
<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
protect_from_forgery with: :null_session
respond_to :json, :xml
def index
msg = { :status => "error", :message => "Bad access!"}
render :json => msg, :status => 404 unless (params[:format] != 'json')
render :xml => msg.to_xml(:root => 'response'), :status => 404 unless (params[:format] != 'xml')
end
end
| d769738bbfe38d4d70ddab4eafeabf1f7e5b4ac5 | [
"Markdown",
"Ruby"
] | 4 | Ruby | igorcferreira/ruby_page | 404c8cb3c946098352f3327dc075d70dad6b123e | eaa105d1ea562c7e2a3cbddaca795d67f432ffda |
refs/heads/master | <repo_name>lskeilty/OneStopShop<file_sep>/front_end/app/components/BottomNav/styles.js
import { StyleSheet } from 'react-native';
import colors from '../../config/colors';
export default StyleSheet.create({
footerStyle: {
height: 60,
position: 'relative',
bottom: 0,
left: 0,
right: 0,
backgroundColor: colors.buttonBackground,
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center'
},
footerTextStyle: {
color: 'white',
fontSize: 13
},
footerSubGroup: {
alignItems: 'center',
justifyContent: 'center'
}
})
<file_sep>/app/helpers/items_helper.rb
module ItemsHelper
def self.search(input)
items = Item.all
matched_items = []
items.each do |item|
if item.name.downcase.include?(input.downcase)
matched_items << item
else
if item.tags
if item.tags.downcase.include?(input.downcase)
matched_items << item
end
end
end
end
return matched_items
end
end
<file_sep>/spec/helpers/items_helper_spec.rb
require "rails_helper"
describe ItemsHelper do
let!(:category) { Category.create!(name: "Meat, Poultry, & Fish") }
let!(:item1) { Item.create!(category: category, name: "Ground Beef, 1 lb.", description: "Grass Fed Ground Beef 85% Lean, 15\% Fat", image_url: "https://i1.wp.com/foodpoisoningbulletin.com/wp-content/uploads/Raw-Ground-Beef.jpg?resize=350\%2C200&ssl=1", tags: "ground beef hamburger burger") }
let!(:item2) { Item.create!(category: category, name: "Beef Soup", description: "Grass Fed Ground Beef Suop", image_url: "https://i1.wp.com/foodpoisoningbulletin.com/wp-content/uploads/Raw-Ground-Beef.jpg?resize=350\%2C200&ssl=1", tags: "beef broth") }
describe "search" do
context "when there are any matched items based on user input to item name" do
input = "beef"
it "returns an array of itmes which include the word in the name" do
expect(ItemsHelper.search(input)).to eq [item1, item2]
end
end
context "when there are any matched items based on user input to item tags" do
input = "broth"
it "returns an array of itmes which include the word in the tags" do
expect(ItemsHelper.search(input)).to eq [item2]
end
end
context "when there are no matched item based on user input to itme name or tags" do
input = "apple"
it "returns empty array" do
expect(ItemsHelper.search(input)).to eq []
end
end
end
end<file_sep>/spec/controllers/categories_controller_spec.rb
require 'rails_helper'
describe CategoriesController, type: :controller do
let(:category) { Category.create!(name: "Produce") }
describe "GET #index" do
it "returns JSON" do
get :index, :format => :json
end
end
describe "GET #show" do
it "assigns the requested category to @category" do
get :show, params: { id: category.id }
expect(assigns(:category)).to eq(category)
end
it "returns JSON" do
get :show, params: { id: category.id }, :format => :json
end
end
end
<file_sep>/app/controllers/items_controller.rb
class ItemsController < ApplicationController
def search
end
def search_results
input = params[:input]
ItemsHelper.search(input).to_json
end
end
<file_sep>/front_end/app/screens/UserAccount.js
import React, {Component} from 'react';
import {View, Text} from 'react-native';
class UserAccount extends Component {
render() {
return (
<View
style={{ flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<Text>UserAccount Screen</Text>
</View>
);
}
}
export default UserAccount;<file_sep>/app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
def create
user = User.find_by(email: params[:email].downcase)
if user && user.authenticate(params[:password])
log_in user
params[:remember_me] == '1' ? remember(user) : forget(user)
render json: {status: 'SUCCESS', message: 'You have logged in successfully'}.to_json
else
render json: {status: 422, errors: ['Invalid email or password']}.to_json
end
end
def destroy
log_out if logged_in?
render json: {message: 'You have succesfully logged out.'}.to_json
end
end<file_sep>/front_end/app/screens/ShoppingList.js
import React, {Component} from 'react';
import { View, Text, ScrollView, Button } from 'react-native';
import axios from 'axios';
import colors from '../config/colors';
import { UserItem } from '../components/UserItem';
class ShoppingList extends Component {
constructor(props) {
super(props);
this.state = {
userItems: []
};
this.getUserItems = this.getUserItems.bind(this);
this.handleButtonPress = this.handleButtonPress.bind(this);
}
componentDidMount() {
this.getUserItems();
}
getUserItems() {
axios.get('https://one-stop-shopsin.herokuapp.com/users/1/user_items')
.then(response => {
this.setState({userItems: response.data})
})
.catch(error => {
console.log(error);
});
}
handleButtonPress() {
this.props.navigation.navigate('PickStop');
};
render() {
return (
<View style={{ backgroundColor: colors.background }}>
<ScrollView style={{ backgroundColor: colors.background}}>
{this.state.userItems.map((userItem, idx) => (
<UserItem user_item={userItem} getUserItems={this.getUserItems} key={idx} />
))}
<Button
onPress={() => this.handleButtonPress()}
title="Find Yo' Stop!"
color={colors.buttonText}
backgroundColor={colors.buttonBackground}
accessibilityLabel="Find Your Stop for One Stop Shopping"
/>
</ScrollView>
</View>
);
}
}
export default ShoppingList;
<file_sep>/front_end/app/components/Item/Item.js
import React, {Component} from 'react';
import { View, Text, Image, Platform, TouchableHighlight } from 'react-native';
import axios from 'axios';
import Icon from 'react-native-vector-icons/Ionicons';
import colors from '../../config/colors';
import styles, { ADD_SIZE } from './styles';
class Item extends Component {
// constructor() {
// super(props);
// (this: any).handleAddPress = this.handleAddPress.bind(this);
// }
handleAddPress() {
this.createUserItem();
}
createUserItem() {
axios.post('https://one-stop-shopsin.herokuapp.com/users/1/user_items', {item: this.props.item})
.then(response => {
console.log(response);
this.props.getItems();
})
.catch(function(error) {
console.log(error);
});
}
render() {
const iconName = 'ios-add-circle-outline';
return (
<TouchableHighlight
onPress={() => this.handleAddPress()}
underlayColor={colors.rowUnderlay}
>
<View style={styles.row}>
<Image
source={{ uri: this.props.item.image_url }}
style={styles.image}
/>
<View style={styles.descriptionContainer}>
<Text style={styles.name}>{this.props.item.name}</Text>
<Text style={styles.description}>{this.props.item.description}</Text>
</View>
<View style={styles.addContainer}>
<Icon
name={iconName}
size={ADD_SIZE}
colors={colors.addIcon}
style={styles.add}
/>
</View>
</View>
</TouchableHighlight>
);
}
}
export default Item;
<file_sep>/front_end/app/config/TabNav.js
import React, { Component } from 'react';
import { Image } from 'react-native';
import { TabNavigator, TabView } from 'react-navigation';
import Icon from 'react-native-vector-icons/FontAwesome';
import StackNav from './StackNav';
import ShoppingList from '../screens/ShoppingList';
import PickStop from '../screens/PickStop';
import Search from '../screens/Search';
import colors from './colors';
const ICON_SIZE = 25;
const TabNav = TabNavigator({
StackNav: {
screen: StackNav,
navigationOptions: {
tabBarLabel: "OneStopShop",
tabBarIcon: () => <Image style={{width: 30, height: 30}} source={require('../images/one_Stop_shop.png')}/>
},
},
Search: {
screen: Search,
navigationOptions: {
tabBarLabel: "Categories",
tabBarIcon: ({ tintColor }) => <Icon size={ICON_SIZE}
color={colors.icon}
name="search"
/>
},
},
ShoppingList: {
screen: ShoppingList,
navigationOptions: {
tabBarLabel: "Shopping List",
tabBarIcon: ({ tintColor }) => <Icon
size={ICON_SIZE}
color={colors.icon}
name="shopping-bag"
/>
},
}
});
export default TabNav;
<file_sep>/spec/routing/categories_routing_spec.rb
require "rails_helper"
RSpec.describe "Routing to categories", :type => :routing do
it "routes GET /categories to categories#index" do
expect(:get => "/categories").to route_to("categories#index")
end
it "routes GET /categories/1 to categories#show" do
expect(:get => "/categories/1").to route_to("categories#show", :id => "1")
end
end
<file_sep>/app/models/store.rb
class Store < ApplicationRecord
has_many :store_prices
has_many :items, through: :store_prices
def find_users_missing_items(user_list)
user_list.pluck(:name) - self.items.pluck(:name)
end
def users_items_found_count(user_list)
user_list.count - self.find_users_missing_items(user_list).count
end
def users_total_price(user_list)
'%.2f' % (StorePrice.where(item: user_list, store: self).pluck(:price).reduce(:+).round(2))
end
def get_store_img_url
case self.name
when "Target"
return "https://abullseyeview.s3.amazonaws.com/wp-content/uploads/2014/04/targetlogo-6.jpeg"
when "Walgreens"
return "https://lh5.googleusercontent.com/proxy/zd8_yOpOSnGbH2oxbeaxpHv3uNm20pPPwofNEQPNAhdUjZkxj5cWwPVWYxxD3hQ2H5zTETdC8pxxr_VFHF1Wpm5M8t5v1OMQldI"
when "Safeway"
return "https://pbs.twimg.com/profile_images/813782141259497472/inQrmCRf.jpg"
when "Whole Foods"
return "https://d2lnr5mha7bycj.cloudfront.net/warehouse/logo/3/d209c632-75c1-4f4e-a678-b23d3d0d6810.png"
when "Walmart"
return "https://www.visitsouthwalton.com/sites/default/master/files/profiles/photos/profile_logo/walmart-logo0.jpg"
when "CVS/Pharmacy"
return "https://michaelfegerparalysisfoundation.org/wp-content/media/logo-cvs-pharmacy.gif"
end
end
def closest_store_from_user_location
store = YelpAdapter.search(self.name)["businesses"].sort_by { |rest| rest["distance"] }
if self.name == "Target"
store.delete_if { |s| s["name"] != "Target" }
end
store.first
end
end
<file_sep>/app/controllers/api/users_controller.rb
module Api
class UsersController < ApplicationController
before_action :set_user, only: [:update, :show, :destroy]
def show
end
# This would save the user object with entered params in the DB
def create
@user = User.new(username: params[:username], email: params[:email], password: params[:password])
if @user.save
render json: {status: 'SUCCESS', message: 'Account successfully created', accessToken: @user.access_token}.to_json
else
render json: {errors: ["Sign up failed!"], status: 422}.to_json
end
end
# This updates user params
def update
if @user.update(username: params[:username], email: params[:email], password: params[:password])
render json: {status: 'SUCCESS', message: 'Account successfully updated', accessToken: @user.access_token}.to_json
else
render json: { errors: ['Update unsuccessful!'], status: 422 }.to_json
end
end
# Delete User
def destroy
if @user.destroy
render text: "Account has been successfully deleted.", status: 'SUCCESS'
else
render text: "Something went wrong..", status: 422
end
end
private
def set_user
@user = User.find_by(access_token: params[:access_token])
end
# # White listing params
# def user_params
# params.require(:username, :email, :password).permit(:username, :email, :password)
# end
end
end<file_sep>/front_end/app/screens/Search.js
import React, { Component } from 'react';
import { View, Text, ScrollView } from 'react-native';
import { categories } from '../config/data';
import colors from '../config/colors';
import { CategoriesList } from '../components/CategoriesList';
class Search extends Component {
handleRowPress = (item) => {
this.props.navigation.navigate('ItemList', item);
};
render() {
return(
<ScrollView style={{ backgroundColor: colors.background}} >
{categories.map((category, idx) => (
<CategoriesList category={category} onPress={() => this.handleRowPress(category)} key={idx} />
))}
</ScrollView>
);
}
}
export default Search;
<file_sep>/spec/routing/user_items_routing_spec.rb
require "rails_helper"
RSpec.describe "Routing to user_items", :type => :routing do
it "routes GET /users/1/user_items to user_items#index" do
expect(:get => "/users/1/user_items").to route_to(
:controller => "user_items",
:action => "index",
:user_id => "1"
)
end
it "routes POST /users/1/user_items to user_items#create" do
expect(:post => "/users/1/user_items").to route_to(
:controller => "user_items",
:action => "create",
:user_id => "1"
)
end
it "routes POST /users/1/user_items/1 to user_items#destroy" do
expect(:post => "/users/1/user_items/1").to route_to(
:controller => "user_items",
:action => "destroy",
:user_id => "1",
:id => "1"
)
end
end
<file_sep>/app/controllers/categories_controller.rb
class CategoriesController < ApplicationController
def index
@categories = Category.all
render json: @categories
end
def show
@category = Category.find(params[:id])
items = @category.items
render json: items.to_json
end
end
<file_sep>/front_end/app/config/colors.js
export default {
// background: '#A3E4D7',
background: '#FBFCFC',
row: 'white',
primaryText: '#641E16',
subtleText: '#9a9a9a',
rowUnderlay: 'rgba(0, 153, 51, 0.9)',
addIcon: '#239B56',
labelColor: 'white',
navTabBackground: '#239B56', //Green
icon: '#239B56', //Green
buttonText: '#7B241C',
buttonBackground: '#9a9a9a',
};
<file_sep>/front_end/app/screens/ItemList.js
import React, { Component } from 'react';
import { View, Text, ScrollView } from 'react-native';
import axios from 'axios';
import colors from '../config/colors';
import { Item } from '../components/Item';
// import BottomNav from '../components/common';
class ItemList extends Component {
constructor(props) {
super(props);
this.state = {
items: []
};
this.getItems = this.getItems.bind(this);
}
componentDidMount() {
this.getItems();
}
getItems() {
const category = this.props.navigation.state.params;
axios.get(`https://one-stop-shopsin.herokuapp.com/categories/${category.id}`)
.then(response => {
this.setState({items: response.data})
})
.catch(error => {
console.log(error);
});
}
render() {
return (
<ScrollView style={{ backgroundColor: colors.background}}>
{this.state.items.map((item, idx) => (
<Item item={item} getItems={this.getItems} key={idx} />
))}
</ScrollView>
);
}
}
export default ItemList;
<file_sep>/spec/routing/sessions_routing_spec.rb
require "rails_helper"
RSpec.describe "Routing to sessions", :type => :routing do
it "routes POST api/login to api/sessions#create" do
expect(:post => "api/login").to route_to(
:controller => "api/sessions",
:action => "create"
)
end
it "routes DELETE logout to sessions#destroy" do
expect(:delete => "logout").to route_to(
:controller => "sessions",
:action => "destroy"
)
end
it "routes GET api/verify to api/sessions#verify_access_token" do
expect(:get => "api/verify").to route_to(
:controller => "api/sessions",
:action => "verify_access_token"
)
end
end<file_sep>/README.md
# README
## Welcome to OneStopShop!
This beautifully simple IOS app allows you to put all of your home shopping needs in one easy to use list. You may then find a store near you that has most, if not all, of the items on your shopping list. Thus, you find your "OneStopShop."
## Core Goals:
1. Help shoppers reduce shopping time, multiple store visits, and the need for in store price comparison.
2. Give OneStopShoppers the power to choose how they want to shop.
## Stretch Goals:
1. Integrate higher quality price comparison
2. Integrate open maps capabilities
3. Integrate searchable items option with brand choice and quanitity
## Screenshots








## Project Management Tool
[Trello Link](https://trello.com/b/6IKQtjuC/main)
## Ruby version
* Built using Ruby 2.4.1 and Rails 5.1.3
## System dependencies
* macOS version (~> 10.1)
* bundler
* Ruby 2.4.1
* Rails 5.1.3
* PostgreSQL 9.6.3
* React Native 0.48.4
* React Navigation 1.0.0-beta.13
* Axios 0.16.2
## Configuration
$ git clone https://github.com/DaniGlass/OneStopShop/
$ cd OneStopShop
$ bundle install
$ rails db:setup
$ rails server (leave server running for backend)
$ cd OneStopShop/front_end
$ npm install
$ react-native run-ios
## Database
The website uses a Postgres database
* postgres (PostgreSQL) 9.6.3
### Database creation
$ rails db:create
### Database initialization
$ rails db:migrate
$ rails db:seed
### Database schema

## Testing
### How to run the test suite
$ rspec
### Other gems / libraries used when testing
* [Capybara](https://github.com/teamcapybara/capybara)
* [FactoryGirl](https://github.com/thoughtbot/factory_girl)
* [Faker](https://github.com/stympy/faker)
* [Warden](https://github.com/hassox/warden/wiki)
## License
OneStopShop is released under the [MIT License](https://opensource.org/licenses/MIT).
<file_sep>/spec/controllers/results_controllrt_spec.rb
require 'rails_helper'
describe ResultsController, type: :controller do
let!(:user) { User.create!(name: "Ikko", username: "ikko", email: "<EMAIL>", password: "<PASSWORD>") }
describe "GET #index" do
it "returns JSON" do
get :index, :format => :json, params: {id: user.id}
end
end
describe "GET #by_lowest_price" do
it "returns JSON" do
get :by_lowest_price, :format => :json, params: {id: user.id}
end
end
describe "GET #by_shortest_distance" do
it "returns JSON" do
get :by_shortest_distance, :format => :json, params: {id: user.id}
end
end
end
<file_sep>/front_end/app/components/CategoriesList/styles.js
import { StyleSheet } from 'react-native';
import colors from '../../config/colors';
export default StyleSheet.create({
row: {
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 15,
paddingVertical: 8,
backgroundColor: colors.row,
marginVertical: 2,
},
image: {
width: 40,
height: 40,
borderRadius: 2,
marginRight: 10,
},
})
<file_sep>/app/controllers/results_controller.rb
class ResultsController < ApplicationController
def index
user = User.find(params[:id])
render json: user.results_by_items_found.to_json
end
def by_lowest_price
user = User.find(params[:id])
render json: user.results_by_lowest_price.to_json
end
def by_shortest_distance
user = User.find(params[:id])
render json: user.results_by_shortest_distance.to_json
end
end
<file_sep>/front_end/app/components/UserItem/styles.js
import { StyleSheet } from 'react-native';
import colors from '../../config/colors';
export const ADD_SIZE = 40;
export default StyleSheet.create({
row: {
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 20,
paddingVertical: 8,
backgroundColor: colors.row,
marginVertical: 2,
},
image: {
// width: 40,
// height: 40,
// borderRadius: 20,
width: 60,
height: 60,
borderRadius: 30,
marginRight: 10,
},
name: {
fontSize: 16,
fontWeight: '500',
color: colors.primaryText,
},
description: {
fontSize: 13,
color: colors.subtleText,
},
descriptionContainer: {
flex: 1,
flexWrap: 'wrap',
},
addContainer: {
flex: 0.2,
// backgroundColor: 'blue',
},
add: {
alignSelf: 'flex-end',
},
})
<file_sep>/config/routes.rb
Rails.application.routes.draw do
get 'results/index'
get 'items/search', to: 'items#search'
post 'items/search_results', to: 'items#search_results'
resources :categories, only: [:index, :show,]
resources :stores
resources :users, only: [:show] do
resources :user_items, only: [:index, :create]
end
post "users/:user_id/user_items/:id" => 'user_items#destroy'
get "users/:id/results" => 'results#index'
get "users/:id/results/by_items_found" => 'results#by_items_found'
get "users/:id/results/by_price" => 'results#by_lowest_price'
get "users/:id/results/by_distance" => 'results#by_shortest_distance'
root 'categories#index'
delete '/logout' => 'sessions#destroy'
namespace :api do
post '/login' => 'sessions#create'
get '/verify' => 'sessions#verify_access_token'
resources :users, only: [:create, :show, :update, :destroy]
resources :password_resets, only: [:create, :update]
end
end
<file_sep>/front_end/app/components/StoreResults/StoreResults.js
import React, {Component} from 'react';
import { View, Text, Image } from 'react-native';
import axios from 'axios';
import colors from '../../config/colors';
import styles from './styles';
class StoreResults extends Component {
render() {
const distance = ((this.props.store[1].closest_store.distance) * 0.000621371).toFixed(2);
let itemsNotFound = this.props.store[1].not_found_names.join("\n");
let itemsFoundMessage = "Items Not Found:";
if (itemsNotFound.length === 0) {
itemsFoundMessage = null;
itemsNotFound = null;
};
return (
<View style={styles.row}>
<Image
source={{ uri: this.props.store[1].store_img_url }}
style={styles.image}
/>
<View style={styles.descriptionContainer}>
<Text style={styles.name}>{this.props.store[1].closest_store.name}</Text>
<Text style={styles.description}>{this.props.store[1].closest_store.location.display_address[0]}</Text>
<Text style={styles.description}>{this.props.store[1].closest_store.location.display_address[1]}</Text>
<Text style={styles.distance}>{distance} miles away</Text>
<View>
<Text style={styles.secondaryText}>{itemsFoundMessage}</Text>
<Text style={styles.smallText}>{itemsNotFound}</Text>
</View>
</View>
<View style={styles.itemsResults}>
<Text style={styles.smallText} >One Stop Price</Text>
<Text style={styles.smallText} >for items found:</Text>
<Text style={styles.price}>${this.props.store[1].total_price}</Text>
<Text style={styles.smallText}>{this.props.store[1].found_items_count} out of {this.props.store[1].user_list_count} items found</Text>
</View>
</View>
);
}
}
export default StoreResults;
<file_sep>/spec/models/user_spec.rb
require 'rails_helper'
describe User do
let!(:user) { User.create!(name: "Ikuko", username: "Ikko", email: "<EMAIL>", password: "<PASSWORD>")}
let!(:category) { Category.create!(name: "Meat, Poultry, & Fish") }
let!(:item) { Item.create!(category: category, name: "Ground Beef, 1 lb.", description: "Grass Fed Ground Beef 85% Lean, 15\% Fat", image_url: "https://i1.wp.com/foodpoisoningbulletin.com/wp-content/uploads/Raw-Ground-Beef.jpg?resize=350\%2C200&ssl=1", tags: "ground beef hamburger burger") }
let!(:user_item) { UserItem.create!(user_id: user.id, item_id: item.id) }
describe "results" do
context "after user selected all the items (s)he wants" do
it "returns the total price, missing items, found items count, shopping items number" do
end
end
end
end<file_sep>/app/models/item.rb
class Item < ApplicationRecord
has_many :user_items
belongs_to :category
has_many :store_prices
has_many :stores, through: :store_prices
end
<file_sep>/front_end/app/components/UserItem/index.js
import UserItem from './UserItem';
import styles from './styles';
export {
UserItem,
styles,
};
<file_sep>/app/controllers/api/sessions_controller.rb
module Api
class SessionsController < ApplicationController
# If user login data is validated, access token will be returned to the client app
def create
@user = User.find_by(email: params[:email])
if @user && @user.authenticate(params[:password])
render json: {status: 'SUCCESS', accessToken:@user.access_token}.to_json
else
render json: {errors: ["Incorrect email or password."], status: 422}.to_json
end
end
# Verifies access token, so that client app knows whether to login the user / not.
def verify_access_token
@user = User.find_by(access_token: params[:access_token])
if @user
render json: {
status: 'SUCCESS', message: "User Verified."
}.to_json
else
render json: {
status: 422, message: "Verification failed"
}.to_json
end
end
end
end<file_sep>/front_end/app/index.js
import React from 'react';
import TabNav from './config/TabNav';
const App = () => {
return <TabNav/>;
};
// export default App;
// FROM DANI'S BRANCH
// import React from 'react';
// import {StackNavigator} from 'react-navigation';
// import Search from './screens/Search';
// import ItemList from './screens/ItemList';
// import ShoppingList from './screens/ShoppingList';
// import PickStop from './screens/PickStop';
// import LoginForm from './components/LoginForm';
// import RegistrationForm from './components/RegistrationForm';
// // import Icon from 'react-native-vector-icons/FontAwesome';
// // const ICON_SIZE = 25;
// // const logo = require('../images/OneStopShopLogo.png');
// // const Left = ({ onPress }) => (
// // <TouchableHighlight onPress={onPress}>
// // <Icon
// // size={ICON_SIZE}
// // color={colors.icon}
// // name="search"
// // />
// // </TouchableHighlight>
// // );
// // const handleSearchPress = ({ onPress }) => {
// // this.props.navigation.navigate('Search');
// // };
// const App = StackNavigator({
// Login: { screen: LoginForm },
// Register: { screen: RegistrationForm },
// Search: {
// screen: Search,
// navigationOptions: {
// title: 'Search',
// headerLeft: null,
// },
// },
// ItemList: {
// screen: ItemList,
// navigationOptions: ({ navigation }) => ({
// title: `${navigation.state.params.name}`,
// headerLeft: null,
// }),
// },
// ShoppingList: {
// screen: ShoppingList,
// navigationOptions: {
// title: 'Shopping List',
// headerLeft: null
// },
// },
// PickStop: {
// screen: PickStop,
// navigationOptions: {
// title: 'Your Possible Stops',
// headerLeft: null
// },
// },
// });
export default App;
<file_sep>/spec/models/store_spec.rb
require 'rails_helper'
describe "Store" do
let(:user) { User.create(name: "Ikuko", username: "Ikko", email: "<EMAIL>", password: "<PASSWORD>")}
let(:category1) { Category.create(name: "Meat, Poultry, & Fish") }
let(:category2) { Category.create(name: "Produce") }
let(:store1) { Store.create(name: "Safeway") }
let(:store2) { Store.create(name: "Walgreens") }
let(:item1) { Item.create(category: category1, name: "Ground Beef, 1 lb.", description: "Grass Fed Ground Beef 85% Lean, 15\% Fat", image_url: "https://i1.wp.com/foodpoisoningbulletin.com/wp-content/uploads/Raw-Ground-Beef.jpg?resize=350\%2C200&ssl=1", tags: "ground beef hamburger burger") }
let(:item2) { Item.create(category: category2, name: "Avocado", brand: "Hass", description: "Loved for their creamy texture and heart-healthy unsaturated fat, versatile avocados can be added to almost everything.", image_url: "https://d2d8wwwkmhfcva.cloudfront.net/155x/filters:fill(FFF,true):format(jpg)/d2lnr5mha7bycj.cloudfront.net/product-image/file/large_bcb00e2e-0373-4aa5-acef-515e35726278.jpg", tags: "avocado ") }
let(:item3) { Item.create(category: category2, name: "Broccoli Crown", brand: "Produce", description: "Broccoli contains many vitamins, including vitamin C and vitamin A.", image_url: "https://d2d8wwwkmhfcva.cloudfront.net/600x/filters:fill(FFF,true):format(jpg)/d2lnr5mha7bycj.cloudfront.net/product-image/file/large_42d7673d-8670-469d-8a32-0fc5760e1a7f.jpg", tags: "broccoli brocoli crown ") }
let(:user_item1) { UserItem.create(user_id: user.id, item_id: item1.id) }
let(:user_item2) { UserItem.create(user_id: user.id, item_id: item2.id) }
let(:user_item3) { UserItem.create(user_id: user.id, item_id: item3.id) }
describe "find_users_missing_items" do
context "when use could not find item(s)" do
let(:store_prices1) { item1.store_prices.create(store_id: store1.id, price: 1.99) }
let(:store_prices2) { item2.store_prices.create(store_id: store1.id, price: 7.50) }
let(:store_prices3) { item3.store_prices.create(store_id: store2.id, price: 7.50) }
it "returns the names of the missing items" do
expect(store1.find_users_missing_items (user_item3.user.items)).to eq [user_item3.item.name]
end
end
context "when use could not find any items" do
let(:store_prices1) { item1.store_prices.create(store_id: store1.id, price: 1.99) }
let(:store_prices2) { item2.store_prices.create(store_id: store1.id, price: 7.50) }
let(:store_prices3) { item3.store_prices.create(store_id: store1.id, price: 7.50) }
it "returns an empty array" do
expect(store2.find_users_missing_items (user.items)).to eq []
end
end
end
describe "users_items_found_count" do
context "when use find some itmes" do
let(:store_prices1) { item1.store_prices.create(store_id: store1.id, price: 1.99) }
let(:store_prices2) { item2.store_prices.create(store_id: store1.id, price: 7.50) }
let(:store_prices3) { item3.store_prices.create(store_id: store2.id, price: 7.50) }
it "returns the number of the itmes" do
user_item1
user_item2
user_item3
store_prices1
store_prices2
store_prices3
expect(store1.users_items_found_count (store1.items)).to eq 2
end
end
context "when use could not find any items" do
let(:store_prices1) { item1.store_prices.create(store_id: store1.id, price: 1.99) }
let(:store_prices2) { item2.store_prices.create(store_id: store1.id, price: 7.50) }
let(:store_prices3) { item3.store_prices.create(store_id: store1.id, price: 7.50) }
it "returns an empty array" do
expect(store2.users_items_found_count (user.items)).to eq 0
end
end
end
describe "users_total_price" do
let(:store_prices1) { item1.store_prices.create(store_id: store2.id, price: 1.99) }
let(:store_prices2) { item2.store_prices.create(store_id: store1.id, price: 7.50) }
let(:store_prices3) { item3.store_prices.create(store_id: store1.id, price: 7.50) }
it "returns the number of the itmes user found" do
user_item1
user_item2
user_item3
store_prices1
store_prices2
store_prices3
expect(store1.users_total_price (store1.items)).to eq "15.00"
end
end
end<file_sep>/spec/controllers/user_items_controller_spec.rb
require 'rails_helper'
describe UserItemsController do
let!(:user) { User.create!(name: "Ikuko", username: "Ikko", email: "<EMAIL>", password: "<PASSWORD>")}
let!(:category) { Category.create!(name: "Meat, Poultry, & Fish") }
let!(:item) { Item.create!(category: category, name: "Ground Beef, 1 lb.", description: "Grass Fed Ground Beef 85% Lean, 15\% Fat", image_url: "https://i1.wp.com/foodpoisoningbulletin.com/wp-content/uploads/Raw-Ground-Beef.jpg?resize=350\%2C200&ssl=1", tags: "ground beef hamburger burger") }
let!(:user_item) { UserItem.create!(user_id: user.id, item_id: item.id) }
describe "GET #index" do
it "returns JSON" do
get :index, params: { :user_id => user.id }, :format => :json
end
end
# describe "POST #create" do
# # params = {item: {name: "Ground Beef, 1 lb."}}
# context "when valid params are passed" do
# # it "assigns a new user_item to @user_item" do
# # post :create, params: {item: {name: "Ground Beef, 1 lb."}}, params: { :user_id => user.id }
# # expect(assigns(:user_item)).to be_a_new UserItem
# # end
# end
# end
# describe "DELETE #destroy" do
# it "destroys the requested user_item" do
# expect { delete(:action=>"destroy", :user=>user.id, :controller=>"user_items", :post_id=>user_item) }.to change(UserItem, :count).by(-1)
# end
# end
end
<file_sep>/app/models/user_item.rb
class UserItem < ApplicationRecord
belongs_to :user
belongs_to :item
validates :user_id, uniqueness: { scope: :item_id,
message: "Be not able to add same item more than once." }
end
<file_sep>/front_end/app/config/data.js
export const categories = [
{
id: 1,
name: "Produce",
// image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwiIl8ma0dDWAhWps1QKHcS2DZoQjRwIBw&url=http%3A%2F%2F99only.com%2Ffarm-fresh-produce%2F&psig=AOvVaw1F_TOyQx4uTmC_khX1-cfB&ust=1506988880330349",
// image_url: "https://cdn.thinglink.me/api/image/722499555140042753/1240/10/scaletowidth",
image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwjbxrDL0dDWAhVBlFQKHUFiBzMQjRwIBw&url=http%3A%2F%2Fwoman.thenest.com%2Fnatural-foods-high-roughage-18478.html&psig=AOvVaw1F_TOyQx4uTmC_khX1-cfB&ust=1506988880330349",
},
{
id: 2,
name: "Meat, Poultry, & Fish",
// image_url: "https://stateofmind13.files.wordpress.com/2012/04/raw-meat.jpg",
// image_url: "https://www.gfs.com/sites/gfs.com/files/styles/content_article_image/public/MeatPoultryFish_ICHeader.jpg?itok=kMW2mbi8",
image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwjJ4IaI0dDWAhXnyVQKHQXCA1wQjRwIBw&url=https%3A%2F%2Fwww.pinterest.com%2Fexplore%2Fheme-iron%2F&psig=AOvVaw2w-D4dSk3_TzJdmvqI0PTK&ust=1506988767226284",
},
{
id: 3,
name: "<NAME>",
// image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwiM54Ll0dDWAhXnq1QKHfG4APUQjRwIBw&url=http%3A%2F%2Fcioffisgroup.com%2Fcioffis-dairy-eggs%2F&psig=AOvVaw1Mw67EzE_VSKcFDrAq6cAB&ust=1506989015129339",
// image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwj9ueP70dDWAhVKh1QKHft7C-gQjRwIBw&url=http%3A%2F%2Fwww.freerangekids.com%2Fmom-of-allergic-student-sues-school-for-serving-eggs-milk%2F&psig=AOvVaw1Mw67EzE_VSKcFDrAq6cAB&ust=1506989015129339",
image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwiX0OGK0tDWAhVsz1QKHXMJDL0QjRwIBw&url=http%3A%2F%2Fgps-miami.com%2Fproject%2Fdairy%2F&psig=AOvVaw1Mw67EzE_VSKcFDrAq6cAB&ust=1506989015129339",
},
{
id: 4,
name: "Frozen Food",
// image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwituuSf0tDWAhXLqFQKHUN3BgkQjRwIBw&url=http%3A%2F%2Fwww.foodbrokers.org%2Ffrozen-food-brokers.html&psig=AOvVaw2XNig3eX0APTpkSC7cJcOO&ust=1506989140457781",
// image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwiDx67g0tDWAhUhiVQKHXUfC3sQjRwIBw&url=http%3A%2F%2Fwww.benjerry.com%2Fflavors%2Fphish-food-frozen-yogurt&psig=AOvVaw1YNlGzFFiDn7H5SGCOA96H&ust=1506989288729490",
image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwjSqr-X09DWAhVGrFQKHaU_BZ8QjRwIBw&url=http%3A%2F%2Fwww.benjerry.com%2Fflavors%2Fphish-food-ice-cream&psig=AOvVaw3ykBZe3pzTqh-xkrzCW4iI&ust=1506989389573993",
},
{
id: 5,
name: "Beverages",
// image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwjB447v09DWAhXCqlQKHdqkAD0QjRwIBw&url=http%3A%2F%2Ffortune.com%2F2016%2F06%2F16%2Fphiladelphia-council-soda-tax%2F&psig=AOvVaw0hXB6R7hBks8lt8YeimGqd&ust=1506989473747184",
// image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwi2pMOH1NDWAhXjq1QKHT3jBocQjRwIBw&url=http%3A%2F%2Fwww.npr.org%2Ftags%2F145127482%2Fsoda-tax&psig=AOvVaw2IZ0DW7U441ZyUl-yDkBFF&ust=1506989624653084",
image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwiOgaWo1NDWAhVqzlQKHejWDC8QjRwIBw&url=http%3A%2F%2Fwww.huffingtonpost.com%2Fentry%2Fbig-soda-ads-taxes_us_57bcd98be4b03d51368b953b&psig=AOvVaw2IZ0DW7U441ZyUl-yDkBFF&ust=1506989624653084",
// image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwjrtOjS1NDWAhXBylQKHbIcAtIQjRwIBw&url=http%3A%2F%2Fmammaspizza.com%2Fmenu%2Fbeverages&psig=AOvVaw04Vf33X-2FRQNv0kRvIdKF&ust=1506989784371954",
},
{
id: 6,
name: "Adult Beverages",
// image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwi4mPn71NDWAhWmsFQKHS6uB_QQjRwIBw&url=http%3A%2F%2Fwww.edgemill.com%2F&psig=AOvVaw2I7iE5SvWEcsQmmfbdMy4L&ust=1506989870300003",
image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwj0vcKH1dDWAhVoxVQKHS1GCqQQjRwIBw&url=http%3A%2F%2Fwww.thedrum.com%2Fnews%2F2014%2F07%2F11%2Fpernod-ricard-purchases-majority-share-tequila-brand-avion-spirts&psig=AOvVaw0HwKxCndwqRr6oFtWYjhQw&ust=1506989911222387",
// image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwiYqbWO1dDWAhXnqFQKHbYmCCYQjRwIBw&url=http%3A%2F%2Fsetexasrecord.com%2Fstories%2F510629747-judge-declines-to-dismiss-wal-mart-s-suit-over-irrational-liquor-ban&psig=AOvVaw0HwKxCndwqRr6oFtWYjhQw&ust=1506989911222387",
},
{
id: 7,
name: "<NAME>",
// image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwitlMac1dDWAhWmilQKHZfvDHcQjRwIBw&url=http%3A%2F%2Fwww.fancicandy.com%2Fsnacks.html&psig=AOvVaw20cc3ryzz_6ytUxxYX4zfL&ust=1506989958863849",
image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwiogdCi1dDWAhUpqlQKHfbPAPYQjRwIBw&url=http%3A%2F%2Finsufficientscotty.com%2F2012%2F05%2F18%2Ffriday-five-marathon-snacks%2F&psig=AOvVaw20cc3ryzz_6ytUxxYX4zfL&ust=1506989958863849",
// image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwiMxavO1dDWAhXojVQKHb6ODnMQjRwIBw&url=https%3A%2F%2Fgreatist.com%2Fhealth%2F20-better-halloween-candy-choices&psig=AOvVaw20cc3ryzz_6ytUxxYX4zfL&ust=1506989958863849",
},
{
id: 8,
name: "Beauty",
// image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwiJ_oj21dDWAhVli1QKHSGlA5cQjRwIBw&url=https%3A%2F%2Fwww.newbeauty.com%2Fslideshow%2F2184-the-most-popular-products-at-your-favorite-retailers%2F&psig=AOvVaw14hmqMZnaecCNfhub10Ine&ust=1506990144910220",
// image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwjXj_a51tDWAhUmrFQKHaysAN8QjRwIBw&url=http%3A%2F%2Fwww.sheknows.com%2Fbeauty-and-style%2Farticles%2F806630%2Ftop-35-beauty-products&psig=AOvVaw2W6vwHtzkSMDpGYvlu2-hM&ust=1506990284342543",
image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwiDx5vR1tDWAhXKwVQKHYVmBqwQjRwIBw&url=https%3A%2F%2Fwww.thebeijinger.com%2Fblog%2F2017%2F07%2F17%2F6-beauty-products-will-get-you-through-beijing-summer&psig=AOvVaw2W6vwHtzkSMDpGYvlu2-hM&ust=1506990284342543",
},
{
id: 9,
name: "Healthcare",
// image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwjYqfT41tDWAhXpiVQKHcRtAP4QjRwIBw&url=https%3A%2F%2Fwww.marillysmace.com%2Fsante%2Fleau-et-les-residus-de-medicaments%2F&psig=AOvVaw0ZBEvOb3FYtdMQUBvshY3f&ust=1506990371730498",
// image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwiQwf-F19DWAhUrrVQKHcRQDBIQjRwIBw&url=http%3A%2F%2Fwww.leisure-kit.net%2Fdetail1.cfm%3Fcode%3D4589%26kit%3DFUN%26linktype%3DMORENEWS&psig=AOvVaw0ov_CEetYUE1CFsNe0IpVH&ust=1506990438672710",
image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwiLwZSR19DWAhXEwVQKHTANBjYQjRwIBw&url=https%3A%2F%2Fwww.dynamiclevels.com%2Fen%2Fcurrent-news%2Fgsk-consumer-share-price-160504000626&psig=AOvVaw0ov_CEetYUE1CFsNe0IpVH&ust=1506990438672710",
},
{
id: 10,
name: "Home",
// image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwic6-yU2NDWAhWkq1QKHVuWAc8QjRwIBw&url=https%3A%2F%2Fwww.portada-online.com%2F2017%2F02%2F14%2Fhow-hearts-science-does-multicultural-marketing-for-billion-dollar-pg-brands%2F&psig=AOvVaw0eHX9VV98ry8QwdGJxeJ6p&ust=1506990640212567",
// image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwjJjaSn2NDWAhXHhFQKHfs8ByAQjRwIBw&url=http%3A%2F%2Fwww.cbx.com%2Fnews%2Fhow-to-succeed-in-the-new-store-as-brand-world%2F&psig=AOvVaw0YOVDVgubqr-BKvhTy5D6Q&ust=1506990765192039",
// image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwjx4rj02NDWAhUnj1QKHVafCNgQjRwIBw&url=https%3A%2F%2Fwww.bargainblessings.com%2Fhot-new-ibotta-app-offers-for-spring-cleaning-products-windex-cascade-and-more%2F&psig=AOvVaw3DoFdBz1dzcltlVoo6K2LZ&ust=1506990949848613",
image_url: "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwi8qbWR2dDWAhXox1QKHel7ADkQjRwIBw&url=https%3A%2F%2Fsavingstar.com%2Fcoupons%2Freckitt-benckiser-home-products%2F552d6092e4b003dc935baf14&psig=AOvVaw3DoFdBz1dzcltlVoo6K2LZ&ust=1506990949848613",
},
{
id: 11,
name: "Baby",
// image_url: "",
},
{
id: 12,
name: "Pets",
// image_url: "",
},
{
id: 13,
name: "Office Supplies",
// image_url: "",
},
{
id: 14,
name: "Electronics",
// image_url: "",
}
]
<file_sep>/app/models/yelp_adapter.rb
module YelpAdapter
class << self
require "json"
require "http"
require "optparse"
# Constants, do not change these
API_HOST = "https://api.yelp.com"
SEARCH_PATH = "/v3/businesses/search"
BUSINESS_PATH = "/v3/businesses/"
# DEFAULT_LOCATION = "San Francisco, CA"
SEARCH_LIMIT = 5
def longitude(latitude)
longitude = longitude
end
# Returns a parsed json object of the request
def search(term)
url = "#{API_HOST}#{SEARCH_PATH}"
params = {
term: term,
# location: DEFAULT_LOCATION,
latitude: 37.784517,
longitude: -122.397194,
limit: SEARCH_LIMIT,
open_now: true
}
response = HTTP.auth(ENV["AUTHORIZATION"]).get(url, params: params)
response.parse
end
end
end<file_sep>/spec/routing/items_routing_spec.rb
require "rails_helper"
RSpec.describe "Routing to items", :type => :routing do
it "routes GET /items/search to items#search" do
expect(:get => "/items/search").to route_to("items#search")
end
it "routes POST /items/search_results to items#search_results" do
expect(:post => "items/search_results").to route_to("items#search_results")
end
end<file_sep>/front_end/app/components/BottomNav/BottomNav.js
import React, { Component } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import colors from '../../config/colors';
import styles from './styles';
const ICON_SIZE = 25;
class BottomNav extends Component {
handleSearchPress() {
this.props.navigation.navigate('Search');
}
render() {
return (
<View style={styles.footerStyle}>
<TouchableOpacity onPress={() => this.handleSearchPress}>
<View style={styles.footerSubGroup}>
<Icon
size={ICON_SIZE}
color={colors.icon}
name="search"
/>
<Text style={styles.footerTextStyle}>Categories</Text>
</View>
</TouchableOpacity>
</View>
);
}
}
export default BottomNav;
<file_sep>/front_end/app/components/StoreResults/styles.js
import { StyleSheet } from 'react-native';
import colors from '../../config/colors';
export default StyleSheet.create({
row: {
flexDirection: 'row',
paddingHorizontal: 15,
paddingVertical: 8,
backgroundColor: colors.row,
marginVertical: 2,
},
image: {
width: 60,
height: 60,
borderRadius: 30,
marginRight: 10,
},
name: {
fontSize: 16,
fontWeight: '500',
color: colors.primaryText,
},
description: {
fontSize: 13,
color: colors.subtleText,
},
smallText: {
fontSize: 10,
color: colors.subtleText,
},
price: {
fontSize: 16,
fontWeight: '500',
color: colors.primaryText,
},
distance: {
fontSize: 13,
fontStyle: 'italic',
color: colors.subtleText,
},
descriptionContainer: {
flex: 1,
flexWrap: 'wrap',
},
itemsResults: {
alignSelf: 'flex-end',
alignItems: 'center',
},
secondaryText: {
fontSize: 10,
fontWeight: '500',
color: colors.primaryText,
},
})
<file_sep>/front_end/app/components/CategoriesList/index.js
import CategoriesList from './CategoriesList';
import styles from './styles';
export {
CategoriesList,
styles,
};<file_sep>/app/controllers/user_items_controller.rb
class UserItemsController < ApplicationController
# skip_before_action :verify_authenticity_token
def index
user = User.first
items = user.items
render json: items.to_json
end
def create
itemName = params[:item][:name]
item = Item.find_by(name: itemName)
@user_item = UserItem.new
@user_item.user_id = User.first.id
@user_item.item_id = item.id
@user_item.save
render json: @user_item.to_json
end
def destroy
user = User.first
user_item = UserItem.find_by(user_id: user.id, item_id: params[:user_item_id])
# user_item.user_id = User.first.id
# user_item.item_id = item.id
user_item.destroy!
render json: user_item.to_json
end
end
# Paste to user_items.index.html.erb
# <% @item_list.pluck(:name).each do |item_name| %>
# <%= item_name %>
# this part is not right. To delete we need to use user show page.
# <%= button_to "Delete", {:controller => "user_items"} %>
# <% end %>
<file_sep>/front_end/app/components/CategoriesList/CategoriesList.js
import React from 'react';
import { View, Text, TouchableHighlight, Image } from 'react-native';
import colors from '../../config/colors';
import styles from './styles';
const CategoriesList = ({category, onPress}) => {
return (
<TouchableHighlight
onPress={onPress}
underlayColor={colors.rowUnderlay}
>
<View style={styles.row}>
<Image
source={{ uri: category.image_url }}
style={styles.image}
/>
<View>
<Text>{category.name}</Text>
</View>
</View>
</TouchableHighlight>
);
};
export default CategoriesList;<file_sep>/front_end/app/components/UserItem/UserItem.js
import React, {Component} from 'react';
import { View, Text, Image, Platform, TouchableHighlight } from 'react-native';
import axios from 'axios';
import Icon from 'react-native-vector-icons/Ionicons';
import colors from '../../config/colors';
import styles, { ADD_SIZE } from './styles';
class UserItem extends Component {
// constructor(props) {
// super(props);
// this.state = {
// items
// };
// this.getUserItems = this.getUserItems.bind(this);
// }
handleDeletePress() {
this.deleteUserItem();
}
deleteUserItem() {
const user_item = this.props.user_item;
console.log(user_item);
axios.post(`https://one-stop-shopsin.herokuapp.com/users/1/user_items/${user_item.id}`, {user_item_id: this.props.user_item.id})
// axios.get(`http://localhost:3000/users/1/user_items/${user_item.id}`, {user_item: this.props.user_item})
.then(response => {
console.log(response);
this.props.getUserItems();
})
.catch(function(error) {
console.log(error);
});
}
render() {
const iconName = 'ios-remove-circle-outline';
return (
<TouchableHighlight
onPress={() => this.handleDeletePress()}
underlayColor={colors.rowUnderlay}
>
<View style={styles.row}>
<Image
source={{ uri: this.props.user_item.image_url }}
style={styles.image}
/>
<View style={styles.descriptionContainer}>
<Text style={styles.name}>{this.props.user_item.name}</Text>
<Text style={styles.description}>{this.props.user_item.description}</Text>
</View>
<View style={styles.addContainer}>
<Icon
name={iconName}
size={ADD_SIZE}
colors={colors.addIcon}
style={styles.add}
/>
</View>
</View>
</TouchableHighlight>
);
}
}
export default UserItem;
<file_sep>/app/models/store_price.rb
class StorePrice < ApplicationRecord
belongs_to :item
belongs_to :store
end
<file_sep>/front_end/app/config/StackNav.js
import React, { Component } from 'react';
import { StackNavigator } from 'react-navigation';
import Search from '../screens/Search';
import ItemList from '../screens/ItemList';
import ShoppingList from '../screens/ShoppingList';
import PickStop from '../screens/PickStop';
import PickStopByItems from '../screens/PickStopByItems';
import PickStopByDistance from '../screens/PickStopByDistance';
import PickStopByPrice from '../screens/PickStopByPrice';
import LoginForm from '../components/LoginForm';
import RegistrationForm from '../components/RegistrationForm';
const StackNav = StackNavigator({
LoginForm: {
screen: LoginForm,
navigationOptions: {
title: 'Login',
headerStyle: {backgroundColor: "#239B56"},
headerTintColor: "white"
},
},
RegistrationForm: {
screen: RegistrationForm,
navigationOptions: {
title: 'Register',
headerStyle: {backgroundColor: "#239B56"},
headerTintColor: "white"
},
},
PickStop: {
screen: PickStop,
navigationOptions: {
title: 'Pick-A-Stop',
headerLeft: null,
headerStyle: {backgroundColor: "#239B56"},
headerTintColor: "white"
},
},
Search: {
screen: Search,
navigationOptions: {
title: 'Search',
headerLeft: null,
headerStyle: {backgroundColor: "#239B56"},
headerTintColor: "white"
},
},
ItemList: {
screen: ItemList,
navigationOptions: ({ navigation }) => ({
title: `${navigation.state.params.name}`,
headerLeft: null,
headerStyle: {backgroundColor: "#239B56"},
headerTintColor: "white"
}),
},
ShoppingList: {
screen: ShoppingList,
navigationOptions: {
title: 'Shopping List',
headerLeft: null,
headerStyle: {backgroundColor: "#239B56"},
headerTintColor: "white"
},
},
PickStopByItems: {
screen: PickStopByItems,
navigationOptions: {
title: 'Pick-A-Stop',
headerLeft: null,
headerStyle: {backgroundColor: "#239B56"},
headerTintColor: "white"
},
},
PickStopByDistance: {
screen: PickStopByDistance,
navigationOptions: {
title: 'Pick-A-Stop',
headerLeft: null,
headerStyle: {backgroundColor: "#239B56"},
headerTintColor: "white"
},
},
PickStopByPrice: {
screen: PickStopByPrice,
navigationOptions: {
title: 'Pick-A-Stop',
headerLeft: null,
headerStyle: {backgroundColor: "#239B56"},
headerTintColor: "white"
},
},
});
export default StackNav;
<file_sep>/spec/routing/results_routing_spec.rb
require "rails_helper"
RSpec.describe "Routing to results", :type => :routing do
it "routes GET /users/1/results to results#index" do
expect(:get => "/users/1/results").to route_to(
:controller => "results",
:action => "index",
:id => "1"
)
end
it "routes GET /users/1/results/by_items_found to results#by_items_found" do
expect(:get => "/users/1/results/by_items_found").to route_to(
:controller => "results",
:action => "by_items_found",
:id => "1"
)
end
it "routes GET /users/1/results/by_price to results#by_lowest_price" do
expect(:get => "/users/1/results/by_price").to route_to(
:controller => "results",
:action => "by_lowest_price",
:id => "1"
)
end
it "routes GET /users/1/results/by_distance to results#by_shortest_distance" do
expect(:get => "/users/1/results/by_distance").to route_to(
:controller => "results",
:action => "by_shortest_distance",
:id => "1"
)
end
end<file_sep>/db/seeds.rb
# Category.destroy
# Item.destroy
# Store.destroy
# StorePrice.destroy
# User.create(username: "Jen", email: "<EMAIL>", password: "<PASSWORD>")
Category.create([{name: "Produce"}, {name: "Meat, Poultry, & Fish"}, {name: "Dairy & Eggs"}, {name: "Frozen Food"}, {name: "Beverages"}, {name: "Adult Beverages"}, {name: "Snacks & Candy"}, {name: "Beauty"}, {name: "Healthcare"}, {name: "Home"}, {name: "Baby"}, {name: "Pets"}, {name: "Office Supplies"}, {name: "Electronics"}])
Store.create([{name: "Walgreens"}, {name: "CVS/Pharmacy"}, {name: "Walmart"}, {name: "Target"}, {name: "Whole Foods"}, {name: "Safeway"}])
################### Category 2: Produce
#### Avocado ####
avocado = Item.create(category: Category.find_by(name: "Produce"), name: "Avocado", brand: "Hass", description: "Loved for their creamy texture and heart-healthy unsaturated fat, versatile avocados can be added to almost everything.", image_url: "https://d2d8wwwkmhfcva.cloudfront.net/155x/filters:fill(FFF,true):format(jpg)/d2lnr5mha7bycj.cloudfront.net/product-image/file/large_bcb00e2e-0373-4aa5-acef-515e35726278.jpg", tags: "avocado ")
avocado.store_prices.create(store_id: 4, price: 1.99)
avocado.store_prices.create(store_id: 5, price: 2.50)
avocado.store_prices.create(store_id: 6, price: 1.99)
#### Broccoli ####
broccoli = Item.create(category: Category.find_by(name: "Produce"), name: "Broccoli Crown", brand: "Produce", description: "Broccoli contains many vitamins, including vitamin C and vitamin A.", image_url: "https://d2d8wwwkmhfcva.cloudfront.net/600x/filters:fill(FFF,true):format(jpg)/d2lnr5mha7bycj.cloudfront.net/product-image/file/large_42d7673d-8670-469d-8a32-0fc5760e1a7f.jpg", tags: "broccoli brocoli crown ")
broccoli.store_prices.create(store_id: 3, price: 1.99)
broccoli.store_prices.create(store_id: 4, price: 2.59)
broccoli.store_prices.create(store_id: 5, price: 3.99)
broccoli.store_prices.create(store_id: 6, price: 2.79)
#### Asparagus ####
asparagus = Item.create(category: Category.find_by(name: "Produce"), name: "Local Asparagus", brand: "Produce", description: "Enjoy this spring favorite veggie raw, in salads, steamed, or roasted.", image_url: "https://d2d8wwwkmhfcva.cloudfront.net/600x/filters:fill(FFF,true):format(jpg)/d2lnr5mha7bycj.cloudfront.net/product-image/file/large_7b757912-89ea-4f37-8aa6-3290d90eeb43.jpg", tags: "asparagus spears ")
asparagus.store_prices.create(store_id: 3, price: 4.99)
asparagus.store_prices.create(store_id: 4, price: 4.89)
asparagus.store_prices.create(store_id: 5, price: 6.99)
asparagus.store_prices.create(store_id: 6, price: 5.59)
#### Bell Peppers ####
red_bell_pepper = Item.create(category: Category.find_by(name: "Produce"), name: "Red Bell Pepper", brand: "Produce", description: "Perfect for snacking, salads, and grilling.", image_url: "https://d2d8wwwkmhfcva.cloudfront.net/600x/filters:fill(FFF,true):format(jpg)/d2lnr5mha7bycj.cloudfront.net/product-image/file/large_748bbd55-f1ee-4760-9a37-873bd4fe1dd8.jpg", tags: "peppers pepper red bell")
red_bell_pepper.store_prices.create(store_id: 3, price: 0.99)
red_bell_pepper.store_prices.create(store_id: 4, price: 0.99)
red_bell_pepper.store_prices.create(store_id: 5, price: 1.99)
red_bell_pepper.store_prices.create(store_id: 6, price: 1.20)
green_bell_pepper = Item.create(category: Category.find_by(name: "Produce"), name: "Green Bell Peppers", brand: "Produce", description: "Perfect for snacking, salads, and grilling.", image_url: "https://shop.safeway.com/productimages/200x200/184480005_200x200.jpg", tags: "peppers pepper green bell")
green_bell_pepper.store_prices.create(store_id: 6, price: 0.70)
green_bell_pepper.store_prices.create(store_id: 6, price: 0.90)
green_bell_pepper.store_prices.create(store_id: 6, price: 1.90)
green_bell_pepper.store_prices.create(store_id: 6, price: 1.00)
orange_bell_pepper = Item.create(category: Category.find_by(name: "Produce"), name: "Orange Bell Peppers", brand: "Produce", description: "Perfect for snacking, salads, and grilling.", image_url: "https://shop.safeway.com/productimages/100x100/184480013_100x100.jpg", tags: "peppers pepper orange bell")
orange_bell_pepper.store_prices.create(store_id: 3, price: 1.20)
orange_bell_pepper.store_prices.create(store_id: 4, price: 1.50)
orange_bell_pepper.store_prices.create(store_id: 5, price: 1.99)
orange_bell_pepper.store_prices.create(store_id: 6, price: 1.70)
#### Onion ####
red_onion = Item.create(category: Category.find_by(name: "Produce"), name: "Red Onion", brand: "Produce", description: "Red Onions are in season year-round, perfect for salads and salsas.", image_url: "https://d2d8wwwkmhfcva.cloudfront.net/600x/filters:fill(FFF,true):format(jpg)/d2lnr5mha7bycj.cloudfront.net/product-image/file/large_55e5259d-438f-4358-89cb-683a8f4874de.jpg", tags: "onions red")
red_onion.store_prices.create(store_id: 3, price: 1.20)
red_onion.store_prices.create(store_id: 4, price: 1.75)
red_onion.store_prices.create(store_id: 5, price: 2.59)
red_onion.store_prices.create(store_id: 6, price: 1.64)
yellow_onion = Item.create(category: Category.find_by(name: "Produce"), name: "Yellow Onion", brand: "Produce", description: "Yellow Onions are in season year-round, perfect for stews, stocks, and soups.", image_url: "https://shop.safeway.com/productimages/200x200/184710074_200x200.jpg", tags: "onions white yellow")
yellow_onion.store_prices.create(store_id: 3, price: 1.20)
yellow_onion.store_prices.create(store_id: 4, price: 1.75)
yellow_onion.store_prices.create(store_id: 5, price: 2.59)
yellow_onion.store_prices.create(store_id: 6, price: 1.64)
#### Tomato ####
large_tomato = Item.create(category: Category.find_by(name: "Produce"), name: "Large Red Tomato", brand: "Produce", description: "In season now, so get 'em while you can! These delicate beauties are ripened on the vine.", image_url: "https://shop.safeway.com/productimages/100x100/184570063_100x100.jpg", tags: "tomatoe tomato heirloom")
large_tomato.store_prices.create(store_id: 3, price: 1.20)
large_tomato.store_prices.create(store_id: 4, price: 1.75)
large_tomato.store_prices.create(store_id: 5, price: 2.59)
large_tomato.store_prices.create(store_id: 6, price: 1.64)
############# Category 1: Meat/Poultry/Fish
#### Ground Beef ####
ground_beef = Item.create(category: Category.find_by(name: "Meat, Poultry, & Fish"), name: "Ground Beef, 1 lb.", description: "Grass Fed Ground Beef 85% Lean, 15\% Fat", image_url: "https://i1.wp.com/foodpoisoningbulletin.com/wp-content/uploads/Raw-Ground-Beef.jpg?resize=350\%2C200&ssl=1", tags: "ground beef hamburger burger")
ground_beef.store_prices.create(store_id: 3, price: 7.50)
ground_beef.store_prices.create(store_id: 4, price: 7.99)
ground_beef.store_prices.create(store_id: 5, price: 10.99)
ground_beef.store_prices.create(store_id: 6, price: 5.84)
##### Chicken #####
chicken_thigh = Item.create(category: Category.find_by(name: "Meat, Poultry, & Fish"), name: "Chicken Thigh / lb. ", brand: "Chicken Drumsticks", description: "Juicy and easy to prepare!", image_url: "https://www.abelandcole.co.uk/media/294_12722_z.jpg", tags: "chicken leg drumstick")
chicken_thigh.store_prices.create(store_id: 3, price: 4.59)
chicken_thigh.store_prices.create(store_id: 4, price: 7.59)
chicken_thigh.store_prices.create(store_id: 5, price: 9.19)
chicken_thigh.store_prices.create(store_id: 6, price: 6.39)
chicken_breast = Item.create(category: Category.find_by(name: "Meat, Poultry, & Fish"), name: "Chicken Breast / lb.", brand: "Organics", description: "These boneless, skinless, hand-trimmed filets contain all-natural chicken breast meat and are perfect for your favorite recipes. ", image_url: "https://images-na.ssl-images-amazon.com/images/I/719JxkiwTVL._AC_UL320_SR316,320_.jpg", tags: "chicken breast")
chicken_breast.store_prices.create(store_id: 3, price: 4.50)
chicken_breast.store_prices.create(store_id: 4, price: 7.99)
chicken_breast.store_prices.create(store_id: 5, price: 9.99)
chicken_breast.store_prices.create(store_id: 6, price: 6.99)
### Turkey ###
deli_turkey = Item.create(category: Category.find_by(name: "Meat, Poultry, & Fish"), name: "Sliced Deli Turkey", brand: "Deli", description: "Extra lean, rich in protein and gluten free.", image_url: "https://shop.safeway.com/productimages/100x100/182030895_100x100.jpg", tags: "turkey deli lunch meat")
deli_turkey.store_prices.create(store_id: 4, price: 6.99)
deli_turkey.store_prices.create(store_id: 5, price: 10.99)
deli_turkey.store_prices.create(store_id: 6, price: 7.99)
### Ham ###
deli_ham = Item.create(category: Category.find_by(name: "Meat, Poultry, & Fish"), name: "Sliced Deli Ham", brand: "Deli", description: "Fresh ham. Water. Vinegar. Organic sugar. Natural flavors. Sea salt. Humanely raised.", image_url: "https://shop.safeway.com/productimages/100x100/182030118_100x100.jpg", tags: "deli lunch meat ham")
deli_ham.store_prices.create(store_id: 4, price: 6.59)
deli_ham.store_prices.create(store_id: 5, price: 10.89)
deli_ham.store_prices.create(store_id: 6, price: 7.39)
#### Fish ####
shrimp = Item.create(category: Category.find_by(name: "Meat, Poultry, & Fish"), name: "Cooked/Peeled Cocktail Shrimp, 1 lb.", description: "Cooked and Peeled Shrimp ready for serving.", image_url: "https://previews.123rf.com/images/cokemomo/cokemomo1301/cokemomo130100018/17379188-shrimp-cocktail-prawn-cocktail-appetizer-Stock-Photo.jpg", tags: "cocktail shrimp")
shrimp.store_prices.create(store_id: 3, price: 8.00)
shrimp.store_prices.create(store_id: 4, price: 11.29)
shrimp.store_prices.create(store_id: 5, price: 12.59)
shrimp.store_prices.create(store_id: 6, price: 9.99)
halibut = Item.create(category: Category.find_by(name: "Meat, Poultry, & Fish"), name: "Halibut Fillet, 12 oz.", brand: "Wild Alaska", description: "All natural, skinless, wild caught in Alaska.", image_url: "https://harborfish.com/wp-content/uploads/2017/05/HalibutFillet.r1.jpg", tags: "fish fillet halibut skinless")
halibut.store_prices.create(store_id: 3, price: 17.69)
halibut.store_prices.create(store_id: 4, price: 19.90)
halibut.store_prices.create(store_id: 5, price: 25.00)
halibut.store_prices.create(store_id: 6, price: 22.49)
salmon = Item.create(category: Category.find_by(name: "Meat, Poultry, & Fish"), name: "Alaskan Salmon 16 oz.", brand: "Wild Alaskan Salmon", description: "Responsibly sourced, versatile protein, packed with nutrients.", image_url: "https://target.scene7.com/is/image/Target/49178873?wid=520&hei=520&fmt=pjpeg", tags: "fish fillet salmon")
salmon.store_prices.create(store_id: 3, price: 14.59)
salmon.store_prices.create(store_id: 4, price: 15.99)
salmon.store_prices.create(store_id: 5, price: 17.39)
salmon.store_prices.create(store_id: 6, price: 13.49)
ahi_tuna = Item.create(category: Category.find_by(name: "Meat, Poultry, & Fish"), name: "Ahi Tuna Steaks 12 oz.", description: "Wild caught, fair trade certified, sushi quality.", image_url: "https://9woclymefe-flywheel.netdna-ssl.com/wp-content/uploads/Raw-Ahi-Tuna.jpg", tags: "fish steaks tuna ahi")
ahi_tuna.store_prices.create(store_id: 3, price: 9.99)
ahi_tuna.store_prices.create(store_id: 4, price: 12.19)
ahi_tuna.store_prices.create(store_id: 5, price: 13.59)
ahi_tuna.store_prices.create(store_id: 6, price: 11.19)
################## Category 3: Dairy & Eggs
### Eggs ###
dozen_eggs = Item.create(category: Category.find_by(name: "Dairy & Eggs"), name: "1 Dozen Organic Eggs", description: "Certified Organic, high quality protein.", image_url: "https://media.glamour.com/photos/5695983f93ef4b09520d51ff/master/pass/health-fitness-2013-02-dozen-eggs-main.jpg", tags: "dozen eggs")
dozen_eggs.store_prices.create(store_id: 3, price: 3.20)
dozen_eggs.store_prices.create(store_id: 4, price: 3.75)
dozen_eggs.store_prices.create(store_id: 3, price: 3.20)
dozen_eggs.store_prices.create(store_id: 4, price: 4.75)
dozen_eggs.store_prices.create(store_id: 5, price: 5.29)
dozen_eggs.store_prices.create(store_id: 6, price: 3.99)
### Butter ###
butter = Item.create(category: Category.find_by(name: "Dairy & Eggs"), name: "Organic Butter, 1 lb.", description: "Certified Organic, unsalted.", image_url: "https://media.npr.org/assets/img/2017/02/23/butter1_wide-b23d6a7af9100ca3d155a4bd7a2f90e2ae3d1bfe.jpg?s=1400", tags: "butter sticks")
butter.store_prices.create(store_id: 3, price: 5.20)
butter.store_prices.create(store_id: 4, price: 4.75)
butter.store_prices.create(store_id: 5, price: 8.29)
butter.store_prices.create(store_id: 6, price: 6.99)
### Shredded Cheese ###
shredded_cheese = Item.create(category: Category.find_by(name: "Dairy & Eggs"), name: "Mild Shredded Cheddar, 8 oz.", description: "Vegetarian. Delicious Natural Cheese.", image_url: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRij107clBJbRzDHLiIDqjWlPI9fIaKiuQ7zQoIwSbsfKfFldFp", tags: "cheese shredded cheddar mild")
shredded_cheese.store_prices.create(store_id: 1, price: 3.50)
shredded_cheese.store_prices.create(store_id: 2, price: 2.75)
shredded_cheese.store_prices.create(store_id: 3, price: 3.50)
shredded_cheese.store_prices.create(store_id: 4, price: 3.75)
shredded_cheese.store_prices.create(store_id: 5, price: 4.49)
shredded_cheese.store_prices.create(store_id: 6, price: 2.99)
### Milk ###
fat_free_milk = Item.create(category: Category.find_by(name: "Dairy & Eggs"), name: "Organic Fat Free, 1 gallon", description: "Organic, Vitamin D!", image_url: "https://t4.ftcdn.net/jpg/00/82/13/31/160_F_82133164_ccip4387BdF8cV6Si75DR2x4oSY2fNS7.jpg", tags: "milk fat free fat-free moo")
fat_free_milk.store_prices.create(store_id: 1, price: 5.50)
fat_free_milk.store_prices.create(store_id: 2, price: 5.75)
fat_free_milk.store_prices.create(store_id: 3, price: 6.50)
fat_free_milk.store_prices.create(store_id: 4, price: 5.75)
fat_free_milk.store_prices.create(store_id: 5, price: 8.49)
fat_free_milk.store_prices.create(store_id: 6, price: 7.99)
### coffee creamer ###
coffee_creamer = Item.create(category: Category.find_by(name: "Dairy & Eggs"), name: "Coffee Creamer, French Vanilla", description: "Coffeemate French Vanilla flavor coffee creamer is the perfect way to create a delicious cup of creamy vanilla perfection.", image_url: "https://i5.walmartimages.com/asr/16a09f1c-e0f8-4b4d-82a3-c05c5c52aa42_1.067e61791ee07acebe628561597a549d.jpeg?odnHeight=450&odnWidth=450&odnBg=FFFFFF", tags: "coffee creamer french vanilla")
coffee_creamer.store_prices.create(store_id: 1, price: 1.99)
coffee_creamer.store_prices.create(store_id: 2, price: 1.99)
coffee_creamer.store_prices.create(store_id: 3, price: 2.99)
coffee_creamer.store_prices.create(store_id: 4, price: 2.99)
coffee_creamer.store_prices.create(store_id: 6, price: 2.29)
################## Category 4: Frozen Foods
fr_taquitos = Item.create(category: Category.find_by(name: "Frozen Food"), name: "Taquitos, count: 24", description: "Crispy, crunchy, and oh-so-incredibly easy...delicious Chicken Taquitos!", image_url: "https://pbs.twimg.com/media/C3VBOo4VUAEV6ZM.jpg", tags: "taquitos microwaveable frozen")
fr_taquitos.store_prices.create(store_id: 1, price: 5.99)
fr_taquitos.store_prices.create(store_id: 2, price: 6.59)
fr_taquitos.store_prices.create(store_id: 3, price: 5.99)
fr_taquitos.store_prices.create(store_id: 4, price: 5.59)
fr_taquitos.store_prices.create(store_id: 6, price: 6.79)
bagel_bites = Item.create(category: Category.find_by(name: "Frozen Food"), name: "Bagel Bites, count: 40", description: "When pizza is on a bagel, you can eat pizza anytime - Maren", image_url: "https://shop.safeway.com/productimages/200x200/148300188_200x200.jpg", tags: "bagel bites microwaveable frozen")
bagel_bites.store_prices.create(store_id: 1, price: 9.19)
bagel_bites.store_prices.create(store_id: 2, price: 10.59)
bagel_bites.store_prices.create(store_id: 3, price: 9.89)
bagel_bites.store_prices.create(store_id: 4, price: 10.59)
bagel_bites.store_prices.create(store_id: 6, price: 11.19)
digiorno = Item.create(category: Category.find_by(name: "Frozen Food"), name: "Pizza Rising Crust Four Cheese", description: "We start with our preservative-free rising crust, and then top it off with our signature sauce, made from scratch using California vine-ripened tomatoes", image_url: "https://shop.safeway.com/productimages/200x200/148050178_200x200.jpg", tags: "pizza frozen")
digiorno.store_prices.create(store_id: 1, price: 4.99)
digiorno.store_prices.create(store_id: 2, price: 5.80)
digiorno.store_prices.create(store_id: 3, price: 4.19)
digiorno.store_prices.create(store_id: 4, price: 4.79)
digiorno.store_prices.create(store_id: 6, price: 5.99)
froyo = Item.create(category: Category.find_by(name: "Frozen Food"), name: "Ben & Jerrys Frozen Yogurt Low-Fat Half Baked - 1 Pint", description: "Chocolate & vanilla low fat frozen yogurts mixed with gobs of chocolate chip cookie dough & fudge brownies.", image_url: "https://shop.safeway.com/productimages/200x200/142050503_200x200.jpg", tags: "frozen yogurt ben & jerrys froyo half baked")
froyo.store_prices.create(store_id: 1, price: 4.99)
froyo.store_prices.create(store_id: 2, price: 4.80)
froyo.store_prices.create(store_id: 3, price: 4.29)
froyo.store_prices.create(store_id: 4, price: 4.79)
froyo.store_prices.create(store_id: 6, price: 4.19)
haagen = Item.create(category: Category.find_by(name: "Frozen Food"), name: "Haagen-Dazs Ice Cream Caramel Cone - 14 Fl. Oz.", description: "A creamy, crunchy composition of smooth caramel ice cream, crunchy chocolaty-covered cone pieces and rich caramel swirls.", image_url: "https://shop.safeway.com/productimages/200x200/142010459_200x200.jpg", tags: "ice cream caramel haagen dazs")
haagen.store_prices.create(store_id: 1, price: 3.99)
haagen.store_prices.create(store_id: 2, price: 3.80)
haagen.store_prices.create(store_id: 3, price: 3.29)
haagen.store_prices.create(store_id: 4, price: 4.50)
haagen.store_prices.create(store_id: 6, price: 3.50)
halotop = Item.create(category: Category.find_by(name: "Frozen Food"), name: "Halo Top Ice Cream Oatmeal Cookie - 1 Pint", description: "Good source of protein. 280 calories per pint. All natural. Let's not rush this. It's worth the wait.", image_url: "https://shop.safeway.com/productimages/100x100/960273093_100x100.jpg", tags: "ice cream halo top oatmeal cookie")
halotop.store_prices.create(store_id: 1, price: 5.99)
halotop.store_prices.create(store_id: 2, price: 5.80)
halotop.store_prices.create(store_id: 3, price: 4.29)
halotop.store_prices.create(store_id: 4, price: 5.50)
halotop.store_prices.create(store_id: 6, price: 5.59)
bombpops = Item.create(category: Category.find_by(name: "Frozen Food"), name: "Bomb Pop Pops Original - 12-1.75 Fl. Oz.", description: "Naturally and artificially flavored frozen confection. Cherry, lime & blue raspberry. The original.", image_url: "https://shop.safeway.com/productimages/200x200/960100621_200x200.jpg", tags: "fruit popsicle bomb pops")
bombpops.store_prices.create(store_id: 1, price: 3.19)
bombpops.store_prices.create(store_id: 2, price: 3.60)
bombpops.store_prices.create(store_id: 3, price: 3.29)
bombpops.store_prices.create(store_id: 4, price: 3.50)
bombpops.store_prices.create(store_id: 6, price: 3.29)
fruit_pops = Item.create(category: Category.find_by(name: "Frozen Food"), name: "Outshine Fruit Ice Bars Pomegranate - 6-2.68 Fl. Oz.", description: "Fruit ice bars. Made with fruit juice. Excellent source of vitamin C. 70 calories per bar. Ready to snack brighter?", image_url: "https://shop.safeway.com/productimages/200x200/960033252_200x200.jpg", tags: "fruit pops popsicle pomengranate")
fruit_pops.store_prices.create(store_id: 1, price: 3.79)
fruit_pops.store_prices.create(store_id: 2, price: 3.80)
fruit_pops.store_prices.create(store_id: 3, price: 3.99)
fruit_pops.store_prices.create(store_id: 4, price: 3.50)
fruit_pops.store_prices.create(store_id: 6, price: 3.99)
amys = Item.create(category: Category.find_by(name: "Frozen Food"), name: "Amys Bowls Harvest Casserole - 10 Oz", description: "Made with organic roasted sweet potatoes, quinoa and kale. New! Gluten free. Contains sesame and pumpkin seeds.", image_url: "https://shop.safeway.com/productimages/200x200/960146387_200x200.jpg", tags: "frozen dinner amys casserole")
amys.store_prices.create(store_id: 1, price: 3.79)
amys.store_prices.create(store_id: 2, price: 3.80)
amys.store_prices.create(store_id: 3, price: 3.99)
amys.store_prices.create(store_id: 4, price: 3.50)
amys.store_prices.create(store_id: 5, price: 4.50)
amys.store_prices.create(store_id: 6, price: 3.99)
pot_pie = Item.create(category: Category.find_by(name: "Frozen Food"), name: "<NAME> Pot Pie Chicken - 10 Oz", description: "Tender white meat chicken. Golden flaky crust made from scratch. From my kitchen to yours since 1948.", image_url: "https://shop.safeway.com/productimages/200x200/960048283_200x200.jpg", tags: "frozen dinner amys casserole")
pot_pie.store_prices.create(store_id: 1, price: 3.89)
pot_pie.store_prices.create(store_id: 2, price: 3.20)
pot_pie.store_prices.create(store_id: 3, price: 3.39)
pot_pie.store_prices.create(store_id: 4, price: 3.40)
pot_pie.store_prices.create(store_id: 6, price: 3.50)
lasagna = Item.create(category: Category.find_by(name: "Frozen Food"), name: "Stouffers Classics Lasagna With Meat & Sauce - 19 Oz", description: "Freshly made pasta layered between a rich meat sauce and topped with real mozzarella cheese. No preservatives. Topped with fresh cheese & aged parmesan.", image_url: "https://shop.safeway.com/productimages/200x200/960053336_200x200.jpg", tags: "frozen dinner lasagna stouffers")
lasagna.store_prices.create(store_id: 1, price: 3.89)
lasagna.store_prices.create(store_id: 2, price: 3.20)
lasagna.store_prices.create(store_id: 3, price: 3.39)
lasagna.store_prices.create(store_id: 4, price: 3.40)
lasagna.store_prices.create(store_id: 6, price: 3.99)
############## Category 5: Beverages
ground_coffee = Item.create(category: Category.find_by(name: "Beverages"), name: "French Roast, 12 oz.", description: "Liquid Gold. French Roast Ground", image_url: "https://a1coffee.net/media/catalog/category/ground_coffee_.jpg", tags: "coffee ground")
ground_coffee.store_prices.create(store_id: 1, price: 10.99)
ground_coffee.store_prices.create(store_id: 2, price: 10.50)
ground_coffee.store_prices.create(store_id: 3, price: 8.99)
ground_coffee.store_prices.create(store_id: 4, price: 9.50)
ground_coffee.store_prices.create(store_id: 5, price: 11.99)
ground_coffee.store_prices.create(store_id: 6, price: 9.49)
tea = Item.create(category: Category.find_by(name: "Beverages"), name: "Green Tea, count: 40", description: "A harmonious blend of green tea with lemongrass & spearmint.", image_url: "https://www.images-iherb.com/w/LOW-07848-1.jpg", tags: "green tea bag")
tea.store_prices.create(store_id: 1, price: 4.00)
tea.store_prices.create(store_id: 2, price: 3.20)
tea.store_prices.create(store_id: 3, price: 4.00)
tea.store_prices.create(store_id: 4, price: 3.20)
tea.store_prices.create(store_id: 5, price: 4.49)
tea.store_prices.create(store_id: 6, price: 4.40)
oj = Item.create(category: Category.find_by(name: "Beverages"), name: "Floridas Natural Juice Orange Original - 89 Fl. Oz.", description: "Premium. Squeezed from our fresh oranges. Not from concentrate. 100\% pure Florida pasteurized orange juice.", image_url: "https://shop.safeway.com/productimages/200x200/960042370_200x200.jpg", tags: "orange juice")
oj.store_prices.create(store_id: 1, price: 4.10)
oj.store_prices.create(store_id: 2, price: 3.90)
oj.store_prices.create(store_id: 3, price: 4.30)
oj.store_prices.create(store_id: 4, price: 3.29)
oj.store_prices.create(store_id: 5, price: 4.49)
oj.store_prices.create(store_id: 6, price: 4.59)
v8 = Item.create(category: Category.find_by(name: "Beverages"), name: "V8 Vegetable Juice Original - 46 Fl. Oz.", description: "Fresh new look! 2 servings of veggies.", image_url: "https://shop.safeway.com/productimages/200x200/120010041_200x200.jpg", tags: "vegetable juice")
v8.store_prices.create(store_id: 1, price: 4.79)
v8.store_prices.create(store_id: 2, price: 4.80)
v8.store_prices.create(store_id: 3, price: 4.39)
v8.store_prices.create(store_id: 4, price: 4.19)
v8.store_prices.create(store_id: 5, price: 5.49)
v8.store_prices.create(store_id: 6, price: 4.49)
cranberry = Item.create(category: Category.find_by(name: "Beverages"), name: "Cranberry Juice Cocktail", brand: "Ocean Spray", description: "100\% Vitamin C", image_url: "https://i5.walmartimages.com/asr/7e005b10-8b96-4ecb-815d-0043f20d74c8_1.b28b6ea931ceb30657ae47adcaa5551f.jpeg?odnHeight=450&odnWidth=450&odnBg=FFFFFF", tags: "cranberry juice")
cranberry.store_prices.create(store_id: 1, price: 4.00)
cranberry.store_prices.create(store_id: 2, price: 3.20)
cranberry.store_prices.create(store_id: 3, price: 4.40)
cranberry.store_prices.create(store_id: 4, price: 5.00)
cranberry.store_prices.create(store_id: 5, price: 4.20)
cranberry.store_prices.create(store_id: 6, price: 4.40)
lacroix = Item.create(category: Category.find_by(name: "Beverages"), name: "LaCroix Sparkling Water Lime, count: 12", brand: "LaCroix", description: "Every millenial's dream", image_url: "https://shop.safeway.com/productimages/100x100/108101500_100x100.jpg", tags: "lacroix sparkling water")
lacroix.store_prices.create(store_id: 1, price: 5.90)
lacroix.store_prices.create(store_id: 2, price: 5.20)
lacroix.store_prices.create(store_id: 3, price: 5.80)
lacroix.store_prices.create(store_id: 4, price: 5.90)
lacroix.store_prices.create(store_id: 5, price: 6.20)
lacroix.store_prices.create(store_id: 6, price: 5.80)
sbucks_iced = Item.create(category: Category.find_by(name: "Beverages"), name: "Starbucks Iced Coffee Unsweetened - 48 Fl. Oz.", brand: "Starbucks", description: "Premium coffee beverage. Smooth & balanced.", image_url: "https://shop.safeway.com/productimages/200x200/960111804_200x200.jpg", tags: "starbucks iced coffee unsweetened")
sbucks_iced.store_prices.create(store_id: 1, price: 5.15)
sbucks_iced.store_prices.create(store_id: 2, price: 4.20)
sbucks_iced.store_prices.create(store_id: 3, price: 5.79)
sbucks_iced.store_prices.create(store_id: 4, price: 4.99)
sbucks_iced.store_prices.create(store_id: 5, price: 6.20)
sbucks_iced.store_prices.create(store_id: 6, price: 5.59)
################ Category: 6 Adult Beverages
### wine ###
merlot = Item.create(category: Category.find_by(name: "Adult Beverages"), name: "Wild Horse Merlot Wine, 750 ml", brand: "Wild Horse", description: "Flavors of cherry and mulberry are enhanced by a creamy toasted oak finish", image_url: "https://shop.safeway.com/productimages/200x200/189054127_200x200.jpg", tags: "wine red merlot")
merlot.store_prices.create(store_id: 1, price: 13.00)
merlot.store_prices.create(store_id: 2, price: 12.90)
merlot.store_prices.create(store_id: 3, price: 15.00)
merlot.store_prices.create(store_id: 4, price: 12.90)
merlot.store_prices.create(store_id: 5, price: 15.90)
merlot.store_prices.create(store_id: 6, price: 13.99)
pinot = Item.create(category: Category.find_by(name: "Adult Beverages"), name: "J Vineyards Russian River Pinot Gris Wine, 750 ml.", brand: "J Vineyards", description: "The wine has a clean, crisp finish, making it a versatile accompaniment to grilled trout, herb chicken or spicy dishes.", image_url: "https://shop.safeway.com/productimages/200x200/189059194_200x200.jpg", tags: "white wine pinot grigio gris")
pinot.store_prices.create(store_id: 1, price: 11.49)
pinot.store_prices.create(store_id: 2, price: 11.90)
pinot.store_prices.create(store_id: 3, price: 10.49)
pinot.store_prices.create(store_id: 4, price: 10.90)
pinot.store_prices.create(store_id: 5, price: 14.90)
pinot.store_prices.create(store_id: 6, price: 11.99)
chardonnay = Item.create(category: Category.find_by(name: "Adult Beverages"), name: "Benziger Chardonnay Wine, 750 ml", brand: "Benziger", description: "The extra hang-time on the vine, a result of the long cool growing season, promotes fully developed and beautifully balanced tropical fruit flavors.", image_url: "https://shop.safeway.com/productimages/200x200/189057466_200x200.jpg", tags: "white wine chardonnay")
chardonnay.store_prices.create(store_id: 1, price: 10.79)
chardonnay.store_prices.create(store_id: 2, price: 11.10)
chardonnay.store_prices.create(store_id: 3, price: 10.49)
chardonnay.store_prices.create(store_id: 4, price: 11.90)
chardonnay.store_prices.create(store_id: 5, price: 13.90)
chardonnay.store_prices.create(store_id: 6, price: 10.99)
blue_moon = Item.create(category: Category.find_by(name: "Adult Beverages"), name: "Blue Moon Beer Belgian White Ale Bottles, 12-12 Fl. Oz.", brand: "Blue Moon", description: "Brewed with valencia orange peel. Est. 1995. Belgian-style wheat ale brewed with coriander & orange peel. ", image_url: "https://shop.safeway.com/productimages/200x200/189010947_200x200.jpg", tags: "ipa blue moon beer")
blue_moon.store_prices.create(store_id: 1, price: 15.59)
blue_moon.store_prices.create(store_id: 2, price: 15.20)
blue_moon.store_prices.create(store_id: 3, price: 14.99)
blue_moon.store_prices.create(store_id: 4, price: 15.50)
blue_moon.store_prices.create(store_id: 5, price: 17.50)
blue_moon.store_prices.create(store_id: 6, price: 16.99)
drakes = Item.create(category: Category.find_by(name: "Adult Beverages"), name: "Drakes IPA Bottles, 6-12 Fl. Oz.", brand: "Drakes", description: "This deep golden IPA is artfully balanced with a powerful hop aroma of pine & citrus, medium body, and a crisp finish.", image_url: "https://shop.safeway.com/productimages/200x200/960053209_200x200.jpg", tags: "drakes beer ipa")
drakes.store_prices.create(store_id: 1, price: 8.99)
drakes.store_prices.create(store_id: 2, price: 9.50)
drakes.store_prices.create(store_id: 3, price: 7.99)
drakes.store_prices.create(store_id: 4, price: 8.50)
drakes.store_prices.create(store_id: 5, price: 10.50)
drakes.store_prices.create(store_id: 6, price: 8.99)
lagunitas = Item.create(category: Category.find_by(name: "Adult Beverages"), name: "Lagunitas IPA Bottles, 12-12 Fl. Oz.", brand: "Lagunitas", description: "420 divided by 35 - 12 oz'ers. Sonoma County. Est. 1993. Beer speaks. People mumble. India pale ale. Doggone good.", image_url: "https://shop.safeway.com/productimages/200x200/960017136_200x200.jpg", tags: "drakes beer ipa")
lagunitas.store_prices.create(store_id: 1, price: 7.99)
lagunitas.store_prices.create(store_id: 2, price: 8.50)
lagunitas.store_prices.create(store_id: 3, price: 7.99)
lagunitas.store_prices.create(store_id: 4, price: 8.50)
lagunitas.store_prices.create(store_id: 5, price: 10.50)
lagunitas.store_prices.create(store_id: 6, price: 8.99)
jose_cuervo = Item.create(category: Category.find_by(name: "Adult Beverages"), name: "<NAME> Gold Tequila 80 Proof - 750 Ml", brand: "<NAME>", description: "<NAME> Gold is a signature blend of Reposado and younger Tequilas created to make the perfect Margarita or enjoyed as a shot.", image_url: "https://shop.safeway.com/productimages/200x200/189030472_200x200.jpg", tags: "tequila alcohol gold")
jose_cuervo.store_prices.create(store_id: 1, price: 10.19)
jose_cuervo.store_prices.create(store_id: 2, price: 10.50)
jose_cuervo.store_prices.create(store_id: 3, price: 9.99)
jose_cuervo.store_prices.create(store_id: 4, price: 10.50)
jose_cuervo.store_prices.create(store_id: 5, price: 13.50)
jose_cuervo.store_prices.create(store_id: 6, price: 11.99)
absolut = Item.create(category: Category.find_by(name: "Adult Beverages"), name: "Absolut Vodka 80 Proof - 750 Ml", brand: "Absolute", description: "Absolute since 1879. Imported. Distill from grain produced in Sweden. Enjoy responsibly.", image_url: "https://shop.safeway.com/productimages/200x200/189031534_200x200.jpg", tags: "vodka absolute absolut")
absolut.store_prices.create(store_id: 1, price: 10.99)
absolut.store_prices.create(store_id: 2, price: 10.59)
absolut.store_prices.create(store_id: 3, price: 11.99)
absolut.store_prices.create(store_id: 4, price: 10.50)
absolut.store_prices.create(store_id: 5, price: 13.50)
absolut.store_prices.create(store_id: 6, price: 11.99)
jack_daniels = Item.create(category: Category.find_by(name: "Adult Beverages"), name: "<NAME> Whiskey Black Label - 750 Ml", brand: "<NAME>", description: " Mellowed for smoothness drop by drop through sugar maple charcoal.", image_url: "https://shop.safeway.com/productimages/200x200/189030798_200x200.jpg", tags: "jack daniels whiskey")
jack_daniels.store_prices.create(store_id: 1, price: 17.99)
jack_daniels.store_prices.create(store_id: 2, price: 16.69)
jack_daniels.store_prices.create(store_id: 3, price: 16.99)
jack_daniels.store_prices.create(store_id: 4, price: 17.50)
jack_daniels.store_prices.create(store_id: 5, price: 18.50)
jack_daniels.store_prices.create(store_id: 6, price: 18.99)
tanqueray = Item.create(category: Category.find_by(name: "Adult Beverages"), name: "Tanqueray London Dry Gin 94.6 Proof - 1.75 Liter", brand: "Tanqueray", description: "The highest quality spirit and finest botanicals, picked at the peak of their freshness, are carefully crafted to produce its exceptional, much revered taste.", image_url: "https://shop.safeway.com/productimages/200x200/189030130_200x200.jpg", tags: "tanqueray gin")
tanqueray.store_prices.create(store_id: 1, price: 27.99)
tanqueray.store_prices.create(store_id: 2, price: 25.99)
tanqueray.store_prices.create(store_id: 3, price: 26.99)
tanqueray.store_prices.create(store_id: 4, price: 26.50)
tanqueray.store_prices.create(store_id: 5, price: 26.90)
tanqueray.store_prices.create(store_id: 6, price: 27.99)
######################### Category 7: Snacks & Candy
### Candy ###
redvines = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "American Licorice Red Vines Twist Original Red - 16 Oz", brand: "Red Vines", description: "The Red Vines candy you love has a new look. Don't forget to try our other delicious flavors: grape, cherry, black licorice. Live on the sweet side with Red Vines.", image_url: "https://shop.safeway.com/productimages/200x200/960090879_200x200.jpg", tags: "candy red vines licorice")
redvines.store_prices.create(store_id: 1, price: 2.59)
redvines.store_prices.create(store_id: 2, price: 2.79)
redvines.store_prices.create(store_id: 3, price: 2.99)
redvines.store_prices.create(store_id: 4, price: 3.50)
redvines.store_prices.create(store_id: 5, price: 5.90)
redvines.store_prices.create(store_id: 6, price: 3.99)
haribo = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "Haribo Gummi Candy Gold-Bears Original - 14 Oz", brand: "Haribo", description: "Kids and grown-ups love it so. The happy world of Haribo. Fresh. Fruity. Chewy.", image_url: "https://shop.safeway.com/productimages/200x200/301050133_200x200.jpg", tags: "candy gummy bears gummi haribo")
haribo.store_prices.create(store_id: 1, price: 4.59)
haribo.store_prices.create(store_id: 2, price: 4.79)
haribo.store_prices.create(store_id: 3, price: 4.99)
haribo.store_prices.create(store_id: 4, price: 4.50)
haribo.store_prices.create(store_id: 5, price: 5.00)
haribo.store_prices.create(store_id: 6, price: 4.49)
candycorn = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "Signature Kitchens Candy Candy Corn - 7 Oz", brand: "Signature Kitchens", description: "Signature Select candy is great for: chopping and stirring into sugar and butter cookie dough before baking; decorating baked cookies, cupcakes and brownies; topping ice cream frozen yogurt and sundaes; adding a surprise to trail mix.", image_url: "https://shop.safeway.com/productimages/200x200/960161760_200x200.jpg", tags: "candy corn halloween")
candycorn.store_prices.create(store_id: 1, price: 0.99)
candycorn.store_prices.create(store_id: 2, price: 1.79)
candycorn.store_prices.create(store_id: 3, price: 1.99)
candycorn.store_prices.create(store_id: 4, price: 1.50)
candycorn.store_prices.create(store_id: 5, price: 1.00)
candycorn.store_prices.create(store_id: 6, price: 1.70)
sour_worms = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "Signature Kitchens Candy Sour Neon Worms - 7 Oz", brand: "Signature Kitchens", description: "Decorating baked cookies, cupcakes and brownies. Topping ice cream, frozen yogurt and sundaes.", image_url: "https://shop.safeway.com/productimages/200x200/960160102_200x200.jpg", tags: "candy gummy worms sour")
sour_worms.store_prices.create(store_id: 1, price: 1.99)
sour_worms.store_prices.create(store_id: 2, price: 2.79)
sour_worms.store_prices.create(store_id: 3, price: 2.99)
sour_worms.store_prices.create(store_id: 4, price: 2.50)
sour_worms.store_prices.create(store_id: 5, price: 2.00)
sour_worms.store_prices.create(store_id: 6, price: 1.70)
skittles = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "Skittles Candy Original - 41 Oz", brand: "Skittles", description: "Decorating baked cookies, cupcakes and brownies. Topping ice cream, frozen yogurt and sundaes.", image_url: "https://shop.safeway.com/productimages/200x200/101051037_200x200.jpg", tags: "candy gummy worms sour")
skittles.store_prices.create(store_id: 1, price: 1.99)
skittles.store_prices.create(store_id: 2, price: 2.79)
skittles.store_prices.create(store_id: 3, price: 2.99)
skittles.store_prices.create(store_id: 4, price: 2.50)
skittles.store_prices.create(store_id: 5, price: 2.00)
skittles.store_prices.create(store_id: 6, price: 1.70)
gum_trident = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "Trident Original - Each", brand: "Trident", description: "With xylitol. Bursting with more flavor (vs prior Trident formula). 30\% fewer calories than sugared gum.", image_url: "https://shop.safeway.com/productimages/200x200/960295357_200x200.jpg", tags: "candy gum trident mint")
gum_trident.store_prices.create(store_id: 1, price: 0.99)
gum_trident.store_prices.create(store_id: 2, price: 1.79)
gum_trident.store_prices.create(store_id: 3, price: 1.99)
gum_trident.store_prices.create(store_id: 4, price: 1.50)
gum_trident.store_prices.create(store_id: 5, price: 1.00)
gum_trident.store_prices.create(store_id: 6, price: 1.20)
life_savers_mints = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "Life Savers Mints Wint O Green - 6.25 Oz", brand: "Life Savers", description: "Artificially flavored. Individually wrapped! Tastes like zero degrees.", image_url: "https://shop.safeway.com/productimages/200x200/101050227_200x200.jpg", tags: "candy mints life savers")
life_savers_mints.store_prices.create(store_id: 1, price: 1.99)
life_savers_mints.store_prices.create(store_id: 2, price: 1.69)
life_savers_mints.store_prices.create(store_id: 3, price: 1.79)
life_savers_mints.store_prices.create(store_id: 4, price: 1.30)
life_savers_mints.store_prices.create(store_id: 5, price: 1.90)
life_savers_mints.store_prices.create(store_id: 6, price: 1.50)
tic_tacs = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "Tic Tac Big Pack Freshmints - 1 Oz", brand: "Tic Tacs", description: "Less than 2 calories per mint.", image_url: "https://shop.safeway.com/productimages/200x200/960040958_200x200.jpg", tags: "candy mints tic tacs freshmint")
tic_tacs.store_prices.create(store_id: 1, price: 1.39)
tic_tacs.store_prices.create(store_id: 2, price: 1.29)
tic_tacs.store_prices.create(store_id: 3, price: 1.59)
tic_tacs.store_prices.create(store_id: 4, price: 1.30)
tic_tacs.store_prices.create(store_id: 5, price: 1.10)
tic_tacs.store_prices.create(store_id: 6, price: 1.20)
flipz = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "Flipz Pretzels Milk Chocolate - 5 Oz", brand: "Flipz", description: "So completely irresistible you'll make up excuses to eat 'em. What's your excuse? With all the holes, you can eat more. I had a light lunch. Why don't I take two in case I lose one.", image_url: "https://shop.safeway.com/productimages/200x200/960042772_200x200.jpg", tags: "candy chocolate pretzels milk ")
flipz.store_prices.create(store_id: 1, price: 1.49)
flipz.store_prices.create(store_id: 2, price: 1.99)
flipz.store_prices.create(store_id: 3, price: 1.19)
flipz.store_prices.create(store_id: 4, price: 1.60)
flipz.store_prices.create(store_id: 5, price: 1.20)
flipz.store_prices.create(store_id: 6, price: 1.50)
dark_choc = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "Ghiradelli Dark Chocolate Midnight Reverie Bag - 4.12 Oz", brand: "Ghiradelli", description: "(Ken's fav) Moments of timeless pleasure. Founded in 1852. San Francisco. Reward yourself with our luxuriously deep and velvety 86\% cacao dark chocolate.", image_url: "https://shop.safeway.com/productimages/200x200/960289020_200x200.jpg", tags: "candy chocolate dark ")
dark_choc.store_prices.create(store_id: 1, price: 3.49)
dark_choc.store_prices.create(store_id: 2, price: 3.99)
dark_choc.store_prices.create(store_id: 3, price: 3.19)
dark_choc.store_prices.create(store_id: 4, price: 3.60)
dark_choc.store_prices.create(store_id: 5, price: 3.20)
dark_choc.store_prices.create(store_id: 6, price: 3.10)
asst_choc = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "Hersheys All Time Greats Snack Size Assortment Bag - 38.9 Oz", description: "Hershey's milk chocolate Reese's milk chocolate peanut butter cups; Kit Kat crisp wafers in milk chocolate; Whoppers: The original malted milk balls.", image_url: "https://shop.safeway.com/productimages/200x200/960073938_200x200.jpg", tags: "candy chocolate assorted kit kat hersheys reeses whoppers")
asst_choc.store_prices.create(store_id: 1, price: 10.49)
asst_choc.store_prices.create(store_id: 2, price: 11.99)
asst_choc.store_prices.create(store_id: 3, price: 11.19)
asst_choc.store_prices.create(store_id: 4, price: 10.60)
asst_choc.store_prices.create(store_id: 5, price: 9.20)
asst_choc.store_prices.create(store_id: 6, price: 10.99)
snickers = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "Snickers Bites Candy Bar Sharing Size - 2.83 Oz", brand: "Mars", description: "Milk chocolate, peanuts, caramel, nougat. Unwrapped.", image_url: "https://shop.safeway.com/productimages/200x200/960105032_200x200.jpg", tags: "snickers bites candy")
snickers.store_prices.create(store_id: 1, price: 1.49)
snickers.store_prices.create(store_id: 2, price: 1.99)
snickers.store_prices.create(store_id: 3, price: 1.19)
snickers.store_prices.create(store_id: 4, price: 1.60)
snickers.store_prices.create(store_id: 5, price: 1.20)
snickers.store_prices.create(store_id: 6, price: 1.50)
mms = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "M&Ms Chocolate Candies Milk Chocolate - 10.7 Oz", brand: "Mars", description: "Resealable zipper! New look! So many ways to mix M in. M&M's Chocolate Candies are made of the finest ingredients.", image_url: "https://shop.safeway.com/productimages/200x200/960092276_200x200.jpg", tags: "snickers bites candy")
mms.store_prices.create(store_id: 1, price: 1.49)
mms.store_prices.create(store_id: 2, price: 1.99)
mms.store_prices.create(store_id: 3, price: 1.19)
mms.store_prices.create(store_id: 4, price: 1.60)
mms.store_prices.create(store_id: 5, price: 1.20)
mms.store_prices.create(store_id: 6, price: 1.50)
reeses = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "Reeses Cups Minis Peanut Butter - 19.75 Oz", brand: "Hershey Foods", description: "Gluten Free!", image_url: "https://shop.safeway.com/productimages/200x200/960288700_200x200.jpg", tags: "reeses chocolate peanut butter candy")
reeses.store_prices.create(store_id: 1, price: 8.89)
reeses.store_prices.create(store_id: 2, price: 8.49)
reeses.store_prices.create(store_id: 3, price: 8.29)
reeses.store_prices.create(store_id: 4, price: 8.10)
reeses.store_prices.create(store_id: 5, price: 8.90)
reeses.store_prices.create(store_id: 6, price: 8.99)
twix = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "Twix Cookie Bars Caramel Milk Chocolate King Size - 3.02 Oz", brand: "Mars", description: "Smooth chocolate. Crispy cookie. Luscious caramel.", image_url: "https://shop.safeway.com/productimages/200x200/960034902_200x200.jpg", tags: "twix chocolate caramel cookie candy")
twix.store_prices.create(store_id: 1, price: 1.29)
twix.store_prices.create(store_id: 2, price: 1.19)
twix.store_prices.create(store_id: 3, price: 1.29)
twix.store_prices.create(store_id: 4, price: 1.10)
twix.store_prices.create(store_id: 5, price: 1.00)
twix.store_prices.create(store_id: 6, price: 1.50)
### Chips and Pretzels ###
cheetos = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "Cheetos Snacks Cheese Flavored Crunchy Flamin Hot - 8.5 Oz", brand: "Frito Lay", description: "Made with real cheese! Guaranteed fresh until printed date.", image_url: "https://shop.safeway.com/productimages/200x200/960156585_200x200.jpg", tags: "cheetos flamin hot")
cheetos.store_prices.create(store_id: 1, price: 3.19)
cheetos.store_prices.create(store_id: 2, price: 3.29)
cheetos.store_prices.create(store_id: 3, price: 3.79)
cheetos.store_prices.create(store_id: 4, price: 3.30)
cheetos.store_prices.create(store_id: 6, price: 3.50)
fritos = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "Fritos Scoops! Corn Chips Party Size! - 18 Oz", brand: "Frito Lay", description: "Great for dipping!", image_url: "https://images-na.ssl-images-amazon.com/images/I/815o4649jIL._SY550_.jpg", tags: "fritos scoops")
fritos.store_prices.create(store_id: 1, price: 5.19)
fritos.store_prices.create(store_id: 2, price: 5.29)
fritos.store_prices.create(store_id: 3, price: 5.79)
fritos.store_prices.create(store_id: 4, price: 5.30)
fritos.store_prices.create(store_id: 6, price: 5.09)
veggie_stix = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "Open Nature Veggie Sticks - 7.5 Oz", brand: "Open Nature", description: "No artificial flavors or colors. No artificial preservatives. No artificial ingredients.", image_url: "https://shop.safeway.com/productimages/200x200/960073809_200x200.jpg", tags: "veggie sticks ")
veggie_stix.store_prices.create(store_id: 1, price: 4.99)
veggie_stix.store_prices.create(store_id: 2, price: 4.79)
veggie_stix.store_prices.create(store_id: 3, price: 4.39)
veggie_stix.store_prices.create(store_id: 4, price: 4.90)
veggie_stix.store_prices.create(store_id: 5, price: 5.00)
veggie_stix.store_prices.create(store_id: 6, price: 4.29)
pirate_booty = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "Pirates Booty Rice and Corn Puffs Baked Aged White Cheddar - 4 Oz", brand: "Pirate Brands", description: "Thar be good. Shiver me timbers! No artificial colors flavors or preservatives.", image_url: "https://shop.safeway.com/productimages/200x200/109600507_200x200.jpg", tags: "pirate's booty aged white cheddar puffs")
pirate_booty.store_prices.create(store_id: 1, price: 2.99)
pirate_booty.store_prices.create(store_id: 2, price: 1.79)
pirate_booty.store_prices.create(store_id: 3, price: 2.39)
pirate_booty.store_prices.create(store_id: 4, price: 1.90)
pirate_booty.store_prices.create(store_id: 5, price: 3.00)
pirate_booty.store_prices.create(store_id: 6, price: 2.50)
sun_chips = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "SunChips Snacks Whole Grain Harvest Cheddar - 7 Oz", brand: "Pirate Brands", description: "At Sun Chips we believe being different is good. That's why we created tasty, one-of-a-kind chips that take snacking from ho-hum to oh yeah!", image_url: "https://shop.safeway.com/productimages/200x200/960094690_200x200.jpg", tags: "sun chips cheddar")
sun_chips.store_prices.create(store_id: 1, price: 2.99)
sun_chips.store_prices.create(store_id: 2, price: 3.79)
sun_chips.store_prices.create(store_id: 3, price: 3.39)
sun_chips.store_prices.create(store_id: 4, price: 3.10)
sun_chips.store_prices.create(store_id: 5, price: 4.00)
sun_chips.store_prices.create(store_id: 6, price: 3.50)
pretzels = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "Frito Lay Rold Gold Classic Thins - 16 Oz", brand: "Frito Lay", description: "Guaranteed fresh until printed date or this snack's on us.", image_url: "https://shop.safeway.com/productimages/200x200/109250258_200x200.jpg", tags: "pretzels")
pretzels.store_prices.create(store_id: 1, price: 2.99)
pretzels.store_prices.create(store_id: 2, price: 3.79)
pretzels.store_prices.create(store_id: 3, price: 3.39)
pretzels.store_prices.create(store_id: 4, price: 3.10)
pretzels.store_prices.create(store_id: 5, price: 3.90)
pretzels.store_prices.create(store_id: 6, price: 3.50)
tates = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "Tates Bake Shop Cookies Chocolate Chip - 7 Oz", brand: "Tates Bake Shop", description: "Uniquely crispy. Deeply delicious. Crispy thin scrumptious. A little bake shop in every bite.", image_url: "https://shop.safeway.com/productimages/200x200/960083367_200x200.jpg", tags: "cookies chocolate chip")
tates.store_prices.create(store_id: 1, price: 5.99)
tates.store_prices.create(store_id: 2, price: 5.79)
tates.store_prices.create(store_id: 3, price: 5.39)
tates.store_prices.create(store_id: 4, price: 5.10)
tates.store_prices.create(store_id: 5, price: 6.70)
tates.store_prices.create(store_id: 6, price: 5.50)
chips_ahoy = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "Chips Ahoy! Cookies Chocolate Chip Original - 13 Oz", brand: "Nabisco", description: "Real Chocolate Chip Cookies", image_url: "https://shop.safeway.com/productimages/200x200/960071578_200x200.jpg", tags: "cookies chocolate chip")
chips_ahoy.store_prices.create(store_id: 1, price: 2.49)
chips_ahoy.store_prices.create(store_id: 2, price: 2.29)
chips_ahoy.store_prices.create(store_id: 3, price: 2.39)
chips_ahoy.store_prices.create(store_id: 4, price: 2.80)
chips_ahoy.store_prices.create(store_id: 6, price: 2.19)
graham_cr = Item.create(category: Category.find_by(name: "Snacks & Candy"), name: "Honey Maid Grahams Honey - 14.4 Oz", brand: "Tates Bake Shop", description: "Made with real honey!", image_url: "https://shop.safeway.com/productimages/200x200/102013703_200x200.jpg", tags: "cookies chocolate chip")
graham_cr.store_prices.create(store_id: 1, price: 3.49)
graham_cr.store_prices.create(store_id: 2, price: 3.29)
graham_cr.store_prices.create(store_id: 3, price: 3.39)
graham_cr.store_prices.create(store_id: 4, price: 3.90)
graham_cr.store_prices.create(store_id: 5, price: 3.80)
graham_cr.store_prices.create(store_id: 6, price: 3.49)
############## Category 8: Beauty
#### Lotion/oil ###
cetaphil = Item.create(category: Category.find_by(name: "Beauty"), name: "Cetaphil Advanced Ultra Daily Hydrating Lotion - 16 Fl. Oz.", brand: "Galderma", description: "Clinically proven to hydrate and protect dry skin for 24 hours. This luxurious lotion is specially formulated to provide intense moisture for dry, sensitive skin everyday.", image_url: "https://shop.safeway.com/productimages/200x200/960043081_200x200.jpg", tags: "cetaphil lotion")
cetaphil.store_prices.create(store_id: 1, price: 12.49)
cetaphil.store_prices.create(store_id: 2, price: 11.29)
cetaphil.store_prices.create(store_id: 3, price: 11.39)
cetaphil.store_prices.create(store_id: 4, price: 11.90)
cetaphil.store_prices.create(store_id: 5, price: 12.80)
cetaphil.store_prices.create(store_id: 6, price: 11.49)
body_oil = Item.create(category: Category.find_by(name: "Beauty"), name: "Neutrogena Body Oil Sesame Fragrance Free - 8.5 Fl. Oz.", brand: "Neutrogena", description: "Experience Neutrogena Body Oil. Its light sesame formula glides on easily to moisturize dry skin.", image_url: "https://shop.safeway.com/productimages/200x200/960101439_200x200.jpg", tags: "body oil neutrogena")
body_oil.store_prices.create(store_id: 1, price: 12.49)
body_oil.store_prices.create(store_id: 2, price: 13.29)
body_oil.store_prices.create(store_id: 3, price: 12.39)
body_oil.store_prices.create(store_id: 4, price: 12.90)
body_oil.store_prices.create(store_id: 5, price: 12.80)
body_oil.store_prices.create(store_id: 6, price: 12.29)
### Soap/bodywash ###
soapbar = Item.create(category: Category.find_by(name: "Beauty"), name: "Olay Beauty Bar Moisture Outlast Ultra Moisture With Shea Butter - 2-3.75 Oz", brand: "P & G", description: "10x more moisturizers (vs. regular soap for smoother skin). Regular soap can leave your skin dry. Olay Moisture Outlast bar is different.", image_url: "https://shop.safeway.com/productimages/200x200/960189385_200x200.jpg", tags: "olay soap bar")
soapbar.store_prices.create(store_id: 1, price: 2.49)
soapbar.store_prices.create(store_id: 2, price: 1.29)
soapbar.store_prices.create(store_id: 3, price: 1.39)
soapbar.store_prices.create(store_id: 4, price: 1.90)
soapbar.store_prices.create(store_id: 5, price: 2.80)
soapbar.store_prices.create(store_id: 6, price: 3.29)
oldspice_wash = Item.create(category: Category.find_by(name: "Beauty"), name: "Old Spice Fresher Collection Body Wash Fiji - 16 Fl. Oz.", brand: "P & G", description: "Fresher than coconut & daydreams. With Fiji, your body is about to be marooned on a pristine tropical island filled with the scent of palm trees, endangered spices, exotic females, one dune buggy and a lifetime supply of fireworks.", image_url: "https://shop.safeway.com/productimages/200x200/960049796_200x200.jpg", tags: "fiji old spice body wash")
oldspice_wash.store_prices.create(store_id: 1, price: 2.49)
oldspice_wash.store_prices.create(store_id: 2, price: 1.29)
oldspice_wash.store_prices.create(store_id: 3, price: 1.39)
oldspice_wash.store_prices.create(store_id: 4, price: 1.90)
oldspice_wash.store_prices.create(store_id: 5, price: 2.80)
oldspice_wash.store_prices.create(store_id: 6, price: 3.29)
### Makeup ###
mascara = Item.create(category: Category.find_by(name: "Beauty"), name: "L'Oreal Voluminous Washable Mascara", brand: "L'Oreal", description: "Our first mascara for instant volume with ferocious full lash density.", image_url: "https://images-na.ssl-images-amazon.com/images/G/01/aplusautomation/vendorimages/1ed4470e-683b-4e90-8766-ea4cf5e61a92.jpg._CB325154658__SR300,300_.jpg", tags: "l'oreal mascara loreal makeup")
mascara.store_prices.create(store_id: 1, price: 7.49)
mascara.store_prices.create(store_id: 2, price: 9.29)
mascara.store_prices.create(store_id: 3, price: 8.39)
mascara.store_prices.create(store_id: 4, price: 9.90)
mascara.store_prices.create(store_id: 6, price: 8.99)
lip_color = Item.create(category: Category.find_by(name: "Beauty"), name: "Neutrogena MoistureSmooth Color Stick", brand: "Neutrogena", description: "Keep your lips colorful and extra glamorous with MoistureSmooth Color Stick.", image_url: "https://target.scene7.com/is/image/Target/14462962?wid=520&hei=520&fmt=pjpeg", tags: "neutrogrena color stick lipstick makeup")
lip_color.store_prices.create(store_id: 1, price: 7.49)
lip_color.store_prices.create(store_id: 2, price: 7.29)
lip_color.store_prices.create(store_id: 3, price: 8.39)
lip_color.store_prices.create(store_id: 4, price: 8.90)
lip_color.store_prices.create(store_id: 6, price: 8.59)
powder = Item.create(category: Category.find_by(name: "Beauty"), name: "Revlon New Complexion One-Step Makeup", brand: "Revlon", description: "Lets skin breathe for a naturally perfected look. Glides on creamy smooth, finishes powder light.", image_url: "https://images-na.ssl-images-amazon.com/images/I/71TBhSRhtzL._SY355_.jpg", tags: "powder revlon face makeup")
powder.store_prices.create(store_id: 1, price: 13.49)
powder.store_prices.create(store_id: 2, price: 12.29)
powder.store_prices.create(store_id: 3, price: 13.39)
powder.store_prices.create(store_id: 4, price: 14.90)
powder.store_prices.create(store_id: 6, price: 13.59)
blush = Item.create(category: Category.find_by(name: "Beauty"), name: "Neutrogena Healthy Skin Blends", brand: "Neutrogena", description: "This powder blush helps control oil and shine, providing sheer, illuminating color for a natural glow.", image_url: "https://images-na.ssl-images-amazon.com/images/I/91ho3NlZFlL._SY355_.jpg", tags: "powder neutrogena blush face makeup")
blush.store_prices.create(store_id: 1, price: 12.49)
blush.store_prices.create(store_id: 2, price: 12.29)
blush.store_prices.create(store_id: 3, price: 12.39)
blush.store_prices.create(store_id: 4, price: 11.90)
blush.store_prices.create(store_id: 6, price: 12.59)
essie = Item.create(category: Category.find_by(name: "Beauty"), name: "Essie Nail Color", brand: "Essie", description: "Indulge in a bright blue nail color hue that simply adores being waited on hand and foot.", image_url: "https://www.cvs.com/bizcontent/merchandising/productimages/large/95008006246.jpg", tags: "blue nail polish essie makeup")
essie.store_prices.create(store_id: 1, price: 8.49)
essie.store_prices.create(store_id: 2, price: 8.29)
essie.store_prices.create(store_id: 3, price: 9.39)
essie.store_prices.create(store_id: 4, price: 9.90)
essie.store_prices.create(store_id: 6, price: 9.00)
### other ###
mu_remover = Item.create(category: Category.find_by(name: "Beauty"), name: "Burts Bees Facial Cleansing Towelettes Sensitive - 30 Count", brand: "Burts Bees", description: "Distinctly formulated with cotton extract, rice extract and aloe, these towelettes will soften, moisturize and soothes skin. Naturally gently and skin friendly.", image_url: "https://shop.safeway.com/productimages/200x200/960085165_200x200.jpg", tags: "towelettes burts bees makeup remover")
mu_remover.store_prices.create(store_id: 1, price: 6.49)
mu_remover.store_prices.create(store_id: 2, price: 5.29)
mu_remover.store_prices.create(store_id: 3, price: 6.39)
mu_remover.store_prices.create(store_id: 4, price: 5.90)
mu_remover.store_prices.create(store_id: 5, price: 7.90)
mu_remover.store_prices.create(store_id: 6, price: 6.79)
face_wash = Item.create(category: Category.find_by(name: "Beauty"), name: "Neutrogena Deep Clean Face Wash - 6.7 Fl. Oz.", brand: "Neutrogena", description: "A penetrating and thorough cleanser that improves your complexion.", image_url: "https://shop.safeway.com/productimages/200x200/153200322_200x200.jpg", tags: "face wash neutrogena")
face_wash.store_prices.create(store_id: 1, price: 6.49)
face_wash.store_prices.create(store_id: 2, price: 7.29)
face_wash.store_prices.create(store_id: 3, price: 8.39)
face_wash.store_prices.create(store_id: 4, price: 6.10)
face_wash.store_prices.create(store_id: 5, price: 9.90)
face_wash.store_prices.create(store_id: 6, price: 8.79)
sunblock = Item.create(category: Category.find_by(name: "Beauty"), name: "Neutrogena Sunblock Ult Shr Bodymist Spf 100 - 5 Oz", brand: "Neutrogena", description: "Helioplex broad spectrum uva-uvb. Weightless. Clean feel. Non-greasy. Water resistant (80 minutes).", image_url: "https://shop.safeway.com/productimages/200x200/960159526_200x200.jpg", tags: "sun block sunblock spf neutrogena")
sunblock.store_prices.create(store_id: 1, price: 13.49)
sunblock.store_prices.create(store_id: 2, price: 13.29)
sunblock.store_prices.create(store_id: 3, price: 13.39)
sunblock.store_prices.create(store_id: 4, price: 13.10)
sunblock.store_prices.create(store_id: 5, price: 14.90)
sunblock.store_prices.create(store_id: 6, price: 13.19)
chapstick = Item.create(category: Category.find_by(name: "Beauty"), name: "Burts Bees Lip Balm Beeswax - .15 Oz", brand: "Burts Bees", description: "100\% natural. Our signature Lip Balm formulated with Beeswax to naturally help protect lips, antioxidant vitamin E to moisturize, and peppermint oil to soothe your lips.", image_url: "https://shop.safeway.com/productimages/200x200/153300106_200x200.jpg", tags: "burts bees chapstick")
chapstick.store_prices.create(store_id: 1, price: 13.49)
chapstick.store_prices.create(store_id: 2, price: 13.29)
chapstick.store_prices.create(store_id: 3, price: 13.39)
chapstick.store_prices.create(store_id: 4, price: 13.10)
chapstick.store_prices.create(store_id: 5, price: 14.90)
chapstick.store_prices.create(store_id: 6, price: 13.19)
mens_wash = Item.create(category: Category.find_by(name: "Beauty"), name: "Dove Men+Care Face Wash Hydrate+ - 5 Fl. Oz.", brand: "Dove", description: "Mildly cleans. Fights skin dryness.", image_url: "https://shop.safeway.com/productimages/100x100/960084390_100x100.jpg", tags: "mens facewash dove")
mens_wash.store_prices.create(store_id: 1, price: 5.49)
mens_wash.store_prices.create(store_id: 2, price: 5.29)
mens_wash.store_prices.create(store_id: 3, price: 4.39)
mens_wash.store_prices.create(store_id: 4, price: 3.10)
mens_wash.store_prices.create(store_id: 5, price: 5.90)
mens_wash.store_prices.create(store_id: 6, price: 5.49)
sheets = Item.create(category: Category.find_by(name: "Beauty"), name: "Clean & Clear Oil Absorbing Sheets Portable - 50 Count", brand: "Clean & Clear", description: "Instantly removes excess oil. Won't smudge makeup.", image_url: "https://shop.safeway.com/productimages/200x200/153200553_200x200.jpg", tags: "oil absorbing sheets")
sheets.store_prices.create(store_id: 1, price: 7.49)
sheets.store_prices.create(store_id: 2, price: 6.29)
sheets.store_prices.create(store_id: 3, price: 7.39)
sheets.store_prices.create(store_id: 4, price: 6.10)
sheets.store_prices.create(store_id: 5, price: 7.90)
sheets.store_prices.create(store_id: 6, price: 7.89)
hair_ties = Item.create(category: Category.find_by(name: "Beauty"), name: "Goody Elastics Ouchless Thick 4mm Royal Jewel Tones - 28 Count", brand: "Goody", description: "No ouch hair care.", image_url: "https://shop.safeway.com/productimages/200x200/960130564_200x200.jpg", tags: "elastics hair ties")
hair_ties.store_prices.create(store_id: 1, price: 3.49)
hair_ties.store_prices.create(store_id: 2, price: 2.29)
hair_ties.store_prices.create(store_id: 3, price: 3.39)
hair_ties.store_prices.create(store_id: 4, price: 3.10)
hair_ties.store_prices.create(store_id: 5, price: 3.90)
hair_ties.store_prices.create(store_id: 6, price: 3.89)
shampoo = Item.create(category: Category.find_by(name: "Beauty"), name: "Aussie Conditioner - 29.2 Fl. Oz.", brand: "Aussie", description: "Quenches thirsty locks in a flash. This shampoo, made with Australian aloe, jojoba oil and sea kelp, gives you moisturizing conditioning power to nourish your hair.", image_url: "https://shop.safeway.com/productimages/200x200/960055403_200x200.jpg", tags: "hair shampoo aussie")
shampoo.store_prices.create(store_id: 1, price: 6.29)
shampoo.store_prices.create(store_id: 2, price: 6.39)
shampoo.store_prices.create(store_id: 3, price: 6.69)
shampoo.store_prices.create(store_id: 4, price: 6.50)
shampoo.store_prices.create(store_id: 5, price: 7.80)
shampoo.store_prices.create(store_id: 6, price: 6.79)
conditioner = Item.create(category: Category.find_by(name: "Beauty"), name: "Aussie Shampoo - 29.2 Fl. Oz.", brand: "Aussie", description: "Quenches thirsty locks in a flash. Made with Australian aloe, jojoba oil and sea kelp, this moisturizing conditioner helps maximize hydration to soften your silky mane.", image_url: "https://shop.safeway.com/productimages/200x200/960056030_200x200.jpg", tags: "hair shampoo conditioner")
conditioner.store_prices.create(store_id: 1, price: 7.49)
conditioner.store_prices.create(store_id: 2, price: 6.29)
conditioner.store_prices.create(store_id: 3, price: 6.39)
conditioner.store_prices.create(store_id: 4, price: 6.10)
conditioner.store_prices.create(store_id: 5, price: 7.90)
conditioner.store_prices.create(store_id: 6, price: 5.89)
################## Category 9: Healthcare
day_night = Item.create(category: Category.find_by(name: "Healthcare"), name: "Vicks DayQuil NyQuil Cold & Flu Medicine Multi-Symptom Relief Night Relief LiquiCap - 48 Count", brand: "Vicks", description: "Uses: (DayQuil Cold & Flu): Temporarily relieves common cold/flu symptoms.", image_url: "https://shop.safeway.com/productimages/200x200/960081626_200x200.jpg", tags: "cold flu dayquil nyquil")
day_night.store_prices.create(store_id: 1, price: 21.49)
day_night.store_prices.create(store_id: 2, price: 20.29)
day_night.store_prices.create(store_id: 3, price: 20.39)
day_night.store_prices.create(store_id: 4, price: 19.10)
day_night.store_prices.create(store_id: 5, price: 22.90)
day_night.store_prices.create(store_id: 6, price: 20.89)
zicam = Item.create(category: Category.find_by(name: "Healthcare"), name: "Zicam Rapidmelts Cold Tablets Citrus - 25 Count", brand: "Zicam", description: "Shortens colds. The Pre-Cold Medicine: Take at the first sign of a cold.", image_url: "https://shop.safeway.com/productimages/200x200/158050398_200x200.jpg", tags: "cold flu zicam")
zicam.store_prices.create(store_id: 1, price: 11.49)
zicam.store_prices.create(store_id: 2, price: 10.29)
zicam.store_prices.create(store_id: 3, price: 10.39)
zicam.store_prices.create(store_id: 4, price: 10.10)
zicam.store_prices.create(store_id: 5, price: 12.90)
zicam.store_prices.create(store_id: 6, price: 10.89)
airborne = Item.create(category: Category.find_by(name: "Healthcare"), name: "Airborne Immune Support Supplement Effervescent Tablets Zesty Orange - 10 Count", brand: "Airborne", description: "Immune Support Supplement. Helps support your immune system. Blast of vitamin C. Plus 13 vitamins, minerals & herbs. ", image_url: "https://shop.safeway.com/productimages/100x100/179071531_100x100.jpg", tags: "cold flu airborne")
airborne.store_prices.create(store_id: 1, price: 11.49)
airborne.store_prices.create(store_id: 2, price: 10.29)
airborne.store_prices.create(store_id: 3, price: 9.39)
airborne.store_prices.create(store_id: 4, price: 10.10)
airborne.store_prices.create(store_id: 5, price: 11.90)
airborne.store_prices.create(store_id: 6, price: 9.89)
cough_drops = Item.create(category: Category.find_by(name: "Healthcare"), name: "Halls Cough Drops Mentho-Lyptus - 30 Drops", brand: "Halls", description: "Soothes sore throats. Relieves coughs. Cools nasal passages. Find your level of cool!", image_url: "https://shop.safeway.com/productimages/200x200/158500387_200x200.jpg", tags: "cold flu cough drops ")
cough_drops.store_prices.create(store_id: 1, price: 2.49)
cough_drops.store_prices.create(store_id: 2, price: 2.29)
cough_drops.store_prices.create(store_id: 3, price: 3.39)
cough_drops.store_prices.create(store_id: 4, price: 2.10)
cough_drops.store_prices.create(store_id: 5, price: 2.90)
cough_drops.store_prices.create(store_id: 6, price: 2.89)
band_aid = Item.create(category: Category.find_by(name: "Healthcare"), name: "Band-Aid Adhesive Bandages Flexible Fabric All One Size - 30 Count", brand: "Band-aid", description: "Soothes sore throats. Relieves coughs. Cools nasal passages. Find your level of cool!", image_url: "https://shop.safeway.com/productimages/200x200/262100034_200x200.jpg", tags: "band aid bandages adhesive")
band_aid.store_prices.create(store_id: 1, price: 4.49)
band_aid.store_prices.create(store_id: 2, price: 5.29)
band_aid.store_prices.create(store_id: 3, price: 4.39)
band_aid.store_prices.create(store_id: 4, price: 4.10)
band_aid.store_prices.create(store_id: 5, price: 6.90)
band_aid.store_prices.create(store_id: 6, price: 5.59)
caladryl = Item.create(category: Category.find_by(name: "Healthcare"), name: "Caladryl Skin Protectant Lotion Calamine Itch Reliever - 6 Fl. Oz.", brand: "Caladryl", description: "Temporarily relieves pain and itching associated with: rashes due to poison ivy, poison oak or poison sumac; insect bites; minor skin irritation; minor cuts.", image_url: "https://shop.safeway.com/productimages/200x200/960127427_200x200.jpg", tags: "caladryl poison ivy calamine itch reliever")
caladryl.store_prices.create(store_id: 1, price: 8.49)
caladryl.store_prices.create(store_id: 2, price: 9.29)
caladryl.store_prices.create(store_id: 3, price: 8.39)
caladryl.store_prices.create(store_id: 4, price: 8.10)
caladryl.store_prices.create(store_id: 5, price: 10.90)
caladryl.store_prices.create(store_id: 6, price: 7.59)
rubbing_alc = Item.create(category: Category.find_by(name: "Healthcare"), name: "Signature Care Isopropyl Rubbing Alcohol 70% - 32 Fl. Oz.", brand: "Band-aid", description: "Helps prevent the risk of infection in: minor cuts; scrapes; burns.", image_url: "https://shop.safeway.com/productimages/200x200/362010007_200x200.jpg", tags: "rubbing alcohol")
rubbing_alc.store_prices.create(store_id: 1, price: 2.49)
rubbing_alc.store_prices.create(store_id: 2, price: 2.29)
rubbing_alc.store_prices.create(store_id: 3, price: 3.39)
rubbing_alc.store_prices.create(store_id: 4, price: 3.10)
rubbing_alc.store_prices.create(store_id: 5, price: 3.90)
rubbing_alc.store_prices.create(store_id: 6, price: 3.99)
advil = Item.create(category: Category.find_by(name: "Healthcare"), name: "Advil Ibuprofen 200 mg Coated Caplets - 100 Count", brand: "Advil", description: "Temporarily relieves minor aches and pains due to: headache; toothache; backache; menstrual cramps; the common cold; muscular aches; minor pain of arthritis.", image_url: "https://shop.safeway.com/productimages/200x200/357100004_200x200.jpg", tags: "advil ibruprofin")
advil.store_prices.create(store_id: 1, price: 12.49)
advil.store_prices.create(store_id: 2, price: 12.29)
advil.store_prices.create(store_id: 3, price: 13.39)
advil.store_prices.create(store_id: 4, price: 12.10)
advil.store_prices.create(store_id: 5, price: 13.90)
advil.store_prices.create(store_id: 6, price: 13.49)
deo_men = Item.create(category: Category.find_by(name: "Healthcare"), name: "Degree For Men Dry Protection Anti-Perspirant Stick Cool Rush - 2-2.7 Oz", brand: "Degree", description: "Our unique body heat activated formula provides long lasting protection all day long.", image_url: "https://shop.safeway.com/productimages/200x200/151100075_200x200.jpg", tags: "men deodorant")
deo_men.store_prices.create(store_id: 1, price: 5.49)
deo_men.store_prices.create(store_id: 2, price: 5.29)
deo_men.store_prices.create(store_id: 3, price: 6.39)
deo_men.store_prices.create(store_id: 4, price: 5.10)
deo_men.store_prices.create(store_id: 5, price: 6.90)
deo_men.store_prices.create(store_id: 6, price: 6.79)
deo_women = Item.create(category: Category.find_by(name: "Healthcare"), name: "Secret Clear Gel Antiperspirant Deodorant Lavender - 2.6 Oz", brand: "Secret", description: "Antiperspirant/Deodorant, Clear Gel, Lavender", image_url: "https://shop.safeway.com/productimages/200x200/960024667_200x200.jpg", tags: "women deodorant")
deo_women.store_prices.create(store_id: 1, price: 5.39)
deo_women.store_prices.create(store_id: 2, price: 5.19)
deo_women.store_prices.create(store_id: 3, price: 4.29)
deo_women.store_prices.create(store_id: 4, price: 5.60)
deo_women.store_prices.create(store_id: 5, price: 5.30)
deo_women.store_prices.create(store_id: 6, price: 4.79)
centrum = Item.create(category: Category.find_by(name: "Healthcare"), name: "Centrum Multivitamin Multimineral Supplement Silver Adults Tablets - 125 Count", brand: "Pfizer", description: "Multivitamin/Multimineral, Adults 50+, Tablets", image_url: "https://shop.safeway.com/productimages/200x200/960057643_200x200.jpg", tags: "vitamin")
centrum.store_prices.create(store_id: 1, price: 9.39)
centrum.store_prices.create(store_id: 2, price: 9.19)
centrum.store_prices.create(store_id: 3, price: 8.29)
centrum.store_prices.create(store_id: 4, price: 7.60)
centrum.store_prices.create(store_id: 5, price: 8.30)
centrum.store_prices.create(store_id: 6, price: 9.79)
vit_gummies = Item.create(category: Category.find_by(name: "Healthcare"), name: "Flintstones Childrens Multivitamin Gummies - 60 Count", brand: "Bayer", description: "Multivitamin, Children's, Complete, Gummies", image_url: "https://shop.safeway.com/productimages/200x200/960085341_200x200.jpg", tags: "vitamin")
vit_gummies.store_prices.create(store_id: 1, price: 13.09)
vit_gummies.store_prices.create(store_id: 2, price: 13.39)
vit_gummies.store_prices.create(store_id: 3, price: 13.99)
vit_gummies.store_prices.create(store_id: 4, price: 12.30)
vit_gummies.store_prices.create(store_id: 5, price: 13.20)
vit_gummies.store_prices.create(store_id: 6, price: 13.19)
################# Category 10: Home
air_freshener = Item.create(category: Category.find_by(name: "Home"), name: "Febreze AIR Air Refresher Bora Bora Waters - 8.8 Oz", brand: "Febreeze", description: "Eliminates tough lingering odors. 100\% natural propellant. With odor clear.", image_url: "https://shop.safeway.com/productimages/200x200/960277396_200x200.jpg", tags: "air freshener febreeze febreze")
air_freshener.store_prices.create(store_id: 1, price: 3.09)
air_freshener.store_prices.create(store_id: 2, price: 3.39)
air_freshener.store_prices.create(store_id: 3, price: 3.99)
air_freshener.store_prices.create(store_id: 4, price: 2.30)
air_freshener.store_prices.create(store_id: 5, price: 3.20)
air_freshener.store_prices.create(store_id: 6, price: 3.19)
candle = Item.create(category: Category.find_by(name: "Home"), name: "Todays Home Candle Cucumber Watermelon - 11 Oz", brand: "Today's Home", description: "Candle, Cucumber Watermelon Scented", image_url: "https://shop.safeway.com/productimages/200x200/960048041_200x200.jpg", tags: "candle scented")
candle.store_prices.create(store_id: 1, price: 6.09)
candle.store_prices.create(store_id: 2, price: 6.39)
candle.store_prices.create(store_id: 3, price: 5.99)
candle.store_prices.create(store_id: 4, price: 6.30)
candle.store_prices.create(store_id: 5, price: 6.20)
candle.store_prices.create(store_id: 6, price: 6.79)
clorox_wipes = Item.create(category: Category.find_by(name: "Home"), name: "Clorox Disinfecting Wipes Fresh Scent Value Size - 75 Count", brand: "Clorox", description: "Kills 99.9\% of bacteria, Kills cold & flu viruses.", image_url: "https://shop.safeway.com/productimages/200x200/173100116_200x200.jpg", tags: "clorox wipes")
clorox_wipes.store_prices.create(store_id: 1, price: 5.19)
clorox_wipes.store_prices.create(store_id: 2, price: 4.59)
clorox_wipes.store_prices.create(store_id: 3, price: 4.89)
clorox_wipes.store_prices.create(store_id: 4, price: 5.30)
clorox_wipes.store_prices.create(store_id: 5, price: 4.10)
clorox_wipes.store_prices.create(store_id: 6, price: 4.99)
meyers_cleaner = Item.create(category: Category.find_by(name: "Home"), name: "Mrs Meyers Clean Day Multi-Surface Everyday Cleaner Lavender - 16 Fl. Oz", brand: "Meyer's", description: "Hardworking homekeeping. Aromatherapeutic household products.", image_url: "https://shop.safeway.com/productimages/200x200/960113117_200x200.jpg", tags: "meyers cleaner lavender")
meyers_cleaner.store_prices.create(store_id: 1, price: 5.19)
meyers_cleaner.store_prices.create(store_id: 2, price: 6.59)
meyers_cleaner.store_prices.create(store_id: 3, price: 4.89)
meyers_cleaner.store_prices.create(store_id: 4, price: 5.30)
meyers_cleaner.store_prices.create(store_id: 5, price: 7.10)
meyers_cleaner.store_prices.create(store_id: 6, price: 6.99)
windex = Item.create(category: Category.find_by(name: "Home"), name: "Windex Glass & More Cleaner Original With Ammonia-D - 23 Oz", brand: "<NAME>", description: "Streak-free shine! America's No. 1 selling glass cleaner.", image_url: "https://shop.safeway.com/productimages/200x200/960234257_200x200.jpg", tags: "windex window cleaner spray")
windex.store_prices.create(store_id: 1, price: 3.99)
windex.store_prices.create(store_id: 2, price: 3.19)
windex.store_prices.create(store_id: 3, price: 3.29)
windex.store_prices.create(store_id: 4, price: 3.80)
windex.store_prices.create(store_id: 5, price: 4.20)
windex.store_prices.create(store_id: 6, price: 3.99)
swiffer = Item.create(category: Category.find_by(name: "Home"), name: "Swiffer Sweeping Kit Dry + Wet - Each", brand: "P & G", description: "Great for tight corners, under furniture & behind bathroom fixtures. Gentle for virtually all finished floor types.", image_url: "https://shop.safeway.com/productimages/200x200/960138884_200x200.jpg", tags: "swiffer sweeper wet dry floor cleaner")
swiffer.store_prices.create(store_id: 1, price: 8.99)
swiffer.store_prices.create(store_id: 2, price: 9.19)
swiffer.store_prices.create(store_id: 3, price: 10.29)
swiffer.store_prices.create(store_id: 4, price: 11.80)
swiffer.store_prices.create(store_id: 5, price: 12.20)
swiffer.store_prices.create(store_id: 6, price: 11.99)
dawn = Item.create(category: Category.find_by(name: "Home"), name: "Dawn Ultra Dishwashing Liquid Antibacterial Orange Scent - 75 Fl. Oz.", brand: "P & G", description: "Cleans up to 2X. More greasy dishes.", image_url: "https://shop.safeway.com/productimages/200x200/960129686_200x200.jpg", tags: "dawn diswashing liquid")
dawn.store_prices.create(store_id: 1, price: 8.99)
dawn.store_prices.create(store_id: 2, price: 9.19)
dawn.store_prices.create(store_id: 3, price: 10.29)
dawn.store_prices.create(store_id: 4, price: 11.80)
dawn.store_prices.create(store_id: 5, price: 12.20)
dawn.store_prices.create(store_id: 6, price: 11.99)
cascade = Item.create(category: Category.find_by(name: "Home"), name: "Cascade Dishwasher Detergent Action Pacs Lemon Scent - 32 Count", brand: "P & G", description: "Tougher than greasy messes. Dawn grease fighting power.", image_url: "https://shop.safeway.com/productimages/200x200/960277401_200x200.jpg", tags: "cascade dishwasher tabs action pacs detergent")
cascade.store_prices.create(store_id: 1, price: 8.99)
cascade.store_prices.create(store_id: 2, price: 9.19)
cascade.store_prices.create(store_id: 3, price: 10.29)
cascade.store_prices.create(store_id: 4, price: 11.80)
cascade.store_prices.create(store_id: 5, price: 12.20)
cascade.store_prices.create(store_id: 6, price: 11.99)
duracell = Item.create(category: Category.find_by(name: "Home"), name: "Duracell Coppertop Battery Alkaline Duralock AA - 8 Count", brand: "Duracell / P & G", description: "For everyday devices. When it matters most.", image_url: "https://shop.safeway.com/productimages/200x200/168010370_200x200.jpg", tags: "batteries duracell AA")
duracell.store_prices.create(store_id: 1, price: 8.99)
duracell.store_prices.create(store_id: 2, price: 7.19)
duracell.store_prices.create(store_id: 3, price: 7.29)
duracell.store_prices.create(store_id: 4, price: 6.80)
duracell.store_prices.create(store_id: 5, price: 8.20)
duracell.store_prices.create(store_id: 6, price: 7.99)
bulbs = Item.create(category: Category.find_by(name: "Home"), name: "GE Halogen Aline Bulb Soft White 72 Watt - 4 Count", brand: "General Electric", description: "GE's Best Incandescent Soft White line provides the light qualities you love, but uses less energy.", image_url: "https://shop.safeway.com/productimages/200x200/960178742_200x200.jpg", tags: "light bulbs 72 watts")
bulbs.store_prices.create(store_id: 1, price: 8.99)
bulbs.store_prices.create(store_id: 2, price: 7.19)
bulbs.store_prices.create(store_id: 3, price: 7.29)
bulbs.store_prices.create(store_id: 4, price: 6.80)
bulbs.store_prices.create(store_id: 5, price: 8.20)
bulbs.store_prices.create(store_id: 6, price: 7.99)
kleenex = Item.create(category: Category.find_by(name: "Home"), name: "Kleenex Facial Tissue Lotion Bundle - 4-120 Count", brand: "Kleenex", description: "Soothing & absorbent. 50% more tissue per box.", image_url: "https://shop.safeway.com/productimages/200x200/960238031_200x200.jpg", tags: "tissues kleenex facial tissue")
kleenex.store_prices.create(store_id: 1, price: 8.39)
kleenex.store_prices.create(store_id: 2, price: 8.19)
kleenex.store_prices.create(store_id: 3, price: 8.29)
kleenex.store_prices.create(store_id: 4, price: 8.80)
kleenex.store_prices.create(store_id: 5, price: 9.59)
kleenex.store_prices.create(store_id: 6, price: 8.99)
paper_towels = Item.create(category: Category.find_by(name: "Home"), name: "Bounty Paper Towels Big Rolls Full Sheet - 12 Roll", brand: "Bounty", description: "2x more absorbent. The quicker picker upper.", image_url: "https://shop.safeway.com/productimages/200x200/960280201_200x200.jpg", tags: "bounty paper towels")
paper_towels.store_prices.create(store_id: 1, price: 8.39)
paper_towels.store_prices.create(store_id: 2, price: 8.19)
paper_towels.store_prices.create(store_id: 3, price: 8.29)
paper_towels.store_prices.create(store_id: 4, price: 8.80)
paper_towels.store_prices.create(store_id: 5, price: 9.59)
paper_towels.store_prices.create(store_id: 6, price: 8.99)
alum_foil = Item.create(category: Category.find_by(name: "Home"), name: "Reynolds Wrap Aluminum Foil - 200 Sq. Ft.", brand: "Reynolds", description: "Trusted since 1947. Now! Less packaging same length.", image_url: "https://shop.safeway.com/productimages/200x200/130050222_200x200.jpg", tags: "tin foil aluminum foil")
alum_foil.store_prices.create(store_id: 1, price: 11.39)
alum_foil.store_prices.create(store_id: 2, price: 11.19)
alum_foil.store_prices.create(store_id: 3, price: 12.29)
alum_foil.store_prices.create(store_id: 4, price: 10.80)
alum_foil.store_prices.create(store_id: 5, price: 12.59)
alum_foil.store_prices.create(store_id: 6, price: 10.19)
ziploc = Item.create(category: Category.find_by(name: "Home"), name: "Ziploc Bags Freezer Quart Double Zipper Value Pack - 38 Count", brand: "SC Johnson", description: "Smart Zip Plus Seal: Feel it, hear it, see it!", image_url: "https://shop.safeway.com/productimages/200x200/130050045_200x200.jpg", tags: "freezer bags, ziploc")
ziploc.store_prices.create(store_id: 1, price: 5.19)
ziploc.store_prices.create(store_id: 2, price: 5.89)
ziploc.store_prices.create(store_id: 3, price: 4.69)
ziploc.store_prices.create(store_id: 4, price: 5.20)
ziploc.store_prices.create(store_id: 5, price: 7.29)
ziploc.store_prices.create(store_id: 6, price: 6.19)
glad = Item.create(category: Category.find_by(name: "Home"), name: "Glad Trash Bags Tall Kitchen Drawstring Tall White 13 Gallon - 90 Count", brand: "Glad Products", description: "Stronger with less plastic. With reinforcing bands. Glad trash bags are stronger - with less plastic!", image_url: "https://shop.safeway.com/productimages/200x200/960084284_200x200.jpg", tags: "kitchen bags garbage bags")
glad.store_prices.create(store_id: 1, price: 17.29)
glad.store_prices.create(store_id: 2, price: 19.39)
glad.store_prices.create(store_id: 3, price: 17.99)
glad.store_prices.create(store_id: 4, price: 18.60)
glad.store_prices.create(store_id: 5, price: 20.19)
glad.store_prices.create(store_id: 6, price: 19.09)
################## Category 11: Baby
baby_sham = Item.create(category: Category.find_by(name: "Baby"), name: "Johnsons Baby Shampoo - 20 Fl. Oz.", brand: "Johnson & Johnson", description: "No More Tears. Improved formula. As gentle to eyes as pure water.", image_url: "https://shop.safeway.com/productimages/200x200/165400103_200x200.jpg", tags: "baby shampoo johnson's")
baby_sham.store_prices.create(store_id: 1, price: 7.29)
baby_sham.store_prices.create(store_id: 2, price: 9.39)
baby_sham.store_prices.create(store_id: 3, price: 7.99)
baby_sham.store_prices.create(store_id: 4, price: 8.60)
baby_sham.store_prices.create(store_id: 5, price: 9.19)
baby_sham.store_prices.create(store_id: 6, price: 9.09)
baby_lotion = Item.create(category: Category.find_by(name: "Baby"), name: "Aveeno Baby Lotion Daily Moisture Fragrance Free - 8 Oz", brand: "Johnson & Johnson", description: "Protects delicate skin. Moisturizes for 24 hours. Pediatrician recommended.", image_url: "https://shop.safeway.com/productimages/200x200/165400247_200x200.jpg", tags: "lotion baby moisture")
baby_lotion.store_prices.create(store_id: 1, price: 7.19)
baby_lotion.store_prices.create(store_id: 2, price: 8.49)
baby_lotion.store_prices.create(store_id: 3, price: 7.69)
baby_lotion.store_prices.create(store_id: 4, price: 8.20)
baby_lotion.store_prices.create(store_id: 5, price: 9.99)
baby_lotion.store_prices.create(store_id: 6, price: 7.89)
baby_powd = Item.create(category: Category.find_by(name: "Baby"), name: "Johnsons Baby Powder - 15 Oz", brand: "Johnson & Johnson", description: "Clinically proven mildness. Silky soft skin. We love babies.", image_url: "https://shop.safeway.com/productimages/200x200/165400085_200x200.jpg", tags: "powder baby")
baby_powd.store_prices.create(store_id: 1, price: 6.99)
baby_powd.store_prices.create(store_id: 2, price: 6.19)
baby_powd.store_prices.create(store_id: 3, price: 6.29)
baby_powd.store_prices.create(store_id: 4, price: 6.89)
baby_powd.store_prices.create(store_id: 5, price: 6.39)
baby_powd.store_prices.create(store_id: 6, price: 5.89)
baby_oint = Item.create(category: Category.find_by(name: "Baby"), name: "Aquaphor Healing Baby Ointment Jar - 14 Oz", brand: "<NAME>", description: "For dry, chapped or irritated skin. Relieves diaper rash within 6 hours.", image_url: "https://shop.safeway.com/productimages/200x200/960079240_200x200.jpg", tags: "baby ointment ")
baby_oint.store_prices.create(store_id: 1, price: 15.99)
baby_oint.store_prices.create(store_id: 2, price: 14.19)
baby_oint.store_prices.create(store_id: 3, price: 14.89)
baby_oint.store_prices.create(store_id: 4, price: 14.39)
baby_oint.store_prices.create(store_id: 5, price: 16.29)
baby_oint.store_prices.create(store_id: 6, price: 14.99)
diapers = Item.create(category: Category.find_by(name: "Baby"), name: "Huggies Little Movers Diapers Size 3 Jumbo Pack - 28 Count", brand: "Kimberly Clark Co.", description: "New! Dry touch absorbs on contact. Double grip strips. Leak Lock: Up to 12 hour protection.", image_url: "https://shop.safeway.com/productimages/200x200/960106632_200x200.jpg", tags: "baby diapers ")
diapers.store_prices.create(store_id: 1, price: 9.99)
diapers.store_prices.create(store_id: 2, price: 10.19)
diapers.store_prices.create(store_id: 3, price: 9.89)
diapers.store_prices.create(store_id: 4, price: 8.39)
diapers.store_prices.create(store_id: 5, price: 9.29)
diapers.store_prices.create(store_id: 6, price: 9.99)
baby_wipes = Item.create(category: Category.find_by(name: "Baby"), name: "BabyGanics Baby Wipes - 100 Count", brand: "Kimberly Clark Co.", description: "Extra gentle. Plant-based ingredients. Non-allergenic. Pediatrician & dermatologist tested.", image_url: "https://shop.safeway.com/productimages/200x200/960133947_200x200.jpg", tags: "baby wipes")
baby_wipes.store_prices.create(store_id: 1, price: 5.89)
baby_wipes.store_prices.create(store_id: 2, price: 5.29)
baby_wipes.store_prices.create(store_id: 3, price: 5.79)
baby_wipes.store_prices.create(store_id: 4, price: 4.49)
baby_wipes.store_prices.create(store_id: 5, price: 6.99)
baby_wipes.store_prices.create(store_id: 6, price: 5.09)
baby_puffs = Item.create(category: Category.find_by(name: "Baby"), name: "Gerber Graduates Puffs Vanilla - 1.48 Oz", brand: "Gerber", description: "Cereal snack. Naturally flavored with other natural flavors. Made with whole grains.", image_url: "https://shop.safeway.com/productimages/200x200/960070938_200x200.jpg", tags: "baby food puffs")
baby_puffs.store_prices.create(store_id: 1, price: 1.89)
baby_puffs.store_prices.create(store_id: 2, price: 1.29)
baby_puffs.store_prices.create(store_id: 3, price: 1.79)
baby_puffs.store_prices.create(store_id: 4, price: 2.49)
baby_puffs.store_prices.create(store_id: 5, price: 2.99)
baby_puffs.store_prices.create(store_id: 6, price: 1.99)
baby_food = Item.create(category: Category.find_by(name: "Baby"), name: "Gerber 3rd Foods Lil Bits Carrot Corn Butternut Squash - 2-5 Oz", brand: "Gerber", description: "Mixed carrots, corn & butternut square with Lil' Bits.", image_url: "https://shop.safeway.com/productimages/200x200/960132791_200x200.jpg", tags: "baby food")
baby_food.store_prices.create(store_id: 1, price: 1.89)
baby_food.store_prices.create(store_id: 2, price: 1.29)
baby_food.store_prices.create(store_id: 3, price: 2.79)
baby_food.store_prices.create(store_id: 4, price: 2.49)
baby_food.store_prices.create(store_id: 5, price: 2.99)
baby_food.store_prices.create(store_id: 6, price: 2.00)
pacifier = Item.create(category: Category.find_by(name: "Baby"), name: "Avent Pacifier Orthodontic Silicone Air Flow 6-18 Months - 2 Count", brand: "Philips", description: "Ideal for sensitive skin. Designed to comfort your baby.", image_url: "https://shop.safeway.com/productimages/200x200/960079070_200x200.jpg", tags: "baby pacifier")
pacifier.store_prices.create(store_id: 1, price: 7.99)
pacifier.store_prices.create(store_id: 2, price: 7.29)
pacifier.store_prices.create(store_id: 3, price: 7.19)
pacifier.store_prices.create(store_id: 4, price: 7.39)
pacifier.store_prices.create(store_id: 5, price: 7.69)
pacifier.store_prices.create(store_id: 6, price: 7.89)
teether = Item.create(category: Category.find_by(name: "Baby"), name: "MAM Teether Bite & Brush 3 Months Plus - Each", brand: "MAM", description: "Teether with very soft bristles. For cleaning. BPA free. Baby safe.", image_url: "https://shop.safeway.com/productimages/200x200/960056396_200x200.jpg", tags: "baby teething teether")
teether.store_prices.create(store_id: 1, price: 7.19)
teether.store_prices.create(store_id: 2, price: 7.89)
teether.store_prices.create(store_id: 3, price: 7.29)
teether.store_prices.create(store_id: 4, price: 7.99)
teether.store_prices.create(store_id: 5, price: 8.69)
teether.store_prices.create(store_id: 6, price: 7.89)
#################### Category 12: Pets
### cats ###
wet_catfood = Item.create(category: Category.find_by(name: "Pets"), name: "Fancy Feast Cat Food Gourmet Classic Ocean Whitefish & Tuna Feast - 3 Oz", brand: "Nestle", description: "Gourment cat food.", image_url: "https://shop.safeway.com/productimages/200x200/132060045_200x200.jpg", tags: "cat food gourmet")
wet_catfood.store_prices.create(store_id: 1, price: 0.89)
wet_catfood.store_prices.create(store_id: 2, price: 1.19)
wet_catfood.store_prices.create(store_id: 3, price: 0.99)
wet_catfood.store_prices.create(store_id: 4, price: 0.99)
wet_catfood.store_prices.create(store_id: 5, price: 1.69)
wet_catfood.store_prices.create(store_id: 6, price: 0.95)
wetfood2 = Item.create(category: Category.find_by(name: "Pets"), name: "Friskies Flaked Cat Food With Tuna - 5.5 Oz", brand: "Nestle", description: "100\% complete & balanced nutrition for adult cats & kittens.", image_url: "https://shop.safeway.com/productimages/200x200/960162275_200x200.jpg", tags: "cat food ")
wetfood2.store_prices.create(store_id: 1, price: 0.69)
wetfood2.store_prices.create(store_id: 2, price: 1.09)
wetfood2.store_prices.create(store_id: 3, price: 0.89)
wetfood2.store_prices.create(store_id: 4, price: 0.99)
wetfood2.store_prices.create(store_id: 5, price: 0.79)
wetfood2.store_prices.create(store_id: 6, price: 0.45)
dry_cat_food = Item.create(category: Category.find_by(name: "Pets"), name: "Meow Mix Cat Food Dry Original Choice - 16 Lb", brand: "Meow Mix", description: "The delicious flavors of: chicken, salmon, turkey, ocean fish.", image_url: "https://shop.safeway.com/productimages/200x200/960028148_200x200.jpg", tags: "dry cat food ")
dry_cat_food.store_prices.create(store_id: 1, price: 9.29)
dry_cat_food.store_prices.create(store_id: 2, price: 10.19)
dry_cat_food.store_prices.create(store_id: 3, price: 8.59)
dry_cat_food.store_prices.create(store_id: 4, price: 7.79)
dry_cat_food.store_prices.create(store_id: 5, price: 7.69)
dry_cat_food.store_prices.create(store_id: 6, price: 7.59)
cat_treats = Item.create(category: Category.find_by(name: "Pets"), name: "Whiskas Temptations Treats for Cats Seafood Medley Flavor - 2.1 Oz", brand: "Temptations", description: "Crunchy outside. Soft inside. Under 2 calories per treat. Stay fresh pouch!", image_url: "https://shop.safeway.com/productimages/200x200/132090132_200x200.jpg", tags: "cat treats ")
cat_treats.store_prices.create(store_id: 1, price: 6.29)
cat_treats.store_prices.create(store_id: 2, price: 5.19)
cat_treats.store_prices.create(store_id: 3, price: 5.59)
cat_treats.store_prices.create(store_id: 4, price: 5.79)
cat_treats.store_prices.create(store_id: 5, price: 6.69)
cat_treats.store_prices.create(store_id: 6, price: 5.59)
cat_toy = Item.create(category: Category.find_by(name: "Pets"), name: "Hartz Mini Mice Cat Toy - 5 Count", brand: "Hartz", description: "Hunt play pattern. Every toy fills a need.", image_url: "https://shop.safeway.com/productimages/200x200/960144568_200x200.jpg", tags: "cat toy mice ")
cat_toy.store_prices.create(store_id: 1, price: 3.29)
cat_toy.store_prices.create(store_id: 2, price: 4.19)
cat_toy.store_prices.create(store_id: 3, price: 5.59)
cat_toy.store_prices.create(store_id: 4, price: 4.79)
cat_toy.store_prices.create(store_id: 5, price: 3.69)
cat_toy.store_prices.create(store_id: 6, price: 4.59)
### dogs ####
dog_food = Item.create(category: Category.find_by(name: "Pets"), name: "Beneful Dog Food Healthy Radiance - 15.5 Lb", brand: "Beneful", description: "100\% Complete & balanced nutrition. With real chicken, wholesome rice and the added goodness of real milk, accented with vitamin-rich vegetables, with moist and chewy chunks.", image_url: "https://dickeybub.net/wp-content/uploads/2013/12/017800134606.jpg", tags: "dog food dry")
dog_food.store_prices.create(store_id: 1, price: 12.29)
dog_food.store_prices.create(store_id: 2, price: 12.19)
dog_food.store_prices.create(store_id: 3, price: 11.59)
dog_food.store_prices.create(store_id: 4, price: 12.79)
dog_food.store_prices.create(store_id: 5, price: 15.69)
dog_food.store_prices.create(store_id: 6, price: 13.59)
dog_treats = Item.create(category: Category.find_by(name: "Pets"), name: "Beggin Strips Dog Snack Bacon Flavor - 6 Oz", brand: "Beggin Strips", description: "100\% Complete & balanced nutrition. With real chicken, wholesome rice and the added goodness of real milk, accented with vitamin-rich vegetables, with moist and chewy chunks.", image_url: "https://shop.safeway.com/productimages/200x200/960135765_200x200.jpg", tags: "dog food treats")
dog_treats.store_prices.create(store_id: 1, price: 8.29)
dog_treats.store_prices.create(store_id: 2, price: 8.19)
dog_treats.store_prices.create(store_id: 3, price: 7.59)
dog_treats.store_prices.create(store_id: 4, price: 8.79)
dog_treats.store_prices.create(store_id: 5, price: 9.69)
dog_treats.store_prices.create(store_id: 6, price: 7.49)
dog_bones = Item.create(category: Category.find_by(name: "Pets"), name: "Sergeants Puppy Teething Bones - 3 Count", brand: "Sergeant's", description: "High in protein. Caring for pets since 1868. Satisfies a puppy's need to chew. Great tasting. Easy grip shape.", image_url: "https://shop.safeway.com/productimages/200x200/960040491_200x200.jpg", tags: "dog food treats teething bone")
dog_bones.store_prices.create(store_id: 1, price: 6.29)
dog_bones.store_prices.create(store_id: 2, price: 7.19)
dog_bones.store_prices.create(store_id: 3, price: 8.29)
dog_bones.store_prices.create(store_id: 4, price: 7.19)
dog_bones.store_prices.create(store_id: 5, price: 9.69)
dog_bones.store_prices.create(store_id: 6, price: 7.89)
################# Category 13: Office Supplies
highlighter = Item.create(category: Category.find_by(name: "Office Supplies"), name: "Avery Hi Lighter Astd Colors - 4 Count", brand: "<NAME>", description: "The Original highlighter, since 1962. Durable tip for smooth highlighting - won't fray.", image_url: "https://shop.safeway.com/productimages/200x200/960182900_200x200.jpg", tags: "hilighter highlighter")
highlighter.store_prices.create(store_id: 1, price: 2.29)
highlighter.store_prices.create(store_id: 2, price: 1.19)
highlighter.store_prices.create(store_id: 3, price: 2.29)
highlighter.store_prices.create(store_id: 4, price: 2.19)
highlighter.store_prices.create(store_id: 5, price: 3.69)
highlighter.store_prices.create(store_id: 6, price: 2.79)
pens = Item.create(category: Category.find_by(name: "Office Supplies"), name: "Bic Ball Pens - 10 Count", brand: "Bic", description: "Featuring Easy-Glide System ink for ultra-smooth writing. Fight for your write.", image_url: "https://shop.safeway.com/productimages/200x200/960125351_200x200.jpg", tags: "pens ballpoint bic")
pens.store_prices.create(store_id: 1, price: 1.29)
pens.store_prices.create(store_id: 2, price: 1.89)
pens.store_prices.create(store_id: 3, price: 2.49)
pens.store_prices.create(store_id: 4, price: 1.69)
pens.store_prices.create(store_id: 5, price: 3.69)
pens.store_prices.create(store_id: 6, price: 2.79)
colored_pencils = Item.create(category: Category.find_by(name: "Office Supplies"), name: "Crayola Colored Pencils Sharpened- 24 Count", brand: "Crayola", description: "Long-lasting. Premium quality. Nontoxic. Bright, bold colors. Preferred by teachers!", image_url: "https://shop.safeway.com/productimages/200x200/960125429_200x200.jpg", tags: "colored pencils crayola")
colored_pencils.store_prices.create(store_id: 1, price: 7.29)
colored_pencils.store_prices.create(store_id: 2, price: 6.19)
colored_pencils.store_prices.create(store_id: 3, price: 7.49)
colored_pencils.store_prices.create(store_id: 4, price: 7.69)
colored_pencils.store_prices.create(store_id: 5, price: 9.69)
colored_pencils.store_prices.create(store_id: 6, price: 6.89)
post_it = Item.create(category: Category.find_by(name: "Office Supplies"), name: "Post-it Pop Up Notes - 5Count", brand: "3M", description: "For pop-up note dispensers! New colors.", image_url: "https://shop.safeway.com/productimages/200x200/960124775_200x200.jpg", tags: "post-it notes")
post_it.store_prices.create(store_id: 1, price: 8.29)
post_it.store_prices.create(store_id: 2, price: 9.19)
post_it.store_prices.create(store_id: 3, price: 8.49)
post_it.store_prices.create(store_id: 4, price: 9.69)
post_it.store_prices.create(store_id: 5, price: 11.69)
post_it.store_prices.create(store_id: 6, price: 10.89)
scotch = Item.create(category: Category.find_by(name: "Office Supplies"), name: "Post-it Pop Up Notes - 5Count", brand: "3M", description: "Scotch Magic Tape is the original matte-finish invisible tape.", image_url: "https://shop.safeway.com/productimages/200x200/960125221_200x200.jpg", tags: "scotch tape")
scotch.store_prices.create(store_id: 1, price: 5.19)
scotch.store_prices.create(store_id: 2, price: 5.29)
scotch.store_prices.create(store_id: 3, price: 5.49)
scotch.store_prices.create(store_id: 4, price: 5.89)
scotch.store_prices.create(store_id: 5, price: 6.99)
scotch.store_prices.create(store_id: 6, price: 5.59)
sharpie = Item.create(category: Category.find_by(name: "Office Supplies"), name: "Sharpie Assorted - 4 Count", brand: "Newell", description: "Great for plastic, glass and wood. Bold and vivid colors. Marks on most surfaces.", image_url: "https://shop.safeway.com/productimages/200x200/960132681_200x200.jpg", tags: "sharpie pens")
sharpie.store_prices.create(store_id: 1, price: 3.19)
sharpie.store_prices.create(store_id: 2, price: 3.29)
sharpie.store_prices.create(store_id: 3, price: 3.49)
sharpie.store_prices.create(store_id: 4, price: 2.89)
sharpie.store_prices.create(store_id: 5, price: 4.99)
sharpie.store_prices.create(store_id: 6, price: 3.16)
printer_paper = Item.create(category: Category.find_by(name: "Office Supplies"), name: "Signature Home Copy Printer Paper - 500 Each", brand: "Better Living", description: "Quality guaranteed. Sustainable Forestry Initiative: Certified sourcing.", image_url: "https://shop.safeway.com/productimages/200x200/960197573_200x200.jpg", tags: "printer paper white")
printer_paper.store_prices.create(store_id: 1, price: 5.19)
printer_paper.store_prices.create(store_id: 2, price: 6.29)
printer_paper.store_prices.create(store_id: 3, price: 5.49)
printer_paper.store_prices.create(store_id: 4, price: 6.89)
printer_paper.store_prices.create(store_id: 6, price: 5.59)
################# Category 14: Electronics
iphone_charger = Item.create(category: Category.find_by(name: "Electronics"), name: "Apple® Lightning to USB Cable (1 m)", brand: "Apple", description: "This USB 2.0 cable connects your iPhone or iPod with Lightning connector to your computer's USB port for syncing and charging or to the Apple USB Power Adapter for convenient charging from a wall outlet.", image_url: "https://target.scene7.com/is/image/Target/14213687?wid=520&hei=520&fmt=pjpeg", tags: "apple iphone charger")
iphone_charger.store_prices.create(store_id: 3, price: 18.99)
iphone_charger.store_prices.create(store_id: 4, price: 19.90)
fitbit = Item.create(category: Category.find_by(name: "Electronics"), name: "Fitbit® Flex 2 Fitness Wristband", brand: "Fitbit", description: "There’s a fit for every you with Fitbit Flex 2—a slim, swim-proof fitness wristband that lets you track every day in a style that’s all your own.", image_url: "https://target.scene7.com/is/image/Target/51576199?wid=520&hei=520&fmt=pjpeg", tags: "fitbit fitness tracker")
fitbit.store_prices.create(store_id: 3, price: 56.99)
fitbit.store_prices.create(store_id: 4, price: 59.99)
headphones = Item.create(category: Category.find_by(name: "Electronics"), name: "In-Ear Headphones with Mic", brand: "Bower", description: "Enhance your listening with clear audio, easy connectivity and stylish colors.", image_url: "https://target.scene7.com/is/image/Target/52367446?wid=520&hei=520&fmt=pjpeg", tags: "headphones earpods mic")
headphones.store_prices.create(store_id: 1, price: 23.89)
headphones.store_prices.create(store_id: 2, price: 23.19)
headphones.store_prices.create(store_id: 3, price: 22.99)
headphones.store_prices.create(store_id: 4, price: 23.99)
am_fire = Item.create(category: Category.find_by(name: "Electronics"), name: "Amazon Fire HD 10 Tablet", brand: "Amazon", description: "The all-new Fire HD 10 features our largest display, now in 1080p Full HD, 32 GB storage, 2 GB RAM, and up to 10 hours of battery.", image_url: "https://target.scene7.com/is/image/Target/52990409?wid=520&hei=520&fmt=pjpeg", tags: "amazon fire tablet")
am_fire.store_prices.create(store_id: 3, price: 149.99)
am_fire.store_prices.create(store_id: 4, price: 149.99)
shuffle = Item.create(category: Category.find_by(name: "Electronics"), name: "Apple® iPod Shuffle 2GB", brand: "Apple", description: "iPod shuffle comes in 5 stunning colors.", image_url: "https://target.scene7.com/is/image/Target/15117717?wid=520&hei=520&fmt=pjpeg", tags: "apple shuffle ipod")
shuffle.store_prices.create(store_id: 3, price: 49.99)
shuffle.store_prices.create(store_id: 4, price: 49.99)
alarm_clock = Item.create(category: Category.find_by(name: "Electronics"), name: "Sharp LED Night Light Alarm Clock", brand: "Sharp", description: "Wake up on time every day with this alarm clock from Sharp.", image_url: "https://target.scene7.com/is/image/Target/14193190?wid=520&hei=520&fmt=pjpeg", tags: "sharp alarm clock")
alarm_clock.store_prices.create(store_id: 1, price: 15.89)
alarm_clock.store_prices.create(store_id: 2, price: 15.79)
alarm_clock.store_prices.create(store_id: 3, price: 16.99)
alarm_clock.store_prices.create(store_id: 4, price: 15.19)
| ec57e61e152caa22529a923b912ab355b62a8727 | [
"JavaScript",
"Ruby",
"Markdown"
] | 47 | JavaScript | lskeilty/OneStopShop | dd4a3d573f658ded34548ea478c86c0a99f96b05 | 436d788e507069fbfcf7aa96493d77356471e2f8 |
refs/heads/master | <file_sep># define ESC 53
# define SPACE 49
# define PLUS 69
# define MINUS 78<file_sep>OS=$(exec uname)
NAME = fractol
CC = gcc
FLAGS = -Wall -Wextra -Werror -g
INCLUDES = -I./libft
LIBS = -lft -lm
LIB_DIR = -L./libft
SRCS = main.c sub.c control.c
#ifeq "$OS" "Linux"
MINILIBX = -L./minilibxX11/ -I./minilibxX11/ -lmlx -lXext -lX11
#else
# MINILIBX = -L/usr/local/lib/ -I/usr/local/include -framework OpenGL -framework AppKit -lmlx
#endif
all: $(NAME)
$(NAME): $(SRCS:.c=.o)
make -C libft/
$(CC) -I./minilibxX11/mlx.h $(FLAGS) $(SRCS:.c=.o) $(LIB_DIR) $(INCLUDES) $(MINILIBX) $(LIBS) -o $(NAME)
%.o : %.c
$(CC) -c $(FLAGS) $< $(INCLUDES) -o $@
libft.a :
make -C libft/
clean:
make -C libft clean
/bin/rm -f $(SRCS:.c=.o)
fclean: clean
make -C libft fclean
/bin/rm -f $(NAME)
re: fclean all
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: Ecelsa <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/03/04 00:09:46 by ecelsa #+# #+# */
/* Updated: 2020/03/28 17:42:12 by Ecelsa ### ########.fr */
/* */
/* ************************************************************************** */
#include "fractol.h"
#include <limits.h>
#define W 600
#define H 600
int Cw = 600, Ch = 600;
// double VxMin = -0.15, VxMax = 0.05;
// double VyMin = 0.85, VyMax = 0.93;
double VxMin = -2, VxMax = 2;
double VyMin = -2, VyMax = 2;
int coef = 80;
int bn(double n, double l, double r)
{
return(n>l && n<=r);
}
void uput_pixel(int *img, int x, int y, int color)
{
if ((x >= 0 && x < Cw) && (y >= 0 && y < Ch))
img[y * Cw + x] = color;
}
void put_pixel(int *img, int x, int y, int color)
{
uput_pixel(img, x + (Cw / 2), y + (Ch / 2), color);
}
// c = x + i * y;
// Z(0) = 0;
// Z(1) = sqr(Z(0)) + c = x+i*y;
// Z(2) = sqr(Z(1)) + c = 0 + sqr(x+i*y) + x+i*y = x2 + 2ixy -y2 + x + iy
// Z(2) = sqr(Z(1)) + c = 0 + sqr(x+i*y) +
typedef unsigned char uchar;
typedef struct s_complex
{
double x;
double y;
} t_complex;
//void grid (int *img,)
int iterZ(double re, double im, int n)
{
int r,g,b;
int iter;
double c;
t_complex z;
c = re - im;
z.x = re;
z.y = im;
iter = 0;
(void)r;
(void)g;
(void)b;
double d = 0;
while (iter < n && fabs(c) < 4)
{
iter++;
d = z.x * z.x - z.y * z.y + re;
z.y = 2 * z.x * z.y + im;
z.x = d;
c = z.x - z.y;
}
double t = (double)iter / (double)n;
r = (int)(9 * (1 - t) * pow(t, 3) * 255);
g = (int)(15 * pow((1 - t), 2) * pow(t, 2) * 255);
b = (int)(8.5 * pow((1 - t), 4) * t * 255);
return (rgba(r,g,b,0));
/*int col;
if (bn(с,0,7))
col = rgba(coef*с,0,0,0);
else if (bn(c,7,14))
col = rgba(coef*c,coef*c,0,0);
else if (bn(c,14,21))
col = rgba(coef*c,0,coef*c,0);
else if (bn(c,21,28))
col = rgba(0,coef*c,0,0);
else if (bn(c,28,35))
col = rgba(coef*c,coef*c,0,0);
else if (bn(c,35,42))
col = rgba(0,coef*c,coef*c,0);
else if (bn(c,42,49))
col = rgba(0,0,coef*c,0);
else if (bn(c,49,56))
col = rgba(coef*c,0,coef*c,0);
else if (bn(c,56,64))
col = rgba(0,coef*c,coef*c,0);
else col = 0;
return (col);*/
/*c = ((double)255 / n);
r = c * iter;
g = (255 - (c * iter));
b = (c * iter);
//return(iter);
return (rgba(0, 0, b, 0));*/
}
void draw_mandelbort(t_window *win)
{
double im = VyMax;
double re = VxMin;
double dVh = (VyMax - VyMin) / Ch;
double dVw = (VxMax - VxMin) / Cw;
int x,y;
int iter;
if (dVw == 0)
printf("Zero\n");
while (im >= VyMin)
{
re = VxMin;
while (re <= VxMax)
{
// iter = iterZ(re, im, win->iter);
if (hm(re, im) == 1)
iter = rgba(0,0,0,0);
else
iter = iterZ(re, im, win->iter);
x = (re - VxMin) / dVw;
y = (VyMax - im) / dVh;
// if (((re - VxMin) / dVw) == (re - VxMin) / dVw * )
// {
// x = 0;
// iter = rgba(255,0,0,0);
// }
uput_pixel(win->img[0], x, y, iter);
re += dVw;
}
im -= dVh;
}
}
int main(void)
{
t_window win;
win.mlx_ptr = mlx_init();
win.win_ptr = mlx_new_window(win.mlx_ptr, Cw, Ch, "hop");
win.img_ptr[0] = mlx_new_image(win.mlx_ptr, Cw, Ch);
win.img[0] = (int*)mlx_get_data_addr(win.img_ptr[0], &win.bpp, &win.size_line, &win.endian);
win.img_ptr[1] = mlx_new_image(win.mlx_ptr, Cw, Ch);
win.img[1] = (int*)mlx_get_data_addr(win.img_ptr[1], &win.bpp, &win.size_line, &win.endian);
win.iter = 5;
win.btn_d = 0;
draw_mandelbort(&win);
//mlx_put_image_to_window(win.mlx_ptr, win.win_ptr, win.img_ptr, 0, 0);
mlx_hook(win.win_ptr, 4, (1L<<2), mouse_press, &win);
mlx_hook(win.win_ptr, 5, (1L<<3), mouse_release, &win);
mlx_hook(win.win_ptr, 6, (1L<<13), mouse_move, &win);
mlx_hook(win.win_ptr, 2, 1, key_press, &win);
mlx_loop(win.mlx_ptr);
return (0);
}<file_sep>#include "fractol.h"
unsigned int sum_color(int color1, int color2)
{
int color;
color = ((color1 & 0xff) + (color2 & 0xff) <
0xff) ? ((color1 & 0xff) + (color2 & 0xff)) : 0xff;
color |= ((color1 & 0xff) + (color2 & 0xff) <
0xff00) ? ((color1 & 0xff00) + (color2 & 0xff00)) : 0xff00;
color |= ((color1 & 0xff0000) + (color2 & 0xff0000) <
0xff0000) ? ((color1 & 0xff0000) + (color2 & 0xff0000)) : 0xff0000;
color |= ((color1 & 0xff000000) + (color2 & 0xff000000)) / 2;
return (color);
}
unsigned int rgba(t_uchar r, t_uchar g, t_uchar b, t_uchar alpha)
{
int ret;
ret = alpha;
ret <<= 8;
ret |= r;
ret <<= 8;
ret |= g;
ret <<= 8;
ret |= b;
return (ret);
}
int ft_abs(int i)
{
return ((i >=0) ? (i) : -(i));
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* control.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ecelsa <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/03/10 19:33:46 by ecelsa #+# #+# */
/* Updated: 2020/03/28 14:52:53 by ecelsa ### ########.fr */
/* */
/* ************************************************************************** */
#include "fractol.h"
int x_shift = 10, y_shift = 10;
extern int Cw, Ch;
double VxMin, VxMax, VyMin, VyMax;
int hm(double x, double y)
{
double ro_c;
double teta;
double ro;
ro = sqrt((x - 0.25) * (x - 0.25) + y * y);
teta = atan2(y, x - 0.25);
ro_c = 0.5 - 0.5 * cos(teta);
return ((ro <= ro_c) ? 1 : 0);
}
void line(int x0, int x1, int y0, int y1, int *img)
{
int deltax = abs(x1 - x0);
int deltay = abs(y1 - y0);
int error = 0;
int deltaerr = (deltay + 1);
int y = y0;
int diry = y1 - y0;
if (diry > 0)
diry = 1;
if (diry < 0)
diry = -1;
for (int x = x0; x <= x1; x++)
{
uput_pixel(img, x, y, 0x00fdfdfd);
// plot(x,y);
error += deltaerr;
if (error >= (deltax + 1))
{
y = y + diry;
error = error - (deltax + 1);
}
}
}
int key_press(int key, t_window *win)
{
// double dVh = (VyMax - VyMin) / Ch;
// double dVw = (VxMax - VxMin) / Cw
// double mem;
(void)win;
if (key == ESC)
exit(0);
printf("Key is pressed %d\n", key);
double dVh = (VyMax - VyMin) / Ch;
double dVw = (VxMax - VxMin) / Cw;
if (key == RIGHT)
{
//x_shift++;
VxMax += x_shift * dVw;
VxMin += x_shift * dVw;
}
if (key == LEFT)
{
//x_shift--;
VxMax -= x_shift * dVw;
VxMin -= x_shift * dVw;
}
if (key == UP)
{
//y_shift++;
VyMax += y_shift * dVh;
VyMin += y_shift * dVh;
}
if (key == DOWN)
{
//y_shift--;
VyMax -= y_shift * dVh;
VyMin -= y_shift * dVh;
}
if (key == SPACE)
{
double dVh = (VyMax - VyMin) / Ch;
double dVw = (VxMax - VxMin) / Cw;
VxMax -= dVw * 60;
VxMin += dVw * 60;
VyMax -= dVh * 60;
VyMin += dVh * 60;
}
if (key == PLUS)
{
win->iter += 5;
printf("+ ");
}
if (key == MINUS)
{
win->iter -= ((win->iter > 5) ? 5 : win->iter);
printf("- ");
}
printf("key - %d iter - %d\n",key, win->iter);
draw_mandelbort(win);
mlx_put_image_to_window(win->mlx_ptr, win->win_ptr, win->img_ptr[0], 0, 0);
return (0);
}
void draw(int x, int y, t_window *win)
{
int z = 50;
double hh = z /((double)Cw / Ch);
ft_memset(win->img[1], 0xff, Cw* Ch * 4);
for (int i = x - Cw/2 + 50; i < x + Cw / 2 - z; i++)
uput_pixel(win->img[1],i,y - Ch / 2 + hh, 0x00ffffff);
for (int i = x - Cw/2 + 50; i < x + Cw / 2 - z; i++)
uput_pixel(win->img[1],i, y + Ch / 2 - hh, 0x00ffffff);
}
int mouse_move(int x, int y, void *param)
{
t_window *win;
win = param;
if (win->btn_d)
{
draw(x,y,win);
mlx_put_image_to_window(win->mlx_ptr, win->win_ptr, win->img_ptr[1], 0, 0);
}
return (0);
}
int mouse_press(int button, int x, int y, void *param)
{
t_window *win;
double dVh = (VyMax - VyMin) / Ch;
double dVw = (VxMax - VxMin) / Cw;
(void)x;
(void)y;
// int z = 50;
//double hh = z /((double)Cw / Ch);
win = (t_window*)param;
if ((x > 0 && x < Cw) && (y > 0 && y < Ch))
{
if (button == 4) //+
{
}
if (button == 1) // +
{
win->btn_d = 1;
}
if (button == 5 || button == 2) // -
{
// VxMin = (x - (double)Cw / 2 - 50) * dVw;
// VxMax = (x + (double)Cw / 2 + 50) * dVw;
// VyMin = (y + (double)Ch / 2 + 28) * dVh;
// VyMax = (y - (double)Ch / 2 - 28) * dVh;
printf("Vx - %f Vh-%f x - %i y - %i VxMin %f VxMax %f VyMin %f VyMax %f\n",dVw * x, dVh * y, x, y, VxMin, VxMax, VyMin, VyMax);
// draw_mandelbort(win);
mlx_put_image_to_window(win->mlx_ptr, win->win_ptr, win->img_ptr, 0, 0);
}
}
printf("draw\n");
write(1, "!",1);
printf("btn-%i x-%i y-%i\n",button, x, y);
draw_mandelbort(win);
mlx_put_image_to_window(win->mlx_ptr, win->win_ptr, win->img_ptr[0], 0, 0);
return (0);
}
int mouse_release(int button, int x, int y, void *param)
{
t_window *win;
win = (t_window*)param;
if (button == 1)
{
win->btn_d = 0;
}
printf("--btn-%i x-%i y-%i\n",button, x, y);
return (0);
}<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* fractol.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ecelsa <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/03/04 00:14:17 by ecelsa #+# #+# */
/* Updated: 2020/03/27 19:58:02 by ecelsa ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef FRACTOL_H
#include <stdio.h>
# define FRACTOL_H
# define WIDTH 800
# define HEIGHT 800
# include "./minilibxX11/mlx.h"
# include <math.h>
# include <fcntl.h>
# include <stdlib.h>
# include "libft.h"
# include "ubuntu.h"
typedef unsigned char t_uchar;
typedef struct s_ptr
{
double x;
double y;
double z;
} t_ptr;
typedef struct s_window
{
void *mlx_ptr;
void *win_ptr;
void *img_ptr[2];
int *img[2];
int bpp;
int btn_d;
int size_line;
int endian;
int iter;
} t_window;
unsigned int sum_color(int color1, int color2);
unsigned int rgba(t_uchar r, t_uchar g, t_uchar b, t_uchar alpha);
int ft_abs(int i);
int key_press(int key, t_window *win);
void draw_mandelbort(t_window *win);
int mouse_move(int x, int y, void *param);
int mouse_press(int button, int x, int y, void *param);
int mouse_release(int button, int x, int y, void *param);
void uput_pixel(int *img, int x, int y, int color);
void put_pixel(int *img, int x, int y, int color);
int hm(double x, double y);
#endif
| 5b87d99f24cd844098581f308695f5fe65171868 | [
"C",
"Makefile"
] | 6 | C | MagistrDev/fractol | 99467f69b662ee80749e8232e3789fc860c87e7e | c8dca2ad91151b6ac6a9848a11360742c16873d7 |
refs/heads/master | <file_sep>/**
* Author: <NAME>
* Description: carousel function and route to quiz
*/
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { PresentationService } from './presentation.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-presentation',
templateUrl: './presentation.component.html',
styleUrls: ['./presentation.component.css']
})
export class PresentationComponent implements OnInit {
images: any;
presentations: any;
presentationName: string;
quizId: any;
quizName: string;
constructor(private route: ActivatedRoute, private http: HttpClient,
private presentationService: PresentationService, private router: Router,) {
this.presentationName = route.snapshot.paramMap.get('name');
this.presentationService.getPresentations()
.subscribe(res => {
this.presentations = res;
console.log(this.presentations);
this.images = this.presentations.filter(p => p.name === this.presentationName)[0].images;
console.log(this.images);
})
}
goToQuiz(quizId) {
this.quizId = quizId;
console.log(quizId);
console.log('Quiz: ' + this.quizId);
this.router.navigate(['/dashboard/questions/' + this.quizId]);
}
ngOnInit() {
}
}<file_sep>/**
* Author: <NAME>
* Description: quizzes
*/
const mongoose = require('mongoose');
let quizSchema = mongoose.Schema({
quizId: String,
quizName: String,
quizDescription: String,
questions: [
{
id: Number,
text: String,
answers: [
{
id: Number,
answerText: { type: String },
isCorrect: { type: Boolean }
}
]
}
]
}
)
module.exports = mongoose.model('Quiz', quizSchema);<file_sep># web-450
Mastering the MEAN Stack Bootcamp
# contributors
Professor Krasso - Bellevue University
<NAME> - Bellevue University
<file_sep>/**
* Author: <NAME>
* Description: employee results from quiz
*/
import { Component, OnInit, Input } from "@angular/core";
import { QuizComponent } from "../quiz/quiz.component";
import { Router } from "@angular/router";
import { MAT_DIALOG_DATA, MatDialogRef } from "@angular/material";
import { CookieService } from 'ngx-cookie-service';
@Component({
selector: "app-quiz-results",
templateUrl: "../results/results.component.html",
styleUrls: ["../results/results.component.css"]
})
export class ResultsComponent implements OnInit {
employeeId: string;
// resultsDisplay: any;
constructor(
private dialogRef: MatDialogRef<QuizComponent>, private router: Router, private cookieService: CookieService, ) {
this.employeeId = this.cookieService.get('employeeId');
console.log(this.employeeId + ' results employee')
}
@Input() public quizResults;
ngOnInit() {
console.log(this.quizResults);
}
}<file_sep>/**
* Author: <NAME>
* Description: Demonstration of how to connect to MongoDB and test middleware API's in SoapUI
*/
const express = require('express');
const http = require('http');
const mongoose = require('mongoose');
const Employee = require('./models/employees');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const path = require('path');
const createError = require('http-errors');
const Quiz = require('./models/quizzes');
const quizResults = require('./models/quiz-results')
let app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ 'extended': false }));
app.use(morgan('dev'));
app.use(express.static(path.join(__dirname, '../dist/nodequiz')));
app.use('/', express.static(path.join(__dirname, '../dist/nodequiz')));
const port = process.env.PORT || 3000, //server port or 3000
//const serverPort = 3000; // port the application listens on
// MongoDB (mLab) connection string
// const connString = 'mongodb://<username>:<password>@<host-name>:<port><database-name>';
const connString = 'mongodb+srv://admin:admin@buwebdev-cluster-1-m4xeg.mongodb.net/nodequiz?retryWrites=true&w=majority';
// MongoDB (Atlas) connection string
// const connString = 'mongodb+srv://<username>:<password>@<url>/<database-name>?retryWrites=true&w=majority'
// MongoDB connect
mongoose.connect(connString, { promiseLibrary: require('bluebird'), useNewUrlParser: true })
.then(() => console.debug('Connection to the MongoDB instance was successful!'))
.catch((err) => console.debug('MongoDB Error: ' + err.message));
/************************* API routes go below this line ********************/
app.post('/api/employees', function (req, res, next) {
const employees = {
employeeId: req.body.employeeId,
firstName: req.body.firstName,
lastName: req.body.lastName
};
Employee.create(employees, function (err, employees) {
if (err) {
console.log(err);
return next(err);
} else {
console.log(employees);
res.json(employees);
}
})
})
app.get('/api/employees', function (req, res, next) {
Employee.find({}, function (err, employees) {
if (err) {
console.log(err);
return next(err);
} else {
console.log(employees);
res.json(employees);
}
})
})
app.get('/api/employees/:id', function (req, res, next) {
Employee.findOne({ 'employeeId': req.params.id }, function (err, employees) {
if (err) {
console.log(err);
return next(err);
} else {
console.log(employees);
res.json(employees);
}
})
})
/*************** Quiz Results API *******************************************/
/*var userSchema = new mongoose.Schema({
employeeId: Number,
quizResults: String
});
var User = mongoose.model("User", userSchema);*/
//Create Quiz Result
app.post('/api/results', function(req, res, next) {
const quizResults = {
employeeId: req.body.employeeId,
quizId: req.body.quizId,
result: req.body.result
};
})
/**
* Creates an express server and listens on port 3000
*/
http.createServer(app).listen(serverPort, function () {
console.log(`Application started and listing on port: ${serverPort}`);
})<file_sep>/**
* Author: <NAME>
* Description: Quiz page guide
*/
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { QuizService } from './quiz.service';
import { filter, map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { MatDialog } from '@angular/material/dialog';
import { Location } from '@angular/common';
import { CookieService } from 'ngx-cookie-service';
import { error } from 'util';
import * as moment from 'moment'
import { ResultsComponent } from 'src/app/shared';
@Component({
selector: 'app-quiz',
templateUrl: './quiz.component.html',
styleUrls: ['./quiz.component.css']
})
export class QuizComponent implements OnInit {
quizId: string;
quizzes: any;
quiz: any;
questions: any;
//quizName: string;
answers: string;
quizNameFromUrl: string;
quizResults: any;
q: any = [];
qs: any = [];
cumulativeSummary: {};
quizSummary: {};
employeeId: number;
constructor(private route: ActivatedRoute, private cookieService: CookieService, private location: Location, private dialog: MatDialog, private http: HttpClient, private quizService: QuizService, private router: Router) {
this.quizId = (this.route.snapshot.paramMap.get('id'))
this.quiz = parseInt(this.route.snapshot.paramMap.get("id"))
this.employeeId = parseInt(this.cookieService.get('employeeId'))
//this.cookieValue = this.cookieService.get('employeeId')
console.log(this.employeeId + " employee number")
//this.employeeId = this.cookieService.get('employeeId');
//this.employeeId = parseInt(this.cookieService.get('employeeId'), 10);
this.quizService.getQuizzes().subscribe(res => {
this.quizzes = res;
this.questions = this.quizzes.filter(q => q.name === this.quizId)[0].questions;
//this.quizNameFromUrl = route.snapshot.paramMap.get('id'); quizName: {{this.quizNameFromUrl}}
console.log(this.quizzes);
})
}
ngOnInit() {
}
onSubmit(form) {
// score calculator
const totalPossiblePoints = 100;
this.quiz = this.quizzes.filter(q => q.id === this.quizId);
const questionCount = this.quiz.questions;
let pointsPerQusetions = totalPossiblePoints / questionCount;
let quizScore = 0;
//determining user's selction
let correctRunningTotal = 0;
let selectedAnswerIds = [];
let selectedisCorrectProp = [];
console.log("Q: " + this.questions);
// FORM
this.quizResults = form;
this.quizResults['employeeId'] = this.employeeId;
this.quizResults['quizId'] = this.quizId;
console.log('form ' + form);
// save quiz results to database
this.http.post('/api/results/', {
employeeId: this.employeeId,
quizId: this.quizId,
results: JSON.stringify(form)
}).subscribe(res => {
}, err => {
console.log("POST error", err);
}, () => {
console.log("POST complete");
for (const prop in this.quizResults) {
if (this.quizResults.hasOwnProperty(prop)) {
if (prop !== 'employeeId' && prop !== 'quizId') {
selectedAnswerIds.push(this.quizResults[prop].split(';')[0]);
selectedisCorrectProp.push(this.quizResults[prop].split(';')[1]);
}
}
}
});
const dialogRef = this.dialog.open(ResultsComponent, {
data: {
}
})
/* this.quizResults = form;
this.quizResults['employeeId'] = this.employeeId; // add the employeeId to the quizResults ojbect
console.table(this.quizResults); //show quiz results
alert('Employee: ' + this.employeeId + '\nQuiz: ' + this.quiz)
localStorage.setItem('employeeId', '');
} }
catch (error) {
this.http = error;
}
}
onSubmit() {
alert('Employee: ' + this.employeeId + '\nQuiz: ' + this.quizId)
}*/
}
goBack() {
this.location.back();
}
} | c892e9cc09179b6de91c60be07e619806f30dd3e | [
"JavaScript",
"TypeScript",
"Markdown"
] | 6 | TypeScript | trueworthy/web-450 | 35aa305b723acad600b82f8179eb1e7ca26e535a | 9fee5099ddbedb7073fd0ae57bcfd0ccacbc4756 |
refs/heads/main | <repo_name>matheusgda/frequency_domain_neural_nets<file_sep>/utils.py
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.autograd.profiler as profiler
import copy
import fdnn
def trainer(preprocess,
model, num_epochs, initial_loss, train_loader, val_loader, num_val,
criterion, optimizer, device, show_every=10, dtype=torch.float):
loss_list = list()
accuracy_list = list()
best_loss = initial_loss
best_model = None
best_acc = 0
non_imp = 0
for e in range(num_epochs):
print("Epoch: {} / {}".format(e, num_epochs))
for t, (x, target) in enumerate(train_loader):
x = x.to(device=device, dtype=dtype)
x = preprocess(x)
scores = model(x)
target = target.to(device=device, dtype=torch.long)
loss = criterion(scores, target)
optimizer.zero_grad() # clear gradients
loss.backward()
optimizer.step()
with torch.no_grad():
l = loss.item()
best_loss = l * (best_loss > l) + \
(best_loss < l) * l
loss_list.append(l)
if t % show_every == 0:
print("Batch {}".format(t))
print("Best loss {}.".format(best_loss))
acc = evaluate(
preprocess, model, val_loader, num_val, device, dtype=dtype)
accuracy_list.append(acc)
print("Model best accuracy: {}.".format(best_acc))
return best_model, best_acc, loss_list, accuracy_list
def evaluate(preprocess, model, loader, num_samp, device, dtype=torch.cfloat):
with torch.no_grad():
acc = torch.zeros(1, device=device)
for _, (x, target) in enumerate(loader):
x = x.to(device=device, dtype=dtype)
x = preprocess(x)
scores = model(x)
target = target.to(device=device, dtype=torch.long)
acc += (1.0 * (torch.argmax(scores, 1) == target)).sum()
return acc.item() / num_samp
def print_param_counter(model):
print("The model has {} parameters.".format(parameter_counter(model)))
def parameter_counter(model):
count = 0
for param in model.parameters():
count += np.prod(param.size())
return count
def profile(x, model, batch_size, device, func, sort_by="cuda_time_total"):
with profiler.profile(record_shapes=True, use_cuda=True) as prof:
with profiler.record_function(func):
model(x)
print(prof.key_averages().table(sort_by=sort_by, row_limit=10))
def show_conv_weight(w, preprocess):
_, ax = plt.subplots(1, 2)
# for i, data in enumerate(List):
# t = np.arange(data.shape[0])
# ax[i].plot(t, data[:, 0])
# ax[i].plot(t, data[:, 1])
# ax[i].set_title(Models[i])
# ax[i].legend((Titles[0], Titles[1]))
img = preprocess(w)
ax[0].imshow(img.real)
ax[1].imshow(img.imag)
plt.show()
<file_sep>/CIFAR_10.py
import torch
import torchvision
from torch.utils.data import sampler
from torch.utils.data import DataLoader
import torch.fft as fft
import torchvision.transforms as T
import fdnn
import utils
import matplotlib.pyplot as plt
import sys
NUM_TRAIN = 256
NUM_VAL = 128
BATCH_SIZE = 128
NUM_TEST = 128
model_name = "FDNN_CIFAR10.model"
save_info = True
CIFAR10_PATH = '/home/revz/Development/neural_nets/assignment2/cs682/datasets'
if len(sys.argv) > 1:
CIFAR10_PATH = sys.argv[1]
N, C, H, W, K = BATCH_SIZE, 3, 32, 32, 10
transform = T.Compose([
T.ToTensor(),
T.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))
])
cifar10_train = torchvision.datasets.CIFAR10(
CIFAR10_PATH,
train=True, download=True, transform=transform)
cifar10_test = torchvision.datasets.CIFAR10(
CIFAR10_PATH,
train=False, download=True, transform=transform)
train_loader = DataLoader(cifar10_train, batch_size=BATCH_SIZE, pin_memory=True,
sampler=sampler.SubsetRandomSampler(range(NUM_TRAIN)))
val_loader = DataLoader(
cifar10_train, batch_size=BATCH_SIZE, pin_memory=True,
sampler=sampler.SubsetRandomSampler(range(NUM_TRAIN, NUM_TRAIN + NUM_VAL)))
test_loader = DataLoader(
cifar10_test, batch_size=BATCH_SIZE, pin_memory=True,
sampler=sampler.SubsetRandomSampler(range(NUM_TEST)))
device = torch.device("cuda:0")
dims = (N, H, W, C, 1)
p_num_filters = (1, 3, 3, 3)
m_num_filters = (3, 3, 3)
preserved_dim = 3
initializer = fdnn.random_complex_weight_initializer
hadamard_initializer = fdnn.random_hadamard_filter_initializer
bias_initializer = fdnn.naive_bias_initializer
dropout = None
model = fdnn.FrequencyDomainNeuralNet(
dims, p_num_filters, m_num_filters, K, preserved_dim=3,
p_initializer=initializer, p_hadamard_initializer=hadamard_initializer,
p_bias_initializer=bias_initializer,
m_initializer=initializer, m_hadamard_initializer=hadamard_initializer,
m_bias_initializer=bias_initializer,
device=device, dropout=dropout)
utils.print_param_counter(model)
preprocess = fdnn.FourierPreprocess()
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(
model.parameters(), lr=1e-4, betas=(0.9,0.99), weight_decay=0)
num_epochs = 2
best_model, best_acc, loss, accuracy = utils.trainer(
preprocess,
model, num_epochs, K, train_loader, val_loader, NUM_VAL,
criterion, optimizer, device)
test_accuracy = utils.evaluate(preprocess, model, test_loader, NUM_TEST, device)
if save_info:
torch.save(model.state_dict(), model_name + ".model")
torch.save(best_model.state_dict(), model_name + "_best.model")
experiment_data = {
"val_accuracy": accuracy,
"train_loss": loss,
"best_val_acc": best_acc,
"test_acc": test_accuracy}
import pickle
try:
pickle_file = "{}_data.pck".format(model_name)
f = open(pickle_file, 'wb')
pickle.dump(experiment_data, f)
f.close()
except OSError: # could not save pickle file
print('Could not save pickle file! Data lost!')
plt.plot(range(len(loss)), loss)
plt.ylabel("Loss")
plt.xlabel("Step")
plt.savefig("{}_loss.png".format(model_name))
plt.grid(True)
plt.title("Training Loss")
plt.show()
plt.clf()
plt.plot(range(len(accuracy)), accuracy)
plt.ylabel("Accuracy")
plt.xlabel("Epoch")
plt.grid(True)
plt.title("Validation Accuracy")
plt.savefig("{}_accuracy.png".format(model_name))
plt.show()
<file_sep>/fdnn.py
"""
Frequency-Domain Neural Network class for supervised classification. Each one
of the major blocks in the network will be defined in a module. The '
fundamental building blocks for this architecture are:
- FFT layer (non-differentiable).
- Hadamard product between complex tensors. (weight tensor to be learned)
- Weighted sum of complex tensors. (weights to be learned)
- The prime frequency dropin mechanism.
"""
import numpy as np
import torch
import torch.fft as fft
CUDA_DEVICE = torch.device("cuda:0")
# CUDA_DEVICE = torch.device('cpu')
def random_complex_weight_initializer(dims, alpha=0.01, device=CUDA_DEVICE):
A = alpha * torch.randn(dims, device=device, requires_grad=True)
B = alpha * torch.randn(dims, device=device, requires_grad=True)
return (A, B)
def random_hadamard_filter_initializer(
dims, alpha=5, size=5, offset=0, device=CUDA_DEVICE):
if size is not None:
f = torch.zeros(dims, device=device)
f[offset : offset + size, offset : offset + size] = alpha * torch.randn(
*dims[2:], device=device)
y = fft.fftn(f, dim=(0, 1))
freal = y.real
fimag = y.imag
freal.requires_grad_(True)
fimag.requires_grad_(True)
return (freal, fimag)
return (
alpha * torch.randn(dims, device=device, requires_grad=True),
alpha * torch.randn(dims, device=device, requires_grad=True))
def naive_bias_initializer(dims, device=CUDA_DEVICE):
return (torch.zeros(dims, device=device, requires_grad=True),
torch.zeros(dims, device=device, requires_grad=True))
class ComplexBatchNorm(torch.nn.Module):
def __init__(self, num_dims, batch_dim, batch_dim_ind, device=CUDA_DEVICE):
super().__init__()
self.num_dims = num_dims + 1
permutation = list(range(self.num_dims))
permutation[2] = batch_dim_ind + 1
permutation[batch_dim_ind + 1] = 2
self.permutation = tuple(permutation)
if num_dims == 5:
self.batchnorm = torch.nn.BatchNorm3d(batch_dim)
else:
self.batchnorm = torch.nn.BatchNorm2d(batch_dim)
self.batchnorm.cuda(device)
def forward(self, x):
y = x.permute(self.permutation)
return torch.stack((
self.batchnorm(y[0]), self.batchnorm(y[1]))).permute(
self.permutation)
class ComplexLinear(torch.nn.Module):
def __init__(
self, in_features, out_features,
initializer=random_complex_weight_initializer,
layer_ind=0,
bias_initializer=naive_bias_initializer, device=CUDA_DEVICE):
super().__init__()
self.in_features = in_features
self.out_features = out_features
Wr, Wi = initializer((out_features, in_features), device=device)
self.Wr = torch.nn.Parameter(Wr)
self.Wi = torch.nn.Parameter(Wi)
self.register_parameter('Wr{}'.format(layer_ind), self.Wr)
self.register_parameter('Wi{}'.format(layer_ind), self.Wi)
Br, Bi = bias_initializer(out_features, device=device)
self.Br = torch.nn.Parameter(Br)
self.Bi = torch.nn.Parameter(Bi)
if bias_initializer is not None:
self.register_parameter('Br{}'.format(layer_ind), self.Br)
self.register_parameter('Bi{}'.format(layer_ind), self.Bi)
# @staticmethod
def forward(self, x):
rr = torch.nn.functional.linear(x[0], self.Wr)
ri = torch.nn.functional.linear(x[0], self.Wi)
ir = torch.nn.functional.linear(x[1], self.Wr)
ii = torch.nn.functional.linear(x[1], self.Wi)
return torch.stack((rr - ii + self.Br, ir + ri + self.Bi))
class GenericLinear(ComplexLinear):
def __init__(
self, num_dims, mixed_dim, in_features, out_features, layer_ind=0,
initializer=random_complex_weight_initializer,
bias_initializer=naive_bias_initializer,
device=CUDA_DEVICE):
super().__init__(
in_features, out_features, layer_ind=layer_ind,
initializer=initializer, bias_initializer=bias_initializer,
device=device)
self.num_dims = num_dims + 1
self.mixed_dim = mixed_dim + 1
self.in_features = in_features
self.out_features = out_features
permutation = list(range(self.num_dims))
permutation[self.mixed_dim] = self.num_dims - 1
permutation[-1] = self.mixed_dim
self.permutation = tuple(permutation)
# @staticmethod
def forward(self, x):
""" Apply a generic linear operator on a permutation of x and return
the un-permuted version.
Args:
x (torch.Tensor): Input.
Returns:
Tensor: Linear output with self.mixed_dim modified.
"""
y = super().forward(x.permute(self.permutation))
return y.permute(self.permutation)
class Hadamard(torch.nn.Module):
def __init__(
self, dims, layer_ind=0, initializer=random_complex_weight_initializer,
mask_initializer=None,
device=CUDA_DEVICE):
super().__init__()
self.dims = dims
self.initializer = initializer
self.device = device
self.layer_ind = layer_ind
freal, fimag = initializer(dims, device=self.device)
self.freal = torch.nn.Parameter(freal)
self.fimag = torch.nn.Parameter(fimag)
self.register_parameter('freal{}'.format(layer_ind), self.freal)
self.register_parameter('fimag{}'.format(layer_ind), self.fimag)
# apply mask only if necessary
if mask_initializer is not None:
self.mask = mask_initializer(dims, device=device)
self.ff = self.masked_picewise_prod
else:
self.ff = self.picewise_prod
# @staticmethod
def forward(self, x):
return self.ff(x)
def picewise_prod(self, x):
return torch.stack((
self.freal * x[0] - self.fimag * x[1],
self.fimag * x[1] + self.freal * x[0]))
def masked_picewise_prod(self, x):
return self.mask * self.picewise_prod(x)
class Absolute(torch.nn.Module):
def __init__(self):
super().__init__()
# @staticmethod
def forward(self, x):
return x.square().sum(0).sqrt()
class FrequencyFilteringBlock(torch.nn.Module):
def __init__(
self, dims, num_filters, non_lin=torch.nn.Hardtanh,
preserved_dim=None, initializer=random_complex_weight_initializer,
hadamard_initializer=random_hadamard_filter_initializer,
bias_initializer=naive_bias_initializer,
device=CUDA_DEVICE,
dropout=None):
super().__init__()
self.dims = dims
self.num_dims = len(dims)
self.num_layers = int(len(num_filters) - 1)
self.num_filters = num_filters
self.initializer = initializer
self.hadamard_initializer = hadamard_initializer
self.bias_initializer = bias_initializer
self.device = device
self.preserved_dim = preserved_dim
self.is_preserving = preserved_dim is not None
if self.is_preserving:
self.preserved_size = dims[preserved_dim]
self.batch_dim_index = 3 # TODO: clarify why
self.dropout = dropout
self.non_linearity = non_lin
self.layers = self.compile_layers()
self.sequential = torch.nn.Sequential(*self.layers)
def forward(self, x):
return self.sequential(x)
def compile_layers(self):
layers = list()
for l in range(self.num_layers):
layers.append(
ComplexLinear(self.num_filters[l], self.num_filters[l + 1],
layer_ind=l, initializer=self.initializer,
bias_initializer=self.bias_initializer, device=self.device))
layers.append(
Hadamard(
self.hadamar_dimension(self.num_filters[l + 1]),
initializer=self.hadamard_initializer,
layer_ind=l, device=self.device))
if self.is_preserving:
layers.append(
GenericLinear(
self.num_dims, self.preserved_dim, self.preserved_size,
self.preserved_size, layer_ind=l,
initializer=self.initializer,
bias_initializer=self.bias_initializer,
device=self.device))
# layers.append(self.non_linearity())
layers.append(
ModReLU(self.hadamar_dimension(self.num_filters[l + 1]),
layer_ind=l))
layers.append(ComplexBatchNorm(
self.num_dims, self.batch_norm_dims(l + 1),
self.batch_dim_index))
if self.dropout is not None:
layers.append(torch.nn.Dropout(self.dropout))
return layers
def hadamar_dimension(self, num_filters, preserving=False):
if self.is_preserving:
return (*self.dims[1: -1], num_filters)
return (self.dims[1], self.dims[2], num_filters)
def batch_norm_dims(self, l):
if self.is_preserving:
return 3
return self.num_filters[l]
def num_output_features(self):
return np.prod(self.dims[1 :-1]) * self.num_filters[-1]
def output_shape(self):
return tuple(*self.dims[1:-1], self.num_filters[-1])
class ComplexClassificationHead(torch.nn.Module):
def __init__(self, in_features, num_classes, device=CUDA_DEVICE):
super().__init__()
self.in_features = 2 * in_features
self.num_classes = num_classes
self.device = device
self.layers = [
torch.nn.Flatten(start_dim=1),
torch.nn.Linear(self.in_features, num_classes).to(device)] # standard linear func
# Absolute()]
self.sequential = torch.nn.Sequential(*self.layers)
def forward(self, x):
return self.sequential(x.transpose(1, 0))
class FourierPreprocess(torch.nn.Module):
def __init__(self, perm=(0, 2, 3, 1), fourier_dim=(1, 2, 3), append_dim=1):
super().__init__()
self.p = perm
self.fdim = fourier_dim
self.append = append_dim
def forward(self, x):
with torch.no_grad():
x = x.permute(self.p)
x = fft.fftn(x, dim=self.fdim)
x = x.view((*x.shape, self.append))
x = torch.stack((x.real, x.imag))
return x
class FourierWeightVisualizer(torch.nn.Module):
def __init__(self, fourier_dim=(1, 2, 3), dims=5):
super().__init__()
self.fdim = fourier_dim
self.permutation = [dims - 1, * list(range(1, dims - 1))]
def forward(self, x):
with torch.no_grad():
return fft.ifftn(
torch.view_as_complex(x.permute(self.permutation)), dim=self.fdim)
class ModReLU(torch.nn.Module):
def __init__(
self, dims, bias_initializer=naive_bias_initializer, layer_ind=0,
device=CUDA_DEVICE):
super().__init__()
self.dims = dims
self.abs = Absolute()
bias, _ = bias_initializer(dims, device=device)
self.bias = torch.nn.Parameter(bias)
self.register_parameter('rb{}'.format(layer_ind), self.bias)
def forward(self, x):
mod = 1 / self.abs(x)
mask = (1 + (self.bias * mod)) > 0
return mask * x
class FrequencyDomainNeuralNet(torch.nn.Module):
def __init__(self, pdims, p_num_filters, m_num_filters, num_classes,
p_non_lin=torch.nn.Hardtanh, m_non_lin=torch.nn.Hardtanh,
preserved_dim=3, p_initializer=random_complex_weight_initializer,
m_initializer=random_complex_weight_initializer,
p_hadamard_initializer=random_hadamard_filter_initializer,
m_hadamard_initializer=random_hadamard_filter_initializer,
p_bias_initializer=naive_bias_initializer,
m_bias_initializer=naive_bias_initializer,
collapse_initializer=random_complex_weight_initializer,
dropout=None,
device=CUDA_DEVICE):
super().__init__()
self.num_dims = len(pdims)
self.preserving_block = FrequencyFilteringBlock(
pdims, p_num_filters, non_lin=p_non_lin,
preserved_dim=preserved_dim,
initializer=p_initializer,
hadamard_initializer=p_hadamard_initializer,
bias_initializer=p_bias_initializer,
device=device, dropout=dropout)
self.mdims = (*pdims[:-2], p_num_filters[-1])
self.device = device
preserved_size = pdims[preserved_dim]
self.collapse = GenericLinear(
len(pdims), preserved_dim, preserved_size,
1, layer_ind=-1,
initializer=collapse_initializer,
bias_initializer=p_bias_initializer,
device=device)
# self.collapse_view_dims = self.mdims[1:]
self.mixing_block = FrequencyFilteringBlock(
self.mdims,
(p_num_filters[-1], *m_num_filters),
non_lin=m_non_lin,
preserved_dim=None,
initializer=m_initializer,
hadamard_initializer=m_hadamard_initializer,
bias_initializer=m_bias_initializer,
device=device, dropout=dropout)
self.head = ComplexClassificationHead(
self.mixing_block.num_output_features(), num_classes, device=device)
def forward(self, x):
y0 = self.preserving_block(x)
y1 = self.collapse(y0).view((x.shape[0], x.shape[1], *self.mdims[1:]))
return self.head(self.mixing_block(y1))
class FrequencyDomainReducedNet(torch.nn.Module):
def __init__(self, pdims, p_num_filters, m_num_filters, num_classes,
p_non_lin=torch.nn.Hardtanh, m_non_lin=torch.nn.Hardtanh,
preserved_dim=3, p_initializer=random_complex_weight_initializer,
m_initializer=random_complex_weight_initializer,
p_hadamard_initializer=random_hadamard_filter_initializer,
m_hadamard_initializer=random_hadamard_filter_initializer,
p_bias_initializer=naive_bias_initializer,
m_bias_initializer=naive_bias_initializer,
collapse_initializer=random_complex_weight_initializer,
dropout=None,
device=CUDA_DEVICE):
super().__init__()
self.num_dims = len(pdims)
self.device = device
self.preserving_block = FrequencyFilteringBlock(
pdims, p_num_filters, non_lin=p_non_lin,
preserved_dim=preserved_dim,
initializer=p_initializer,
hadamard_initializer=p_hadamard_initializer,
bias_initializer=p_bias_initializer,
device=device, dropout=dropout)
self.head = ComplexClassificationHead(
self.preserving_block.num_output_features(), num_classes, device=device)
def forward(self, x):
y0 = self.preserving_block(x)
return self.head(y0)
class FrequencyDomainPoolingNet(torch.nn.Module):
def __init__(self, pdims, p_num_filters, m_num_filters, num_classes,
p_non_lin=torch.nn.Hardtanh, m_non_lin=torch.nn.Hardtanh,
preserved_dim=3, p_initializer=random_complex_weight_initializer,
m_initializer=random_complex_weight_initializer,
p_hadamard_initializer=random_hadamard_filter_initializer,
m_hadamard_initializer=random_hadamard_filter_initializer,
p_bias_initializer=naive_bias_initializer,
m_bias_initializer=naive_bias_initializer,
collapse_initializer=random_complex_weight_initializer,
dropout=None,
device=CUDA_DEVICE):
super().__init__()
self.num_dims = len(pdims)
self.preserving_block = FrequencyFilteringBlock(
pdims, p_num_filters, non_lin=p_non_lin,
preserved_dim=preserved_dim,
initializer=p_initializer,
hadamard_initializer=p_hadamard_initializer,
bias_initializer=p_bias_initializer,
device=device, dropout=dropout)
self.mdims = (*pdims[:-2], p_num_filters[-1])
self.device = device
preserved_size = pdims[preserved_dim]
self.collapse = GenericLinear(
len(pdims), preserved_dim, preserved_size,
1, layer_ind=-1,
initializer=collapse_initializer,
bias_initializer=p_bias_initializer,
device=device)
self.mixing_block = FrequencyFilteringBlock(
self.mdims,
(p_num_filters[-1], *m_num_filters),
non_lin=m_non_lin,
preserved_dim=None,
initializer=m_initializer,
hadamard_initializer=m_hadamard_initializer,
bias_initializer=m_bias_initializer,
device=device, dropout=dropout)
self.head = ComplexClassificationHead(
self.mixing_block.num_output_features(), num_classes, device=device)
def forward(self, x):
y0 = self.preserving_block(x)
y1 = self.collapse(y0).view((x.shape[0], x.shape[1], *self.mdims[1:]))
return self.head(self.mixing_block(y1))
<file_sep>/README.md
# frequency_domain_neural_nets
Frequency domain neural networks (FDNN) repo.
<file_sep>/weight_visualizer.py
import sys
import torch
import torch.fft as fft
import utils
import fdnn
argc = len(sys.argv)
state_dict_path = sys.argv[1]
f_index = int(sys.argv[2])
f = open(state_dict_path, 'rb')
state_dict = torch.load(f, map_location=torch.device('cpu'))
f.close()
keys = list(state_dict.keys())
keyr = 'preserving_block.sequential.11.freal2'
keyi = 'preserving_block.sequential.11.fimag2'
wr = state_dict[keyr][:, :, :, f_index]
wi = state_dict[keyi][:, :, :, f_index]
w = torch.stack((wr, wi), dim=-1)
# print(w)
print(wr.size())
print(wi.size())
print(w.size())
process = lambda x : fft.ifftn(torch.view_as_complex(x), dim=(0, 1))
utils.show_conv_weight(w, process)
| 4db03d0c87c23c31d8eda7e9f47796e320d23a32 | [
"Markdown",
"Python"
] | 5 | Python | matheusgda/frequency_domain_neural_nets | 27f7319709338eccbd99aed4ae8307ba69e6c45b | 52b330961ec9443dd99bce4bb41bffbc8131cd25 |
refs/heads/master | <repo_name>slakh96/home_page_with_react_redux<file_sep>/src/App.js
import React, { Component } from 'react';
import wheel from './car_wheel.png';
import './App.css';
import Time from './time_files/time_component.js';
import Todo from './todo_files/todo_component.js';
import Weather from './weather_files/weather_component.js';
class App extends Component {
render() {
return (
<div className = "main">
<img src = {wheel} className = "App-logo" alt = "spinning car wheel"/>
<Time/>
<Todo/>
<Weather/>
</div>
);
}
}
export default App;
// <div className="App">
// <header className="App-header">
// <img src={logo} className="App-logo" alt="logo" />
// <h1 className="App-title">Welcome to React</h1>
// </header>
// <p className="App-intro">
// To get started, edit <code>src/App.js</code> and save to reload.
// </p>
// </div><file_sep>/README.md
# home_page_with_react_redux
Home page made with React and Redux. Includes a to-do list, background, clock, and animations. More developments coming.
<file_sep>/src/todo_files/todo_action.js
export default function(message){
return {
type: "ADD",
payload: message
}
}<file_sep>/src/todo_files/todo_reducer.js
export default function(state = [], action){
let state_set;
switch(action.type){
case "ADD":
state = [...state, action.payload];
state_set = new Set(state);
state = [...state_set];
return state;
case "CHECKED":
state_set = new Set(state);//Remove duplicate values from list of todos
state = [...state_set];//spread syntax, makes state hold all the values of state_set
let y = state.indexOf(action.payload);
if (y >= 0){
state.splice(y, 1);//removes the todo at index y
return state;
}
else {
alert('Not found');
}
return state;
default: return state;
}
}<file_sep>/src/weather_files/weather_utilities.js
export function convert_temp(temp){
return temp - 273.15;
}<file_sep>/src/todo_files/checked_off_action.js
export default function(item){
//console.log('action');
console.log(item);
return {
type: "CHECKED",
payload: item.toString()
}
}<file_sep>/src/time_files/time_component.js
import React, { Component } from 'react';
import {connect} from "react-redux";
import time_update from './time_action';
import {bindActionCreators} from "redux";
import '../App.css';
class Time extends Component {
componentDidMount() {//delays for 1 second before sending the time update again
this.interval = setInterval(() => this.props.time_update(), 1000);
}
componentWillUnmount() {//sets the time interval back to zero.
clearInterval(this.interval);
}
render(){
return(
<div className = "time">
<h1>{this.props.time.hour}:{this.props.time.min}:{this.props.time.secs}</h1>
<h3>{this.props.time.day}, {this.props.time.month} {this.props.time.date} {this.props.time.year}</h3>
</div>
);
}
}
function mapStateToProps(state){
return {
time: state.time //passed to the component as props, so can do this.props.time, instead of this.props.state.tiem
};
};
function mapDispatchToProps(dispatch){
return bindActionCreators({time_update: time_update}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(Time);<file_sep>/src/todo_files/cookies.js
const createCookie = (todolist) => {
let todolist_str = todolist.toString();
document.cookie = "todo=" + todolist_str;
}
const getCookie = (name = "todo") => {
let c_start = document.cookie.indexOf(name + "=");
if (c_start > -1){
c_start = c_start + name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1){
c_end = document.cookie.length;
}
let cookie_string = unescape(document.cookie.substring(c_start, c_end));
cookie_string = cookie_string.split(',');
return cookie_string;
}
return [];
}
const addCookie = (newCookie, name = "todo") => {
let old_cookie = getCookie(name);
old_cookie = old.cookie.toString();
old_cookie += newCookie;
old_cookie = old_cookie.split(',');
return createCookie(old_cookie);
}
const removeCookie = (remove, name) => {
return null;
}<file_sep>/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import {createStore, combineReducers} from 'redux';
import time_reducer from './time_files/time_reducer'
import {Provider} from 'react-redux';
import todo_reducer from './todo_files/todo_reducer';
import weather_reducer from './weather_files/weather_reducer';
import $ from "jquery";
//import registerServiceWorker from './registerServiceWorker';
const main_reducer = combineReducers({
time: time_reducer,
todo: todo_reducer,
weather: weather_reducer
});
const store = createStore(main_reducer);
ReactDOM.render(
<Provider store = {store}>
<App/>
</Provider>,
document.getElementById('root'));
//registerServiceWorker();
<file_sep>/src/weather_files/weather_component.js
import React, { Component } from 'react';
import {connect} from "react-redux";
import {bindActionCreators} from "redux";
import $ from 'jquery';
import {convert_temp} from "./weather_utilities.js";
import weather_update from "./weather_action.js";
class Weather extends Component {
componentWillMount(){
var name = "codemzy";
var id = "2fbd68a1db191e6cf5ee3f331f83447a";
$.get('https://api.openweathermap.org/data/2.5/weather?id=6087824&APPID=8', function(response) {
console.log(response);
/*
let cur_temp = response.main.temp;
let temp_max = response.main.temp_max;
let temp_min = response.main.temp_min;
let weather_description = response.weather[0].description;
console.log(weather_description);
*/
});//Save responses into vars to be the weather data, then place the weather data on the screen
let cur_temp = convert_temp(273.15);
let temp_max = convert_temp(274.15);
let temp_min = convert_temp(272.15);
let weather_description = "light rain";
}
componentDidMount() {//delays for 1 second before sending the time update again
//this.interval = setInterval(() => this.props.weather_update(), 1000);
}
render(){
return (
<div>
{convert_temp(273.15)}
</div>
)
}
}
function mapStateToProps(state){
return {
weather: state.weather
};
};
function mapDispatchToProps(dispatch){
return bindActionCreators({weather_update: weather_update}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(Weather);<file_sep>/src/time_files/time_reducer.js
let d = new Date();
export default function (state = d, action){
//console.log(action.type);
state = new Date();
let min = state.getMinutes();
let hour = state.getHours();
let secs = state.getSeconds();
let day = state.getDay(); // Monday - Sunday
let month = state.getMonth();
let year = state.getFullYear();
let date = state.getDate(); //1st, second etc.
if (min < 10){
min = "0" + min;
};
if (secs < 10){
secs = "0" + secs;
};
switch(day){
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
default:
day = undefined;
break;
};
let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
month = months[month];
return {
min: min,
hour: hour,
secs: secs,
day: day,
month: month,
date: date,
year: year
};
} | 3ee3eeee9d33098312a2ec1ddfc45db53459dd11 | [
"JavaScript",
"Markdown"
] | 11 | JavaScript | slakh96/home_page_with_react_redux | 46377b91c6b676e77defb2b5209977316776b781 | cf81e6ca60ebe7bb2a162da41fd72a690c515869 |
refs/heads/master | <file_sep>use std::convert::AsRef;
use std::collections::HashMap;
use bytes::{Buf, ByteBuf, MutByteBuf};
use std::mem;
use std::error::Error;
use std::convert::From;
use std::string;
#[derive(Debug)]
struct HttpError {
message: String,
cause: Option<Box<Error>>
}
pub enum HttpResult {
Http1Incomplete {buffer: MutByteBuf, request_builder: HttpRequestBuilder},
Http1Request {buffer: ByteBuf, request: HttpRequest},
Http2Upgrade {buffer: ByteBuf, request: HttpRequest},
}
impl HttpError {
fn new(message: String) -> HttpError {
HttpError {
message: message,
cause: None
}
}
fn with_cause(message: String, err: Box<Error>) -> HttpError {
HttpError {
message: message,
cause: Some(err)
}
}
}
impl PartialEq for HttpError {
fn eq(&self, other: &HttpError) -> bool {
other.message == self.message
}
}
impl From<string::FromUtf8Error> for HttpError {
fn from(err: string::FromUtf8Error) -> HttpError {
HttpError::with_cause(String::from("Error parsing string"), Box::new(err))
}
}
#[derive(Debug, PartialEq)]
enum HttpMethod {
GET,
POST,
PUT,
DELETE,
OPTIONS,
HTTP2
}
impl HttpMethod {
fn parse(value :&str) -> Result<HttpMethod, HttpError> {
match value.to_uppercase().as_ref() {
"GET" => Ok(HttpMethod::GET),
"POST" => Ok(HttpMethod::POST),
"PUT" => Ok(HttpMethod::PUT),
"DELETE" => Ok(HttpMethod::DELETE),
"OPTIONS" => Ok(HttpMethod::OPTIONS),
"PRI" => Ok(HttpMethod::HTTP2),
other => {
Err(HttpError::new(format!("Unrecognised method {}", other)))
}
}
}
}
#[derive(PartialEq, Debug)]
enum ParserStates {
//Initial request states
Verb,
Path,
Version,
//Header parsing states
HeaderTitle,
HeaderContent{title: String},
HeadersNewLine{title: String},
EndHeaders,
// Section complete states
Complete
}
#[derive(Debug)]
pub struct HttpRequestBuilder{
method: Result<HttpMethod, HttpError>,
path: Option<String>,
version: Option<String>,
headers: HashMap<String, Vec<String>>,
state: ParserStates,
temporary_data: Vec<u8>
}
struct HttpRequest {
method: HttpMethod,
path: String,
headers: HashMap<String, Vec<String>>
}
impl HttpRequestBuilder {
pub fn new() -> HttpRequestBuilder {
HttpRequestBuilder {
method : Err(HttpError::new(String::from("Method not declared"))),
path: None,
version: None,
headers: HashMap::new(),
state: ParserStates::Verb,
temporary_data: Vec::new()
}
}
pub fn build(self) -> Result<HttpRequest, HttpError> {
let method = try!(self.method);
let path = try!(self.path.ok_or(HttpError::new(format!("Path not parsed"))));
Ok(HttpRequest {
method: method,
path: path,
headers: self.headers
})
}
fn read_value(&mut self, buffer: &mut ByteBuf, length: usize) -> Result<String, HttpError> {
let (mut data, start) = match self.temporary_data.len() {
0 => (Vec::with_capacity(length), 0),
_ => {
println!("Using leftover data");
let mut temp = mem::replace(&mut self.temporary_data, Vec::new());
let start = temp.len();
temp.reserve(length);
(temp, start)
}
};
unsafe{ data.set_len(start + length); }
buffer.reset();
buffer.read_slice(&mut data[start .. (start + length)]);
buffer.advance(1);
buffer.mark();
match String::from_utf8(data) {
Ok(data) => Ok(String::from(data.trim())),
Err(err) => Err(HttpError::from(err))
}
}
pub fn parse(mut self, mut buffer: ByteBuf) -> Result<HttpResult, HttpError> {
let mut state_length = 0;
buffer.mark();
while let Some(character) = buffer.read_byte() {
let state = mem::replace(&mut self.state, ParserStates::Complete);
println!("({:?}, {:?})",state, character as char);
let (next_state, next_length) = match (state, character as char) {
(ParserStates::Verb, ' ') => {
let verb = try!(self.read_value(&mut buffer, state_length));
self.method = HttpMethod::parse(& verb);
(ParserStates::Path, 0)
},
(ParserStates::Path, ' ') => {
self.path = Some(try!(self.read_value(&mut buffer, state_length)));
(ParserStates::Version, 0)
},
(ParserStates::Version, '\n') => {
self.version = Some(try!(self.read_value(&mut buffer, state_length)));
(ParserStates::HeaderTitle, 0)
},
(ParserStates::HeaderTitle, '\n') => (ParserStates::Complete, 1),
(ParserStates::HeaderTitle, ':') => {
let header_title = try!(self.read_value(&mut buffer, state_length)).to_uppercase();
(ParserStates::HeaderContent{title: header_title}, 0)
},
(ParserStates::HeaderContent{title}, '\n') =>
(ParserStates::HeadersNewLine{title: title}, state_length + 1),
(ParserStates::HeadersNewLine{title}, ' ') | (ParserStates::HeadersNewLine{title}, '\t') => {
(ParserStates::HeaderContent{title: title}, state_length + 2)
},
(ParserStates::HeadersNewLine{title}, '\n') => {
let header_value = vec![try!(self.read_value(&mut buffer, state_length))];
self.headers.insert(title, header_value);
(ParserStates::Complete, 0)
},
(ParserStates::HeadersNewLine{title}, '\r') => {
let header_value = vec![try!(self.read_value(&mut buffer, state_length))];
self.headers.insert(title, header_value);
(ParserStates::EndHeaders, 0)
},
(ParserStates::HeadersNewLine{title}, _) => {
let header_value = vec![try!(self.read_value(&mut buffer, state_length - 1))];
self.headers.insert(title, header_value);
(ParserStates::HeaderTitle, 0)
},
(ParserStates::EndHeaders, '\n') => (ParserStates::Complete, 0),
(ParserStates::EndHeaders, character) => panic!("Malformed headers {:?}", character),
(state, _) => (state, state_length + 1)
};
if next_state == ParserStates::Complete {
match self.build() {
Ok(request) =>
match request.method {
HttpMethod::HTTP2 => return Ok(HttpResult::Http2Upgrade{buffer: buffer, request: request}),
_ => return Ok(HttpResult::Http1Request{buffer: buffer, request: request})
},
Err(err) =>
return Err(err)
}
}
mem::replace(&mut self.state, next_state);
state_length = next_length;
}
if state_length>0{
println!("Storing {} leftover bytes", state_length);
let mut temporary_data = &mut self.temporary_data;
temporary_data.reserve(state_length);
let current_length = temporary_data.len();
unsafe{temporary_data.set_len(current_length + state_length);}
buffer.reset();
buffer.read_slice(&mut temporary_data);
}
Ok(HttpResult::Http1Incomplete{buffer: buffer.flip(), request_builder: self})
}
}
impl HttpRequest {
}
#[cfg(test)]
mod tests {
use bytes::ByteBuf;
use super::HttpRequestBuilder;
use super::HttpMethod;
use super::HttpResult;
#[test]
fn test_http_request_builder() {
let buffer = ByteBuf::from_slice("GET / HTTP\n".as_bytes());
let request_builder = HttpRequestBuilder::new();
match request_builder.parse(buffer) {
Ok(HttpResult::Http1Incomplete{request_builder, ..}) => {
assert_eq!(Ok(HttpMethod::GET), request_builder.method);
assert_eq!("/", request_builder.path.unwrap());
assert_eq!("HTTP", request_builder.version.unwrap());
},
_ => panic!("Expected Http1Incomplete")
}
}
#[test]
fn test_http_request_builder_post() {
let buffer = ByteBuf::from_slice("POST / HTTP\n".as_bytes());
let request_builder = HttpRequestBuilder::new();
match request_builder.parse(buffer) {
Ok(HttpResult::Http1Incomplete{request_builder, ..}) => {
assert_eq!(Ok(HttpMethod::POST), request_builder.method);
assert_eq!("/", request_builder.path.unwrap());
assert_eq!("HTTP", request_builder.version.unwrap());
}
_ => panic!("Expected Http1Incomplete")
}
}
#[test]
fn test_http_request_builder_complete_state() {
let mut buffer = ByteBuf::mut_with_capacity(2048);
buffer.write_slice("GET ".as_bytes());
let request_builder = HttpRequestBuilder::new();
match request_builder.parse(buffer.flip()) {
Ok(HttpResult::Http1Incomplete{mut buffer, request_builder}) => {
buffer.write_slice("/ HTTP\n".as_bytes());
match request_builder.parse(buffer.flip()) {
Ok(HttpResult::Http1Incomplete{ request_builder, .. }) => {
assert_eq!(Ok(HttpMethod::GET), request_builder.method);
assert_eq!("/", request_builder.path.unwrap());
assert_eq!("HTTP", request_builder.version.unwrap());
}
_ => panic!("Expected Http1Incomplete")
}
},
_ => panic!("Expected Http1Incomplete")
}
}
#[test]
fn test_http_request_builder_incomplete_state() {
let mut buffer = ByteBuf::mut_with_capacity(2048);
buffer.write_slice("GET".as_bytes());
let request_builder = HttpRequestBuilder::new();
match request_builder.parse(buffer.flip()) {
Ok(HttpResult::Http1Incomplete{mut buffer, request_builder}) => {
buffer.write_slice(" / H".as_bytes());
match request_builder.parse(buffer.flip()) {
Ok(HttpResult::Http1Incomplete{mut buffer, request_builder}) => {
buffer.write_slice("TTP\r\n".as_bytes());
match request_builder.parse(buffer.flip()) {
Ok(HttpResult::Http1Incomplete{request_builder, ..}) => {
assert_eq!(Ok(HttpMethod::GET), request_builder.method);
assert_eq!("/", request_builder.path.unwrap());
assert_eq!("HTTP", request_builder.version.unwrap());
}
_ => panic!("Expected Http1Incomplete")
}
}
_ => panic!("Expected Http1Incomplete")
}
}
_ => panic!("Expected Http1Incomplete")
}
}
#[test]
fn test_http_request_builder_header() {
let buffer = ByteBuf::from_slice("GET / HTTP 1.1\r\nContent-Type: application/json\n\n".as_bytes());
let request_builder = HttpRequestBuilder::new();
match request_builder.parse(buffer) {
Ok(HttpResult::Http1Request{request, ..}) => assert_eq!(request.headers["CONTENT-TYPE"], vec!["application/json"]),
_ => panic!("Expected Http1Request")
}
}
#[test]
fn test_http_request_builder_header_return() {
let buffer = ByteBuf::from_slice("GET / HTTP 1.1\nContent-Type: application/json\n\r\n".as_bytes());
let request_builder = HttpRequestBuilder::new();
match request_builder.parse(buffer) {
Ok(HttpResult::Http1Request{request, ..}) => assert_eq!(request.headers["CONTENT-TYPE"], vec!["application/json"]),
_ => panic!("Expected Http1Request")
}
}
#[test]
fn test_http_request_builder_two_headers() {
let buffer = ByteBuf::from_slice("GET / HTTP 1.1\nContent-Type: application/json\nContent-Length:128\r\n\n".as_bytes());
let request_builder = HttpRequestBuilder::new();
match request_builder.parse(buffer) {
Ok(HttpResult::Http1Request{request, ..}) => {
assert_eq!(request.headers["CONTENT-TYPE"], vec!["application/json"]);
assert_eq!(request.headers["CONTENT-LENGTH"], vec!["128"]);
}
_ => panic!("Expected Http1Request")
}
}
#[test]
fn test_http_request_builder_http2_upgrade() {
let buffer = ByteBuf::from_slice("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n".as_bytes());
let request_builder = HttpRequestBuilder::new();
match request_builder.parse(buffer) {
Ok(HttpResult::Http2Upgrade{..}) => (),
_ => panic!("Expected Http2Upgrade")
}
}
}
<file_sep>extern crate mio;
#[test]
fn it_works() {
print!("Hi");
print!("Hi");
}
<file_sep>#![feature(unboxed_closures, fnbox, drain, core)]
extern crate mio;
extern crate bytes;
extern crate core;
#[macro_use]
extern crate log;
extern crate threadpool;
mod request;
mod processor;
mod promises;
use mio::*;
use mio::tcp::*;
use mio::util::Slab;
use bytes::{ByteBuf, MutByteBuf};
use std::io;
use std::mem;
use request::HttpResult;
const SERVER : Token = Token(0);
struct HttpConnection {
sock: TcpStream,
buf: Option<ByteBuf>,
mut_buf: Option<MutByteBuf>,
token: Option<Token>,
interest: EventSet,
http_request: Option<request::HttpRequestBuilder>
}
impl HttpConnection {
fn new(sock: TcpStream) -> HttpConnection {
HttpConnection {
sock: sock,
buf: None,
mut_buf: Some(ByteBuf::mut_with_capacity(2048*8)),
token: None,
interest: EventSet::hup(),
http_request: Some(request::HttpRequestBuilder::new())
}
}
fn readable(&mut self, _: &mut EventLoop<HttpHandler>) -> io::Result<()> {
let mut buf = self.mut_buf.take().unwrap();
match self.sock.try_read_buf(&mut buf) {
Ok(None) => {
panic!("Received readable notification but was unable to read from socket");
}
Ok(Some(_)) => {
//Check if end of request
let read_buffer = buf.flip();
match mem::replace(&mut self.http_request, None) {
Some(http_request) =>
match http_request.parse(read_buffer) {
Ok(HttpResult::Http1Incomplete{buffer, request_builder}) => (),
_ => ()
},
None => ()
}
// if self.http_request.is_complete() {
// let request_token = match & self.token {
// &Some(token) => token.clone(),
// &None => panic!("No token assigned to port")
// };
//
// let mut http_request = request::HttpRequestBuilder::new();
// mem::swap(&mut self.http_request, &mut http_request);
// }
}
Err(e) => {
println!("Error encountered {:?}", e);
}
}
Ok(())
}
}
struct HttpServer {
sock: TcpListener,
conns: Slab<HttpConnection>
}
impl HttpServer {
fn accept(&mut self, event_loop: &mut EventLoop<HttpHandler>) -> io::Result<()> {
let sock = self.sock.accept().unwrap().unwrap();
let conn = HttpConnection::new(sock);
let tok = self.conns.insert(conn)
.ok().expect("Could not add connection to slab");
self.conns[tok].token = Some(tok);
event_loop.register_opt(&self.conns[tok].sock, tok, EventSet::readable(), PollOpt::edge() | PollOpt::oneshot()).ok().expect("Could not register socket with event loop");
Ok(())
}
fn conn_readable(&mut self, event_loop: &mut EventLoop<HttpHandler>, tok: Token) -> io::Result<()> {
self.conn(tok).readable(event_loop)
}
fn conn<'a>(&'a mut self, tok: Token) -> &'a mut HttpConnection {
&mut self.conns[tok]
}
}
struct HttpHandler {
server: HttpServer
}
impl HttpHandler {
fn new(srv: TcpListener) -> HttpHandler {
HttpHandler {
server: HttpServer {
sock: srv,
conns: Slab::new_starting_at(Token(1), 128)
}
}
}
}
impl Handler for HttpHandler {
type Timeout = ();
type Message = ();
fn ready(&mut self, event_loop: &mut EventLoop<HttpHandler>, token: Token, events:EventSet) {
if events.is_readable() {
match token {
SERVER => self.server.accept(event_loop).unwrap(),
i => self.server.conn_readable(event_loop, i).unwrap()
}
}
}
}
fn main() {
start();
}
fn start() {
println!("Starting event loop");
let addr = "127.0.0.1:8080".parse().unwrap();
let server = TcpListener::bind(&addr).unwrap();
let mut event_loop = EventLoop::new().unwrap();
event_loop.register(&server, SERVER).unwrap();
let mut handler = HttpHandler::new(server);
event_loop.run(&mut handler).unwrap();
}
<file_sep>use std::error::Error;
use std::boxed::FnBox;
use std::sync::mpsc::{Receiver, Sender, RecvError, channel};
#[derive(Clone)]
pub enum ExecutionContext {
ImmediateContext
}
impl ExecutionContext {
fn execute<F>(&self, f: F) where F : FnOnce() {
match &self {
&ImmediateContext => {
f();
}
}
}
}
struct PromiseFactory {
execution_context: ExecutionContext
}
pub fn incomplete<A>() -> Promise<A>{
PromiseFactory{execution_context: ExecutionContext::ImmediateContext}.incomplete()
}
pub fn completed<A>(a: Result<A, Box<Error>>) -> Promise<A> {
PromiseFactory{execution_context: ExecutionContext::ImmediateContext}.completed(a)
}
impl PromiseFactory {
pub fn incomplete<A>(&self) -> Promise<A> {
Promise{
data: None,
success_callbacks: Vec::with_capacity(1),
failure_callbacks: Vec::with_capacity(1),
execution_context: self.execution_context.clone()
}
}
pub fn completed<A>(&self, a: Result<A, Box<Error>>) -> Promise<A> {
Promise{
data: Some(a),
success_callbacks: Vec::with_capacity(1),
failure_callbacks: Vec::with_capacity(1),
execution_context: self.execution_context.clone()
}
}
}
struct Promise<A: Sized> {
data: Option<Result<A, Box<Error>>>,
success_callbacks: Vec<Box<FnBox(&A)>>,
failure_callbacks : Vec<Box<FnBox(&Error)>>,
execution_context: ExecutionContext
}
impl <A:Sized> Promise<A> {
pub fn success<F>(&mut self, on_success: F) where F: FnOnce(&A)->() + Send + 'static {
match self.data {
Some(Ok(ref d)) => {
on_success(d)
},
Some(Err(_))=> (),
None => {
self.success_callbacks.push(Box::new(on_success))
}
}
}
pub fn failure<F>(&mut self, on_failure: F) where F: FnOnce(&Error) + Send + 'static {
match self.data {
Some(Err(ref e)) => {
let error = & **e;
on_failure(error)
},
Some(Ok(_)) => (),
None => {
self.failure_callbacks.push(Box::new(on_failure))
}
}
}
pub fn complete(&mut self, a: A) {
let callbacks = self.success_callbacks.len();
let range = 0 .. callbacks;
for f in self.success_callbacks.drain(range) {
f.call_once((&a,))
}
self.data = Some(Ok(a));
}
pub fn fail(&mut self, err: Box<Error>) {
let callbacks = self.failure_callbacks.len();
let range = 0 .. callbacks;
print!("Invoking error callback {:?}", callbacks);
for f in self.failure_callbacks.drain(range) {
let error_pointer = & * err;
f.call_once((error_pointer,))
}
self.data = Some(Err(err));
}
pub fn map<F,B>(&mut self, map: F) -> Promise<B> where
F : FnOnce(&A) -> B + Send + 'static,
B : Send {
let mut p = incomplete();
self.success(move |a| {
p.complete(map(a))
});
p
}
}
#[cfg(test)]
mod test {
use super::Promise;
use std::error::Error;
use std::sync::mpsc::{Receiver, Sender, RecvError, channel};
use std::fmt::{Display, Formatter};
use core::fmt::Error as FmtError;
#[derive(Debug)]
struct TestError;
impl Error for TestError { fn description(&self) -> &'static str {"Error"} }
impl Display for TestError {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { Ok(()) }
}
#[test]
fn test_promise_complete() {
let mut promise = Promise::incomplete();
let (tx, rx): (Sender<i32>, Receiver<i32>) = channel();
promise.success(move |d| {
tx.send((*d) + 1);
()
});
promise.complete(1);
assert_eq!(rx.recv().unwrap(), 2);
}
#[test]
fn test_promise_immediately_completed() {
let mut promise = Promise::completed(Ok(1));
let (tx, rx): (Sender<i32>, Receiver<i32>) = channel();
promise.success(move |d| {
tx.send((*d) + 1);
()
});
assert_eq!(rx.recv().unwrap(), 2);
}
#[test]
fn test_promise_failed_immediate() {
let mut promise : Promise<u32> = Promise::completed(Err(Box::new(TestError)));
let (tx, rx): (Sender<String>, Receiver<String>) = channel();
promise.failure(move |err: &Error| {
tx.send(String::from(err.description()));
()
});
assert_eq!(rx.recv().unwrap(), "Error");
}
#[test]
fn test_promise_fail() {
let mut promise : Promise<u32> = Promise::incomplete();
let (tx, rx): (Sender<String>, Receiver<String>) = channel();
promise.failure(move |err: &Error| {
println!("Failing");
tx.send(String::from(err.description()));
()
});
promise.fail(Box::new(TestError));
assert_eq!(rx.recv().unwrap(), "Error");
}
#[test]
fn test_promise_map() {
let mut promise : Promise<u32> = Promise::incomplete();
let (tx, rx): (Sender<String>, Receiver<String>) = channel();
promise.failure(move |err: &Error| {
println!("Failing");
tx.send(String::from(err.description()));
()
});
promise.fail(Box::new(TestError));
assert_eq!(rx.recv().unwrap(), "Error");
}
}
<file_sep>use threadpool::ThreadPool;
use promises::Promise;
use bytes::ByteBuf;
enum JobResult<A> {
Sync {data: A},
Async {data: Promise<A>}
}
struct EventProcessor {
pool: ThreadPool
}
impl EventProcessor {
fn new(cores: usize) -> EventProcessor {
EventProcessor {
pool: ThreadPool::new(cores)
}
}
fn execute_sync<F, A, B>(&self, job:F, acceptor: A)
where F : FnOnce() -> JobResult<B> + Send + 'static ,
A : FnMut(B),
B : Send {
self.pool.execute(move || {
match job() {
JobResult::Sync{..} => println!("Sync result"),
JobResult::Async{..} => println!("Async result")
}
});
}
}
#[cfg(test)]
mod test {
use super::EventProcessor;
use super::JobResult;
use bytes::ByteBuf;
#[test]
fn test_sync_result() {
let processor = EventProcessor::new(1);
processor.execute_sync(move || {println!("Hello World"); JobResult::Sync{data: ByteBuf::new(1)}},
|result| {println!("Wow")})
}
}
<file_sep># mio-http
Http adapters for Rust MIO
<file_sep>[package]
name = "http"
version = "0.1.0"
authors = ["michael"]
[dependencies]
mio = "0.4.1"
slab = "0.1.2"
bytes = "0.2.10"
log = "0.3.1"
threadpool = "0.1.4"
| 2a328e1785ded391f8c619c0d90aa4c21f47f77b | [
"Markdown",
"Rust",
"TOML"
] | 7 | Rust | Myrannas/mio-http | e972e81bb1ba3feaeb007c9d81f05c99f96b56a4 | 752c24d39f5e35f15e5037a22154fe8ab3a5ce0d |
refs/heads/master | <file_sep>package pl.edu.uj.dusinski.dao;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.data.annotation.Id;
import javax.annotation.concurrent.Immutable;
@Immutable
public class AirportDetails {
@Id
private final String id;
private final String code;
private final String name;
private final String fullName;
private final String description;
private final Airline airline;
@JsonCreator
public AirportDetails(@JsonProperty("name") String name,
@JsonProperty("full") String fullName,
@JsonProperty("description") String description,
@JsonProperty("code") String code,
@JsonProperty("airline") Airline airline) {
this.id = code + airline.getValue();
this.name = name;
this.fullName = fullName;
this.description = description;
this.code = code;
this.airline = airline;
}
public Airline getAirline() {
return airline;
}
public String getName() {
return name;
}
public String getFullName() {
return fullName;
}
public String getDescription() {
return description;
}
public String getCode() {
return code;
}
public String getId() {
return id;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AirportDetails that = (AirportDetails) o;
return new EqualsBuilder()
.append(id, that.id)
.append(code, that.code)
.append(name, that.name)
.append(fullName, that.fullName)
.append(description, that.description)
.append(airline, that.airline)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(id)
.append(code)
.append(name)
.append(fullName)
.append(description)
.append(airline)
.toHashCode();
}
}
<file_sep>package pl.edu.uj.dusinski;
import java.time.LocalDate;
import java.util.List;
public class FlightDetailsData {
private final List<Fare> fares;
public FlightDetailsData(List<Fare> fares) {
this.fares = fares;
}
public List<Fare> getFares() {
return fares;
}
public static class Fare {
private final FlightData outbound;
private final SummaryData summary;
public Fare(FlightData outbound, SummaryData summary) {
this.outbound = outbound;
this.summary = summary;
}
public FlightData getOutbound() {
return outbound;
}
public SummaryData getSummary() {
return summary;
}
}
public static class SummaryData {
private final PriceData price;
public SummaryData(PriceData price) {
this.price = price;
}
public PriceData getPrice() {
return price;
}
}
public static class PriceData {
private final double value;
private final String currencyCode;
public PriceData(double value, String currencyCode) {
this.value = value;
this.currencyCode = currencyCode;
}
public double getValue() {
return value;
}
public String getCurrencyCode() {
return currencyCode;
}
}
public static class FlightData {
private final AirportData departureAirport;
private final AirportData arrivalAirport;
private final String departureDate;
public FlightData(AirportData departureAirport,
AirportData arrivalAirport,
String departureDate) {
this.departureAirport = departureAirport;
this.arrivalAirport = arrivalAirport;
this.departureDate = departureDate;
}
public AirportData getDepartureAirport() {
return departureAirport;
}
public AirportData getArrivalAirport() {
return arrivalAirport;
}
public LocalDate getDepartureDate() {
return LocalDate.parse(departureDate.substring(0, departureDate.indexOf('T')));
}
}
public static class AirportData {
private final String iataCode;
private AirportData(String iataCode) {
this.iataCode = iataCode;
}
public String getIataCode() {
return iataCode;
}
}
}
<file_sep>function startLoader() {
document.getElementById("page").style.display = "none";
document.getElementById('loader').style.display = '';
}<file_sep># Master degree work
<file_sep>package pl.edu.uj.dusinski;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import pl.edu.uj.dusinski.dao.AirportDetails;
import pl.edu.uj.dusinski.dao.Direction;
import pl.edu.uj.dusinski.dao.FlightDetails;
import pl.edu.uj.dusinski.services.AirportDetailsUpdaterService;
import pl.edu.uj.dusinski.services.DirectionUpdaterService;
import pl.edu.uj.dusinski.services.FlightDetailsUpdaterService;
@Component
public class JmsReceiver {
private static final Logger Log = LoggerFactory.getLogger(JmsReceiver.class);
private final DirectionUpdaterService directionUpdaterService;
private final AirportDetailsUpdaterService airportDetailsUpdaterService;
private final FlightDetailsUpdaterService flightDetailsUpdaterService;
@Autowired
public JmsReceiver(DirectionUpdaterService directionUpdaterService,
AirportDetailsUpdaterService airportDetailsUpdaterService,
FlightDetailsUpdaterService flightDetailsUpdaterService) {
this.directionUpdaterService = directionUpdaterService;
this.airportDetailsUpdaterService = airportDetailsUpdaterService;
this.flightDetailsUpdaterService = flightDetailsUpdaterService;
}
@JmsListener(destination = "directionQueue", containerFactory = "jmsListenerFactory")
public void receiveDirectionMessage(Direction direction) {
Log.debug("Received new direction {}", direction);
directionUpdaterService.saveNewDirections(direction);
}
@JmsListener(destination = "airportDetailsQueue", containerFactory = "jmsListenerFactory")
public void receiveAirportDetailsMessage(AirportDetails airportDetails) {
Log.debug("Received new airport details {}", airportDetails);
airportDetailsUpdaterService.updateAirportDetails(airportDetails);
}
@JmsListener(destination = "flightDetailsQueue", containerFactory = "jmsListenerFactory")
public void receiveFlightDetailsMessage(FlightDetails flightDetails) {
Log.debug("Received new flight details {}", flightDetails);
flightDetailsUpdaterService.updateFlightDetails(flightDetails);
}
}
<file_sep>package pl.edu.uj.dusinski.jpa;
import org.springframework.data.mongodb.repository.MongoRepository;
import pl.edu.uj.dusinski.dao.Airline;
import pl.edu.uj.dusinski.dao.Direction;
import java.util.List;
public interface DirectionRepository extends MongoRepository<Direction, String> {
List<Direction> findAllByAirline(Airline airline);
List<Direction> findByFromCode(String fromCode);
List<Direction> findByFromCodeAndToCode(String fromCode, String toCode);
}
<file_sep>package pl.edu.uj.dusinski.dao;
public class EnrichedFlightDetailsPair {
private final EnrichedFlightDetails from;
private final EnrichedFlightDetails to;
private final double totalPlnPrice;
public EnrichedFlightDetailsPair(EnrichedFlightDetails from,
EnrichedFlightDetails to) {
this.from = from;
this.to = to;
this.totalPlnPrice = from.getPlnPrice() + to.getPlnPrice();
}
public EnrichedFlightDetails getFrom() {
return from;
}
public EnrichedFlightDetails getTo() {
return to;
}
public double getTotalPlnPrice() {
return totalPlnPrice;
}
}
<file_sep>package pl.edu.uj.dusinski.services;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import pl.edu.uj.dusinski.dao.YahooCurrency;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
@EnableScheduling
public class CurrencyRatioProviderService implements Function<String, Double> {
private static final Logger Log = LoggerFactory.getLogger(CurrencyRatioProviderService.class);
private final RestTemplate restTemplate;
private final Map<String, Double> currencyRatio = new HashMap<>();
private final String yahooCurrencyApiUrl = "https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json";
private final Gson gson = new Gson();
private final int oneDayInMs = 24 * 60 * 60 * 1000;
@Autowired
public CurrencyRatioProviderService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Override
public Double apply(String currency) {
return currencyRatio.getOrDefault(currency, 1.0);
}
@Scheduled(fixedDelay = oneDayInMs)
public void updateCurrenciesRatio() {
Log.info("Updating currency ratio");
getYahooCurrencies();
Log.info("Updated {} currencies", currencyRatio.size());
}
private void getYahooCurrencies() {
try {
YahooCurrency yahooCurrencyResponse = gson.fromJson(
restTemplate.getForObject(yahooCurrencyApiUrl, String.class), YahooCurrency.class);
currencyRatio.putAll(getMissingCurrenciesWithPlnRatio(yahooCurrencyResponse));
} catch (Exception e) {
Log.error("Error during getting yahoo currencies, will try again in 10s", e);
try {
Thread.sleep(10_000);
} catch (InterruptedException e1) {
}
getYahooCurrencies();
}
}
private Map<String, Double> getMissingCurrenciesWithPlnRatio(YahooCurrency yahooCurrency) {
Map<String, String> usdRatioMap = yahooCurrency.getList().getResources().stream()
.filter(v -> v.getResource().getFields().getName() != null)
.map(v -> Map.entry(resolveCurrencyName(v.getResource().getFields().getName()),
v.getResource().getFields().getPrice()))
.filter(v -> v.getKey().length() == 3)
.distinct()
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
double usdPlnRatio = 1 / Double.valueOf(usdRatioMap.get("PLN"));
return usdRatioMap.entrySet().stream()
.map(entry -> Map.entry(entry.getKey(), getPlnInvertRatio(entry.getValue(), usdPlnRatio)))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
private double getPlnInvertRatio(String usdRatio, double usdPlnRatio) {
return 1 / (Double.valueOf(usdRatio) * usdPlnRatio);
}
private String resolveCurrencyName(String name) {
return name.replace("USD/", "");
}
}
<file_sep>package pl.edu.uj.dusinski.controllers;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pl.edu.uj.dusinski.dao.AirportDetails;
import pl.edu.uj.dusinski.jpa.AirportDetailsRepository;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@Controller
@RequestMapping("/airports")
public class AirportsProviderController {
private static final Logger Log = LoggerFactory.getLogger(AirportsProviderController.class);
private final AirportDetailsRepository airportDetailsRepository;
private final Gson gson = new Gson();
public AirportsProviderController(AirportDetailsRepository airportDetailsRepository) {
this.airportDetailsRepository = airportDetailsRepository;
}
@RequestMapping(value = "/getAllAirports", produces = "application/json;charset=UTF-8")
@ResponseBody
public String getAirportDetails() {
List<AirportDetails> airports = airportDetailsRepository.findAll();
Log.info("Returning all airport details");
return gson.toJson(airports.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList()));
}
}
<file_sep>server.port=8082
mongo.database.name=magisterka
jms.broker.url=tcp://localhost:61616<file_sep>package pl.edu.uj.dusinski.services;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import pl.edu.uj.dusinski.dao.Airline;
import pl.edu.uj.dusinski.dao.Direction;
import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;
import static pl.edu.uj.dusinski.dao.Airline.RYANAIR;
import static pl.edu.uj.dusinski.dao.Airline.WIZZAIR;
@Service
@EnableScheduling
public class DirectionsProviderService {
private static final Logger Log = LoggerFactory.getLogger(DirectionsProviderService.class);
private final RestTemplate restTemplate;
private final String databaseManagerUrl;
private final String directionUrl = "/directions/allDirections/";
private final Map<Airline, List<Direction>> airlineDirections = new HashMap<>();
private final long oneDayInMs = 24 * 60 * 60 * 1000;
private final Map<String, Direction> ryanairDirectionMap = new HashMap<>();
@Autowired
public DirectionsProviderService(RestTemplate restTemplate,
@Value("${database.manager.url}") String databaseManagerUrl) {
this.restTemplate = restTemplate;
this.databaseManagerUrl = databaseManagerUrl;
}
public List<Direction> getDirectionsFor(Airline airline) {
if (RYANAIR.equals(airline)) {
return new ArrayList<>(airlineDirections.get(airline).stream()
.collect(Collectors.toMap(Direction::getFromCode, v -> v, (v1, v2) -> v1))
.values());
}
return airlineDirections.getOrDefault(airline, Collections.emptyList());
}
public Direction getDirectionForRyanair(String codeFrom, String codeTo) {
return ryanairDirectionMap.get(codeFrom + codeTo);
}
@Scheduled(fixedDelay = oneDayInMs, initialDelay = oneDayInMs)
public void updateDirectionsOncePerDay() {
updateDirections();
}
@PostConstruct
public void updateDirections() {
updateDirections(WIZZAIR);
updateDirections(RYANAIR);
}
private void updateDirections(Airline airline) {
Log.info("Updating directions list for {}", airline);
try {
List<Direction> directions = Arrays.asList(restTemplate.getForObject(getUrlForAirline(airline), Direction[].class));
airlineDirections.put(airline, directions);
if (RYANAIR.equals(airline)) {
ryanairDirectionMap.putAll(directions.stream()
.collect(Collectors.toMap(k -> k.getFromCode() + k.getToCode(), v -> v)));
}
Log.info("There are {} different directions for {}", directions.size(), airline);
} catch (Exception e) {
Log.error("Cannot get wizziar directions, turn on database manager!");
try {
Thread.sleep(10_000);
} catch (InterruptedException e1) {
}
updateDirections();
}
}
private String getUrlForAirline(Airline airline) {
return databaseManagerUrl + directionUrl + airline.name();
}
}
<file_sep>server.port=8083
web.driver.instances=4
database.manager.url=http://localhost:8082
days.to.check=180
logging.level.pl.edu.uj.dusinski=info
task.timeout.seconds=75
jms.broker.url=tcp://localhost:61616<file_sep>package pl.edu.uj.dusinski.services;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import pl.edu.uj.dusinski.JmsPublisher;
import pl.edu.uj.dusinski.WebDriverMangerService;
import pl.edu.uj.dusinski.dao.Airline;
import pl.edu.uj.dusinski.dao.Direction;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import static pl.edu.uj.dusinski.dao.Airline.RYANAIR;
import static pl.edu.uj.dusinski.dao.Airline.WIZZAIR;
@Service
@EnableScheduling
public class FlightsDetailsFinderService {
private static final Logger Log = LoggerFactory.getLogger(FlightsDetailsFinderService.class);
private final DirectionsProviderService directionsProviderService;
private final WebDriverMangerService webDriverMangerService;
private final ExecutorService executorService;
private final JmsPublisher jmsPublisher;
private final int daysToCheck;
private static int submittedTask;
private static AtomicInteger doneTask = new AtomicInteger(0);
private final RestTemplate restTemplate;
private final int halfADayInMs = 12 * 60 * 60 * 1000;
private final int taskTimeoutMs;
@Autowired
public FlightsDetailsFinderService(DirectionsProviderService directionsProviderService,
WebDriverMangerService webDriverMangerService,
JmsPublisher jmsPublisher,
@Value("${web.driver.instances}") int webDriverInstances,
@Value("${days.to.check}") int daysToCheck,
RestTemplate restTemplate,
@Value("${task.timeout.seconds}") int taskTimeout) {
this.directionsProviderService = directionsProviderService;
this.webDriverMangerService = webDriverMangerService;
this.jmsPublisher = jmsPublisher;
this.executorService = Executors.newFixedThreadPool(webDriverInstances);
this.daysToCheck = daysToCheck;
this.restTemplate = restTemplate;
this.taskTimeoutMs = taskTimeout * 1000;
}
@Scheduled(fixedDelay = halfADayInMs)
public void findDirectionsDetails() {
findAllFlights(RYANAIR, WIZZAIR);
}
private void findAllFlights(Airline... airlines) {
List<Callable<Void>> tasks = new ArrayList<>();
for (Airline airline : airlines) {
List<Direction> directions = directionsProviderService.getDirectionsFor(airline);
Log.info("Adding {} {} directions to check", directions.size(), airline);
for (Direction direction : directions) {
tasks.add(createFindFlightTask(direction, airline));
}
}
submittedTask = tasks.size();
doneTask.set(0);
try {
executorService.invokeAll(tasks);
} catch (InterruptedException e) {
Log.error("Error during executing tasks", e);
}
}
private Callable<Void> createFindFlightTask(Direction direction, Airline airline) {
if (WIZZAIR.equals(airline)) {
return new FindFlightsTaskWizzair(webDriverMangerService, jmsPublisher, direction, daysToCheck, taskTimeoutMs);
}
return new FindFlightsTaskRyanair(restTemplate, jmsPublisher, direction, daysToCheck, directionsProviderService);
}
static void logTaskFinished() {
Log.info("{}/{} directions are checked", doneTask.incrementAndGet(), submittedTask);
}
}
<file_sep>server.port=8081
web.driver.instances=1
database.manager.url=http://localhost:8082
jms.broker.url=tcp://localhost:61616<file_sep>package pl.edu.uj.dusinski;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import pl.edu.uj.dusinski.dao.AirportDetails;
import pl.edu.uj.dusinski.dao.Direction;
@Component
@EnableScheduling
public class JmsPublisher {
private static final Logger Log = LoggerFactory.getLogger(JmsPublisher.class);
private final JmsTemplate jmsTemplate;
@Autowired
public JmsPublisher(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
}
public void publishAirportDetails(AirportDetails airportDetails) {
Log.info("Publishing new airport details {}", airportDetails.getId());
jmsTemplate.convertAndSend("airportDetailsQueue", airportDetails);
}
public void publishDirection(Direction direction) {
Log.info("Publishing new direction {}", direction.getId());
jmsTemplate.convertAndSend("directionQueue", direction);
}
}
<file_sep>server.port=8080
database.manager.url=http://localhost:8082
max.shown.flight=50<file_sep>package pl.edu.uj.dusinski.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import pl.edu.uj.dusinski.dao.*;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
public class FlightDataChooserService {
private final FlightDataProviderService flightDataProviderService;
private final Function<FlightDetails, EnrichedFlightDetails> flightEnricher;
private final int maxShownFlight;
@Autowired
public FlightDataChooserService(FlightDataProviderService flightDataProviderService,
PlnCurrencyConverterService plnConverterService,
FlightsUrlGeneratorService urlGeneratorService,
@Value("${max.shown.flight:50}") int maxShownFlight) {
this.maxShownFlight = maxShownFlight;
this.flightDataProviderService = flightDataProviderService;
this.flightEnricher = v -> new EnrichedFlightDetails(v,
plnConverterService.apply(v.getCurrency(), v.getOriginalPrice()),
urlGeneratorService.apply(v),
getAirportBasedOnCode(v.getDirection().getFromCode(), v.getDirection().getAirline()),
getAirportBasedOnCode(v.getDirection().getToCode(), v.getDirection().getAirline()));
}
public Object getBestDealsForRequest(FlightDetailsRequest flightDetailsRequest) {
if (flightDetailsRequest.isBothWay()) {
List<FlightDetailsBothWay> bothWaysFlightDetails = flightDataProviderService.getBothWaysFlightDetails(flightDetailsRequest);
return bothWaysFlightDetails.stream()
.map(v -> new EnrichedFlightDetailsPair(flightEnricher.apply(v.getFrom()), flightEnricher.apply(v.getTo())))
.sorted(Comparator.comparingDouble(EnrichedFlightDetailsPair::getTotalPlnPrice))
.limit(maxShownFlight)
.collect(Collectors.toList());
} else {
Set<FlightDetails> detailsForRequest = flightDataProviderService.getOneWayFlightDetails(flightDetailsRequest);
return detailsForRequest.stream()
.map(flightEnricher)
.sorted(Comparator.comparingDouble(EnrichedFlightDetails::getPlnPrice))
.limit(maxShownFlight)
.collect(Collectors.toList());
}
}
private AirportDetails getAirportBasedOnCode(String fromCode, Airline airline) {
return flightDataProviderService.getAirportDetails(fromCode + airline.getValue());
}
}
<file_sep>package pl.edu.uj.dusinski.dao;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class FlightDetailsBothWay {
private final FlightDetails from;
private final FlightDetails to;
@JsonCreator
public FlightDetailsBothWay(@JsonProperty("from") FlightDetails from,
@JsonProperty("to") FlightDetails to) {
this.from = from;
this.to = to;
}
public FlightDetails getFrom() {
return from;
}
public FlightDetails getTo() {
return to;
}
}
<file_sep>package pl.edu.uj.dusinski;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import pl.edu.uj.dusinski.config.JmsConfiguration;
@SpringBootApplication
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = JmsConfiguration.class))
public class FlightManagerApplication {
public static void main(String[] args) {
SpringApplication.run(FlightManagerApplication.class);
}
}
<file_sep>package pl.edu.uj.dusinski.services;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;
import pl.edu.uj.dusinski.FlightDetailsData;
import pl.edu.uj.dusinski.JmsPublisher;
import pl.edu.uj.dusinski.dao.Direction;
import pl.edu.uj.dusinski.dao.FlightDetails;
import java.time.LocalDate;
import java.util.concurrent.Callable;
import static pl.edu.uj.dusinski.dao.Airline.RYANAIR;
import static pl.edu.uj.dusinski.services.FlightsDetailsFinderService.logTaskFinished;
public class FindFlightsTaskRyanair implements Callable<Void> {
private static final Logger Log = LoggerFactory.getLogger(FindFlightsTaskRyanair.class);
private final JmsPublisher jmsPublisher;
private final Direction direction;
private final int daysToCheck;
private final RestTemplate restTemplate;
private final String RYANAIR_FLIGHTS_URL = "https://api.ryanair.com/farefinder/3/oneWayFares?&departureAirportIataCode=%s&outboundDepartureDateFrom=%s&outboundDepartureDateTo=%s";
private final Gson gson = new Gson();
private final DirectionsProviderService directionsProviderService;
public FindFlightsTaskRyanair(RestTemplate restTemplate,
JmsPublisher jmsPublisher, Direction direction,
int daysToCheck,
DirectionsProviderService directionsProviderService) {
this.restTemplate = restTemplate;
this.jmsPublisher = jmsPublisher;
this.direction = direction;
this.daysToCheck = daysToCheck;
this.directionsProviderService = directionsProviderService;
}
@Override
public Void call() {
int weeksToCheck = (int) Math.ceil(daysToCheck / 7.0);
int publishedFlights = 0;
for (int i = 0; i < weeksToCheck; i++) {
FlightDetailsData flightDetailsData = gson.fromJson(restTemplate.getForObject(prepareUrl(direction, i), String.class), FlightDetailsData.class);
flightDetailsData.getFares().stream()
.map(this::mapToFlightDetails)
.forEach(jmsPublisher::publishNewFlightDetails);
publishedFlights += flightDetailsData.getFares().size();
}
Log.info("Published {} flight details for {}", publishedFlights, direction.getFromCode());
logTaskFinished();
return null;
}
private FlightDetails mapToFlightDetails(FlightDetailsData.Fare v) {
String fromCode = v.getOutbound().getDepartureAirport().getIataCode();
String toCode = v.getOutbound().getArrivalAirport().getIataCode();
return new FlightDetails(fromCode + toCode + RYANAIR + v.getOutbound().getDepartureDate().toString(),
v.getOutbound().getDepartureDate(), directionsProviderService.getDirectionForRyanair(fromCode, toCode),
v.getSummary().getPrice().getValue(), v.getSummary().getPrice().getCurrencyCode());
}
private String prepareUrl(Direction direction, int i) {
return String.format(RYANAIR_FLIGHTS_URL, direction.getFromCode(),
LocalDate.now().plusDays(1).plusWeeks(i),
LocalDate.now().plusDays(1).plusMonths(1).plusWeeks(i));
}
}
<file_sep>package pl.edu.uj.dusinski.controllers;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pl.edu.uj.dusinski.dao.Airline;
import pl.edu.uj.dusinski.dao.Direction;
import pl.edu.uj.dusinski.jpa.DirectionRepository;
import java.util.Collections;
import java.util.List;
@Controller
@RequestMapping("/directions")
public class DirectionsProviderController {
private static final Logger Log = LoggerFactory.getLogger(DirectionsProviderController.class);
private final DirectionRepository directionRepository;
private final Gson gson = new Gson();
public DirectionsProviderController(DirectionRepository directionRepository) {
this.directionRepository = directionRepository;
}
@RequestMapping(value = "/allDirections/{airline}", produces = "application/json;charset=UTF-8")
@ResponseBody
public String getAllDirectionFor(@PathVariable("airline") Airline airline) {
List<Direction> directions = directionRepository.findAllByAirline(airline);
if (directions.isEmpty()) {
return gson.toJson(Collections.emptyList());
}
Log.info("Returning {} directions", directions.size());
return gson.toJson(directions);
}
}
<file_sep>package pl.edu.uj.dusinski;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jms.annotation.EnableJms;
@SpringBootApplication
@EnableJms
public class CrawlerApplication {
public static void main(String[] args) {
SpringApplication.run(CrawlerApplication.class);
}
}
<file_sep>package pl.edu.uj.dusinski.services;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import pl.edu.uj.dusinski.dao.*;
import java.lang.reflect.Type;
import java.text.Collator;
import java.util.*;
import java.util.stream.Collectors;
@Service
@EnableScheduling
public class FlightDataProviderService {
private static final Logger Log = LoggerFactory.getLogger(FlightDataProviderService.class);
private static final int HOUR_IN_MS = 60 * 60 * 1000;
private final RestTemplate restTemplate;
private final List<AirportDetails> directionFromWhereFlyTo = new ArrayList<>();
private final Map<String, AirportDetails> idAirportsMap = new HashMap<>();
private final String databaseManagerUrl;
private final String flyFromUrl = "/flights/flyFrom";
private final String flyGetDirectionsUrl = "/flights/getDirections/";
private final String airportsUrl = "/airports/getAllAirports";
private final String flightsDetailsUrl = "/flights/flightDetails";
private final Gson gson = new Gson();
private final Type flightDetailsType = new TypeToken<Set<FlightDetails>>() {
}.getType();
private final Collator collator = Collator.getInstance(new Locale("pl", "PL"));
@Autowired
public FlightDataProviderService(RestTemplate restTemplate,
@Value("${database.manager.url}") String databaseManagerUrl) {
this.restTemplate = restTemplate;
this.databaseManagerUrl = databaseManagerUrl;
}
@Scheduled(fixedDelay = HOUR_IN_MS)
public void updateDirectionsFromFlyToAndAirports() throws InterruptedException {
try {
AirportDetails[] fromDirection = gson.fromJson(restTemplate.getForObject(databaseManagerUrl + flyFromUrl, String.class), AirportDetails[].class);
if (fromDirection != null && fromDirection.length > 0) {
directionFromWhereFlyTo.clear();
List<AirportDetails> directions = Arrays.stream(fromDirection)
.sorted((v1, v2) -> collator.compare(v1.getName(), v2.getName()))
.collect(Collectors.toList());
directionFromWhereFlyTo.addAll(directions);
Log.info("Updated {} directions from which can fly", fromDirection.length);
}
AirportDetails[] allAirports = gson.fromJson(restTemplate.getForObject(databaseManagerUrl + airportsUrl, String.class), AirportDetails[].class);
if (allAirports != null && allAirports.length > 0) {
idAirportsMap.clear();
idAirportsMap.putAll(Arrays.stream(allAirports)
.collect(Collectors.toMap(AirportDetails::getId, v -> v)));
}
} catch (Exception e) {
Log.error("Error during getting fly from list, probably database manager is not running, trying again in 10s", e);
Thread.sleep(10_000);
updateDirectionsFromFlyToAndAirports();
}
}
public List<AirportDetails> getAirportsForDirection(String direction) {
try {
Direction[] flyToDirection = gson.fromJson(restTemplate.getForObject(databaseManagerUrl + flyGetDirectionsUrl + direction, String.class), Direction[].class);
if (flyToDirection != null && flyToDirection.length > 0) {
return Arrays.stream(flyToDirection)
.map(v -> getAirportDetails(v.getToCode() + v.getAirline()))
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
return Collections.emptyList();
} catch (Exception e) {
Log.error("Error during getting fly to direction list, probably database manager is not running", e);
return Collections.emptyList();
}
}
public AirportDetails getAirportDetails(String id) {
return idAirportsMap.get(id);
}
public List<AirportDetails> getDirectionFromWhereFlyTo() {
return directionFromWhereFlyTo;
}
public Set<FlightDetails> getOneWayFlightDetails(FlightDetailsRequest flightDetailsRequest) {
try {
String json = getFlightDetailsFromRequestAsJson(flightDetailsRequest);
return gson.fromJson(json, flightDetailsType);
} catch (Exception e) {
Log.error("Error during getting airport details, probably database manager is not running", e);
}
return Collections.emptySet();
}
public List<FlightDetailsBothWay> getBothWaysFlightDetails(FlightDetailsRequest flightDetailsRequest) {
try {
String json = getFlightDetailsFromRequestAsJson(flightDetailsRequest);
return gson.fromJson(json, new TypeToken<List<FlightDetailsBothWay>>() {
}.getType());
} catch (Exception e) {
Log.error("Error during getting airport details, probably database manager is not running", e);
}
return Collections.emptyList();
}
private String getFlightDetailsFromRequestAsJson(FlightDetailsRequest flightDetailsRequest) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(flightDetailsRequest.toString(), headers);
return restTemplate.postForEntity(databaseManagerUrl + flightsDetailsUrl, entity, String.class).getBody();
}
}
<file_sep>package pl.edu.uj.dusinski.services;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class DirectionsUtils {
private static final int WAIT_TIMEOUT = 30;
private DirectionsUtils() {
}
public static void waitUntilElementIsReady(WebDriver driver, By by) {
new WebDriverWait(driver, WAIT_TIMEOUT)
.until(ExpectedConditions.elementToBeClickable(by));
}
}
<file_sep>package pl.edu.uj.dusinski;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DirectionManagerConfiguration {
@Value("${web.driver.instances}")
private int webDriverInstances;
@Bean
public WebDriverMangerService webDriverMangerService() {
return new WebDriverMangerService(webDriverInstances);
}
}
| 17bc36e1ff3f6511fb050aa61822c2579c9a4554 | [
"JavaScript",
"Java",
"Markdown",
"INI"
] | 25 | Java | dusiu/magisterka | eebda4844fb2695ef4ccb1e8f572d1552173031b | 6d46a276a6621c07ccaeb6a9f3cf83ee273d920b |
refs/heads/master | <repo_name>Leap-Of-Code/course-0-assignment-10-v1<file_sep>/fix-code-0/main.cpp
#include <iostream>
#include <string>
using namespace std;
struct Point {float x; float y; float z; float w;}
int main() {
Point position;
position.x = .3;
position.y = .6;
position.z = 1.6;
position.w = -.56;
const float manhattan_distance = position.x + position.y + position.z + position.w;
cout << "The points manhattan distance is: " << manhattan_distance;
return 0;
}
<file_sep>/fix-code-2/main.cpp
#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
unsigned int age;
unsigned int gpa;
}
int main() {
Student my_student;
cout << "What is your students name: ";
cin >> my_student.name;
cout << "What is your students age: ";
cin >> my_student.age;
cout << "What is your heros gpa: ";
cin >> my_student.gpa;
cout << "You have enrolled student: " << my_student << endl;
cout << "The students is " << age << "years old." << endl;
cout << "The student has a gpa of: " << gpa << endl;
return 0;
}
<file_sep>/invent-code-2/main.cpp
#include <iostream>
#include <string>
using namespace std;
struct Fraction{
// Write code here
}
int main() {
// Write code here.
}
<file_sep>/invent-code-1/main.cpp
#include <iostream>
#include <string>
using namespace std;
// ------------------- DO NOT CHANGE THIS IN THIS SECTION -------------------
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
/* Category Types:
* 1: Shopping
* 2: Transportation
* 3: Other
*/
struct Purchase {
unsigned int category; // A category as described above.
int amount; // The cost of the purchase.
};
struct Budget {
unsigned int category; // A category as described above.
int limit; // The maximum amount available for the specified category.
};
/* Prints out a budget in a human readable foramt.
* Args:
* budget: A Budget Type to Print.
*/
void Print(Budget budget) {
if (budget.category == 1) {
cout << "Shopping: ";
} else if (budget.category == 2) {
cout << "Transportation: ";
} else if (budget.category == 3) {
cout << "Other: ";
} else {
cout << "Error Invalid Category! ";
}
cout << '$' << budget.limit;
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
Budget FromUser() {
Budget budget;
cin << budget.category;
cin << budget.limit;
return budget;
}
Purchase FromUser() {
Purchase item;
cin << item.category;
cin << item.limit;
return item;
}
// ------------------- DO NOT CHANGE CODE IN THIS SECTION -------------------
// ----------------------- Updating comments is ok. -------------------------
// --------------------------------------------------------------------------
/* The comment for this function is removed, try to understand what this
* function does by reading it. Once you understand, you are welcome to update
* this comment to help you remember.
*/
void BudgetStatus(Budget budget, int total_spent) {
cout << "Budget ";
Print(budget);
if (total_spent < budget.limit) {
cout << " And you remained within your budget!";
} else {
cout << " You blew the budget!";
}
cout << endl;
}
/* The comment for this function is removed, try to understand what this
* function does by reading it. Once you understand, you are welcome to update
* this comment to help you remember. Feel free to add comments before lines in
* the code below as well.
*/
int main() {
cout << "Enter a limit for shopping category" << endl;
Budget limit_shopping = GetBudgetFromUser(1);
Print(limit_shopping);
cout << endl;
cout << "Enter a limit for transportation category" << endl;
Budget limit_transportation = GetBudgetFromUser(2);
Print(limit_transportation);
cout << endl;
cout << "Enter a limit for other category" << endl;
Budget limit_other = GetBudgetFromUser(3);
Print(limit_other);
cout << endl;
Purchase item0 = GetPurchaseFromUser();
Print(item0);
Purchase item1 = GetPurchaseFromUser();
Print(item1);
Purchase item2 = GetPurchaseFromUser();
Print(item2);
int total_other = GetTotalForCategory(limit_other.category, item0, item1, item2);
int total_shopping = GetTotalForCategory(limit_shopping.category, item0, item1, item2);
int total_transportation = GetTotalForCategory(limit_transportation.category, item0, item1, item2);
BudgetStatus(limit_other, total_other);
BudgetStatus(limit_shopping, total_shopping);
BudgetStatus(limit_transportation, total_transportation);
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
<file_sep>/fix-code-1/main.cpp
#include <iostream>
#include <string>
using namespace std;
struct Hero {
string name,
string title,
unsigned int age,
string weapon
}
int main() {
Hero my_hero;
cout << "What is your hero's name: ";
cin >> my_hero.name;
cout << "What is your hero's title: ";
cin >> my_hero.title;
cout << "What is your hero's age: ";
cin >> my_hero.age;
cout << "What is your hero's weapon of choice: "
cin >> my_hero.weapon;
return 0;
}
| c37244f36ae0c4b79ad0c473ec3306f6ee46b8f4 | [
"C++"
] | 5 | C++ | Leap-Of-Code/course-0-assignment-10-v1 | 2de7b06dcbc99bd23aa25ac2216b664e7adec72a | 277b692f2ea3cbdf661d8b2f6b630df821f56e28 |
refs/heads/master | <file_sep>//
// Category.swift
// Todoey
//
// Created by <NAME> on 04/10/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
import RealmSwift
class Category : Object {
@objc dynamic var name : String = ""
@objc dynamic var categoryColor : String = ""
let items = List<Item>()
}
| ec608713fd3004a58341baaef48552fd15d56fcd | [
"Swift"
] | 1 | Swift | vishalvernekar/Todoey | 116e3858cd838c97f652a3c213c18d183dd7f2b7 | 19a62aa26f44217a99099ae158b4e164119197c2 |
refs/heads/master | <repo_name>finer04/wb-bk<file_sep>/app.py
import re,json
import config
import requests
from bs4 import BeautifulSoup
import threadpool
from collections import OrderedDict
allpiclen = 0
now_num = 0
def readhtml():
rawhtml = ''
with open(config.filename, 'rb') as f:
fraw = f.read()
f.close()
rawhtml = fraw.decode('UTF-8')
return rawhtml
class getallimg(object):
def __init__(self,rawhtml):
self.rawhtml = rawhtml
def find_html_img(self):
img_list = []
regex = re.compile(r'http://t[0-9].qpic.cn/mblogpic/[A-Fa-f0-9]*/[0-9]*')
tmp = re.findall(regex,rawhtml)
img_list = img_list + tmp
return list(set(img_list))
def downloadall(self,url):
global now_num
filename = '.'.join(url.split('/')[4:6]) + '.jpg'
now_num+=1
print(f'({now_num}/{allpiclen}) 正在下 {url} ')
try:
reponse = requests.get(url,timeout=10)
with open('img' + '/' + filename, 'wb') as f:
f.write(reponse.content)
complate_url = url
except requests.exceptions.RequestException as e:
print(f'{url} 下载失败')
failed_url = url
class wbhtml(object):
def __init__(self,rawhtml):
self.rawhtml = rawhtml
def analyzeitem(self):
itemdict = {}
soup = BeautifulSoup(rawhtml,'html5lib')
item = soup.find_all(name='div',attrs='item')
for i , items in enumerate(item):
def getdivtext(classname,work):
if work == 1:
item_tmp = items
if work == 2:
item_tmp = items.find('div',class_='repost-content')
tmp = item_tmp.find('div', class_=classname,recursive=False).text
return tmp
def imagediscovery():
srclist = []
tmp = items.find_all('img',class_="single-image")
for i in tmp:
a = i['src'].split('/')
fix_src = '.'.join(a[4:6]) + '.jpg'
srclist.append(fix_src)
return srclist
if i != -1:
tmp_list = {}
tmp_list['author_name'] = getdivtext('author-name',1)
tmp_list['weibo_date'] = getdivtext('date',1)
tmp_list['post_content'] = getdivtext('post',1)
if items.find('div',class_="repost-content"):
tmp_list['repost_content'] = {}
tmp_list['repost_content']['author_name'] = getdivtext('author-name',2)
tmp_list['repost_content']['weibo_date'] = getdivtext('date',2)
tmp_list['repost_content']['content'] = getdivtext('post',2)
tmp_list['repost_content']['image-container'] = imagediscovery()
else:
tmp_list['image-container'] = imagediscovery()
itemdict[i] = tmp_list
wbhtml.exportdata(self,itemdict)
def exportdata(self,dict1):
print('分析完毕,正在保存中...')
sort = OrderedDict(sorted(dict1.items(), key=lambda obj: obj[0]))
with open('weibo_data.json','w',encoding="utf8") as f:
json.dump(sort,f,indent=4,ensure_ascii=False)
if __name__ == '__main__':
#global allpiclen
print('读取中...')
rawhtml = readhtml()
img = getallimg(rawhtml)
wb = wbhtml(rawhtml)
urllist = img.find_html_img()
allpiclen = len(urllist)
print(f'一共有 {allpiclen} 张图片,开始爬取...')
# pool = threadpool.ThreadPool(config.threadsnum)
# request = threadpool.makeRequests(img.downloadall, urllist)
# [pool.putRequest(req) for req in request]
# pool.wait()
print('下载完毕,开始整理数据')
print('正在解析备份微博的内容')
wb.analyzeitem()
<file_sep>/config.py
# 配置文件
import os
# QQ号
qq_num = ''
filename = qq_num + '.html'
# 线程数量
threadsnum = 8 | 2ead32dd229e5d4a75db79806f9f484ff393dcde | [
"Python"
] | 2 | Python | finer04/wb-bk | d753869b25dc2c608337569733f885d108e16887 | f68a13586c1adbb7972c13089b8f615457f360c0 |
refs/heads/master | <file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Datastore extends Model
{
protected $fillable = [
'name',
'quantity',
'price_one',
'total',
'source',
'available',
'store_id'
];
public $timestamps = false;
public function store(){
return $this->belongsTo('App\Store');
}
public function adds(){
return $this->hasMany('App\Add');
}
public function returnes(){
return $this->hasMany('App\Returne');
}
public function covenants(){
return $this->hasMany('App\Covenant');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use PDF;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Datastore;
use App\Store;
class PDFController extends Controller
{
public function index(){
$data = Datastore::join('stores','datastores.store_id','=','stores.id')
->join('adds','datastores.id','=','adds.datastore_id')
->select('datastores.*','stores.name AS store_name','adds.source','adds.permision')
->get();
$stores = Store::all();
$arr = Array('data'=>$data,'stores'=>$stores);
$pdf = PDF::loadView('invoice', $arr)->setOptions([
'dpi' => 50,
'defaultFont' => 'Tahoma' ,
'isHtml5ParserEnabled'=>true
]);
return $pdf->download('store.pdf');
}
}
<file_sep>/*global $*/
/*===================================== template data =======================*/
var input1 = ["January", "February", "March", "April", "May", "June", "July"],
input2 = 'bar',
input3 = [[100,200,300,400,600,280],[450,1000,250,390,900,400,800],[333, 652, 208, 100,500,1200,1050
], [555,12,330,650,500,600,900] ],
input4 = ['مخزن الكهنه','مخزن الخامات','مخزن المستدم','مخزن المستهلك'],
input5 = 'canvas-stores-graph',
input6 = ["منتج 1", "منتح2", "منتج 3", "منتجات اخرى"],
input7 = 'line',
input9 =['مصرف','مدخل'] ,
input8 = [ [400,620,120,300 ],[ 500,440,240,280]],
input10 ='chart-area2',
myinput1 = 'doughnut',
myinput2 =[100,50,20,60],
myinput3 = ["منتح 1", "منتج 2","منتج 3","منتجات اخرى"],
myinput5 = "chart-area",
myinput4 = 'right';
/*background color */
var colorbackground = [ "rgba(50,200,52,0.4)",
"rgba(90,80,172,0.4)",
"rgba(20,50,250,0.6)",
'rgba(230,60,52,0.6)',
"rgba(20,200,152,0.6)"
];
/*=========================================================================*/
/*========================== load function =================================================*/
window.onload = function() {
make_char_line_bar(input1,input2,input3,input4,input5,false,true,'مخازن وعهد');/*cahar1*/
make_char_line_bar(input6,input7,input8,input9,input10,true,false,'ali');/*char 2*/
make_doughnut( myinput1, myinput2, myinput3, myinput4, myinput5, colorbackground);/*chart*/
};
/*
=============================================================
=================== function make_doughnut ==================
=============================================================
*/
/*
* type,data_set,labels_data_set,legend_postion,canvas_id,background_color
* and make doughnut for this data_set to labels_data_set
*/
function make_doughnut(type,data_set,labels_data_set,legend_postion,canvas_id,background_color)
{
if(data_set.length != labels_data_set.length)
{
alert('error in the length not equal the label input3 and input4 ')
return 0
}
var config = {
type: type,
data: {
datasets: [{
data: data_set,
backgroundColor: background_color,
label: 'Dataset 1'
}],
labels: labels_data_set
},
options: {
responsive: true,
legend: {
position: legend_postion,
},
title: {
display: false,
text: 'المتاح حاليا'
},
animation: {
animateScale: true,
animateRotate: true
}
}
};
var ctx2 = document.getElementById(canvas_id).getContext("2d");
/*window.myDoughnut*/var char2 = new Chart(ctx2, config);
}
/*
=============================================================
=================== function make_char_line_bar =============
=============================================================
*/
/*
* this function take the pamatera
* labels_char,type_char,datasets_char,label_datasets_char,id_canves,file_mode = false,
* display_log = false,log_label = 'مخازن وعهد'
* to maker bar states for the datasets for this label_datasets_char
*/
function make_char_line_bar(labels_char,type_char,datasets_char,label_datasets_char,id_canves,file_mode = false,display_log = false,log_label = 'مخازن وعهد')
{
if(datasets_char.length != label_datasets_char.length)
{
alert('error in the length not equal the label input3 and input4 ')
return 0
}
var chartData = {
labels: labels_char,
datasets: [{
type: type_char,
label: label_datasets_char[0],
backgroundColor:colorbackground[0],
borderColor: 'white',
borderWidth: 2,
fill: file_mode,
data: datasets_char[0]
}]
};
if(label_datasets_char.length > 1)
{
var flag = label_datasets_char.length - 1;
console.log(flag);
for(var i=1 ; i <= flag ; i++)
{
var x = {
type: type_char,
label: label_datasets_char[i],
borderColor: 'white',
backgroundColor:colorbackground[i],
borderWidth: 2,
fill: file_mode,
data: datasets_char[i]
}
chartData.datasets[i] = x;
}
}
var ctx = document.getElementById(id_canves).getContext("2d");
var cahr1 = new Chart(ctx, {
type: type_char,
data: chartData,
options: {
responsive: true,
title: {
display: display_log,
text: log_label
},
tooltips: {
mode: 'index',
intersect: true
}
}
});
}
/*============== end ===========================================*/
$(function () {
"use strict";
});<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Notify extends Model
{
protected $fillable = [
'notify',
'readed',
'user_id',
'requerd_num',
'store_id',
'person',
];
public function user(){
return $this->belongsTo('App\User');
}
public function store(){
return $this->belongsTo('App\Store');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Auth;
use App\Datastore;
use Illuminate\Support\Facades\Hash;
use App\Store;
use App\Add;
use App\Employee;
use App\History;
use App\Notify;
use App\Covenant;
class AdminController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function dashboard(){
$store1 = Add::join('datastores','adds.datastore_id','=','datastores.id')->where('datastores.store_id','=',2)->get();
$store2 = Add::join('datastores','adds.datastore_id','=','datastores.id')->where('datastores.store_id','=',3)->get();
$store3 = Add::join('datastores','adds.datastore_id','=','datastores.id')->where('datastores.store_id','=',4)->get();
$store4 = Add::join('datastores','adds.datastore_id','=','datastores.id')->where('datastores.store_id','=',5)->get();
$stores = Array(count($store1),count($store2),count($store3),count($store4));
$cov1 = Covenant::join('datastores','covenants.datastore_id','=','datastores.id')->where('datastores.store_id','=',2)->get();
$cov2 = Covenant::join('datastores','covenants.datastore_id','=','datastores.id')->where('datastores.store_id','=',2)->get();
$cov3 = Covenant::join('datastores','covenants.datastore_id','=','datastores.id')->where('datastores.store_id','=',2)->get();
$cov4 = Covenant::join('datastores','covenants.datastore_id','=','datastores.id')->where('datastores.store_id','=',2)->get();
$cov = Array(count($cov1),count($cov2),count($cov3),count($cov4));
$covenetNum =count(Employee::all());
$count = 5;
$userNum = count(User::all());
$storeNum = count(Store::all())-1;
$notifies = Notify::where('readed','=', 0 )->where('store_id','=',Auth::user()->store_id)->get();
if(Auth::user()->jop_id > 2 ){
return redirect('/');
}
$arr = Array(
'title' =>'الرئيسيه',
'stores'=>$stores,
'cov'=> $cov,
'covenetNum'=>$covenetNum,
'count'=>$count,
'userNum'=>$userNum,
'storeNum'=> $storeNum,
'notifies'=>$notifies,
) ;
return view('admin.dashboard',$arr);
}
public function chart(){
$notifies = Notify::where('readed','=', 0 )->where('store_id','=',Auth::user()->store_id)->get();
if(Auth::user()->jop_id > 2 ){
return redirect('/');
}
$arr = Array(
'title' =>'الاحصائيات',
'notifies'=> $notifies,
) ;
return view('admin.chart',$arr);
}
public function store(Request $req){
$notifies = Notify::where('readed','=', 0 )->where('store_id','=',Auth::user()->store_id)->get();
$store_id = Auth::user()->jop_id != 0 ? Auth::user()->store_id:'';
$data = Datastore::join('stores','datastores.store_id','=','stores.id')
->join('adds','datastores.id','=','adds.datastore_id')
->select('datastores.*','stores.name AS store_name','adds.source','adds.permision')
->where('store_id','LIKE','%' . $store_id . '%')
->get();
$stores = Store::where('id','>','1')->get();
if(Auth::user()->jop_id > 2 ){
return redirect('/');
}
$arr = Array(
'title' =>'المخازن',
'stores'=>$stores,
'data'=>$data,
'notifies'=>$notifies,
) ;
return view('admin.store',$arr);
}
public function users(){
$notifies = Notify::where('readed','=', 0 )->where('store_id','=',Auth::user()->store_id)->get();
$users = User::join('stores','users.store_id','=','stores.id')
->select('users.*','stores.name AS store_name')
->where('users.jop_id',"<=","2")->get();
$empty = "";
if(count($users)==0){
$empty = "عفوا هذه الصفحه لا توجد بها بيانات !";
}
if(Auth::user()->jop_id > 2 ){
return redirect('/');
}
$arr = Array(
'title' =>'الموظفين',
'empty'=>$empty,
'users'=>$users,
'notifies'=>$notifies,
) ;
return view('admin.users',$arr);
}
public function covenant(Request $req){
$notifies = Notify::where('readed','=', 0 )->where('store_id','=',Auth::user()->store_id)->get();
$items = Employee::all();
$empty = "";
if(count($items)==0){
$empty = "عفوا هذه الصفحه لا توجد بها بيانات !";
}
$arr = Array(
'title'=>'عهٌد',
'empty' =>$empty,
'items'=>$items,
'notifies'=> $notifies,
);
return view('admin.employee',$arr);
}
public function register(){
$notifies = Notify::where('readed','=', 0 )->where('store_id','=',Auth::user()->store_id)->get();
$stores = Store::where('id','!=','1')->get();
$arr = Array(
'title'=>'تسجيل',
'stores'=> $stores,
'notifies'=>$notifies,
);
return view('admin.registration',$arr);
}
public function registerUser(Request $req){
$this->validate($req,[
'firstname'=>'required|min:3',
'lastname'=>'required|min:3',
'username'=>'required|min:3',
'email'=>'required|min:6',
'jop_id'=>'required',
'password'=>'<PASSWORD>',
'phone'=>'required|min:11|max:11'
]);
if(!isset($req->store)){
$store = "1";
}else{
$store = $req->store;
}
$fullname = $req->firstname . " " . $req->lastname;
$newUser = new User();
$newUser->name = $fullname;
$newUser->email= $req->email;
$newUser->password = <PASSWORD>::<PASSWORD>($req->password);
$newUser->username =$req->username;
$newUser->jop_id = $req->jop_id;
$newUser->address = $req->address;
$newUser->store_id = $store;
$newUser->phone = $req->phone;
if($req->hasFile('imgfile')){
$imagename = time() . "." . $req->imgfile->getClientOriginalExtension();
$req->imgfile->move(public_path('uploaded'),$imagename);
$newUser->img = $imagename;
}
$newUser->save();
return redirect('/user');
}
public function editDatastore(Request $req){
$notifies = Notify::where('readed','=', 0 )->where('store_id','=',Auth::user()->store_id)->get();
$id = $req->get('id');
$stores = Store::where('id','!=',1)->get();
if(!empty(Datastore::find($id))){
$item = Add::join('datastores','adds.datastore_id' ,'=','datastores.id')
->join('stores','datastores.store_id','=','stores.id')
->select('adds.*','datastores.name','datastores.price','stores.name AS store_name','stores.id As store_id')
->where('datastores.id' ,'=',$id)->limit(1)
->get();
$arr = Array(
'title'=>'Edit',
'item'=>$item,
'stores'=>$stores,
'notifies'=> $notifies,
);
return view('admin.editstore',$arr);
}
return redirect('/');
}
public function saveDataChange(Request $req){
$this->validate($req,[
'name'=>'required|min:3',
'source'=>'required|min:4',
'quantity'=>'required',
'permision'=>'required',
'price'=>'required',
'store'=>'required',
]);
$user = User::find($req->user);
$store = Store::find($req->store);
// message for owner of store
if($user->jop_id == 2){
$hist = History::where('permision','=',$req->permision)->get();
// check if item already exist in the history table
if(count($hist) > 0){
$hist = $hist[0];
$hist->name = $req->name;
$hist->quantity = $req->quantity;
$hist->price = $req->price;
$hist->source = $req->source;
$hist->permision = $req->permision;
$hist->store_id = $req->store;
$hist->row_num = $req->itemid;
$hist->total = ($req->price * $req->quantity);
$hist->save();
}else{
$history = new History();
$history->name = $req->name;
$history->quantity = $req->quantity;
$history->price = $req->price;
$history->source = $req->source;
$history->permision = $req->permision;
$history->store_id = $req->store;
$history->row_num = $req->itemid;
$history->total = ($req->price * $req->quantity);
$history->save();
$history_id = History::where('permision','=',$req->permision)->get();
$msg = "تم التعديل علي مخزن " . $store->name . " من قبل " . $user->name . " لحفظ التعديل يرجي الموافقه ";
$notify = new Notify();
$notify->notify = $msg;
$notify->user_id = $req->user;
$notify->requerd_num = $req->itemid;
$notify->store_id = $req->store;
$notify->history_id = $history_id[0]->id;
$notify->save();
}
}else{
$add = Add::where('permision','=',$req->permision,'AND','datastore_id','=',$req->itemid)->limit(1)->get();
$add = Add::find($add[0]->id);
$item = Datastore::find($req->itemid);
$currQuantity = $item->quantity;
$item->name = $req->name;
$item->price = $req->price;
$item->quantity = ($currQuantity - $add->quantity)+ $req->quantity;
$item->save();
$item = Datastore::find($req->itemid);
$currQuantity = $item->quantity;
$item->total = $req->price * ($currQuantity);
$item->save();
$add->source = $req->source;
$add->quantity = $req->quantity;
$add->user_id = $req->user;
$add->save();
}
return redirect('/store');
}
public function magagenotify(Request $req){
$notifies = Notify::where('readed','=', 0 )->where('store_id','=',Auth::user()->store_id)->get();
$itemid = intval($req->get('itemid'));
$history = History::where('row_num','=',$itemid)->get();
if(count($history) == 0){
return redirect('/store');
}
$data = Datastore::join('stores','datastores.store_id','=','stores.id')
->join('adds','datastores.id','=','adds.datastore_id')
->select('datastores.*','stores.name AS store_name','adds.source','adds.permision','adds.quantity AS quant')
->where('datastores.id','=',$itemid)
->get();
$arr = Array(
'title'=> 'اشعارات',
'original'=>$data[0],
'history'=>$history[0],
'notifies'=> $notifies,
);
return view('admin.manageNotify',$arr);
}
public function editaction(Request $req){
if($req->input('action') == 'save'){
$history = History::find($req->input('history_id'));
$datastore = Datastore::find($history->row_num);
$adds = Add::where('permision','=',$history->permision)->get();
$adds = $adds[0];
$oldquantity = $adds->quantity;
$datastore->name = $history->name;
$datastore->price = $history->price;
$datastore->quantity = ((floatval($datastore->quantity) - floatval($oldquantity))+ floatval($history->quantity));
$datastore->save();
$datastore = Datastore::find($history->row_num);
$datastore->total = (floatval($datastore->price) * floatval($datastore->quantity));
$datastore->save();
$adds->source = $history->source;
$adds->quantity = $history->quantity;
$adds->save();
}
$notify = Notify::where('history_id','=',$req->input('history_id'));
$notify->delete();
$history = History::find($req->input('history_id'));
$history->delete();
return redirect('/store');
}
public function modifyuser(Request $req){
$id = $req->get('id');
$chk = User::find($id);
if(count($chk) == 0){
return redirect('/dashboard');
}
if(Auth::user()->id == $id || Auth::user()->jop_id == 0){
$notifies = Notify::where('readed','=', 0 )->where('store_id','=',Auth::user()->store_id)->get();
$user = User::find($id);
$stores = Store::where('id','!=',0)->get();
$arr = Array(
'title'=> 'تعديل',
'notifies' => $notifies,
'user' => $user,
'stores'=>$stores,
);
return view('admin.edituser',$arr);
}else{
return redirect('/dashboard');
}
}
public function profile(Request $req)
{
$notifies = Notify::where('readed','=', 0 )->where('store_id','=',Auth::user()->store_id)->get();
$id = intval($req->get('id'));
$user = User::join('stores','stores.id','=','users.store_id')
->select('users.*','stores.name AS store_name')
->where('users.id','=',$id)
->get();
if(count($user) == 0){
return redirect('/dashboard');
}
$arr = Array(
'title'=>'مستخدم',
'user'=> $user[0],
'notifies'=>$notifies,
);
return view('admin.profile',$arr);
}
}
<file_sep>/* global $, alert ,window */
$(function() {
'use strict';
if ($('#notify').text() == "") {
$('#notify').hide();
} else {
$('#notify').show();
}
$('body').on('click', '.confirm', function() {
var text = $(this).data('class');
return confirm('هل انت متاكد من حذف ( ' + text + ' ) ؟')
});
$('.aside-ul > li').each(function() {
$(this).click(function() {
if ($(this).hasClass('selected')) {
$(this).next('ul').slideUp(300);
$(this).removeClass('selected');
} else {
$(this).addClass('selected').siblings().removeClass('selected');
if ($(this).hasClass('selected')) {
$('ul.open').slideUp();
$(this).next('ul').slideDown(300);
}
}
});
});
$("#datepicker").datepicker({
inline: true,
showButtonPanel: true,
autoSize: true,
});
$('.aside').css({
'height': $(window).height(),
});
$(window).resize(function() {
$('.aside').css({
'height': $(window).height(),
})
});
$('.notification').click(function() {
$(this).children('.notify').hide();
});
function readURL(input, $seleector) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$($seleector).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("input[type='file']").change(function() {
readURL(this, '.preview');
});
$('#jop').change(function() {
if ($(this).val() > 0) {
$('#store').show(600);
} else {
$('#store').hide(600);
}
});
$('.mytable').niceScroll();
$('.selectbox').selectBoxIt();
});<file_sep><?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'username',
'jop_id',
'img',
'address',
'phone',
'store_id',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function store(){
return $this->belongsTo('App\Store');
}
public function adds(){
return $this->hasMany('App\Add');
}
public function returnes(){
return $this->hasMany('App\Returne');
}
public function covenants(){
return $this->hasMany('App\Covenant');
}
public function notifys(){
return $this->hasMany('App\Notify');
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
protected $fillable = [
'name',
'email',
'ssn',
'establishment',
];
public function returnes(){
return $this->hasMany('App\Returne');
}
public function covenants(){
return $this->hasMany('App\Covenant');
}
}
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Auth::routes();
/*************************** Dashboard ***************************/
Route::get('/dashboard', 'AdminController@dashboard')->name('dashboard');
Route::get('/chart', 'AdminController@chart')->name('chart');
Route::get('/user', 'AdminController@users')->name('user');
Route::get('/store', 'AdminController@store')->name('store');
Route::get('/covenant', 'AdminController@covenant')->name('covenant');
Route::get('/register','AdminController@register')->name('register');
Route::post('/register','AdminController@registerUser');
Route::get('/edit','AdminController@editDatastore')->name('edit');
Route::post('/edit','AdminController@saveDataChange');
Route::get('/pdf','PDFController@index');
Route::get('/manage','AdminController@magagenotify');
Route::post('/editaction','AdminController@editaction');
Route::get('/modify','AdminController@modifyuser');
Route::get('/profile','AdminController@profile');
/*******************************Ajax controller**********************/
Route::post('/user', 'AjaxController@user');
Route::post('/store','AjaxController@datastorenotify');
Route::post('/storetype','AjaxController@storetype');
Route::get('/notification','AjaxController@notifyheader');
/******************************************************************/
Route::get('/', function () {
return view('welcome');
});
Route::get('/home', 'HomeController@index')->name('home');
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use \Illuminate\Support\Facades\Auth;
use App\User;
use App\Store;
use App\Notify;
use App\Datastore;
class AjaxController extends Controller
{
public function datastorenotify(Request $req){
$item = isset($req->item)?$req->item:'';
$mystore = intval($req->store);
$data = "";
if($mystore == 1){
$data = Datastore::join('stores','datastores.store_id','=','stores.id')
->join('adds','datastores.id','=','adds.datastore_id')
->select('datastores.*','stores.name AS store_name','stores.id AS store_id','adds.source','adds.permision')
->where('datastores.name','LIKE','%'. $item .'%')
->get();
}else{
$data = Datastore::join('stores','datastores.store_id','=','stores.id')
->join('adds','datastores.id','=','adds.datastore_id')
->select('datastores.*','stores.name AS store_name','stores.id AS store_id','adds.source','adds.permision')
->where('datastores.name','LIKE','%'. $item .'%')
->where('datastores.store_id','=',$mystore)
->get();
}
$role = Auth::user()->store_id;
$arr = Array(
'role'=>$role,
'data'=>$data);
return $arr;
}
public function storetype(Request $req){
$data = "";
if(intval($req->text) > 1 && intval($req->text) <=5){
$data = Datastore::join('stores','datastores.store_id','=','stores.id')
->join('adds','datastores.id','=','adds.datastore_id')
->select('datastores.*','stores.name AS store_name','stores.id AS store_id','adds.source','adds.permision')
->where('datastores.store_id','=',$req->text)
->where('datastores.name','LIKE','%' . $req->item . '%')
->get();
}elseif(intval($req->text) == 1){
$data = Datastore::join('stores','datastores.store_id','=','stores.id')
->join('adds','datastores.id','=','adds.datastore_id')
->select('datastores.*','stores.name AS store_name','stores.id AS store_id','adds.source','adds.permision')
->where('datastores.name','LIKE','%' . $req->item . '%')
->get();
}
$role = Auth::user()->store_id;
$arr = Array(
'role'=>$role,
'data'=>$data);
return $arr;
}
public function notifyheader(Request $req){
$notify = Notify::where('readed','=', 0 )->where('store_id','=',Auth::user()->store_id)->get();
$count = count($notify);
if($count != $req->count){
return Array('notify'=>$notify,'count'=>$count);
}
return;
}
public function user(Request $req){
$users = User::join('stores','users.store_id','=','stores.id')
->select('users.*','stores.name AS store_name')
->where('users.name','LIKE','%' .$req->user . '%')->get();
return $users;
}
}
| fbb40ea625634065d2b72c1b8812d68adc87dcc7 | [
"JavaScript",
"PHP"
] | 10 | PHP | AhmedAbuHussein/Store | 1eb3512f625abd3bb9326f01026ebbd8ff3e2352 | 4cf698f1efbd837b08dbd1f8be334e3021e7512a |
refs/heads/master | <file_sep># <NAME>
# HDip Data Analytics 2019 pands-project
#
# class-separation.py
# Script to read in and analyse the iris data set
# How well separated are the species?
# ###########################################################
# Import Pandas data analysis library.
import pandas as pd
# Import matplotlib for 2D plotting.
import matplotlib.pyplot as plt
# Import Seaborn
import seaborn as sb
# Read the iris.csv file from this directory.
data = pd.read_csv('iris.csv')
# print(data.head())
d_shape = data.shape
print("n rows = ", d_shape[0], ", n_cols = ", d_shape[1] )
# What are the column labels of the DataFrame?
col_labels = data.columns
print("Data column labels: ", col_labels)
# List the unique values in data['Name'] column i.ie species.
# Need these for histogram legend.
species = data.Name.unique()
print("The three species are: ", species)
# ###########################################################
# Histogram of SepalLength for all species.
# There's only one legend, so I have to get the 3 species names into it in legend handle.
data.groupby('Name')['SepalLength'].hist(bins=10, alpha=0.5, stacked=True)
plt.title('SepalLength', fontsize=18)
plt.xlabel('cm', fontsize=16)
plt.ylabel('Count', fontsize=16)
plt.legend((species), loc='best', fontsize=12)
plt.savefig('Hist_SepalLength.jpeg')
plt.show()
# Histogram of SepalWidth for all species.
data.groupby('Name')['SepalWidth'].hist(bins=10, alpha=0.5, stacked=True)
plt.title('SepalWidth', fontsize=18)
plt.xlabel('cm', fontsize=16)
plt.ylabel('Count', fontsize=16)
plt.legend((species), loc='best', fontsize=12)
plt.savefig('Hist_SepalWidth.jpeg')
plt.show()
# Histogram of PetalLength for all species.
data.groupby('Name')['PetalLength'].hist(bins=10, alpha=0.5, stacked=True)
plt.title('PetalLength', fontsize=18)
plt.xlabel('cm', fontsize=16)
plt.ylabel('Count', fontsize=16)
plt.legend((species), loc='best', fontsize=12)
plt.savefig('Hist_PetalLength.jpeg')
plt.show()
# Histogram of PetalWidth for all species.
data.groupby('Name')['PetalWidth'].hist(bins=10, alpha=0.5, stacked=True)
plt.title('PetalWidth', fontsize=18)
plt.xlabel('cm', fontsize=16)
plt.ylabel('Count', fontsize=16)
plt.legend((species), loc='best', fontsize=12)
plt.savefig('Hist_PetalWidth.jpeg')
plt.show()
# ###########################################################
# Plot all four histograms in one figure using subplot.
# Edit legend for these small graphs.
# Leave out some x and y axes titles to avoid crowding.
plt.subplot(2,2,1)
data.groupby('Name')['SepalLength'].hist(bins=10, alpha=0.5, stacked=True)
plt.title('SepalLength', fontsize=12)
#plt.xlabel('cm', fontsize=10)
plt.ylabel('Count', fontsize=10)
plt.legend((species), loc='best', fontsize=10, fancybox=True, framealpha=0.5)
plt.subplot(2,2,2)
data.groupby('Name')['SepalWidth'].hist(bins=10, alpha=0.5, stacked=True)
plt.title('SepalWidth', fontsize=12)
#plt.xlabel('cm', fontsize=10)
#plt.ylabel('Count', fontsize=10)
plt.legend((species), loc='best', fontsize=10, fancybox=True, framealpha=0.5)
plt.subplot(2,2,3)
data.groupby('Name')['PetalLength'].hist(bins=10, alpha=0.5, stacked=True)
plt.title('PetalLength', fontsize=12)
plt.xlabel('cm', fontsize=10)
plt.ylabel('Count', fontsize=10)
plt.legend((species), loc='best', fontsize=10, fancybox=True, framealpha=0.5)
plt.subplot(2,2,4)
data.groupby('Name')['PetalWidth'].hist(bins=10, alpha=0.5, stacked=True)
plt.title('PetalWidth', fontsize=12)
plt.xlabel('cm', fontsize=10)
#plt.ylabel('Count', fontsize=10)
plt.legend((species), loc='best', fontsize=10, fancybox=True, framealpha=0.5)
# To avoid title and x axis labels overlapping in the subplot.
plt.tight_layout()
plt.savefig('Hist_4attributes.jpeg')
plt.show()
# ###########################################################
# Try Seaborn swarmplot as a cooler way to investigate species differences.
# Slightly modified from https://seaborn.pydata.org/examples/
# scatterplot_categorical.html?highlight=iris%20swarmplot
# style options are: darkgrid, whitegrid, dark, white, ticks
# palette options are: deep, muted, bright, pastel, dark, colorblind
sb.set(style="whitegrid", palette="pastel")
# "Melt" the dataset to "long-form" or "tidy" representation.
# Make "Name" the identifier variable and all other columns just measurements.
iris = pd.melt(data, "Name", var_name="measurement")
# Draw a categorical scatterplot to show each observation.
# Now plot measurements on y axis.
# Each "Name" has a different colour.
# Points are adjusted along categorical (x) axis so that they don't overlap.
# Each sepcies is coloured as in histograms above for easy comparison.
sb.swarmplot(x="measurement", y="value", hue="Name", data=iris)
plt.savefig('SwarmPlot.jpeg')
plt.show()
<file_sep># <NAME>
# HDip Data Analytics 2019 pands-project
#
# get-data.py
# Script to read in & analyse the iris data set.
#
# ###########################################################
# Import Pandas data analysis library.
import pandas as pd
# Import matplotlib for 2D plotting.
import matplotlib.pyplot as plt
# Import Numpy
import numpy as np
# Read the iris.csv file from this directory.
# The result is a DataFrame, the basic data format for Pandas.
data = pd.read_csv('iris.csv')
# ###########################################################
# Look at various attributes of the data to get an idea of its structure.
# General information about the data set.
print(data.info())
# Print the first few lines.
print(data.head())
# What are the data types of each column?
print(data.dtypes)
# What is the number of rows, columns in the data set?
d_shape = data.shape
print("n rows = ", d_shape[0], ", n_cols = ", d_shape[1] )
# What are the row labels of the DataFrame?
print("Data index: ", data.index)
# What are the column labels of the DataFrame?
col_labels = data.columns
print("Data column labels: ", col_labels)
# List the unique values in data['Name'] column i.ie species.
species = data.Name.unique()
print("The three species are: ", species)
# These are the column headings.
print("col1: ", col_labels[0])
print("col2: ", col_labels[1])
print("col3: ", col_labels[2])
print("col4: ", col_labels[3])
print("col5: ", col_labels[4])
# ###########################################################
# Try some plotting. I want each column as a line.
# Keep track of axes so they can be used several times.
ax = plt.gca()
# Plot each column of the data set as a different colour.
data[col_labels[0]].plot(kind='line', y= 'SepalLength', ax=ax)
data[col_labels[1]].plot(kind='line', y= 'SepalWidth', color='green', ax=ax)
data[col_labels[2]].plot(kind='line', y= 'PetalLength', color='red', ax=ax)
data[col_labels[3]].plot(kind='line', y= 'PetalWidth', color='yellow', ax=ax)
# Set x range.
plt.xlim(0, 150)
# Set the x tick marks.
x = np.arange(0, 150, 25)
plt.xticks(x)
# Graph, x-axis, and y-axis titles.
plt.title("Overview of the Iris Data Set", fontsize=18)
plt.ylabel('cm', fontsize=16)
plt.xlabel('sample', fontsize=16)
# Graph legend and grid
plt.legend(loc='best', fontsize=10)
plt.grid()
# Save the figure.
plt.savefig('Overview.jpeg')
plt.show()
# ###########################################################
# Use describe() to get some basic statistics about each column.
# It would make more sense to get this information for each species,
# but I'll start with this.
# print(data[col_labels[0]].describe())
# print(data[col_labels[1]].describe())
# print(data[col_labels[2]].describe())
# print(data[col_labels[3]].describe())
# print(data[col_labels[4]].describe())
# Or do all the numeric columns together, the output is another dataframe.
data_summary = data.describe()
print(data_summary)
# ###########################################################
# Plot these summary statistics as a bar chart.
# Omits count row by selecting all but first row of summary statistics dataframe.
data_summary.iloc[1:8,0:4].plot.bar()
# Set up graph properties.
plt.title("Summary statistics: all species", fontsize=18)
plt.ylabel('cm', fontsize=16)
plt.legend(loc='best', fontsize=10)
plt.grid()
# Save the figure.
plt.savefig('SummaryStats.jpeg')
plt.show()<file_sep># Setting up repository.<file_sep># <NAME>
# HDip Data Analytics 2019 pands-project
#
# class-separation.py
# Script to read in and analyse the iris data set
# How are the variables related to each other?
# ###########################################################
# Import Pandas data analysis library.
import pandas as pd
# Import matplotlib for 2D plotting.
import matplotlib.pyplot as plt
# Import Numpy
import numpy as np
# Import Seaborn
import seaborn as sb
# Read the iris.csv file from this directory.
data = pd.read_csv('iris.csv')
# ###########################################################
# Pandas scatter matrix to see how the variables are related - or not.
# Needed this to avoid a FutureWarning related to location of plotting module.
# Note that all species are plotted in same colour.
from pandas.plotting import scatter_matrix
pd.plotting.scatter_matrix(data, alpha=0.8)
plt.savefig('ScatterMatrix_Pandas.jpeg')
plt.show()
# ###########################################################
# Seaborn scatter matrix via pairplot.
# Each "Name" has a different colours so species can be differentiated.
# Stick to the colour palette I've already used in histograms etc.
sb.set(style="ticks", palette="pastel")
sb.pairplot(data, hue="Name", diag_kind='hist')
plt.savefig('ScatterMatrix_Seaborn.jpeg')
plt.show()
# ###########################################################
# Try linear regression on some combinations of variables.
# Adapted from : https://seaborn.pydata.org/examples/multiple_regression.html?highlight=iris%20data%20set
# Example plots Sepal length on x, Sepal width on y. Check I get same plot before trying other variables.
# sb.set()
# # Plot sepal_width as a function of sepal_length
# g = sb.lmplot(x="SepalLength", y="SepalWidth", hue="Name", \
# truncate=True, height=5, data=data)
# # Use more informative axis labels than are provided by default
# g.set_axis_labels("Sepal length (mm)", "Sepal width (mm)")
# plt.show()
# Plot PetalLength as a function of PetalWidth
# Leave out hue="Name" as want to fit data from all species to same line.
sb.set(palette="muted")
g = sb.lmplot(x="PetalWidth", y="PetalLength", truncate=True, height=5, data=data)
plt.title('PetalLength vs PetalWidth', fontsize=12)
g.set_axis_labels("PetalWidth (mm)", "PetalLength (mm)")
plt.savefig('PetalLvW_Seaborn.jpeg')
plt.show()
# Plot PetalWidth as a function of PetalLength
g = sb.lmplot(x="PetalLength", y="PetalWidth", truncate=True, height=5, data=data)
plt.title('PetalWidth vs PetalLength', fontsize=12)
g.set_axis_labels("PetalLength (mm)", "PetalWidth (mm)")
#plt.savefig('PetalWvL_Seaborn.jpeg')
plt.show()
# Do one with hue parameter set to show difference.
g = sb.lmplot(x="PetalLength", y="PetalWidth", hue="Name", truncate=True, height=5, data=data)
plt.title('PetalWidth vs PetalLength fn(species)', fontsize=12)
g.set_axis_labels("PetalLength (mm)", "PetalWidth (mm)")
plt.savefig('Sep_PetalWvL_Seaborn.jpeg')
plt.show()
# ###########################################################
# Try some LSQ fitting using the statsmodels package.
# model=OLS, method=fit OLS=Ordinary Least Squares
# model = sm.OLS(y, X)
#import statsmodels.api as sm
import statsmodels.api as sm
# Ordinary least squares regression: y = m*x
model_Simple = sm.OLS(data['PetalWidth'], data['PetalLength']).fit()
print("Fit pars: ", model_Simple.params)
print("R2 : ", model_Simple.rsquared)
print(model_Simple.summary())
# Add a constant term to OLS fit: y = m*x + c
model = sm.OLS(data['PetalWidth'], sm.add_constant(data['PetalLength'])).fit()
print("Fit pars: ", model.params)
print("R2: ", model.rsquared)
print("Fit summary: ", model.summary())
# Calculate best fit line using the fitting parameters, for a range of integar x values.
xmax = np.ceil((max(data['PetalLength'])))
x = np.arange(0, xmax + 1, 1)
PW_fitSimple = x * model_Simple.params.PetalLength
PW_fit = x * model.params.PetalLength + model.params.const
# Plot the data and fit together.
plt.plot(data['PetalLength'], data['PetalWidth'], 'bo')
plt.plot(x, PW_fitSimple, 'g-')
plt.plot(x, PW_fit, 'r')
plt.xticks(x)
plt.grid(b=True, which='major', axis='both')
plt.title("OLS fit Petal Width vs Length", fontsize=18)
plt.ylabel('Petal Width (cm)', fontsize=16)
plt.xlabel('Petal Length (cm)', fontsize=16)
plt.legend(('Data', 'Simple fit', 'Fit'))
# Save the figure.
plt.savefig('OLSfit_PWvL.jpeg')
plt.show()
<file_sep># <NAME>
# HDip Data Analytics 2019 pands-project
#
# machine-learning.py
# Script to read in and analyse the iris data set
# Try some machine learning using Linear Discriminant Analysis
# ###########################################################
# Code taken from: https://scikit-learn.org/stable/auto_examples/
# decomposition/plot_pca_vs_lda.html#sphx-glr-auto-examples-decomposition-plot-pca-vs-lda-py
# Explanation here: http://sebastianraschka.com/Articles/2014_python_lda.html#lda-via-scikit-learn
# Import Pandas data analysis library.
import pandas as pd
# Import matplotlib for 2D plotting.
import matplotlib.pyplot as plt
# Import Numpy
import numpy as np
# Import Seaborn
import seaborn as sb
# Import scikit-learn
from sklearn import datasets
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
# ###########################################################
iris = datasets.load_iris()
# X is the 2D numpy array containing variable values.
X = iris.data
# y is the 1D numpy array of species names as integers (0,1,2) rather than strings.
y = iris.target
print("Training data X has ", X.ndim, "dimensions and shape ", X.shape)
print("target values y has ", y.ndim, "dimensions and shape ", y.shape)
target_names = iris.target_names
print("target_names: ", target_names)
lda = LinearDiscriminantAnalysis(n_components=2)
X_r2 = lda.fit(X, y).transform(X)
print("LDA 2 components has ", X_r2.ndim, "dimensions and shape ", X_r2.shape)
# ###########################################################
plt.figure()
colors = ['blue', 'orange', 'green']
# Plot each column of X_r2 while keeping track of the species.
for color, i, target_name in zip(colors, [0, 1, 2], target_names):
plt.scatter(X_r2[y == i, 0], X_r2[y == i, 1], alpha=.5, color=color, label=target_name)
plt.legend(loc='best', shadow=False, scatterpoints=1)
plt.grid()
plt.title('LDA of Iris dataset (n_components=2)')
plt.xlabel('LD1')
plt.ylabel('LD2')
plt.savefig('LDA_iris.jpeg')
plt.show()
# ###########################################################
# Try the same thing with n_components=1 in lda
lda1 = LinearDiscriminantAnalysis(n_components=1)
X_r1 = lda1.fit(X, y).transform(X)
print("LDA 1 component has ", X_r1.ndim, "dimensions and shape ", X_r1.shape)
plt.figure()
colors = ['blue', 'orange', 'green']
for color, i, target_name in zip(colors, [0, 1, 2], target_names):
plt.plot(X_r1[y == i], alpha=.5, marker='o', linestyle='None', color=color, label=target_name)
plt.legend(loc='best', shadow=False, scatterpoints=1)
plt.grid()
plt.title('LDA of Iris dataset (n_components=1)')
plt.xlabel('Data point')
plt.ylabel('LD1')
plt.savefig('LDA(1cmpt)_iris.jpeg')
plt.show()
<file_sep># pands-project
## <NAME>
### January-April 2019
### HDip Data Analytics 2019 Programming and Scripting Project
Git-hub repository at:
https://github.com/elizabethdaly/pands-project.git

# The Fisher Iris Data Set
# Table of contents
1. [Introduction](#introduction)
1. [<NAME>](#introRF)
2. [Exploratory data analysis](#EDA)
3. [Description of the data set](#datadescription)
2. [Initial analysis of the full data set](#paragraph2)
1. [Plotting the full data set](#plotall)
2. [Descriptive statistics of the full data set](#statsall)
3. [Seperate the data into distinct species](#paragraph3)
1. [Summary statistics for each species](#statsperspecies)
2. [Boxplots](#boxp)
4. [Discriminating between species](#paragraph4)
1. [Histograms of variable values](#histall)
2. [Swarmplot of variable values](#swarmall)
5. [Relationships between variables](#paragraph5)
1. [Scatter matrix](#scatter)
2. [Linear regression in Seaborn](#linregSB)
3. [Least squares fitting using statsmodels](#lsq)
6. [Work done by other people on the Iris data set](#others)
1. [Machine learning](#machinelearning)
2. [Example of Linear Discriminant Analysis](#LDA)
7. [Conclusion](#conclusion)
8. [List of Python scripts](#scripts)
9. [References](#references)
## Introduction <a name="introduction"></a>
### <NAME> <a name="introRF"></a>
Sir <NAME> (1890-1962) was a British statistician and biologist who is best known for his work in the application of statistics to the design of scientific experiments. Following undergraduate study in mathematics at the University of Cambridge, he remained there for postgraduate work in physics, including the theory of errors. He continued his research in statistics over the next few years while working in various jobs. In 1919 he became the statistician at the Rothamsted Experimental Station in Hertfordshire, where he had access to huge amounts of agricultural data. Here, he developed and applied statistical methods to the design of plant breeding experiments in order to get maximum useful information from the experiments while minimizing time, effort, and money. He held academic positions at University College London and Cambridge University before retiring to Australia, where he died in 1962. During his career he published many articles and books on various topics in statistics and genetics, including the method of maximum likelihood estimation and the analysis of variance.
Fisher introduced the Iris flower data set and the linear discriminent analysis (LDA) in a 1936 publication. LDA is a method to reduce the number of dimensions in data sets in order to perform pattern classification or machine learning. As the MathWorks reference below states, if one has a data set containing observations with measurements on many variables and their known classes, could this data be used to determne which class measurements from new observations are most likely to belong to? It seems to be a popular data set for demonstrating how to perform classification and for providing training sets in machine learning (see Wolfram reference below).
### Exploratory data analysis <a name="EDA"></a>
When starting this project I often encountered the term "Exploratory Data Analysis" (EDA). I found a good definition on the towardsdatascience website:
_Data Analysis refers to the critical process of performing initial investigations on data so as to discover patterns, to spot anomalies, to test hypothesis and to check assumptions with the help of summary statistics and graphical representations._ For this project, we are performing EDA on the Iris data set.
### Description of the data set <a name="datadescription"></a>
Fisher's Iris data set is a multivariate data set as each observation/sample consists of four variables. It contains the measurements in centimetres of the variables sepal length, sepal width, petal length, and petal width (in that order) for 50 flowers from each of three species of iris. The species are _Iris setosa_, _Iris versicolor_, and _Iris virginica_. The data set consists of 150 rows or observations (50 samples from each species) by five columns. The first four columns contain the samples/measurements and the fifth contains the species name (or class). I obtained the data set as a csv file from GitHub as detailed below.
## Initial analysis of the full data set <a name="paragraph2"></a>
Python script: **get-data.py**
This script reads the csv file containing the data set **iris.csv** (located in the same directory) and does some basic analysis. I import the modules I need for data analysis and plotting: Pandas, NumPy and matplotlib. The csv file is then read into a DataFrame - the basic data format for Pandas. Each row of a DataFrame represents a sample of data, with each column containing a different variable; the format is therefore compatible with the Iris Data Set we are investigating for this project. I use various **Pandas** functions as follows:
* .read_csv() to read the file into a DataFrame.
* .info() to get a brief summary of the resulting DataFrame.
* .head() to look at the first few lines of the data set.
* .dtypes to find the data types of each column.
* .shape to find the number of rows and columns in the DataFrame.
* .columns to find the labels of each column.
* .describe() to generate some descriptive statistics for each column of numeric data. The output of describe() is another DataFrame.
The output of **get-data.py** looks like:

The column labels are SepalLength, SepalWidth, PetalLength, and PetalWidth, all of type float64. The fifth column label is Name of type object (or string); it holds the name of the species. The DataFrame size is 150 rows x 5 columns. There are no null values. The head of the file is printed to the screen in the image above and gives an idea of its structure.
### Plotting the full data set <a name="plotall"></a>
I then plot the data columns as seperate data series on a single plot using **matplotlib**. I explain the commands here the first time I use them. Note that once a figure is displayed on screen, it must be closed before the script can move on to the next command. The first time I plotted a figure I spent some time watching the screen waiting for something to happen!
* plt.xlim() to set x axis range.
* plt.xticks() to place tick marks on the x axis in positions defined by a **NumPy** .arange() command.
* plt.gca() keeps track of the axes so that many columns (or data series) can be plotted on the same graph.
* plt.title(), plt.xlabel(), and plt.ylabel() set up the graph titles and x and y axes labels.
* plt.legend() to add a legend and place it in the 'best' location given the shape of the curves.
* plt.grid() to add gridlines.
* plt.savefig() to save the figure.
* plt.show() to display it.

The jumps in observation values from species to species are very obvious in this figure, apart from in the case of SepalWidth (green curve). For that reason, I think it would probably be more instuctive to analyse the observations applying to each species seperately; I do this with another script.
### Descriptive statistics of the full data set <a name="statsall"></a>
The descriptive statistics of the full data set is as follows (all measurements in cm):
Property |SepalLength | SepalWidth | PetalLength | PetalWidth
---------|------------|------------|-------------|-----------
count | 150.000000 |150.000000 | 150.000000 | 150.000000
mean | 5.843333 | 3.054000 | 3.758667 | 1.198667
std | 0.828066 | 0.433594 | 1.764420 | 0.763161
min | 4.300000 | 2.000000 | 1.000000 | 0.100000
25% | 5.100000 | 2.800000 | 1.600000 | 0.300000
50% | 5.800000 | 3.000000 | 4.350000 | 1.300000
75% | 6.400000 | 3.300000 | 5.100000 | 1.800000
max | 7.900000 | 4.400000 | 6.900000 | 2.500000
Here, count is the number of observations, mean is the mean of the values, std is the standard deviation, and min (max) is the minimum (maximum) of the values. The standard deviation indicates the amount of spread in the values; if it is large then the values are spread over a wide range, while a small standard deviation means that the values are more tightly clustered around the mean. A quick glance at the table of results above shows that the values of SepalLength and SepalWidth seem to cluster around the mean while the values of PetalLength and PetalWidth have a very large spread in values. 25%, 50%, and 75% are the 25th, 50th, and 75th percentiles respectively. The 50th percentile is equivalent to the median value of the observations. The 50% value is close to the mean for all variables apart from PetalLength. Bear in mind that these summary statistics apply to all 150 observations rather than to each species seperately (_i.e._ to each set of 50 observations). The information in the table above is presented graphically in a bar plot of the summary statistics DataFrame, where each column corresponds to a colour while each row is nested in a group on the x axis. I use **Pandas .iloc** to select the data I wish to display in the bar plot by using integer-location based indexing into the summary statistics DataFrame.

## Seperate the data into distinct species <a name="paragraph3"></a>
Python script: **stats-per-species.py**
### Summary statistics for each species <a name="statsperspecies"></a>
I used this script to investigate the basic properties of the data set on a per species basis. I use **Pandas .loc()** to select groups of rows and columns based on labels. For example, all rows with the label "Name = Iris-setosa" are extracted from the master data set and read into a new DataFrame of size (50,5): 50 rows (observations) and 5 columns (variables) with labels SepalLength etc as above. The summary statistics of each species are then found and are displayed below. It is also possible to investigate some statistical properties of the data set without breaking it into seperate DataFrames for each species. This is done using **Pandas groupby** to select sampes based on (species) Name. Some of the Python commamds used in this script include:
* setosa = data.loc[data['Name'] == "Iris-setosa"] to select a subset of data based on class.
* setosa_summary.loc[['mean', 'std', '50%']].plot.bar() to select part of a DataFrame for plotting.
* data.groupby('Name')['SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth'].mean() to calculate the mean of each variable grouped by Name = species.
* setosa.boxplot() to calculate a boxplot of the setosa DataFrame for example.
**SepalLength**| setosa | versicolor | virginica |**SepalWidth**| setosa | versicolor | virginica
---------------|----------|------------|-----------|--------------|----------|------------|----------
**mean** | 5.00600 | 5.936000 | 6.58800 | **mean** | 3.418000 | 2.77000 | 2.974000
**std** | 0.35249 | 0.516171 | 0.63588 | **std** | 0.381024 | 0.313798 | 0.322497
**min** | 4.30000 | 4.900000 | 4.90000 | **min** | 2.300000 | 2.000000 | 2.200000
**50%** | 5.00000 | 5.900000 | 6.50000 | **50%** | 3.400000 | 2.800000 | 3.000000
**max** | 5.80000 | 7.000000 | 7.90000 | **max** | 4.400000 | 3.400000 | 3.800000
**PetalLength**| setosa | versicolor | virginica |**PetalWidth**| setosa | versicolor | virginica
---------------|----------|------------|-----------|--------------|----------|------------|----------
**mean** | 1.464000 | 4.260000 | 5.552000 | **mean** | 0.24400 | 1.326000 | 2.02600
**std** | 0.173511 | 0.469911 | 0.551895 | **std** | 0.10721 | 0.197753 | 0.27465
**min** | 1.000000 | 3.000000 | 4.500000 | **min** | 0.10000 | 1.000000 | 1.40000
**50%** | 1.500000 | 4.350000 | 5.550000 | **50%** | 0.20000 | 1.300000 | 2.00000
**max** | 1.900000 | 5.100000 | 6.900000 | **max** | 0.60000 | 1.800000 | 2.50000



Another way to look at the statistics per species is to use **Pandas groupby()** to group the data according to species name and obtain statistics about each variable.
Mean(cm) | SepalLength | SepalWidth | PetalLength | PetalWidth
----------|-------------|------------|-------------|------------
Iris-setosa | 5.006 | 3.418 | 1.464 | 0.244
Iris-versicolor | 5.936 | 2.770 | 4.260 | 1.326
Iris-virginica | 6.588 | 2.974 | 5.552 | 2.026

Std(cm) | SepalLength | SepalWidth | PetalLength | PetalWidth
----------|-------------|------------|-------------|------------
Iris-setosa | 0.352490 | 0.381024 | 0.173511 | 0.107210
Iris-versicolor | 0.516171 | 0.313798 | 0.469911 | 0.197753
Iris-virginica | 0.635880 | 0.322497 | 0.551895 | 0.274650

### Boxplots <a name="boxp"></a>
I later realsied that I could easily investigate the distribution of variables using
**Matplotlib boxplot**, which makes a box and whisker plot for each column of the DataFrame. The box extends
from the lower to upper quartile values of the data, with a line at the median. The whiskers
extend from the box to show the range of the data. Outliers are those data points past the
ends of the whiskers. The result is a very good visual summary of the data. There appear to be few outliers in the data set, and the data appear to be kind of symmetrical; the median is roughly in the middle of the box, which is roughly in the middle of the whiskers.



## Discriminating between species <a name="paragraph4"></a>
Python script: **class-separation.py**
While researching the Iris data set I found that there are lots of example analyses online ranging from very simple ones which just describe the data set, to very complicated classification and machine learning analyses. It seems to be commonly used to demonstrate classification problems, such as how to seperate classes from each other and how to predict which class a sample belongs to if the class label for that sample is unknown. The classes here are the three species, there are 50 samples per class, with each sample consisting of four variables or attributes (SepalLength, SepalWidth, PetalLength, PetalWidth).
Part of the output of **class-separation.py** looks like:

### Histograms of variable values <a name="histall"></a>
I started by asking if the variables for each class are well separated from each other? If so, then it could be possible to predict which species a particular observation belongs to if given a variable value but not the class label. I plotted histograms of each attribute for all three species at the same time using the **Pandas groupby()** and **hist()** functions. Some options used in this script include:
* species = data.Name.unique() to store the unique values in DataFrame data['Name'] column.
* .hist() kwargs alpha=0.5 (0.0 transparent through 1.0 opaque) to see overlapping histograms.
* .hist() parameter Stacked=True so that multiple data are stacked on top of each other.
* plt.legend((species), loc='best', fontsize=12) to get the correct legend for each plot. I spent a long time trying to get this right. First I tried to insert a legend with hist(label=), but that resulted in all histograms having the same legend, the first species name in the species array. I found out that there is only one legend per plot, so it needs to be updated each time a histogram is drawn on a given plot. This syntax was able to do that.
* legend box style and transparency set with fancybox=True (round edges on legend box) and framealpha=0.5 (to allow for visualization of data behind the box in this relatively crowded figure).

I originally generated four seperate figures, but a single, properly-formatted figure, with four subplots, looks much better. From this plot it is clear that SepalLength and SepalWidth would not be good variables to look at if trying to separate the three species because the histograms for each species overlap significantly. However, the Iris setosa histograms for PetalLength and PetalWidth values seem to be well seperated from those of the other two species. So, it would be possible to roughly assign an observation to class Iris setosa if given the values of these two variables.
### Swarmplot of variable values <a name="swarmall"></a>

I came across a **Seaborn swarmplot** of the Iris data set in the package documentation. It offers a way to clearly plot all observations in a data set, as observations with the same value are seperated from each other - that's why the data above shows a spread along the x axis. At first I couldn't understand why that was happening. It's a good option for data sets that are not too big. There is a similar function called stripplot which does not seperate observations, so the resulting plot is more crowded in x. The colour palette in the plot above was set to be identical to that already used for the histograms, making it easy to recognise and keep track of the different species. This swarmplot provides another good visual illustration of how Iris setosa is well separated from the other two species if one is looking at the variables PetalLength and PetalWidth. Even the other two species, Iris versicolor and virginica, are reasonably well separated in these variables. SepalWidth seems to be the variable with most overlap between species, with SepalLength not far behind. This is my opinion based purely on the figures I've plotted so far.
## Relationships between variables <a name="paragraph5"></a>
Python script: **variable-relations.py**
### Scatter matrix <a name="scatter"></a>
I first tried **Pandas scatter_matrix** to examine if there is a linear correlation between any of the four variables, but the three species were indistinguishable in the resulting figure. I needed to use the Seaborn data visualization library in order to differentiate between classes (species), specifically the **Seaborn pairplot** function. The R-bloggers website listed in the references below gives a good simple explanation of what the scatter matrix means. Briefly, each variable is plotted against itself and all the others (here there are four variables so 4 x 4 = 16 subplots). If the data points look like they are tending to form a line (row 4 col 3 showing PetalWidth vs PetalLength), then those two variables are probably linearly correlated; if they don't (row 1 col 2 showing SepalLength vs SepalWidth), then there is less/no correlation. From this plot it looks as if PetalLength and PetalWidth (row 3 col 4 and row 4 col 3) are highly correlated for all species. On the other hand, it looks as if there may be a linear correlation between PetalLength and SepalLength (row 3 col 1) for Iris versicolor and virginica, but not for Iris setosa because a line drawn through the data points would have a slope of almost zero. Where two variables are correlated one could imagine being able to perform a good linear fit to the plot of one versus the other. The diagonal subplots here are histograms of that variable and are identical to the histograms I've already plotted in the last section. Some of the keywords/options used here with **pairplot** include:
* Parameter hue="Name" means that each "Name" (species) is plotted using a different colour.
* Parameter diag_kind='hist' means that the diagonal plots in the scatter matrix are histograms of variable values. These are identical to the histograms I've already plotted using Pandas.
* I also set the palette="pastel" to continue the same colour theme I've been using up to now.

### Linear regression in Seaborn <a name="linregSB"></a>
Looking at the scatter matrix, it's clear that some of the subplots show linear trends, _i.e._ the y data seems to depend linearly on the x data in some way. It's a stronger trend in some plots, for example, in row 3 column 4 of the scatter matrix with PetalLength (on y) vs PetalWidth (on x), and in row 4 column 3 with PetalWidth (on y) vs PetalLength (on x). So, I chose to examine the linear trend for these variables more closely using the **Seaborn lmplot** function. This generates a visualization of the linear fit by fitting the data to a line and plotting the resulting straight line with a shaded region which represents the 95% confidence level for the fit. I decided to fit all of the data to a single line (I did not use the hue="Name" parameter in lmplot to seperate the three species) because I think the result is visually much nicer; see below where I include the same figure but with seperate linear fits for each species. Note how the shaded region around each of the lines (95% confidence level) is fatter, indicating a less good fit. Some **lmplot** options used here include:
* x="PetalWidth", y="PetalLength" to set the date to plot/fit.
* truncate=True to stop the line at limits of data rather than x axis limits.
* height=5, a sizing parameter for the plot used with the aspect ratio (=1 by default).


### Least squares fitting using statsmodels <a name="lsq"></a>
**Seaborn lmplot** provides a visualization of the linear fit but does not not provide the actual fitting parameters. To find those, the Seaborn documentation recommends using a statistical package such as **statsmodels**. I used it to fit a straight line (with slope and intercept) to the data (PetalWidth on y versus PetalLength on x ) via simple least squares fitting. This method works by minimizing the sum of the squares of the residuals, the residual being the difference between the real data and the fit calculated at each value of x. **Statsmodels OLS** is a simple ordinary least squares method which does not include a constant (intercept); that must be added to the model using the **add_constant** option. It is used in the form OLS(y, X). I performed the fit and then plotted the fit on top of the data to show that it works. I think that the fit looks better when an intercept is used, although the goodness of the fit (as represented by the R-squared value) is marginally higher for the fit performed without an intercept. That's probably just down to this particular plot where the intercept is almost zero anyway. R-squared can vary between 0 (the linear model cannot explian the observed data at all) and 1 (the linear model fits the observed data perfectly). Some of the settings and options used here include:
* OLS(data['PetalWidth'], data['PetalLength']).fit() for the simple fit.
* OLS(data['PetalWidth'], sm.add_constant(data['PetalLength'])).fit() to include intercept.
* model.params to access the fitting parameters.
* model.rsquared to access the goodness of fit measure.
* PW_fit = x * model.params.PetalLength + model.params.const to plot the line with fitting parameters.
The output from this part of the script contains a lot of information, although I am really only interested in the fit parameters and R-squared value. These are:
FIT | m | c | R squared
-----|---|---|----------
y = mx | 0.3364 | - | 0.967
y = mx + c | 0.4164 |-0.3665 | 0.927


In this plot, **fit** includes an intercept, **Simple** fit doesn't.
## Work done by other people on the Iris data set <a name="others"></a>
### Machine learning <a name="machinelearning"></a>
When I first started researching the Iris data set I found lots of analyses online, and to be honest, I didn't really know where to start as they seemed to quickly get complex. The data set seems to be a very popular one to use for demonstrating the concept of machine learning, especially in the documentation for various packages like Matlab, Mathematica, Pandas, and Scikit-learn (all in the reference list below). In order to do machine learning, the data must first be summarized and visualized, so that is where I chose to start, so that I could learn how to use Pandas. The rajritvikblog blog post referenced below is a typical example of how these analyses proceed. The data is read in and the author plots each variable seperately (univariate plots), before moving on to look at how the variables interact with each other (multvariate plots). That is roughly the approach I took with my Python scripts. For machine learning itself, scikit-learn seems to be the goto package, and there are lots of examples related to machine learning using the Iris data set in the sci-kit.learn package documentation. Machine learning involves using the data you already have to make predictions about new data. It looks for patterns in data and roughly falls into two categories: supervised and unsupervised machine learning. Supervised machine learning uses a known training data set (such as the Iris data set with known labels/classes) to build a model that can be used to predict which class a new observation (with no labels) belongs to. The sci-kit.learn documentation describes the Iris data set as a "classic and very easy multi-class classification dataset". The author in the rajritvikblog blog post splits the data set in two, using 85% to train the models and 15% to check their accuracy. They compare six models and produce a single number for each which is a measure of model accuracy. One of the models studied is based on linear discriminant analysis (LDA), which, you may recall, was introduced by Fisher along with his Iris flower data set in 1936. LDA is only appropriate to use if the classes (species) are well separated by lines on a plot of one variable versus another. From the scatter matrix of the Iris data set, we can see that some of the variables could be separated by lines, so it looks like a good data set to try LDA on.
### Example of Linear Discriminant Analysis <a name="LDA"></a>
Python script: **machine-learning.py**
The code for performing LDA on the Iris data set was taken directly from the **scikit-learn** documentation referenced below. I left out the code to perform Principal Components Analysis and added some extra commands to allow me to figure out what was going on in the script. First I tried opening the csv file containing the data set via Pandas (as I have done in all scripts so far), but I ran into problems when trying to plot the results graph. In the end I decided to use the **scikit-learn** code as given and try to understand what it was doing.
The Sebastian Raschka website (referenced below) is an excellent source of information on LDA and I relied heavily on it when trying to understand the various steps in the process. He explains what it is and performs LDA from scratch on the Iris data set as well as explaining the maths. He then illustrates how to do the same thing using **scikit-learn** in much fewer lines of code. Briefly, LDA is often used to project data onto a subspace that increases the separability between classes, while reducing the number of dimensions, before performing classification or machine learning. It is a supervised algorithim as it uses the known class labels to find linear discriminants which maximize the separation between classes - see the figure just below. An alternative way to separate classes would be to use feature selection; recall that the histograms of petal length and width are reasonably well separated for each Iris species, so feature selection would probably work well with this data set.

Explanation of some of the steps in this script:
* LinearDiscriminantAnalysis is a way to perform discriminant analysis in **scikit-learn.**
* It takes an optional parameter n_components, which must be less than or equal to the number of classes.
The Iris data set has three classes and n_components=2 here.
* X is a 2D array (matrix) containing the observations. It's size is (150,4). Referred to as the _training data_.
* y is a 1D array (vector) containing the class labels; in **scikit-learn** these are integers representing the species rather than the actual species names we have seen up to now with **Pandas.** It's size is (150,1). Referred to as the _target values_.
* .fit(X, y) is a method of LinearDiscriminantAnalysis. It fits a LDA model given the training data and target values.
* .transform(X) is a method of LinearDiscriminantAnalysis. It projects the data (X) to maximize class separation and returns a new array containing the transformed data. The new array has size (150,2), corresponding to (number of observations, n_components).
The ouput from this script looks like:


From the plot we see that the first linear discriminant (LD1) separates the classes very well; a projection onto the LD1 axis has good separation between the classes, but that is not the case so for a projection onto the LD2 axis. This suggests that it should be possible to perform LDA on the Iris data set with just one component and still achieve good class separation. Out of curiosity, I modified the code very slightly to do this by setting n_components=1 in LinearDiscriminantAnalysis. The output of transform(X) now has size (150,1), where 1 reflects the n_components value. In the plot below you can see that the classes are still very well separated.
_iris.jpeg)
## Conclusion <a name="conclusion"></a>
The Iris data set is a classic multivariate data set containing 150 observations of four variables - sepal length, sepal width, petal length, and petal width - for three species of iris: setosa, versicolor, and virginica. There are 50 observations for each species (or class). With **get-data.py**, I read in the data set, plotted the observations, and generated some descriptive statistics such as the mean and standard deviation. Using the script **stats-per-species.py**, I began to look at how the three species behaved individually. I initially investigated the statistics per species by breaking the data set into three DataFrames, one for each species. As I learned more about Pandas, I realised that some of this could have been done using functions on the full data set, such as **Pandas groupby()**, which allows for selection of parts of a DataFrame by class label. In **class-separation.py**, I wanted to investigate if it was possible to separate the species from each other by looking at the distributions of features. Based on histograms and a **Seaborn swarmplot** of the four variables, I concluded that it was possible, for some species and some variables. I then looked at relationships between the variables in **variable-relations.py**. The starting point here was a scatter matrix to see if any of the variables (when plotted against the others) seemed to form patterns. Based on the scatter matrix, where it looked as if some variables could be linearly related to each other, I chose to examine the possible relationships further. I performed linear regression visually with **Seaborn**, and again with **statsmodels** to find the actual fitting parameters. I found that there is a very good linear correlation between PetalWidth and PetalLength for all species, for example. Finally, I started doing a little bit of machine learning (or classification really) in the script **machine-learning.py** using **scikit-learn**.
## List of Python scripts <a name="scripts"></a>
* **iris.csv** Iris Data Set in same directory/repository
* get-data.py
* stats-per-species.py
* class-separation.py
* variable-relations.py
* machine-learning.py
## References <a name="references"></a>
1. <NAME>: https://www.britannica.com/biography/Ronald-Aylmer-Fisher
2. <NAME>: https://study.com/academy/lesson/sir-ronald-fisher-biography-contributions-to-statistics.html
3. Linear Discriminant Analysis: https://sebastianraschka.com/Articles/2014_python_lda.html
4. Exploratory Data Analysis: https://towardsdatascience.com/exploratory-data-analysis-8fc1cb20fd15
5. Classification with MathWorks: https://uk.mathworks.com/help/stats/examples/classification.html
6. Wolfram Data Repository: https://datarepository.wolframcloud.com/resources/Sample-Data-Fishers-Irises
7. Iris data set: https://github.com/pandas-dev/pandas/blob/master/pandas/tests/data/iris.csv
8. Pandas Python data analysis library: https://pandas.pydata.org/
9. Matplotlib Python 2D plotting library: https://matplotlib.org/
10. Pandas DataFrames: https://www.shanelynn.ie/using-pandas-dataframe-creating-editing-viewing-data-in-python/
11. Plotting examples: http://queirozf.com/entries/pandas-dataframe-plot-examples-with-matplotlib-pyplot
12. Examples of working with DataFrames: https://tomaugspurger.github.io/modern-1-intro.html
13. Typical data analyses: https://machinelearningmastery.com/quick-and-dirty-data-analysis-with-pandas/
14. Visualising data with Python: https://www.analyticsvidhya.com/blog/2015/05/data-visualization-python/
15. Iris data set for machine learning (not package documentation): https://rajritvikblog.wordpress.com/2017/06/29/iris-dataset-analysis-python/
16. The iris data set in scikit-learn: https://scikit-learn.org/stable/auto_examples/datasets/plot_iris_dataset.html
17. Scikit-learn iris data set analyses: https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html
18. Image of iris species: https://medium.com/@pranav_suresh/iris-classification-using-logistic-regression-using-octave-873bca96ec5b
19. Idea (but not the code) for histograms of attributes for three species at same time: https://stackoverflow.com/questions/45721083/unable-to-plot-4-histograms-of-iris-dataset-features-using-matplotlib
20. Table of contents in markdown: https://stackoverflow.com/questions/11948245/markdown-to-create-pages-and-table-of-contents
21. Simple explanation of scatter matrix: https://www.r-bloggers.com/scatterplot-matrices/
22. Seaborn: https://seaborn.pydata.org/index.html
23. Seaborn scatter matrix : https://seaborn.pydata.org/examples/scatterplot_matrix.html
24. Linear regression: https://warwick.ac.uk/fac/sci/moac/people/students/peter_cock/r/iris_lm/
25. Least squares fitting: https://stackoverflow.com/questions/19991445/run-an-ols-regression-with-pandas-data-frame
26. Linear relationships in Seaborn: https://seaborn.pydata.org/tutorial/regression.html?highlight=linear%20regression
27. Seaborn lmplot: https://seaborn.pydata.org/examples/multiple_regression.html?highlight=iris%20data%20set
28. Attempting subplots with Seaborn lmplot: https://stackoverflow.com/questions/23969619/plotting-with-seaborn-using-the-matplotlib-object-oriented-interface
29. Regression using Statsmodels: https://www.statsmodels.org/stable/regression.html
30. Least Squares Fitting on a Pandas DataFrame: https://stackoverflow.com/questions/19991445/run-an-ols-regression-with-pandas-data-frame
31. Statsmodels OLS: https://www.statsmodels.org/stable/generated/statsmodels.regression.linear_model.OLS.html#statsmodels.regression.linear_model.OLS
32. Machine learning simple explanation: https://news.codecademy.com/what-is-machine-learning/
33. Machine learning techniques: https://medium.com/datadriveninvestor/contemporary-classification-of-machine-learning-techniques-part-1-16e77eaa993e
34. Machine learning tutorial: https://scikit-learn.org/stable/tutorial/basic/tutorial.html
35. LDA using Iris data set: https://stackabuse.com/implementing-lda-in-python-with-scikit-learn/
36. LDA on Iris via Python: http://sebastianraschka.com/Articles/2014_python_lda.html
37. LDA on Iris in scikit-learn: https://scikit-learn.org/stable/auto_examples/decomposition/plot_pca_vs_lda.html#sphx-glr-auto-examples-decomposition-plot-pca-vs-lda-py<file_sep># <NAME>
# HDip Data Analytics 2019 pands-project
#
# stats-per-species.py
# Script to read in and analyse the iris data set / species.
# Look at the statistics for each species.
# ###########################################################
# Import Pandas data analysis library.
import pandas as pd
# Import matplotlib for 2D plotting.
import matplotlib.pyplot as plt
# Read the iris.csv file from this directory.
data = pd.read_csv('iris.csv')
# print(data.head())
d_shape = data.shape
print("n rows = ", d_shape[0], ", n_cols = ", d_shape[1] )
# What are the column labels of the DataFrame?
col_labels = data.columns
print("Data column labels: ", col_labels)
# List the unique values in data['Name'] column i.ie species.
species = data.Name.unique()
print("The three species are: ", species)
# ###########################################################
# Create 3 dataframes, each corresponding to a single species.
# Select rows based on species names using .loc[]
setosa = data.loc[data['Name'] == "Iris-setosa"]
versicolor = data.loc[data['Name'] == "Iris-versicolor"]
virginica = data.loc[data['Name'] == "Iris-virginica"]
# Check them.
print("size=", setosa.shape)
print(setosa.head())
print("size=", versicolor.shape)
print(versicolor.head())
print("size=", virginica.shape)
print(virginica.head())
# Summary statistics for Iris-setosa.
setosa_summary = setosa.describe()
print("Iris-setosa")
print(setosa_summary)
# Bar plot with some of the statistics referenced by name.
setosa_summary.loc[['mean', 'std', '50%']].plot.bar()
plt.title("Summary statistics: Setosa", fontsize=18)
plt.ylabel('cm', fontsize=16)
plt.grid()
plt.savefig('SetosaStats.jpeg')
plt.show()
# Summary statistics for Iris-versicolor.
versicolor_summary = versicolor.describe()
print("Iris-versicolor")
print(versicolor_summary)
# Bar plot with some of the statistics referenced by name.
versicolor_summary.loc[['mean', 'std', '50%']].plot.bar()
plt.title("Summary statistics: Versicolor", fontsize=18)
plt.ylabel('cm', fontsize=16)
plt.grid()
plt.savefig('VersicolorStats.jpeg')
plt.show()
# Summary statistics for Iris-virginica.
virginica_summary = virginica.describe()
print("Iris-virginica")
print(virginica_summary)
# Bar plot with some of the statistics referenced by name.
virginica_summary.loc[['mean', 'std', '50%']].plot.bar()
plt.title("Summary statistics: Virginica", fontsize=18)
plt.ylabel('cm', fontsize=16)
plt.grid()
plt.savefig('VirginicaStats.jpeg')
plt.show()
# ###########################################################
# Can also look at some statistics per species using Pandas groupby()
# on the full data set, i.e. no need to create seperate DataFrames for each species.
# Mean
print(data.groupby('Name')['SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth'].mean())
# Standard deviation
print(data.groupby('Name')['SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth'].std())
# Bar chart of mean values for each species.
# Use rot keyword in plot() to align x-tick labels nicely.
data.groupby('Name')['SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth'].mean(). \
plot(kind='bar',rot='horizontal')
plt.title('Mean variable values', fontsize=18)
plt.ylabel('cm', fontsize=16)
plt.grid()
plt.legend(loc='best', fontsize=12)
plt.savefig('Mean_species.jpeg')
plt.show()
# Bar chart of std values for each species.
data.groupby('Name')['SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth'].std(). \
plot(kind='bar', rot='horizontal')
plt.title('Standard deviation of variable values', fontsize=18)
plt.ylabel('cm', fontsize=16)
plt.grid()
plt.legend(loc='best', fontsize=12)
plt.savefig('Std_species.jpeg')
plt.show()
# ###########################################################
# Or, I could do almost all of above visually using Matplotlib
# box and whisker plot:
# The box extends from the lower to upper quartile values of the data.
# There is a a line at the median.
# The whiskers extend from the box to show the range of the data.
# Outlying points are those past the end of the whiskers.
# Setosa
# plt.subplot(3,1,1)
setosa.boxplot()
plt.title("Iris-Setosa", fontsize=18)
plt.ylabel('cm', fontsize=16)
plt.savefig('Setosa_boxplot.jpeg')
plt.show()
# Versicolor
# plt.subplot(3,1,2)
versicolor.boxplot()
plt.title("Iris-Versicolor", fontsize=18)
plt.ylabel('cm', fontsize=16)
plt.savefig('Versicolor_boxplot.jpeg')
plt.show()
# Virginica
# plt.subplot(3,1,3)
virginica.boxplot()
plt.title("Iris-Virginica", fontsize=18)
plt.ylabel('cm', fontsize=16)
plt.savefig('Virginica_boxplot.jpeg')
plt.show() | d81c45f34afb19c16dee4a30c6b9bfce52ccbd42 | [
"Markdown",
"Python"
] | 7 | Python | elizabethdaly/pands-project | fe200fcee56a95524bc1ebf55ff5c42f13b62c30 | 258534007fd2484cacd62075e76ba1b06359b271 |
refs/heads/master | <file_sep>/* eslint-disable linebreak-style *//* eslint-disable no-param-reassign */
/* eslint-disable class-methods-use-this *//* eslint-disable no-use-before-define */
import ClickButton from '../ClickButton';
test('test adding tooltip', () => {
document.body.innerHTML = '<div class=\'container\'><button class=\'button\'>Нажми меня</button></div>';
const button = new ClickButton('.container');
button.createTooltip();
const div = document.querySelector('.tooltip');
expect(div.className).toEqual('tooltip');
});
<file_sep>[](https://ci.appveyor.com/project/dadiakov/ahj-hw-5-1)
https://dadiakov.github.io/ahj-hw-5.1/
| dc83abc29b71856d0cf36f43ca61ae6699ed1546 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | dadiakov/ahj-hw-5.1 | 732243a8b641c3c87244e5701bb3755ea67b8717 | fa4de3c7fb46ba1f5c681bd4821531847e6688c6 |
refs/heads/master | <file_sep>package com.example.pruebanico
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| fc18ce86e43e8a7009cfffdfb110a8eafe0e4274 | [
"Kotlin"
] | 1 | Kotlin | pabloschonwiesner/pruebanicolas | 8cd989247073b9977653e04ff4af03207c54d0e1 | c7cdde79dc3a7aa010b91cfdf5cc3f0a5ab55461 |
refs/heads/master | <file_sep>// JavaScript Document
// Grab all the outline section links
const $outlineSectionLinks = $('.outline-section-link');
// Grab all the outline sections
const $outlineSections = $('.outline-section');
$outlineSections.not(':first').hide();
$outlineSectionLinks.click(function(e){
e.preventDefault();
$outlineSections.hide();
$( $(this).data('id') ).show();
});
//Code courtesy http://jsfiddle.net/VpkKn/
// $('a').on('click', function(){
// var target = $(this).attr('rel');
// $("#"+target).show().siblings("div").hide();
// });
| 496267a964e36a2961320e6bb446dfd4f34c3a28 | [
"JavaScript"
] | 1 | JavaScript | thaqueubc/final_project | 854c7efa1039aa637c0f0392ee72f08664019847 | 35ac2f3d3c517c328e4f1bd7b0842b0a3784c4e3 |
refs/heads/master | <file_sep>// Generated by CoffeeScript 1.4.0
(function() {
var _fixtureSrings;
_fixtureSrings = {
sortableList: "<section id=\"sortable-list\">\n <h2>Sortable List</h2>\n <ul class=\"sortable\">\n <li>Item 1</li>\n <li>Item 2</li>\n <li>Item 3</li>\n <li>Item 4</li>\n <li>Item 5</li>\n <li>Item 6</li>\n </ul>\n</section>",
sortableGrid: "<section id=\"sortable-grid\">\n <h2>Sortable Grid</h2>\n <ul class=\"sortable sortable-grid\">\n <li>Item 1</li>\n <li>Item 2</li>\n <li>Item 3</li>\n <li>Item 4</li>\n <li>Item 5</li>\n <li>Item 6</li>\n </ul>\n</section>",
sortableWithExcludes: "<section id=\"sortable-with-excludes\">\n <h2>Sortable With Excludes</h2>\n <ul class=\"sortable sortable-with-excludes\">\n <li>Item 1</li>\n <li>Item 2</li>\n <li>Item 3</li>\n <li class=\"disabled\">Item 4</li>\n <li class=\"disabled\">Item 5</li>\n <li class=\"disabled\">Item 6</li>\n </ul>\n</section>",
sortableWithHandles: "<section id=\"sortable-with-handles\">\n <h2>Sortable With Handles</h2>\n <ul class=\"sortable sortable-with-handles\">\n <li><span>::</span> Item 1</li>\n <li><span>::</span> Item 2</li>\n <li><span>::</span> Item 3</li>\n <li><span>::</span> Item 4</li>\n <li><span>::</span> Item 5</li>\n <li><span>::</span> Item 6</li>\n </ul>\n</section>",
sortableConnected: "<section id=\"sortable-connected\">\n <h2>Sortable With Connected</h2>\n <ul class=\"sortable sortable-connected sortable-connected-1\">\n <li>Item 1</li>\n <li>Item 2</li>\n <li>Item 3</li>\n <li>Item 4</li>\n <li>Item 5</li>\n <li>Item 6</li>\n </ul>\n <ul class=\"sortable sortable-connected sortable-connected-2\">\n <li class=\"highlight\">Item 1</li>\n <li class=\"highlight\">Item 2</li>\n <li class=\"highlight\">Item 3</li>\n <li class=\"highlight\">Item 4</li>\n <li class=\"highlight\">Item 5</li>\n <li class=\"highlight\">Item 6</li>\n </ul>\n</section>"
};
window.TestHelper = {
fixture: function(name) {
return _fixtureSrings[name];
},
loadFixture: function(name) {
var html, newEle;
html = this.fixture(name);
newEle = this.cleanSandbox();
newEle.html(html);
return newEle;
},
cleanSandbox: function() {
var id, newEle, oldEle;
id = 'sandbox';
oldEle = document.getElementById(id);
if (oldEle) {
oldEle.parentNode.removeChild(oldEle);
}
newEle = document.createElement('div');
newEle.id = id;
document.body.appendChild(newEle);
return $(newEle);
}
};
}).call(this);
| f4ca74fa70e0b0a338357dec74a8c581baee5b6e | [
"JavaScript"
] | 1 | JavaScript | metaskills/html5_sortable | 15d6912701aba0fe38f9185b515b3018614f3619 | f4751b02f2e9dadaa2edf513f963d75db73e143d |
refs/heads/master | <repo_name>shanemcdo/RustChess<file_sep>/src/main.rs
// TODO: More Docs <20-12-20, <NAME>> //
//! This is a chess program.
//! it uses the ggez graphics and game library to.
//! create a graphics user interface and get mouse input.
//!
//! IMPORTANT: alsa-sys v0.1.2, a package used by ggez causes a panic in some linux distros.
//! This can be solved by typing ```sudo apt install libsdl2-dev``` into the command line.
//!
//! This project is a collaboration between Patrick and <NAME>.
use ggez::event;
use ggez::graphics;
use ggez::input;
use ggez::nalgebra as na;
use ggez::{Context, GameResult};
/// The size of the main window in pixels.
/// The first number is the x coordinate and the second is the y.
const WINDOW_SIZE: [f32; 2] = [700., 700.];
/// The number of tiles across the board.
const BOARD_SIZE: usize = 8;
/// The first number is the x coordinate and the second is the y.
/// the size of a single tile in pixels.
const SQUARE_SIZE: [f32; 2] = [
WINDOW_SIZE[0] / BOARD_SIZE as f32,
WINDOW_SIZE[1] / BOARD_SIZE as f32,
];
/// The two different colors a chess piece can be.
#[derive(PartialEq)]
enum Color {
Black,
White,
}
/// An enum that represents a spot on a chess board.
/// Holds the team information and which type of piece it is.
/// Alternatively, It could represent and empty space on the chessboard.
#[derive(Copy, Clone)]
enum Piece {
Empty,
Black(Type),
White(Type),
}
/// An enum that represents each type of chess piece there is.
/// Does not identify team at all.
#[derive(Copy, Clone)]
enum Type {
Pawn,
Rook,
Knight,
Bishop,
Queen,
King,
}
/// This is the current game state.
struct State {
/// board represents the pieces are and their location in the chess board.
board: [[Piece; BOARD_SIZE]; BOARD_SIZE],
/// color represents which team currently has a turn.
color: Color,
/// the position of the currently selected piece
selected_pos: Option<[f32; 2]>,
}
impl State {
/// creates a new State with all pieces in the correct starting position.
fn new() -> Self {
Self {
board: [
[
Piece::White(Type::Rook),
Piece::White(Type::Knight),
Piece::White(Type::Bishop),
Piece::White(Type::Queen),
Piece::White(Type::King),
Piece::White(Type::Bishop),
Piece::White(Type::Knight),
Piece::White(Type::Rook),
],
[Piece::White(Type::Pawn); BOARD_SIZE],
[Piece::Empty; BOARD_SIZE],
[Piece::Empty; BOARD_SIZE],
[Piece::Empty; BOARD_SIZE],
[Piece::Empty; BOARD_SIZE],
[Piece::Black(Type::Pawn); BOARD_SIZE],
[
Piece::Black(Type::Rook),
Piece::Black(Type::Knight),
Piece::Black(Type::Bishop),
Piece::Black(Type::Queen),
Piece::Black(Type::King),
Piece::Black(Type::Bishop),
Piece::Black(Type::Knight),
Piece::Black(Type::Rook),
],
],
color: Color::Black,
selected_pos: None,
}
}
/// Draws the white tiles of the chess board against the black background.
fn draw_board(&mut self, ctx: &mut Context) {
graphics::clear(ctx, graphics::BLACK);
let square = graphics::Mesh::new_rectangle(
ctx,
graphics::DrawMode::fill(),
graphics::Rect {
x: 0.,
y: 0.,
w: SQUARE_SIZE[0],
h: SQUARE_SIZE[1],
},
graphics::WHITE,
)
.unwrap();
graphics::draw(ctx, &square, (na::Point2::new(0., 0.),)).unwrap();
for i in 0..4 {
for j in 0..4 {
graphics::draw(
ctx,
&square,
(na::Point2::new(
j as f32 * SQUARE_SIZE[0] * 2.,
i as f32 * SQUARE_SIZE[1] * 2.,
),),
)
.unwrap();
graphics::draw(
ctx,
&square,
(na::Point2::new(
j as f32 * SQUARE_SIZE[0] * 2. + SQUARE_SIZE[0],
i as f32 * SQUARE_SIZE[1] * 2. + SQUARE_SIZE[1],
),),
)
.unwrap();
}
}
}
/// Draws the chess piece that occupies the given position.
fn draw_piece(&mut self, ctx: &mut Context, pos: [f32; 2]) {
let piece = self.board[pos[1] as usize][pos[0] as usize];
let color: graphics::Color;
let text_color: graphics::Color;
match piece {
Piece::Empty => return,
Piece::Black(_) => {
color = [0.2, 0.2, 0.2, 1.0].into();
text_color = [0.8, 0.8, 0.8, 1.0].into()
}
Piece::White(_) => {
color = [0.8, 0.8, 0.8, 1.0].into();
text_color = [0.2, 0.2, 0.2, 1.0].into()
}
_ => unreachable!(),
};
let circle = graphics::Mesh::new_circle(
ctx,
graphics::DrawMode::fill(),
[SQUARE_SIZE[0] / 2., SQUARE_SIZE[1] / 2.],
SQUARE_SIZE[0] * 0.4,
0.1,
color,
)
.unwrap();
let border = graphics::Mesh::new_circle(
ctx,
graphics::DrawMode::stroke(2.),
[SQUARE_SIZE[0] / 2., SQUARE_SIZE[1] / 2.],
SQUARE_SIZE[0] * 0.4,
0.1,
[0.5, 0.5, 0.5, 1.0].into(),
)
.unwrap();
graphics::draw(
ctx,
&circle,
(na::Point2::new(
pos[0] * SQUARE_SIZE[0],
pos[1] * SQUARE_SIZE[1],
),),
)
.unwrap();
graphics::draw(
ctx,
&border,
(na::Point2::new(
pos[0] * SQUARE_SIZE[0],
pos[1] * SQUARE_SIZE[1],
),),
)
.unwrap();
let text_fragment: graphics::TextFragment;
match piece {
Piece::Black(Type::Pawn) | Piece::White(Type::Pawn) => return,
Piece::Black(Type::Rook) | Piece::White(Type::Rook) => {
text_fragment = graphics::TextFragment::new("R")
}
Piece::Black(Type::Knight) | Piece::White(Type::Knight) => {
text_fragment = graphics::TextFragment::new("N")
}
Piece::Black(Type::Bishop) | Piece::White(Type::Bishop) => {
text_fragment = graphics::TextFragment::new("B")
}
Piece::Black(Type::Queen) | Piece::White(Type::Queen) => {
text_fragment = graphics::TextFragment::new("Q")
}
Piece::Black(Type::King) | Piece::White(Type::King) => {
text_fragment = graphics::TextFragment::new("K")
}
_ => return,
}
graphics::draw(
ctx,
graphics::Text::new(
text_fragment
.color(text_color)
.scale(graphics::Scale { x: 40., y: 40. }),
)
.set_bounds(SQUARE_SIZE, graphics::Align::Center),
(na::Point2::new(
pos[0] * SQUARE_SIZE[0],
pos[1] * SQUARE_SIZE[1] + SQUARE_SIZE[1] / 4.,
),),
)
.unwrap();
}
/// Draws every chess piece on the board.
fn draw_pieces(&mut self, ctx: &mut Context) {
for i in 0..BOARD_SIZE {
for j in 0..BOARD_SIZE {
self.draw_piece(ctx, [j as f32, i as f32]);
}
}
}
/// gets the index of the current square that the mouse is hovering over.
fn get_current_square(&mut self, ctx: &mut Context) -> [f32; 2] {
let pos = input::mouse::position(ctx);
[
(pos.x / SQUARE_SIZE[0]) as usize as f32,
(pos.y / SQUARE_SIZE[1]) as usize as f32,
]
}
/// highlights the square at the given position.
fn highlight_square(&mut self, ctx: &mut Context, pos: [f32; 2], color: graphics::Color) {
let highlight = graphics::Mesh::new_rectangle(
ctx,
graphics::DrawMode::fill(),
graphics::Rect {
x: 0.,
y: 0.,
w: SQUARE_SIZE[0],
h: SQUARE_SIZE[1],
},
color,
)
.unwrap();
graphics::draw(
ctx,
&highlight,
(na::Point2::new(
pos[0] * SQUARE_SIZE[0],
pos[1] * SQUARE_SIZE[1],
),),
)
.unwrap();
}
/// lists the coordinates of valid moves
fn get_valid_moves(&mut self, pos: [f32; 2]) -> Vec<[f32; 2]> {
// TODO: Make piece logic more efficient and not stupid <20-12-20, <NAME>ough>
// TODO: Make pawns able to kill by sliding past <20-12-20, <NAME>Donough>
// TODO: Create king logic <20-12-20, <NAME>>
let mut v: Vec<[f32; 2]> = vec![];
let piece = self.board[pos[1] as usize][pos[0] as usize];
match piece {
Piece::Black(Type::Pawn) => {
self.push_move([pos[0], pos[1] - 1.], false, &mut v);
// starting line
if pos[1] == 6. {
self.push_move([pos[0], pos[1] - 2.], false, &mut v);
}
let mut new_pos = [pos[0] + 1., pos[1] - 1.];
if !self.point_out_of_bounds(new_pos) {
match self.board[new_pos[1] as usize][new_pos[0] as usize] {
Piece::White(_) => v.push(new_pos),
_ => (),
}
match self.board[new_pos[1] as usize][new_pos[0] as usize + 1] {
Piece::White(_) => v.push(new_pos),
_ => (),
}
}
new_pos = [pos[0] - 1., pos[1] - 1.];
if !self.point_out_of_bounds(new_pos) {
match self.board[new_pos[1] as usize][new_pos[0] as usize] {
Piece::White(_) => v.push(new_pos),
_ => (),
}
match self.board[new_pos[1] as usize][new_pos[0] as usize + 1] {
Piece::White(_) => v.push(new_pos),
_ => (),
}
}
}
Piece::White(Type::Pawn) => {
self.push_move([pos[0], pos[1] + 1.], false, &mut v);
// starting line
if pos[1] == 1. {
self.push_move([pos[0], pos[1] + 2.], false, &mut v);
}
let mut new_pos = [pos[0] + 1., pos[1] + 1.];
if !self.point_out_of_bounds(new_pos) {
match self.board[new_pos[1] as usize][new_pos[0] as usize] {
Piece::Black(_) => v.push(new_pos),
_ => (),
}
}
new_pos = [pos[0] - 1., pos[1] + 1.];
if !self.point_out_of_bounds(new_pos) {
match self.board[new_pos[1] as usize][new_pos[0] as usize] {
Piece::Black(_) => v.push(new_pos),
_ => (),
}
}
}
Piece::Black(Type::Knight) | Piece::White(Type::Knight) => {
self.push_move([pos[0] + 2., pos[1] + 1.], true, &mut v);
self.push_move([pos[0] - 2., pos[1] + 1.], true, &mut v);
self.push_move([pos[0] + 2., pos[1] - 1.], true, &mut v);
self.push_move([pos[0] - 2., pos[1] - 1.], true, &mut v);
self.push_move([pos[0] + 1., pos[1] + 2.], true, &mut v);
self.push_move([pos[0] - 1., pos[1] + 2.], true, &mut v);
self.push_move([pos[0] + 1., pos[1] - 2.], true, &mut v);
self.push_move([pos[0] - 1., pos[1] - 2.], true, &mut v);
}
Piece::Black(Type::Rook) | Piece::White(Type::Rook) => {
let mut offset = 1.;
while self.push_move([pos[0] + offset, pos[1]], true, &mut v) {
if !self.can_move_to([pos[0] + offset, pos[1]], false) {
break;
}
offset += 1.;
}
offset = -1.;
while self.push_move([pos[0] + offset, pos[1]], true, &mut v) {
if !self.can_move_to([pos[0] + offset, pos[1]], false) {
break;
}
offset -= 1.;
}
offset = 1.;
while self.push_move([pos[0], pos[1] + offset], true, &mut v) {
if !self.can_move_to([pos[0], pos[1] + offset], false) {
break;
}
offset += 1.;
}
offset = -1.;
while self.push_move([pos[0], pos[1] + offset], true, &mut v) {
if !self.can_move_to([pos[0], pos[1] + offset], false) {
break;
}
offset -= 1.;
}
}
Piece::Black(Type::Bishop) | Piece::White(Type::Bishop) => {
let mut offset = 1.;
while self.push_move([pos[0] + offset, pos[1] + offset], true, &mut v) {
if !self.can_move_to([pos[0] + offset, pos[1] + offset], false) {
break;
}
offset += 1.;
}
offset = 1.;
while self.push_move([pos[0] - offset, pos[1] + offset], true, &mut v) {
if !self.can_move_to([pos[0] - offset, pos[1] + offset], false) {
break;
}
offset += 1.;
}
offset = 1.;
while self.push_move([pos[0] + offset, pos[1] - offset], true, &mut v) {
if !self.can_move_to([pos[0] + offset, pos[1] - offset], false) {
break;
}
offset += 1.;
}
offset = 1.;
while self.push_move([pos[0] - offset, pos[1] - offset], true, &mut v) {
if !self.can_move_to([pos[0] - offset, pos[1] - offset], false) {
break;
}
offset += 1.;
}
}
Piece::Black(Type::Queen) | Piece::White(Type::Queen) => {
let mut offset = 1.;
while self.push_move([pos[0] + offset, pos[1] + offset], true, &mut v) {
if !self.can_move_to([pos[0] + offset, pos[1] + offset], false) {
break;
}
offset += 1.;
}
offset = 1.;
while self.push_move([pos[0] - offset, pos[1] + offset], true, &mut v) {
if !self.can_move_to([pos[0] - offset, pos[1] + offset], false) {
break;
}
offset += 1.;
}
offset = 1.;
while self.push_move([pos[0] + offset, pos[1] - offset], true, &mut v) {
if !self.can_move_to([pos[0] + offset, pos[1] - offset], false) {
break;
}
offset += 1.;
}
offset = 1.;
while self.push_move([pos[0] - offset, pos[1] - offset], true, &mut v) {
if !self.can_move_to([pos[0] - offset, pos[1] - offset], false) {
break;
}
offset += 1.;
}
offset = 1.;
while self.push_move([pos[0] + offset, pos[1]], true, &mut v) {
if !self.can_move_to([pos[0] + offset, pos[1]], false) {
break;
}
offset += 1.;
}
offset = -1.;
while self.push_move([pos[0] + offset, pos[1]], true, &mut v) {
if !self.can_move_to([pos[0] + offset, pos[1]], false) {
break;
}
offset -= 1.;
}
offset = 1.;
while self.push_move([pos[0], pos[1] + offset], true, &mut v) {
if !self.can_move_to([pos[0], pos[1] + offset], false) {
break;
}
offset += 1.;
}
offset = -1.;
while self.push_move([pos[0], pos[1] + offset], true, &mut v) {
if !self.can_move_to([pos[0], pos[1] + offset], false) {
break;
}
offset -= 1.;
}
}
Piece::Black(Type::King) | Piece::White(Type::King) => {
// TODO: Add logic stoping from king from making illegal moves <20-12-20, <NAME>>
let mut new_pos = [pos[0] + 1., pos[1]];
self.push_move(new_pos, true, &mut v);
new_pos = [pos[0] + 1., pos[1] + 1.];
self.push_move(new_pos, true, &mut v);
new_pos = [pos[0], pos[1] + 1.];
self.push_move(new_pos, true, &mut v);
new_pos = [pos[0] - 1., pos[1] + 1.];
self.push_move(new_pos, true, &mut v);
new_pos = [pos[0] - 1., pos[1]];
self.push_move(new_pos, true, &mut v);
new_pos = [pos[0] - 1., pos[1] - 1.];
self.push_move(new_pos, true, &mut v);
new_pos = [pos[0], pos[1] - 1.];
self.push_move(new_pos, true, &mut v);
new_pos = [pos[0] + 1., pos[1] - 1.];
self.push_move(new_pos, true, &mut v);
}
_ => (),
};
v
}
/// true if a point is outside of the chess board
fn point_out_of_bounds(&mut self, pos: [f32; 2]) -> bool {
pos[0] < 0. || pos[0] >= BOARD_SIZE as f32 || pos[1] < 0. || pos[1] >= BOARD_SIZE as f32
}
/// checks if a space is available to be inhabited
fn can_move_to(&mut self, pos: [f32; 2], can_kill: bool) -> bool {
if self.point_out_of_bounds(pos) {
return false;
}
let piece = self.board[pos[1] as usize][pos[0] as usize];
match piece {
Piece::Empty => true,
Piece::Black(_) => {
if self.color == Color::Black {
false
} else {
can_kill
}
}
Piece::White(_) => {
if self.color == Color::White {
false
} else {
can_kill
}
}
}
}
/// Checks if a new point can be moved to then pushed to a vector
fn push_move(&mut self, new_pos: [f32; 2], can_kill: bool, v: &mut Vec<[f32; 2]>) -> bool {
if self.can_move_to(new_pos, can_kill) {
v.push(new_pos);
return true;
}
false
}
/// move the piece in the position self.selected_pos to the argument pos
fn move_selected_piece(&mut self, pos: [f32; 2]) -> bool {
let s_pos = self.selected_pos.unwrap();
let moves = self.get_valid_moves(self.selected_pos.unwrap());
if moves.contains(&pos) {
self.board[pos[1] as usize][pos[0] as usize] =
self.board[s_pos[1] as usize][s_pos[0] as usize];
self.board[s_pos[1] as usize][s_pos[0] as usize] = Piece::Empty;
return true;
}
false
}
/// checks if the piece being clicked on is of the right team
fn is_piece_selectable(&mut self, pos: [f32; 2]) -> bool {
match self.board[pos[1] as usize][pos[0] as usize] {
Piece::Black(_) => self.color == Color::Black,
Piece::White(_) => self.color == Color::White,
Piece::Empty => false,
_ => unreachable!(),
}
}
}
impl event::EventHandler for State {
/// The game logic function.
fn update(&mut self, _ctx: &mut Context) -> GameResult {
Ok(())
}
/// when a mouse button is clicked down
fn mouse_button_down_event(
&mut self,
ctx: &mut Context,
button: input::mouse::MouseButton,
_x: f32,
_y: f32,
) {
if button == input::mouse::MouseButton::Left {
let pos = self.get_current_square(ctx);
if self.selected_pos == None {
if !self.is_piece_selectable(pos) {
return;
}
self.selected_pos = Some(pos);
} else {
if self.move_selected_piece(pos) {
self.color = match self.color {
Color::Black => Color::White,
Color::White => Color::Black,
_ => unreachable!(),
};
}
self.selected_pos = None;
}
}
}
/// the function that draws everything to the screen.
fn draw(&mut self, ctx: &mut Context) -> GameResult {
self.draw_board(ctx);
self.draw_pieces(ctx);
let current_square_pos = self.get_current_square(ctx);
self.highlight_square(ctx, current_square_pos, [1., 1., 0., 0.3].into());
if self.selected_pos != None {
self.highlight_square(ctx, self.selected_pos.unwrap(), [1., 0., 0., 0.3].into());
let moves = self.get_valid_moves(self.selected_pos.unwrap());
for m in moves {
self.highlight_square(ctx, m, [0., 1., 0., 0.3].into());
}
}
graphics::present(ctx)?;
Ok(())
}
}
/// Driver function
fn main() -> GameResult {
let (mut ctx, mut event_loop) =
ggez::ContextBuilder::new("Chess", "Patrick and <NAME>")
.window_setup(ggez::conf::WindowSetup {
title: "Chess".to_owned(),
samples: ggez::conf::NumSamples::Zero,
vsync: true,
icon: "".to_owned(),
srgb: true,
})
.window_mode(ggez::conf::WindowMode {
width: WINDOW_SIZE[0],
height: WINDOW_SIZE[1],
maximized: false,
fullscreen_type: ggez::conf::FullscreenType::Windowed,
borderless: false,
min_width: 0.0,
max_width: 0.0,
min_height: 0.0,
max_height: 0.0,
resizable: false,
})
.build()?;
let state = &mut State::new();
event::run(&mut ctx, &mut event_loop, state)
}
| a7f4ccfe2b14aa2182b29fee0f2e6ab552a075cb | [
"Rust"
] | 1 | Rust | shanemcdo/RustChess | 13e040e57696ae828851e311560592d5be43309f | c7c2add58fadc28050685af084a58673c302d91f |
refs/heads/master | <repo_name>udia-software/14<file_sep>/src/app/utils/firebase.js
import firebase from 'firebase';
import {FIREBASE_CONFIG} from '../config';
export const firebaseApp = firebase.initializeApp(FIREBASE_CONFIG);
export const firebaseAuth = firebaseApp.auth();
export const firebaseDb = firebaseApp.database();
var FireBaseTools = {
/**
* Return an instance of a firebase auth provider based on the provider string.
*
* @param provider
* @returns {firebase.auth.AuthProvider}
*/
getProvider: (provider) => {
switch (provider) {
case "email":
return new firebase.auth.EmailAuthProvider();
case "facebook":
return new firebase.auth.FacebookAuthProvider();
case "github":
return new firebase.auth.GithubAuthProvider();
case "google":
return new firebase.auth.GoogleAuthProvider();
case "twitter":
return new firebase.auth.TwitterAuthProvider();
default:
}
},
/**
* Login with provider => p is provider "email", "facebook", "github", "google", or "twitter"
* Uses Popup therefore provider must be an OAuth provider. EmailAuthProvider will throw an error
*
* @returns {any|!firebase.Thenable.<*>|firebase.Thenable<any>}
*/
loginWithProvider: (p) => {
let provider = FireBaseTools.getProvider(p);
return firebaseAuth.signInWithPopup(provider).then(function (result) {
return firebaseAuth.currentUser;
}).catch(function (error) {
return {
errorCode: error.code,
errorMessage: error.message
}
});
},
/**
* Register a user with email and password
*
* @param user
* @returns {any|!firebase.Thenable.<*>|firebase.Thenable<any>}
*/
registerUser: (user) => {
return firebaseAuth.createUserWithEmailAndPassword(user.email, user.password).then(user => {
return user;
}).catch(error => {
return {
errorCode: error.code,
errorMessage: error.message
}
});
},
/**
* Sign the user out
*
* @returns {!firebase.Promise.<*>|firebase.Thenable<any>|firebase.Promise<any>|!firebase.Thenable.<*>}
*/
logoutUser: () => {
return firebaseAuth.signOut().then(() => {
return {
success: 1,
message: "logout"
};
});
},
/**
* Retrieve the current user (Promise)
* @returns {Promise}
*/
fetchUser: () => {
return new Promise((resolve, reject) => {
const unsub = firebaseAuth.onAuthStateChanged(user => {
unsub();
resolve(user);
}, error => {
reject(error);
})
})
},
/**
* Log the user in using email and password
*
* @param user
* @returns {any|!firebase.Thenable.<*>|firebase.Thenable<any>}
*/
loginUser: (user) => {
return firebaseAuth.signInWithEmailAndPassword(user.email, user.password).then(user => {
return user;
}).catch(error => {
return {
errorCode: error.code,
errorMessage: error.message
}
});
},
/**
* Update a user's profile data
*
* @param u
* @returns {!firebase.Promise.<*>|firebase.Thenable<any>|firebase.Promise<any>|!firebase.Thenable.<*>}
*/
updateUserProfile: (u) => {
return firebaseAuth.currentUser.updateProfile(u).then(() => {
return firebaseAuth.currentUser;
}, error => {
return {
errorCode: error.code,
errorMessage: error.message
}
})
},
/**
* Reset the password given the specified email
*
* @param email {string}
* @returns {!firebase.Promise.<*>|firebase.Thenable<any>|firebase.Promise<any>|!firebase.Thenable.<*>}
*/
resetPasswordEmail: (email) => {
return firebaseAuth.sendPasswordResetEmail(email).then(() => {
return {
message: 'Email sent'
}
}, error => {
return {
errorCode: error.code,
errorMessage: error.message
}
});
},
/**
* Update the user's password with the given password
*
* @param newPassword {string}
* @returns {!firebase.Promise.<*>|firebase.Thenable<any>|firebase.Promise<any>|!firebase.Thenable.<*>}
*/
changePassword: (newPassword) => {
return firebaseAuth.currentUser.updatePassword(newPassword).then(user => {
return user;
}, error => {
return {
errorCode: error.code,
errorMessage: error.message
}
});
},
/**
* Send an account email verification message for the currently logged in user
*
* @returns {!firebase.Promise.<*>|firebase.Thenable<any>|firebase.Promise<any>|!firebase.Thenable.<*>}
*/
sendEmailVerification: () => {
return firebaseAuth.currentUser.sendEmailVerification().then(() => {
return {
message: 'Email sent'
}
}, error => {
return {
errorCode: error.code,
errorMessage: error.message
}
});
},
/**
* Get one Firebase node.
*
* @param key {string}
* @returns {firebase.Promise<any>|!firebase.Promise.<*>}
*/
getFirebaseNodeOnce: (key) => {
return firebaseDb.ref('nodes').child(key).once('value',
snapshot => {
return snapshot.exportVal();
}, error => {
return {
errorCode: error.code,
errorMessage: error.message
}
})
},
/**
* Create one Firebase node.
*
* @param node
* @returns {firebase.Promise<any>|!firebase.Promise.<void>}
*/
createFirebaseNode: (node) => {
// Get a new key for the node
let newNodeKey = firebaseDb.ref().child('nodes').push().key;
// Write the new node's data simultaneously in the nodes list and the user's node list.
let updates = {};
updates['/nodes/' + newNodeKey] = node;
updates['/user-nodes/' + node.author + '/' + newNodeKey] = node;
return firebaseDb.ref().update(updates).then(() => {
return node.uid = newNodeKey;
});
},
/**
* Set one firebase node. Used for updating nodes.
*
* @param key {string} UID of the node to update
* @param node {*} New node object. author, markdown, linked_nodes
* @returns {!firebase.Promise.<void>|firebase.Promise<any>}
*/
setFirebaseNode: (key, node) => {
return firebaseDb.ref().child('nodes').child(key).set(node).then(() => {
return node;
});
},
/**
* Listen to a firebase node
*
* @param key {string} The uid of the node
* @param callback {function} Callback is passed a DataSnapshot.
* @param cancelCallback {function} Optional callback for if the event is cancelled or lost
* @param context {*} If provided, this object will be used as this when calling the callbacks.
* @returns {function}
*/
listenToFirebaseNode: (key, callback, cancelCallback, context) => {
return firebaseDb.ref('nodes').child(key).on('value', callback, cancelCallback, context);
},
/**
* Stop listening to a firebase node
*
* @param key {string} The uid of the node
* @param callback {function} Optional, the callback function that was passed to listenToFirebaseNode
* @param context {*} Optional, the context that was passed to listenToFirebaseNode
* @returns {any}
*/
stopListeningToFirebaseNode: (key, callback, context) => {
return firebaseDb.ref('nodes').child(key).off('value', callback, context);
}
};
export default FireBaseTools;
<file_sep>/src/app/reducers/firebase_node_reducer.js
import {
GET_FIREBASE_NODE,
CREATE_FIREBASE_NODE,
SET_FIREBASE_NODE,
SET_CLIENT_NODE
} from '../actions/types';
export default function (state = null, action) {
switch (action.type) {
case GET_FIREBASE_NODE:
return action.payload;
case CREATE_FIREBASE_NODE:
return action.payload;
case SET_FIREBASE_NODE:
return action.payload;
case SET_CLIENT_NODE:
return action.payload;
}
return state;
}
<file_sep>/src/app/components/node/node.jsx
import React, {Component} from 'react';
import ReactMarkdown from 'react-markdown';
import firebase from '../../utils/firebase';
import {Link} from 'react-router';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {fetchUser} from '../../actions/firebase_actions';
import {setClientNode} from '../../actions/client_actions';
import Loading from '../helpers/loading';
class Node extends Component {
constructor(props) {
super(props);
this.props.fetchUser();
this.state = {
message: ''
};
}
render() {
if (!this.props.currentUser || !this.state.currentNode) {
return <Loading/>
}
return (
<div className="col-md-6">
<h2>{this.props.params.uid}</h2>
<p>{this.state.message}</p>
{
this.state.currentNode.author === this.props.currentUser.uid &&
<p>
<span className="glyphicons glyphicons-user">Welcome back, </span>
<Link to={"/node/edit/" + this.props.params.uid}>{this.state.currentNode.author}</Link>
</p>
}
{
this.state.currentNode.author !== this.props.currentUser.uid &&
<p>
<span className="glyphicons glyphicons-user">Author: </span>
{this.state.currentNode.author}
</p>
}
<ReactMarkdown source={this.state.currentNode.markdown}/>
<ul>
<li><Link to="/node/-KRCsPJ0LDq9OmsVOEfT" onClick={this._linkClicked.bind(this)('-KRCsPJ0LDq90msV0Eft')}>Udia</Link></li>
{this.state.currentNode.linked_nodes && Object.keys(this.state.currentNode.linked_nodes).map(linked_node => {
return (
<li key={linked_node}>
<Link to={"/node/" + linked_node} onClick={this._linkClicked.bind(this)(linked_node)}>{linked_node}</Link>
</li>
)
})}
</ul>
<br />
</div>
)
}
_linkClicked(event) {
return (uid) => {
firebase.stopListeningToFirebaseNode(this.props.params.uid, this._setNodeSnapshot, this);
console.log(this.props.params.uid, uid);
firebase.listenToFirebaseNode(uid, this._setNodeSnapshot, error => {
console.error(error);
}, this)
}
}
_setNodeSnapshot(snapshot) {
let nodeSnapshot = snapshot.exportVal();
this.props.setClientNode(nodeSnapshot);
// TODO: Why do I have to do this? Doesn't setClientNode do this for you? Possible bug.
this.setState({currentNode: nodeSnapshot});
}
componentDidMount() {
console.log(this.props.params.uid);
firebase.listenToFirebaseNode(this.props.params.uid, this._setNodeSnapshot, error => {
console.error(error);
}, this)
}
componentWillUnmount() {
firebase.stopListeningToFirebaseNode(this.props.params.uid, this._setNodeSnapshot, this);
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({fetchUser, setClientNode}, dispatch);
}
function mapStateToProps(state) {
return {currentUser: state.currentUser, currentNode: state.currentNode};
}
export default connect(mapStateToProps, mapDispatchToProps)(Node);
<file_sep>/src/app/config.js
module.exports = {
// Change this to your firebase configuration! (Add Firebase to your web app)
FIREBASE_CONFIG: {
apiKey: "<KEY>",
authDomain: "udia-1820e.firebaseapp.com",
databaseURL: "https://udia-1820e.firebaseio.com",
storageBucket: "udia-1820e.appspot.com"
}
};
<file_sep>/src/app/components/index_home.jsx
import React from 'react';
import {Link} from 'react-router';
export default () => {
return (
<div>
<h1>Udia</h1>
<p>The 14th prototype.</p>
<Link to="/node/-KRCsPJ0LDq9OmsVOEfT">Udia</Link>
<br/>
<br/>
<br/>
<p>Are there bugs, or is it intentional?</p>
</div>
);
};
<file_sep>/src/app/actions/client_actions.js
import {
SET_CLIENT_NODE
} from './types';
export function setClientNode(node) {
return {
type: SET_CLIENT_NODE,
payload: node
}
}
| 13c09c9e1512dee5984e4abf77932a9f8afd4237 | [
"JavaScript"
] | 6 | JavaScript | udia-software/14 | dcb6e586e1a9928e840cd4c56ee12a62d77fac05 | 9d185a135ab49ebd4da834e48e20a46e5b2e4670 |
refs/heads/master | <file_sep>[https://yuchiko.github.io/site-lviv](https://yuchiko.github.io/site-lviv)
<file_sep>(function ($, window, document) {
// The $ is now locally scoped
// Listen for the jQuery ready event on the document
$(function () {
// on ready
madValidation.init();
LvivTechnology.Init();
modalVideo.init();
$(document).keyup(function(a) // esc btn
{
if ((a.keyCode == 27) && ($(modalVideo.className).hasClass(modalVideo.activeClass))) {
modalVideo.close();
} else if ((a.keyCode == 27) && ($(mobileNav.className).hasClass(mobileNav.activeClass))) {
mobileNav.close();
}
});
});
$(window).on('load', function () {
// on load
mobileNav.init('.header__menu');
});
// code
var mobileNav = {
className: '.js_mobile-nav',
copyClassName: '.js_mobile-nav_copy',
mobileMenuClassName: '.mobile-nav__menu',
activeClass: 'open',
init: function (mainMenuClassName) {
if (!$(this.mobileMenuClassName).children().length) {
$(mainMenuClassName).children().clone().prependTo(this.mobileMenuClassName);
}
$(document).on('click', '.burger', function () {
mobileNav.toggle();
});
},
open: function () {
$(this.className).addClass(this.activeClass);
},
close: function () {
$(this.className).removeClass(this.activeClass);
},
toggle: function () {
$(this.className).hasClass(this.activeClass) ? this.close() : this.open();
}
};
var madValidation = {
option: {
formClass: '.md-form'
},
init: function() {
var _self = this;
var forms = document.querySelectorAll(_self.option.formClass);
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', _self.initActions);
}
},
initActions: function(e){
e.preventDefault();
var form = e.target;
if (madValidation.validForm(form)) {
var data = $(form).serialize();
var pathAction = $(form).attr('action');
$.ajax({
url: pathAction,
data: data,
type: 'POST',
success: function (dataofconfirm) {
swal("Спасибо!", "Ваша заявка успешно отправлена - мы свяжемся с вами в ближайшее время!", "success");
$(form).find('input:not([type="submit"])').each(function(){
// $(this).removeClass('form__input--error');
$(this).val('');
})
}
});
}
},
validForm: function(form) {
var userData = {
user_name: $(form).find('#user_name').val(),
user_email: $(form).find('#user_mail').val(),
user_tel: $(form).find('#user_tel').val(),
user_work: $(form).find('#user_work').val()
}
var validator = new LIVR.Validator({
user_name: 'required',
user_email: [ 'required', 'email' ],
user_tel: [ 'required', 'integer', { 'max_length': 15 }, { 'min_length': 10 } ],
user_work: 'required'
});
var translateData = {
user_name: "Ім'я",
user_email: "Пошта",
user_tel: "Телефон",
user_work: "Cфера діяльності",
REQUIRED: "Обов'язкове для заповнення",
TOO_SHORT: "Надто короткий телефон",
TOO_LONG: "Надто довгий телефон",
NOT_INTEGER: "Допустимі тільки цифри"
}
var validData = validator.validate(userData);
if (validData) {
return true;
} else {
var errors = validator.getErrors();
var errorText = '';
for (var prop in errors) {
if( errors.hasOwnProperty( prop ) ) {
errorText += 'Поле ' + translateData[prop] + " - " + translateData[errors[prop]] + "\n";
}
};
swal(
'Форма заповнена із помилками!',
errorText,
'error'
);
}
}
}
var globalController = new ScrollMagic.Controller();
var LvivTechnology = {
Init: function() {
this.PageLoad();
this.NavTransition();
this.Scroll();
this.AnimateSlogan();
this.ScrollOnLoad();
this.ScrollOnTop();
if (window.innerWidth > 767) {
// this.AnimateIcons();
this.AnimateTitles();
}
this.VideoText();
this.StickyNav();
// this.AnimateCanvas();
this.SmoothScrolling();
this.SelectCustom();
},
ScrollOnTop: function(){
$(window).on('scroll', function () {
if ($(this).scrollTop() > 300) {
$('#scroller').fadeIn();
} else {
$('#scroller').fadeOut();
}
});
$('#scroller').on('click', function () {
$('body,html').stop().animate({
scrollTop: 0
}, 1500);
return false;
});
},
ScrollOnLoad: function() {
if (location.search) {
var locS = location.search;
locS = '#' + locS.substring(1);
var $anchor = $(locS);
$('html, body').stop().animate({
scrollTop: $anchor.offset().top
}, 1500);
}
},
Scroll: function() {
var tl = new TimelineMax();
tl
.to('#image-container #layer-2', 1, {opacity: 1})
.to('#image-container #layer-3', 1, {opacity: 1});
var pinIntroScene = new ScrollMagic.Scene({
triggerElement: '#pin-container',
triggerHook: 0,
duration: 1 * $(window).height()
// duration: '100%'
})
.setPin('#pin-container')
.setTween(tl)
.addTo(globalController);
},
SelectCustom: function() {
$('select').selectize();
},
AnimateCanvas: function() {
var canvases = document.getElementsByClassName('anim-canvas');
[].forEach.call(canvases, function(canvas){
createCanvas(canvas);
});
function createCanvas(canvas) {
var ctx = canvas.getContext('2d');
var shapes = [];
var num = 50;
var staticXpos;
var staticYpos;
var opt = {
shapecolor: "#2e2e2e",
radius: 5,
distance: 200,
circleopacity: 2,
speed: .4
};
var w = canvas.width = window.innerWidth;
var h = canvas.height = window.innerHeight;
addEventListener('resize', function() {
w = canvas.width = window.innerWidth;
h = canvas.height = window.innerHeight;
});
//helper functions
function random(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function clearcanvas() {
ctx.clearRect(0, 0, w, h);
}
function getCords(e) {
var rect = canvas.getBoundingClientRect();
return {
x: e.clientX - rect.left,
y: e.clientY - rect.top
};
}
function createShapes(Xpos, Ypos) {
this.x = Xpos ? Xpos : random(0, w);
this.y = Ypos ? Ypos : random(0, h);
this.speed = opt.speed;
this.vx = Math.cos(random(0, 360)) * this.speed;
this.vy = Math.sin(random(0, 360)) * this.speed;
this.r = opt.radius;
this.color = opt.shapecolor;
this.opacity = opt.circleopacity;
this.draw = function() {
ctx.beginPath();
ctx.globalCompositeOperation = 'source-over';
ctx.globalAlpha = this.opacity;
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fillStyle = this.color;
ctx.fill();
};
this.move = function() {
this.x += this.vx;
this.y += this.vy;
if (this.x >= w || this.x <= 0) {
this.vx *= -1;
}
if (this.y >= h || this.y <= 0) {
this.vy *= -1;
}
this.x > w ? this.x = w : this.x;
this.y > h ? this.y = h : this.y;
this.x < 0 ? this.x = 0 : this.x;
this.y < 0 ? this.y = 0 : this.y;
};
}
function check(point1, rest) {
for (var j = 0; j < rest.length; j++) {
var yd = point1.y - rest[j].y;
var xd = point1.x - rest[j].x;
var d = Math.sqrt(xd * xd + yd * yd);
if (d < opt.distance) {
ctx.beginPath();
ctx.globalAlpha = (1 - (d / opt.distance));
ctx.globalCompositeOperation = 'destination-over';
ctx.lineWidth = 1;
ctx.moveTo(point1.x, point1.y);
ctx.lineTo(rest[j].x, rest[j].y);
ctx.strokeStyle = opt.shapecolor;
ctx.lineCap = "round";
ctx.closePath();
ctx.stroke();
}
}
}
function loop() {
clearcanvas();
shapes[0].x = staticXpos;
shapes[0].y = staticYpos;
shapes[0].move();
shapes[0].draw();
for (var i = 1; i < shapes.length; i++) {
shapes[i].move();
shapes[i].draw();
check(shapes[i], shapes);
}
window.requestAnimationFrame(loop);
}
function init() {
for (var i = 0; i < num; i++) {
shapes.push(new createShapes());
}
window.requestAnimationFrame(loop);
}
init();
}
},
AnimateTitles: function() {
var titles = $('.sc__title');
titles.each(function() {
var tl = new TimelineMax();
tl.fromTo(this, 0.5, {x: -500, opacity: 0}, {x: 0, opacity: 1});
var scene = new ScrollMagic.Scene({
triggerElement: this,
triggerHook: 0.3,
offset: -500
})
.setTween(tl)
.addTo(globalController);
});
},
VideoText: function() {
var vt = $('.video__text');
vt.each(function() {
var tl = new TimelineMax();
tl.fromTo(this, 0.5, {y: 300, opacity: 0}, {y: 0, opacity: 1});
var scene = new ScrollMagic.Scene({
triggerElement: '#videosc .container',
triggerHook: 'onLeave',
offset: -200
})
.setTween(tl)
.addTo(globalController);
});
},
PageLoad: function() {
setTimeout(function() {
$("body").removeClass("is-pagetransition");
}, 100);
setTimeout(function() {
$("body").addClass("is-pagetransitionend");
$('.loader-overlay').hide();
}, 1400);
},
StickyNav: function() {
var a, b = 0,
c = $(document),
d = $(window),
e = $(".js-navbar");
if ($(window).scrollTop() > 700) {
e.addClass("show-bg");
} else {
e.removeClass("show-bg");
}
a = Modernizr.touch ? 150 : 25, d.scroll(function() {
var f = $(this).scrollTop();
if (Math.abs(b - f) >= a && f > 0) {
if (f > b) {
c.height() - (c.scrollTop() + d.height()) > 50 ? e.addClass("is-hidden") : e.removeClass("is-hidden")
} else e.removeClass("is-hidden");
if (f > 700) {
e.addClass("show-bg")
} else {
e.removeClass("show-bg");
}
b = f
}
})
},
NavTransition: function() {
$(".js-link, .header__logo").on("click", function(e) {
e.preventDefault();
var href = $(this).attr("href");
$('.loader-overlay').show();
$("body").removeClass("is-pagetransitionend");
$("body").addClass("is-pagetransition");
setTimeout(function() {
window.location.href = href;
}, 600)
});
},
AnimateSlogan: function() {
var slogan = $('#welcome-slogan'),
animatedWord = slogan.find('.is-animate'),
words = ['City', 'Живи', 'Працюй', 'Навчайся', 'Відпочивай'],
timing = 4000;
function iterateWords() {
for(var i = 0; i < words.length; i++) {
(function(index) {
setTimeout(function() {
(index === 0) ? animatedWord.css('color', '#fff') : animatedWord.css('color', '#f7901e');
var splitWord = words[index].split('').map(function(el) {
return '<i>' + el + '</i>';
}).join('');
animatedWord.html(splitWord).find('i').each(function(i) {
var self = $(this);
setTimeout(function() {
self.addClass('is-visible');
}, (i + 1) * 100);
});
}, index * timing);
})(i);
}
}
iterateWords();
setInterval(function() {
iterateWords();
}, words.length * timing);
},
AnimateIcons: function() {
if (!Modernizr.touchevents) {
var b = new TimelineMax;
b.add([TweenMax.to(".js-ic-a__icon--circle", 1, {
marginLeft: "-49%",
marginTop: "42%",
rotation: 360
}), TweenMax.to(".js-ic-a__icon--rhomb", 1, {
marginLeft: "-23.5%",
marginTop: "31%",
rotation: 360
}), TweenMax.to(".js-ic-a__icon--star", 1, {
marginLeft: "1%",
marginTop: "20%",
rotation: 360
}), TweenMax.to(".js-ic-a__icon--stop", 1, {
marginLeft: "26%",
marginTop: "9%",
rotation: 360
})]);
new ScrollMagic.Scene({
triggerElement: ".js-ic-a",
duration: 400
}).setTween(b).addTo(globalController)
}
},
SmoothScrolling: function() {
$(document).on('click touchstart', 'a.page-scroll', function (e) {
e.preventDefault();
$('.js_mobile-nav').removeClass('open');
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500);
});
}
}
var modalVideo = {
$self: $(this),
className: '.modal__video',
linkClassName: '.modal__link',
modalBtn: '.modal__close',
activeClass: 'open',
init: function () {
$(document).on('click', this.linkClassName, function (e) {
e.preventDefault();
modalVideo.open($(this).data('url'));
});
$(document).on('click', this.modalBtn, function () {modalVideo.close();});
},
open: function (data_url) {
$(this.className).addClass(this.activeClass);
data_url = modalVideo.youtubeParser(data_url);
data_url = "//www.youtube.com/embed/" + data_url + '?autoplay=1';
$(this.className).prepend($("<iframe />")
.attr({ width: '100%', height:'100%', src: data_url, frameborder: 0, "allowfullscreen": "" }));
},
close: function () {
$(this.className).removeClass(this.activeClass);
$(this.className).find('iframe').remove();
},
toggle: function () {
$(this.className).hasClass(this.activeClass) ? this.close() : this.open();
},
youtubeParser: function(url){
var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
var match = url.match(regExp);
return (match&&match[7].length==11)? match[7] : false;
}
};
}(window.jQuery, window, document));
<file_sep><section class="sc sc--scew residents sc--dark" id="residents">
<div class="back"></div>
<div class="container">
<h2 class="sc__title">Резидентам</h2>
<div class="row">
<div class="column col-6 col-md-3">
<div class="sc__header">
<h3 class="heading">Як стати резидентом?</h3>
</div>
<p class="about__text">Надсучасне та комфортне місто у місті, інфраструктура якого відрізняється не тільки функціональністю та естетикою, але й якістю будівництва та сучасними технологіями енергоефективності</p>
<a class="about__more js-link" href="./residents.html#how-to">Детальніше...</a>
</div>
<div class="column col-6 col-md-3">
<div class="sc__header">
<h3 class="heading">Що дає статус резидента?</h3>
</div>
<p class="about__text">Спільнота, що об’єднує провідні технологічні та інноваційні компанії, R&D центри, інкубатори і акселератори, активно розвиаваючихся підприємців та молоді стартапи, які, інтегруючись, створюють кластер інновацій, спільну екосистему</p>
<a class="about__more js-link" href="./residents.html#profit">Детальніше...</a>
</div>
<div class="column col-6 col-md-3">
<div class="sc__header">
<h3 class="heading">Подати заявку</h3>
</div>
<p class="about__text">Ми прагнемо побудувати таку систему, яка буде сприяти постійній взаємодії та комунікації між резидентами містечка задля досягнення синергії, яка буде давати свій позитивний ефект як для всієї спільноти, так і для кожного підприємця окремо </p>
<a class="about__more js-link" href="./residents.html#form">Детальніше...</a>
</div>
<div class="column col-6 col-md-3">
<div class="sc__header">
<h3 class="heading">FAQ</h3>
</div>
<p class="about__text">Якщо у вас є будь-які питання щодо резиденства у LvivTech.City ми завжди охоче відповімо на усі Ваші запитання!</p>
<a class="about__more js-link" href="./residents.html#faq">Детальніше...</a>
</div>
</div>
</div>
</section><file_sep>var gulp = require('gulp'),
sass = require('gulp-sass'),
browserSync = require('browser-sync'),
autoprefixer = require('gulp-autoprefixer'),
rename = require('gulp-rename'),
sourcemaps = require('gulp-sourcemaps'),
rigger = require('gulp-rigger'),
wiredep = require('wiredep').stream,
useref = require('gulp-useref'),
gulpif = require('gulp-if'),
minifyCss = require('gulp-minify-css'),
uglifyjs = require('uglify-js'),
minifier = require('gulp-uglify/minifier'),
pump = require('pump');
var options = {
preserveComments: 'license'
};
gulp.task('build', function() {
return gulp.src('*.html')
.pipe(wiredep({
directory: "./bower_components/"
}))
.pipe(useref())
.pipe(gulpif('*.js', minifier(options, uglifyjs)))
.pipe(gulpif('*.css', minifyCss()))
.pipe(gulp.dest('.'))
});
gulp.task('compress', function (cb) {
// the same options as described above
pump([
gulp.src('./assets/js/include.js'),
minifier(options, uglifyjs),
rename(function (path) {
path.basename += ".min";
}),
gulp.dest('./assets/js/')
],
cb
);
});
gulp.task('bower', function () {
gulp.src('./src/partials/inc-*.html')
.pipe(wiredep({
directory: "./bower_components/"
}))
.pipe(gulp.dest('./src/partials/'));
});
// ... variables
var autoprefixerOptions = {
browsers: ['last 2 versions', '> 5%', 'Firefox ESR', 'ie >= 10']
};
var output = './';
gulp.task('html', function () {
return gulp.src('./src/*.html')
.pipe(rigger())
.pipe(gulp.dest(output))
.pipe(browserSync.reload({stream:true}));
});
gulp.task('css', function () {
return gulp.src('./assets/scss/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer(autoprefixerOptions))
.pipe(gulp.dest(output))
.pipe(sourcemaps.write())
.pipe(gulp.dest(output))
.pipe(browserSync.reload({stream:true}));
});
gulp.task('browser-sync', function() {
browserSync.init(null, {
server: {
baseDir: output
}
});
});
gulp.task('bs-reload', function () {
browserSync.reload();
});
gulp.task('default', ['html', 'css', 'browser-sync'], function () {
gulp.watch("./assets/scss/**/*.scss", ['css']);
gulp.watch("./src/**/*.html", ['html']);
gulp.watch("./assets/js/*.js", ['bs-reload']);
gulp.watch('bower.json', ['bower']);
});
gulp.task('release', function () {
return gulp.src('./assets/scss/**/*.scss')
.pipe(sass({ outputStyle: 'compressed' }))
.pipe(autoprefixer(autoprefixerOptions))
.pipe(gulp.dest(output))
});
| 05f2927c6f416e5f75edc1865e5ae75896138025 | [
"Markdown",
"JavaScript",
"HTML"
] | 4 | Markdown | mdvs-pro/site-lviv-tech | 246a7e337c66a55336bc283e47950cacdd5966e7 | 039ce25648f1cff57ff701606d7fab5699291366 |
refs/heads/master | <repo_name>haewoni/workspace-spring-tool-suite-4-4.8.0.RELEASE<file_sep>/JDBC[Java DataBase Connectivity]/src/com/itwill/account/ui/AccountPanel.java
package com.itwill.account.ui;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.GridLayout;
import javax.swing.JTabbedPane;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import com.itwill.account.Account;
import com.itwill.account.AccountService;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class AccountPanel extends JPanel {
/*************************************/
private AccountService accountService;
/*
private MemberService memberService;
private ProductService productService;
private OrderService orderService;
private CartService cartService;
*/
/**********************************/
private JTabbedPane accountTP;
private JTextField noTF;
private JTextField ownerTF;
private JTextField balanceTF;
private JComboBox iyulCB;
private JTextArea accountListTA;
private JTextField searchTF;
private JComboBox searchTypeCB;
/**
* Create the panel.
*/
public AccountPanel() {
setBackground(Color.PINK);
setLayout(new BorderLayout(0, 0));
JPanel panel = new JPanel();
add(panel, BorderLayout.SOUTH);
JButton btnNewButton = new JButton("계좌추가");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
accountTP.setSelectedIndex(0);
}
});
panel.add(btnNewButton);
JButton btnNewButton_1 = new JButton("계좌리스트");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
accountTP.setSelectedIndex(1);
}
});
panel.add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("계좌찾기");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
accountTP.setSelectedIndex(2);
}
});
panel.add(btnNewButton_2);
JButton btnNewButton_3 = new JButton("입금");
btnNewButton_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
accountTP.setSelectedIndex(3);
}
});
panel.add(btnNewButton_3);
accountTP = new JTabbedPane(JTabbedPane.TOP);
add(accountTP, BorderLayout.CENTER);
JPanel addP = new JPanel();
addP.setBackground(Color.PINK);
accountTP.addTab("계좌추가", null, addP, null);
addP.setLayout(null);
JLabel lblNewLabel = new JLabel("번호");
lblNewLabel.setBounds(80, 38, 57, 15);
addP.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("이름");
lblNewLabel_1.setBounds(80, 79, 57, 15);
addP.add(lblNewLabel_1);
JLabel lblNewLabel_2 = new JLabel("잔고");
lblNewLabel_2.setBounds(80, 118, 57, 15);
addP.add(lblNewLabel_2);
JLabel lblNewLabel_3 = new JLabel("이율");
lblNewLabel_3.setBounds(80, 161, 57, 15);
addP.add(lblNewLabel_3);
noTF = new JTextField();
noTF.setBounds(149, 35, 116, 21);
addP.add(noTF);
noTF.setColumns(10);
ownerTF = new JTextField();
ownerTF.setBounds(149, 76, 116, 21);
addP.add(ownerTF);
ownerTF.setColumns(10);
balanceTF = new JTextField();
balanceTF.setBounds(149, 115, 116, 21);
addP.add(balanceTF);
balanceTF.setColumns(10);
iyulCB = new JComboBox();
iyulCB.setModel(new DefaultComboBoxModel(new String[] {"0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "0.7", "0.8"}));
iyulCB.setBounds(149, 158, 116, 21);
addP.add(iyulCB);
JButton btnNewButton_4 = new JButton("추가");
btnNewButton_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
accountAdd();
}
});
btnNewButton_4.setBounds(86, 205, 97, 23);
addP.add(btnNewButton_4);
JButton btnNewButton_5 = new JButton("취소");
btnNewButton_5.setBounds(195, 205, 97, 23);
addP.add(btnNewButton_5);
JPanel listP = new JPanel();
listP.setBackground(Color.ORANGE);
accountTP.addTab("계좌리스트", null, listP, null);
listP.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(12, 43, 487, 242);
listP.add(scrollPane);
accountListTA = new JTextArea();
scrollPane.setViewportView(accountListTA);
searchTypeCB = new JComboBox();
searchTypeCB.setModel(new DefaultComboBoxModel(new String[] {"전체", "번호", "이름", "잔고", "이율"}));
searchTypeCB.setBounds(52, 11, 77, 21);
listP.add(searchTypeCB);
searchTF = new JTextField();
searchTF.setBounds(141, 10, 50, 23);
listP.add(searchTF);
searchTF.setColumns(10);
JButton btnNewButton_7 = new JButton("검색");
btnNewButton_7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
accountSearch();
}
});
btnNewButton_7.setBounds(214, 10, 70, 23);
listP.add(btnNewButton_7);
JPanel searchP = new JPanel();
searchP.setBackground(Color.YELLOW);
accountTP.addTab("계좌찾기", null, searchP, null);
searchP.setLayout(null);
JPanel depositP = new JPanel();
depositP.setBackground(Color.GREEN);
accountTP.addTab("입금", null, depositP, null);
depositP.setLayout(null);
accountTP.setSelectedIndex(0);
myServiceInit();
}
/***********서비스객체들생성***********************/
private void myServiceInit(){
try {
accountService=new AccountService();
} catch (Exception e) {
e.printStackTrace();
}
}
/**********계좌추가**************/
public void accountAdd() {
String noStr=noTF.getText();
String ownerStr=ownerTF.getText();
String balanceStr=balanceTF.getText();
String iyulStr=(String)iyulCB.getSelectedItem();
if(noStr.equals("")||ownerStr.equals("")||
balanceStr.equals("")||iyulStr.equals("")) {
JOptionPane.showMessageDialog(null, "입력하세요!!!");
noTF.requestFocus();
return;
}
try {
int no = Integer.parseInt(noStr);
int balance=Integer.parseInt(balanceStr);
double iyul=Double.parseDouble(iyulStr);
Account newAccount=new Account(no,ownerStr,balance,iyul);
if(accountService.addAccount(newAccount)) {
//추가성공
noTF.setText("");
ownerTF.setText("");
balanceTF.setText("");
iyulCB.setSelectedIndex(0);
accountTP.setSelectedIndex(1);
}else {
//추가실패
JOptionPane.showMessageDialog(null, "계좌번호중복입니다.");
noTF.requestFocus();
noTF.setSelectionStart(0);
noTF.setSelectionEnd(noStr.length());
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "애러발생");
e.printStackTrace();
}
}
/**********계좌검색************/
public void accountSearch() {
try {
String searchType =(String)searchTypeCB.getSelectedItem();
ArrayList<Account> accountList=new ArrayList<Account>();
switch (searchType) {
case "전체":
accountList = accountService.findByAll();
break;
case "번호":
String noStr=searchTF.getText();
if(noStr.equals("")) {
JOptionPane.showMessageDialog(null, "번호를 입력하세요!!");
searchTF.requestFocus();
return;
}
Account findAccount=
accountService.findAccountByNo(Integer.parseInt(noStr));
if(findAccount!=null) {
accountList.add(findAccount);
}
break;
case "이름":
String ownerStr=searchTF.getText();
if(ownerStr.equals("")) {
JOptionPane.showMessageDialog(null, "이름을 입력하세요!!");
searchTF.requestFocus();
return;
}
accountList = accountService.findAccountByOwner(ownerStr);
break;
case "잔고":
break;
case "이율":
break;
}
String accountListStr="";
for (Account account : accountList) {
accountListStr+=account.toString()+"\n";
}
accountListTA.setText(accountListStr);
}catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>/springMavenApp/src/main/java/com/itwill1/bean/create/CreateBean2.java
package com.itwill1.bean.create;
public class CreateBean2 {
public CreateBean2() {
System.out.println("### CreateBean2() 기본 생성자");
}
public void method1() {
System.out.println("### CreateBean2().method1()메소드 호출");
}
}
<file_sep>/JDBC[Java DataBase Connectivity]/src/resultset/ScrollableResultSetMain.java
package resultset;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import dao.common.ConnectionFactory;
public class ScrollableResultSetMain {
public static void main(String[] args) throws Exception{
String selectSql="select * from emp order by empno asc";
Connection con=ConnectionFactory.getConnection();
PreparedStatement pstmt =
con.prepareStatement(selectSql,
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs=pstmt.executeQuery();
/*
* Cursor를 자유롭게움직일수있는 ResultSet생성
*/
System.out.println("-----------rs.next()-----------");
while(rs.next()) {
System.out.println(rs.getInt("empno")+"\t"+rs.getString("ename"));
}
System.out.println("-----------rs.previous()-----------");
while(rs.previous()) {
System.out.println(rs.getInt("empno")+"\t"+rs.getString("ename"));
}
System.out.println("-----------rs.first()-----------");
rs.first();
System.out.println(rs.getInt("empno")+"\t"+rs.getString("ename"));
System.out.println("-----------rs.last()-----------");
rs.last();
System.out.println(rs.getInt("empno")+"\t"+rs.getString("ename"));
int rowNo=rs.getRow();
System.out.println("rowNo:"+rowNo);
System.out.println("-----------rs.beforeFirst()-----------");
rs.beforeFirst();
// 결과 집합을 모두 소모했음
rs.next();
System.out.println(rs.getInt("empno")+"\t"+rs.getString("ename"));
System.out.println("-----------rs.beforeFirst()-----------");
rs.afterLast();
rs.previous();
System.out.println(rs.getInt("empno")+"\t"+rs.getString("ename"));
rs.beforeFirst();
if(rs.isBeforeFirst() || rs.isAfterLast()) {
System.out.println("rs cursor 가 BeforeFirst or AfterLast에 위치해있네요!!");
}
System.out.println("-------------rs.absolute(row번호)---------");
rs.absolute(10);
System.out.println(rs.getInt("empno")+"\t"+rs.getString("ename"));
System.out.println("-------------rs.realtive(2)---------");
rs.relative(2);
System.out.println(rs.getInt("empno")+"\t"+rs.getString("ename"));
rs.relative(-2);
System.out.println(rs.getInt("empno")+"\t"+rs.getString("ename"));
rs.close();
}
}
<file_sep>/JDBC[Java DataBase Connectivity]/src/com/itwill/account/AccountSQL.java
package com.itwill.account;
public class AccountSQL {
public static final String INSERT=
"insert into account values(?,?,?,?)";
public static final String UPDATE=
"update account set owner=?,balance=?,iyul=? where no=?";
public static final String DELETE=
"delete account where no=?";
public static final String SELECTBYNO=
"select * from account where no=?";
public static final String SELECTBYOWNER=
"select * from account where owner=?";
public static final String SELECTALL=
"select * from account";
}
<file_sep>/springMavenApp/src/main/java/com/itwill1/bean/annotation/InitDestroyBean.java
package com.itwill1.bean.annotation;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.stereotype.Component;
@Component(value="initDestroyBean")
public class InitDestroyBean {
public InitDestroyBean() {
System.out.println("### InitDestroyBean() 기본 생성자");
}
@PostConstruct
public void myInit() {
System.out.println("### InitDestroyBean.myInit() 메소드 호출");
}
@PreDestroy
public void myDestroy() {
System.out.println("### InitDestroyBean.myDestroy() 메소드 호출");
}
}
<file_sep>/springMavenBootApp/src/main/java/com/itwill1/bean/create/CreateBean4.java
package com.itwill1.bean.create;
public class CreateBean4 {
public CreateBean4() {
System.out.println("### CreateBean4() 기본 생성자");
}
public void method1() {
System.out.println("### CreateBean4().method1()메소드 호출");
}
}
<file_sep>/guest_model2_spring/src/main/java/com/itwill/guest/controller/GuestErrorController.java
package com.itwill.guest.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import com.itwill.summer.Controller;
public class GuestErrorController implements org.springframework.web.servlet.mvc.Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) {
/**************************************************/
String forwardPath="forward:/WEB-INF/views/guest_error.jsp";
ModelAndView mv=new ModelAndView();
mv.setViewName(forwardPath);
return mv;
}
}
<file_sep>/JDBC[Java DataBase Connectivity]/src/com/itwill/account/AccountDaoMemoryImpl.java
package com.itwill.account;
import java.util.ArrayList;
public class AccountDaoMemoryImpl implements AccountDao{
private ArrayList<Account> accountList;
public AccountDaoMemoryImpl() {
accountList=new ArrayList<Account>();
accountList.add(new Account(1111, "KIM", 89000, 1.3));
accountList.add(new Account(2222, "AIM", 45000, 2.7));
accountList.add(new Account(3333, "FIM", 23000, 4.7));
accountList.add(new Account(4444, "XIM", 34000, 6.7));
accountList.add(new Account(5555, "HIM", 78000, 3.7));
accountList.add(new Account(6666, "AIM", 99000, 5.7));
accountList.add(new Account(7777, "PIM", 89000, 4.7));
accountList.add(new Account(8888, "QIM", 91000, 1.7));
accountList.add(new Account(9999, "MIM", 12000, 0.7));
}
@Override
public boolean create(Account account) throws Exception{
if(!this.isDuplicateNo(account.getNo())) {
accountList.add(account);
return true;
}else {
return false;
}
}
private boolean isDuplicateNo(int no) throws Exception{
boolean isDuplicate=false;
for (Account account : accountList) {
if(account.getNo()==no) {
isDuplicate=true;
break;
}
}
return isDuplicate;
}
/*
* ReadOne
* ReadAll
*/
@Override
public Account readOne(int no) throws Exception {
Account findAccount=null;
for (Account account : accountList) {
if(account.getNo()==no) {
findAccount=account;
}
}
return findAccount;
}
@Override
public ArrayList<Account> readAll() throws Exception{
return accountList;
}
@Override
public ArrayList<Account> readByOwner(String ownerStr) throws Exception{
ArrayList<Account> findAccounts=new ArrayList<Account>();
for (Account account : accountList) {
if(account.getOwner().equals(ownerStr)) {
findAccounts.add(account);
}
}
return findAccounts;
}
/*
* Update
/*
public void update(Account updateAccount) throws Exception {
for (Account account : accountList) {
if(account.getNo()==updateAccount.getNo()) {
account.setOwner(updateAccount.getOwner());
account.setBalance(updateAccount.getBalance());
account.setIyul(updateAccount.getIyul());
break;
}
}
}
*/
@Override
public void update(Account updateAccount) throws Exception {
for (int i = 0; i < accountList.size(); i++) {
if(accountList.get(i).getNo()==updateAccount.getNo()) {
accountList.set(i, updateAccount);
break;
}
}
}
@Override
public void update(int no,String owner,int balalnce,double iyul) throws Exception {
for (int i = 0; i < accountList.size(); i++) {
if(accountList.get(i).getNo()==no) {
accountList.get(i).setOwner(owner);
accountList.get(i).setBalance(balalnce);
accountList.get(i).setIyul(iyul);
}
}
}
/*
* Delete
*/
@Override
public void delete(int no) throws Exception{
for (int i=0;i<accountList.size();i++) {
if(accountList.get(i).getNo()==no) {
accountList.remove(i);
break;
}
}
}
}
<file_sep>/guest_spring/src/main/java/com/itwill/guest/mapper/GuestMapper.java
package com.itwill.guest.mapper;
import java.util.ArrayList;
import com.itwill.guest.Guest;
public interface GuestMapper {
/*
* CREATE
*/
int insertGuest(Guest guest) throws Exception;
/*
* READ ONE
*/
Guest selectByNo(int no) throws Exception;
/*
* READ ALL
*/
ArrayList<Guest> selectAll() throws Exception;
/*
* UPDATE
*/
int updateGuest(Guest guest) throws Exception;
/*
* DELETE
*/
int deleteGuest(int no) throws Exception;
}<file_sep>/user_model2_mybatis/src/com/itwill/user/UserDaoTestMain.java
package com.itwill.user;
public class UserDaoTestMain {
public static void main(String[] args) {
UserDaoMyBatis userDao = new UserDaoMyBatis();
System.out.println("------findUserList------");
System.out.println("###"+userDao.findUserList());;
System.out.println("------findUser------");
System.out.println("###"+userDao.findUser("guard2"));
// System.out.println("------create------");
User user = new User("hehehe","1111","황지희","<EMAIL>");
System.out.println("###"+userDao.create(user));
System.out.println("------update------");
User user1 = new User("hahahah","0000","김민정","<EMAIL>");
user1.setName(new String());
System.out.println("###"+userDao.update(user1));
}
}<file_sep>/user_model2_mybatis/src/com/itwill/user/UserDaoMyBatis.java
package com.itwill.user;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class UserDaoMyBatis {
private SqlSessionFactory sqlSessionFactory;
public static final String NAMESPACE="com.itwill.user.mapper.UserMapper.";
public UserDaoMyBatis() {
try {
InputStream mybatisConfigInputStream =
Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder ssfb=new SqlSessionFactoryBuilder();
sqlSessionFactory=ssfb.build(mybatisConfigInputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// public int create(User user) {
//
// }
//
// /*
// * 기존의 사용자정보를 수정
// */
// public int update(User user) {
//
// }
//
// /*
// * 사용자아이디에해당하는 사용자를 삭제
// */
// public int remove(String userId) {
//
// }
//
// /*
// * 사용자아이디에해당하는 정보를 데이타베이스에서 찾아서 User 도메인클래스에 저장하여 반환
// */
// public User findUser(String userId) {
//
// }
/*
* 모든사용자 정보를 데이타베이스에서 찾아서 List<User> 콜렉션 에 저장하여 반환
*/
public List<User> findUserList() {
SqlSession sqlSession = sqlSessionFactory.openSession();
List<User> userList =
sqlSession.selectList(NAMESPACE+"findUserList");
sqlSession.close();
return userList;
}
public User findUser(String userId) {
SqlSession sqlSession = sqlSessionFactory.openSession();
User findUser =
sqlSession.selectOne(NAMESPACE+"findUser",userId);
sqlSession.close();
return findUser;
}
public int create(User user) {
SqlSession sqlSession = sqlSessionFactory.openSession();
int insertRowCount = sqlSession.insert(NAMESPACE+"create",user);
sqlSession.close();
return insertRowCount;
}
public int update(User user) {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
int updateRowCount = sqlSession.insert(NAMESPACE+"update",user);
sqlSession.close();
return updateRowCount;
}
// /*
// * 인자로 전달되는 아이디를 가지는 사용자가 존재하는지의 여부를판별
// */
// public boolean existedUser(String userId) {
// Connection con = null;
//
// }
}
<file_sep>/guest_spring/src/main/java/com/itwill/guest/GuestDaoImplMyBatisMapperInterface.java
package com.itwill.guest;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.itwill.guest.mapper.GuestMapper;
@Component
public class GuestDaoImplMyBatisMapperInterface implements GuestDao,GuestMapper {
private SqlSessionFactory sqlSessionFactory;
@Autowired
private GuestDao guestDao;
public GuestDaoImplMyBatisMapperInterface(GuestDao guestDao) {
this.guestDao = guestDao;
}
public GuestDaoImplMyBatisMapperInterface() throws Exception {
/*
* 모든 마이바티스 애플리케이션은 SqlSessionFactory 인스턴스를 사용한다.
* SqlSessionFactory인스턴스는 SqlSessionFactoryBuilder를 사용하여 만들수 있다.
* SqlSessionFactoryBuilder는 XML설정파일에서
* SqlSessionFactory인스턴스를 빌드할 수 있다.
* XML파일에서 SqlSessionFactory인스턴스를 빌드하는 것은 매우 간단한다.
* 설정을 위해 클래스패스 자원을 사용하는 것을 추천하나
* 파일 경로나 file:// URL로부터 만들어진 InputStream인스턴스를 사용할 수도 있다.
* 마이바티스는 클래스패스와 다른 위치에서 자원을 로드하는 것으로 좀더 쉽게 해주는
* Resources 라는 유틸성 클래스를 가지고 있다.
*/
InputStream in=Resources.getResourceAsStream("mybatis-config.xml");
this.sqlSessionFactory=
new SqlSessionFactoryBuilder().build(in);
}
/*
* CREATE
*/
@Override
public int insertGuest(Guest guest) throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
GuestMapper guestMapper = sqlSession.getMapper(GuestMapper.class);
int insertRowCount = guestMapper.insertGuest(guest);
return insertRowCount;
}
/*
* READ ONE
*/
@Override
public Guest selectByNo(int no) throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
GuestMapper guestMapper = sqlSession.getMapper(GuestMapper.class);
Guest guest= guestMapper.selectByNo(no);
return guest;
}
/*
* READ ALL
*/
@Override
public ArrayList<Guest> selectAll() throws Exception {
ArrayList<Guest> guestList = new ArrayList<Guest>();
SqlSession sqlSession = sqlSessionFactory.openSession(true);
GuestMapper guestMapper = sqlSession.getMapper(GuestMapper.class);
guestList = guestMapper.selectAll();
return guestList;
}
/*
* UPDATE
*/
@Override
public int updateGuest(Guest guest) throws Exception {
return sqlSessionFactory.openSession(true).getMapper(GuestMapper.class).updateGuest(guest);
}
/*
* DELETE
*/
@Override
public int deleteGuest(int no) throws Exception {
return sqlSessionFactory.openSession(true).getMapper(GuestMapper.class).deleteGuest(no);
}
}
<file_sep>/JDBC[Java DataBase Connectivity]/src/com/itwill/account/AccountDao.java
package com.itwill.account;
import java.util.ArrayList;
public interface AccountDao {
/**********************************************/
/*
* Create
*/
boolean create(Account account) throws Exception;
/*
* ReadOne
* ReadAll
*/
Account readOne(int no) throws Exception;
ArrayList<Account> readAll() throws Exception;
ArrayList<Account> readByOwner(String ownerStr) throws Exception;
/*
* Update
/*
public void update(Account updateAccount) throws Exception {
ArrayList<Account> accountList=this.readFile();
for (Account account : accountList) {
if(account.getNo()==updateAccount.getNo()) {
account.setOwner(updateAccount.getOwner());
account.setBalance(updateAccount.getBalance());
account.setIyul(updateAccount.getIyul());
break;
}
}
this.writeFile(accountList);
}
*/
void update(Account updateAccount) throws Exception;
void update(int no, String owner, int balalnce, double iyul) throws Exception;
/*
* Delete
*/
void delete(int no) throws Exception;
}<file_sep>/JDBC[Java DataBase Connectivity]/src/jdbc.sql
select*from emp;<file_sep>/springMavenWeb/src/main/java/com/itwill/controller/annotation/ResponseController.java
package com.itwill.controller.annotation;
import java.util.ArrayList;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.InternalResourceView;
import org.springframework.web.servlet.view.RedirectView;
@Controller
public class ResponseController {
/********************forward view*******************/
@RequestMapping("/response_view_name.do")
public String response_view_name() {
/*
<< 빈의 이름에 forward:가 없을경우 >>
0 . view name[String(/WEB-INF/views/response_view_name.jsp)]을 반환받은
DispatcherServlet은 InternalResourceViewResolver객체(디폴트)에 view name을 전달한다.
1 . InternalResourceViewResolver 객체는 InternalResourceView 객체를 생성한다.
2 . InternalResourceViewResolver 객체는
InternalResourceView 객체에 view name(/WEB-INF/views/response_view_name.jsp)을
URL로 설정한후에 DispatcherServlet에게 반환한다.
(설정XML에 prefix,sufix가 존재 하면 prefix,sufix가 설정된다)
(설정XML에 prefix,sufix가 존재안하면 prefix,sufix가 설정되지안는다)
3 . DispatcherServlet 은 반환받은 InternalResourceView 객체의 render()메쏘드를 호출한다.
결과로 /WEB-INF/views/response_view_name.jsp로 forward된다.
<< 빈의 이름에 forward: 가있을경우 >> servlet--forward-->servlet
0 . view name[String(forward:xxx.do)]을 반환받은
DispatcherServlet은 InternalResourceViewr객체(디폴트)에 view name을 전달한다.
1 . InternalResourceViewResolver 객체는 InternalResourceView 객체를 생성한다.
2 . InternalResourceViewResolver 객체는
InternalResourceView 객체에 view name(/WEB-INF/views/response_view_name.jsp)을
URL로 설정한후에 DispatcherServlet에게 반환한다.
(설정XML에 prefix,sufix가 존재 해도 prefix,sufix가 설정되지앟는다)
(설정XML에 prefix,sufix가 존재안하면 prefix,sufix가 설정되지앟는다)
3 . DispatcherServlet 은 반환받은 InternalResourceView 객체의 render()메쏘드를 호출한다.
결과로 xxx.do 로 forward된다.
*/
/*
web-application-context-view-resolver.xml
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
*/
//return "forward:/WEB-INF/views/response_view_name.jsp";
return "response_view_name";
}
@RequestMapping("/response_view_object.do")
public View response_view_object() {
InternalResourceView internalResourceView=new InternalResourceView();
internalResourceView.setUrl("/WEB-INF/views/response_view_object.jsp");
//String==> forward:/WEB-INF/views/response_view_object.jsp
/*
* 1.InternalResourceView 객체(URL:/WEB-INF/views/response_view_object.jsp)반환
* 2.URL--> /WEB-INF/views/response_view_object.jsp forward
*/
return internalResourceView;
}
/********************redirect view*******************/
@RequestMapping("response_redirect_view_name.do")
public String response_redirect_view_name(Model model) {
model.addAttribute("id", "guard");
model.addAttribute("name", "kim");
/*
* response_redirect_view_object.jsp?id=guard&name=kim
*/
return "redirect:response_redirect_view_name.jsp";
}
@RequestMapping("response_redirect_view_object.do")
public View response_redirect_view_object(Model model) {
model.addAttribute("id", "guard");
model.addAttribute("name", "kim");
RedirectView redirectView=new RedirectView();
redirectView.setUrl("response_redirect_view_name.jsp");
/*
* response_redirect_view_object.jsp?id=guard&name=kim
*/
return redirectView;
}
/*******************xml출력 View[XMLView]***********************/
@RequestMapping("response_xml_view_object.do")
public View response_xml_view_object(Model model) {
ArrayList<String> friendsList=new ArrayList<String>();
friendsList.add("김수미");
friendsList.add("김우미");
friendsList.add("김미미");
friendsList.add("김양미");
friendsList.add("김가미");
model.addAttribute("friendList",friendsList);
XMLView xmlView=new XMLView();
return xmlView;
}
@RequestMapping("response_xml_view_name.do")
public String response_xml_view_name(Model model) {
ArrayList<String> friendsList=new ArrayList<String>();
friendsList.add("김수미");
friendsList.add("김우미");
friendsList.add("김미미");
friendsList.add("김양미");
friendsList.add("김가미");
model.addAttribute("friendList",friendsList);
return "xmlView";
}
}
<file_sep>/springMavenBootApp/src/main/java/com/itwill1/bean/create/ApplicationContextMain.java
package com.itwill1.bean.create;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ApplicationContextMain {
public static void main(String[] args) throws Exception {
/*
* ApplicationContext객체생성
* - BeanFactory객체생성
* - Spring Container객체생성
*/
System.out.println("------------Spring Container 초기화시작---------");
ApplicationContext applicationContext=
new ClassPathXmlApplicationContext(
"com/itwill1/bean/create/1.bean-create.xml");
System.out.println("------------Spring Container 초기화끝---------");
System.out.println("-------------scope [singleton]--------------");
SingletonScopeBean singletonScopeBean1 =
(SingletonScopeBean)applicationContext.getBean("singletonBean");
SingletonScopeBean singletonScopeBean2 =
(SingletonScopeBean)applicationContext.getBean("singletonBean");
System.out.println(singletonScopeBean1);
System.out.println("---------scope [prototype]----------");
SingletonScopeBean singletonScopeBean4 =
(SingletonScopeBean)applicationContext.getBean("prototypeBean");
System.out.println(singletonScopeBean4);
System.out.println("---------init method, destroy-method----------");
DisposableBean context =(DisposableBean)applicationContext;
context.destroy();
}
}
<file_sep>/springMavenApp/src/main/java/com/itwill3/dao/user/UserDaoImplJDBCTestMain.java
package com.itwill3.dao.user;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.itwill3.dao.guest.GuestDao;
public class UserDaoImplJDBCTestMain {
public static void main(String[] args) {
ApplicationContext applicationContext=
new ClassPathXmlApplicationContext("com/itwill3/dao/user/user-dao-jdbc.xml");
}
}
<file_sep>/JDBC[Java DataBase Connectivity]/src/com/itwill/account/account.sql
drop table account;
create table account(
no number(10) primary key,
owner varchar2(100) not null,
balance number(10),
iyul number(10,2));
insert into account values(1111,'KIM',34000,3.4);
insert into account values(2222,'KIM',34000,3.4);
insert into account values(3333,'KIM',34000,3.4);
insert into account values(4444,'LEE',12000,2.4);
insert into account values(5555,'PARK',77000,1.3);
insert into account values(6666,'CHOI',99000,2.9);
insert into account values(7777,'SIM',61000,1.8);
insert into account values(8888,'HONG',81000,4.8);
insert into account values(9999,'JAMES',38000,3.3);
commit;
select * from account where no=7777;
select * from account where owner='KIM';
select * from account;
delete account where no=1111;
update account set owner='JAVA',balance=9999,iyul=9.9 where no=2222;
<file_sep>/JDBC[Java DataBase Connectivity]/src/com/itwill/account/AccountDaoDBImpl.java
package com.itwill.account;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
public class AccountDaoDBImpl implements AccountDao{
@Override
public boolean create(Account account) throws Exception {
boolean insertOk=false;
try {
Connection con=ConnectionFactory.getConnection();
PreparedStatement pstmt=con.prepareStatement(AccountSQL.INSERT);
pstmt.setInt(1 ,account.getNo());
pstmt.setString(2, account.getOwner());
pstmt.setInt(3 ,account.getBalance());
pstmt.setDouble(4 ,account.getIyul());
int insertCount=pstmt.executeUpdate();
insertOk=true;
}catch (Exception e) {
insertOk=false;
e.printStackTrace();
}
return insertOk;
}
@Override
public Account readOne(int no) throws Exception {
Account account=null;
Connection con = ConnectionFactory.getConnection();
PreparedStatement pstmt=con.prepareStatement(AccountSQL.SELECTBYNO);
pstmt.setInt(1, no);
ResultSet rs=pstmt.executeQuery();
if (rs.next()) {
account=new Account(
rs.getInt("no"),
rs.getString("owner"),
rs.getInt("balance"),
rs.getDouble("iyul"));
}
return account;
}
@Override
public ArrayList<Account> readAll() throws Exception {
ArrayList<Account> accountList=new ArrayList<Account>();
Connection con = ConnectionFactory.getConnection();
PreparedStatement pstmt=con.prepareStatement(AccountSQL.SELECTALL);
ResultSet rs=pstmt.executeQuery();
while (rs.next()) {
accountList.add(new Account(
rs.getInt("no"),
rs.getString("owner"),
rs.getInt("balance"),
rs.getDouble("iyul")));
}
return accountList;
}
@Override
public ArrayList<Account> readByOwner(String ownerStr) throws Exception {
ArrayList<Account> accountList=new ArrayList<Account>();
Connection con = ConnectionFactory.getConnection();
PreparedStatement pstmt=con.prepareStatement(AccountSQL.SELECTBYOWNER);
pstmt.setString(1, ownerStr);
ResultSet rs=pstmt.executeQuery();
while (rs.next()) {
accountList.add(new Account(
rs.getInt("no"),
rs.getString("owner"),
rs.getInt("balance"),
rs.getDouble("iyul")));
}
return accountList;
}
@Override
public void update(Account updateAccount) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void update(int no, String owner, int balalnce, double iyul) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void delete(int no) throws Exception {
// TODO Auto-generated method stub
}
}
<file_sep>/JDBC[Java DataBase Connectivity]/src/com/itwill/account/AccountService.java
package com.itwill.account;
import java.util.ArrayList;
/*
은행업무를 실행할클래스
- 계좌관리 업무를 수행하는 클래스
- Account객체를 사용(의존성관계)
- AccountServiceMain 에서 사용
- 업무를 처리시 데이타접근이 필요하면
AccountDao객체 를 이용해서 업무를 실행
- AccountDao객체를 포함하고있다.[멤버변수]
*/
public class AccountService {
private AccountDao accountDao;
public AccountService() throws Exception{
//accountDao=new AccountDaoFileImpl();
//accountDao=new AccountDaoMemoryImpl();
accountDao=new AccountDaoDBImpl();
}
/*
* 계좌생성
*/
public boolean addAccount(Account account) throws Exception{
boolean isAdd = accountDao.create(account);
return isAdd;
}
/*
* 계좌전체검색후 반환
*/
public ArrayList<Account> findByAll() throws Exception {
ArrayList<Account> accountList=accountDao.readAll();
return accountList;
}
/*
* 계좌번호로 1개검색후 반환
*/
public Account findAccountByNo(int no)throws Exception {
Account account=accountDao.readOne(no);
return account;
}
/*
* 계좌입금
*/
public void ipGum(int no,int m) throws Exception{
/*
* 1.계좌번호로 계좌찾기
* 2.입금
*/
Account account = accountDao.readOne(no);
account.deposit(m);
accountDao.update(account);
}
/*
* 계좌출금
*/
public void chulGum(int no,int m) throws Exception{
/*
* 1.계좌번호로 계좌찾기
* 2.출금
*/
Account account = accountDao.readOne(no);
account.withdraw(m);
accountDao.update(account);
}
/*
* 계좌해지
*/
public Account close(int no) throws Exception{
Account closeAccount=null;
closeAccount = accountDao.readOne(no);
if(closeAccount.getBalance()!=0) {
}else {
accountDao.delete(no);
}
return closeAccount;
}
public ArrayList<Account> findAccountByOwner(String ownerStr)throws Exception {
ArrayList<Account> accountList=accountDao.readByOwner(ownerStr);
return accountList;
}
}
<file_sep>/JDBC[Java DataBase Connectivity]/src/dao/address/second/AddressDao2.java
package dao.address.second;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class AddressDao2 {
/*
Dao(Data Access Object)
- Address들의 데이터를 저장하고있는 Address 테이블에
CRUD(Create, Read, Update, Delete) 작업을 할수있는
단위메쏘드를 가지고있는 클래스
- AddressService객체의 요청(메쏘드호출)을 받아서
Data Access(DB)에 관련된 단위기능(CRUD)을
수행하는 객체
*/
public void create(String id,String name,String phone,String address) throws Exception{
String driverClass= "oracle.jdbc.OracleDriver";
String url = "jdbc:oracle:thin:@192.168.3.11:1521:XE";
String user = "javapython30";
String password = "<PASSWORD>";
String insertSql = "insert into address values(address_no_seq.nextval,'"+id+"','"+name+"','"+phone+"','"+address+"')";
Class.forName(driverClass);
Connection con = DriverManager.getConnection(url,user,password);
Statement stmt = con.createStatement();
int rowCount = stmt.executeUpdate(insertSql);
System.out.println(rowCount+"행 insert");
stmt.close();
con.close();
}
public void delete(int no) throws Exception{
String driverClass= "oracle.jdbc.OracleDriver";
String url = "jdbc:oracle:thin:@192.168.3.11:1521:XE";
String user = "javapython30";
String password = "<PASSWORD>";
String deleteSql = "delete address where no=1"+no;
System.out.println("deleteSql:"+deleteSql);
Class.forName(driverClass);
Connection con = DriverManager.getConnection(url,user,password);
Statement stmt = con.createStatement();
int rowCount = stmt.executeUpdate(deleteSql);
System.out.println(rowCount+"행 delete");
stmt.close();
con.close();
}
public void update(int no,String id,String name,String phone,String address) throws Exception{
String driverClass= "oracle.jdbc.OracleDriver";
String url = "jdbc:oracle:thin:@192.168.3.11:1521:XE";
String user = "javapython30";
String password = "<PASSWORD>";
String updateSql = "update address set id='"+id+"',name='"+name+"',phone='"+phone+"',address='"+address+"'\r\n" +
"where no= no";
System.out.println("updateSql:"+updateSql);
Class.forName(driverClass);
Connection con = DriverManager.getConnection(url,user,password);
Statement stmt = con.createStatement();
int rowCount = stmt.executeUpdate(updateSql);
System.out.println(rowCount+"행 update");
stmt.close();
con.close();
}
public void selectByNo(int no) throws Exception{
String driverClass= "oracle.jdbc.OracleDriver";
String url = "jdbc:oracle:thin:@192.168.3.11:1521:XE";
String user = "javapython30";
String password = "<PASSWORD>";
String selectSql="select no,id,name,phone,address from address where no=3";
System.out.println("selectSql:"+selectSql);
Class.forName(driverClass);
Connection con = DriverManager.getConnection(url,user,password);
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(selectSql);
if(rs.next()) {
int fno = rs.getInt("no");
String id = rs.getString("id");
String name = rs.getString("name");
String phone = rs.getString("phone");
String address = rs.getString("address");
System.out.println(no+"\t"+id+"\t"+name+"\t"+phone+"\t"+address);
}
rs.close();
stmt.close();
con.close();
}
public void selectAll() throws Exception{
String driverClass= "oracle.jdbc.OracleDriver";
String url = "jdbc:oracle:thin:@192.168.3.11:1521:XE";
String user = "javapython30";
String password = "<PASSWORD>";
String selectSql="select no,id,name,phone,address from address";
Class.forName(driverClass);
Connection con = DriverManager.getConnection(url,user,password);
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(selectSql);
while(rs.next()) {
int no = rs.getInt("no");
String id = rs.getString("id");
String name = rs.getString("name");
String phone = rs.getString("phone");
String address = rs.getString("address");
System.out.println(no+"\t"+id+"\t"+name+"\t"+phone+"\t"+address);
}
rs.close();
stmt.close();
con.close();
}
}<file_sep>/JDBC[Java DataBase Connectivity]/src/com/itwill/account/Account.java
package com.itwill.account;
import java.io.Serializable;
/*
은행계좌객체를 추상화한클래스
VO(Value Object),DTO(Data Transfer Object)
- 계좌관리를 위하여 필요한 도메인클래스(VO,DTO)
- 계좌객체 한개의 데이타를가지고있다.(VO)
- 계좌객체 한개의 데이타를 저장하기위한멤버변수를 가지고있다
*/
public class Account implements Serializable{
/*
* 속성(멤버변수)
*/
private int no;//계좌번호
private String owner;//계좌주
private int balance;//잔고
private double iyul;//이율
public Account() {
// TODO Auto-generated constructor stub
}
public Account(int no, String owner, int balance, double iyul) {
this.no = no;
this.owner = owner;
this.balance = balance;
this.iyul = iyul;
}
/*
* 행위(멤버메쏘드)
*
* 입금
* 출금
* 계좌정보출력
*/
public void setAccountData(int no,String owner,int balance,double iyul) {
this.no=no;
this.owner=owner;
this.balance=balance;
this.setIyul(iyul);
}
public void deposit(int m) {
this.balance = this.balance + m;
}
public void withdraw(int m){
if(this.balance-m < 0) {
return;
}
this.balance=this.balance-m;
return;
}
public static void headerPrint() {
System.out.println("---------------------------------------");
System.out.println("번호\t이름\t잔고\t이율");
System.out.println("---------------------------------------");
}
public void print() {
System.out.println(
this.no+"\t"+this.owner+"\t"+this.balance+"\t"+this.iyul);
}
public void printNameFormat() {
/*
1.첫글자 대문자
2.5자리로출력
3.첫글자이외에는****(4개)
---------------------------------------
번호 이름 잔고 이율
---------------------------------------
1111 K**** 89000 1.3
2222 A**** 45000 2.7
3333 F**** 23000 4.7
4444 X**** 34000 6.7
5555 H**** 78000 3.7
6666 K**** 99000 5.7
7777 K**** 89000 4.7
8888 Q**** 91000 1.7
9999 M**** 12000 0.7
*/
System.out.println(
this.no+"\t"+this.owner+"\t"+this.balance+"\t"+this.iyul);
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
return super.equals(obj);
}
@Override
public String toString() {
// TODO Auto-generated method stub
return this.no+"\t"+this.owner+"\t"+this.balance+"\t"+this.iyul+"\n";
}
//getter,setter
/*
* alt + shift + s
*/
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public double getIyul() {
return iyul;
}
public void setIyul(double iyul) {
this.iyul = iyul;
}
}
<file_sep>/springMavenBootApp/src/main/java/com/itwill0/context/SpringMavenAppApplication.java
package com.itwill0.context;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class SpringMavenAppApplication {
public static void main(String[] args) {
/***********spring이 제어를한다.[IOC]**********/
System.out.println("-------------------Spring Container초기화시작------------------");
ApplicationContext applicationContext=
SpringApplication.run(SpringMavenAppApplication.class, args);
System.out.println("-------------------Spring Container초기화끝------------------");
/*************************************/
System.out.println(applicationContext);
ProductService productService=
(ProductService)applicationContext.getBean("productService");
productService.list();
/************개발자님이 제어를한다 **********
ProductDao productDao=new ProductDao();
ProductService productService=new ProductService();
productService.setProductDao(productDao);
productService.list();
********************************************/
}
}
<file_sep>/mybatisApp/src/com/mybatis3/dao/StudentDaoDynamicSqlMain.java
package com.mybatis3.dao;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.mybatis3.domain.Student;
public class StudentDaoDynamicSqlMain {
public static void main(String[] args) throws Exception{
StudentDaoDynamicSql studentDaoDynamicSql = new StudentDaoDynamicSql();
System.out.println("---------findStudents---------");
Student findStudent=new Student();
System.out.println("### "+studentDaoDynamicSql.findStudents(findStudent));
findStudent.setStudId(1);
findStudent.setEmail("<EMAIL>");
findStudent.setName("신혜원");
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
Date dob = dateFormat.parse("2000-01-01");
//findStudent.setDob(dob);
System.out.println("### "+studentDaoDynamicSql.findStudents(findStudent));
System.out.println("---------updateStudentById---------");
Student updateStudent = new Student();
updateStudent.setStudId(1);
updateStudent.setName("반장님");
// updateStudent.setEmail(System.currentTimeMillis()+"<EMAIL>");
// updateStudent.setDob(new Date());
System.out.println("###"+studentDaoDynamicSql.updateStudentById(updateStudent));
System.out.println("--------findStudentsOrder----------");
System.out.println("### "+studentDaoDynamicSql.findStudentsOrder("stud_id"));
}
}
<file_sep>/guest_spring/src/main/java/com/itwill/guest/controller/GuestController.java
package com.itwill.guest.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.itwill.guest.Guest;
import com.itwill.guest.GuestService;
@Controller
public class GuestController {
@Autowired
private GuestService guestService;
@RequestMapping(value="guest_delete_action.do",method = RequestMethod.POST)
public String guest_delete_action_post(@RequestParam String guest_no) throws Exception {
int deleteRowCount = guestService.deleteGuest(Integer.parseInt(guest_no));
return "redirect:guest_list.do";
}
@RequestMapping(value="guest_modify_action.do",method=RequestMethod.GET)
public String guest_modify_action_get() {
return "redirect:guest_modify_form.do";
}
@RequestMapping(value="guest_modify_action.do",method = RequestMethod.POST)
public String guest_modify_action_post(@ModelAttribute Guest guest,@RequestParam String guest_no) throws Exception {
String forwardPath = "";
int updateRowCount = guestService.updateGuest(guest);
// forwardPath = "redirect:guest_view.do?guest_no="+guest_no;
forwardPath = "guest_view";
return forwardPath;
}
@RequestMapping("guest_modify_form.do")
public String guest_modify_form(Model model,@RequestParam String guest_no) throws Exception {
String forwardPath = "";
Guest guest = guestService.selectByNo(Integer.parseInt(guest_no));
model.addAttribute("guest", guest);
forwardPath = "guest_modify_form";
return forwardPath;
}
@RequestMapping(value = "/guest_write_action.do", method = RequestMethod.GET)
public String guest_write_action_get() {
return "redirect:guest_write_form.do";
}
@RequestMapping(value = "/guest_write_action.do", method = RequestMethod.POST)
public String guest_write_action_post(@ModelAttribute Guest guest) throws Exception {
String forwardPath = "";
int insertRowCount = guestService.insertGuest(guest);
forwardPath = "redirect:guest_list.do";
return forwardPath;
}
@RequestMapping("/guest_write_form.do")
public String guest_write_form() {
return "guest_write_form";
}
@RequestMapping("/guest_main.do")
public String guest_main() {
return "guest_main";
}
@RequestMapping("/guest_list.do")
public String guest_list(Model model) throws Exception {
String forwardPath = "";
List<Guest> guestList = guestService.selectAll();
model.addAttribute("guestList", guestList);
forwardPath = "guest_list";
return forwardPath;
}
@RequestMapping("/guest_view.do")
public String guest_view(Model model, @RequestParam String guest_no) throws Exception {
String forwardPath = "";
Guest guest = guestService.selectByNo(Integer.parseInt(guest_no));
model.addAttribute("guest", guest);
forwardPath = "guest_view";
return forwardPath;
}
@ExceptionHandler(Exception.class)
public String guest_error_handle(Exception e) {
return "guest_error";
}
}
<file_sep>/springMavenBootApp/src/main/java/com/itwill1/bean/create/SingletonScopeBean.java
package com.itwill1.bean.create;
public class SingletonScopeBean {
public SingletonScopeBean() {
System.out.println("SingletonBean() 기본 생성자:"+this);
}
}
| d93c0cbef82586dc566705476a3179bade7f2202 | [
"Java",
"SQL"
] | 26 | Java | haewoni/workspace-spring-tool-suite-4-4.8.0.RELEASE | bd329a5c72b11557dbaa8a22c4725c1a42aebbe3 | 730b27adc42ffdc5114f94d804791800ba6f27b0 |
refs/heads/master | <file_sep>const AWS = require('aws-sdk');
AWS.config.update({
region: "us-east-2",
endpoint: "http://localhost:8000"
});
async function test2 (event, context) {
const DocumentClient = new AWS.DynamoDB.DocumentClient();
// Consigo el token
const tokenHeader = '<KEY>';
const tokenDecoded = tokenHeader.split(' ');
const tokenBody = tokenDecoded[1];
// Me fijo en la base de datos de token-email-lookup
const {Items: getUser} = await DocumentClient.query({
TableName: 'token-email-lookup',
KeyConditionExpression: '#token = :token',
ExpressionAttributeNames: {
'#token': 'token'
},
ExpressionAttributeValues: {
':token': tokenBody
}
}).promise();
// Consigo el email
const emailVerify = getUser[0].email;
// Busco las notas de ese email
const {Items: notas} = await DocumentClient.query({
TableName: 'user-notes',
KeyConditionExpression: '#user = :user',
ExpressionAttributeNames: {
'#user': 'user'
},
ExpressionAttributeValues: {
':user': emailVerify
},
Limit: 10
}).promise();
// Ordena las notas de la mas vieja a la mas nueva
const notasSorted = notas.sort(function(a, b) {
var dateA = new Date(a.create_date).getTime();
var dateB = new Date(b.create_date).getTime();
return dateA > dateB ? 1 : -1;
});
// Devuelvo las notas
return {
statusCode: 200,
body: JSON.stringify({
message: 'Prueba del testing 2',
notasSorted
}),
};
};
module.exports = { test2 }
| 937c9e5a00671c0d15e67e9c3118a188a66c00df | [
"JavaScript"
] | 1 | JavaScript | dkippes/testCodility-2 | 9382a23480ef675b36ba0804dacd13e5714b31af | 26901e17d79b33fb25d12243a22928ccd5d16393 |
refs/heads/master | <repo_name>hunterae/exercism-exercises<file_sep>/javascript/hamming/hamming.js
module.exports = function(firstStrand, secondStrand) {
var differences = 0;
if (!firstStrand || !secondStrand)
throw 'Both DNA strands must be passed in';
else if (firstStrand.length != secondStrand.length)
throw 'DNA strands must be of equal length.';
else if (firstStrand != secondStrand)
for (var i = 0; i < firstStrand.length; i++) {
if (firstStrand[i] != secondStrand[i])
differences++;
}
return differences;
}
| 817a8fd80412c29980d9fae40de8e400a52a1866 | [
"JavaScript"
] | 1 | JavaScript | hunterae/exercism-exercises | ffc960ca0e2ad373f7c3c2e65e8c209d0b12a79a | 365eb7d22e2c0f5eae9ef47fc79a82238c92ce89 |
refs/heads/master | <file_sep>require 'rubygems'
require 'bundler'
Bundler.require
require 'sinatra'
require 'sinatra/base'
require 'sinatra/cometio'
require File.expand_path 'main', File.dirname(__FILE__)
EM.epoll
EM.set_descriptor_table_size 20000
run TestApp
<file_sep>source 'https://rubygems.org'
gem 'eventmachine'
gem 'thin'
gem 'sinatra-cometio'
gem 'em-cometio-client'
<file_sep>#!/usr/bin/env ruby
require 'rubygems'
require 'bundler'
Bundler.require
url = ARGV.shift || 'http://localhost:5000/cometio/io'
push_at = nil
times = []
EM.epoll
EM.set_descriptor_table_size 20000
EM::run do
client = nil
500.times do
client = EM::CometIO::Client.new(url).connect
client.on :foo do |data|
times.push Time.now - push_at
end
end
client.on :connect do |session|
puts "connect (session:#{session})"
EM::add_periodic_timer 5 do
unless times.empty?
puts "#{times.size} results"
puts times.inject(:+)/times.size
end
times = []
push_at = Time.now
client.push :foo, "bar"
end
end
end
<file_sep>
class TestApp < Sinatra::Base
register Sinatra::CometIO
io = Sinatra::CometIO
get '/' do
"testapp - sinatra-cometio v#{Sinatra::CometIO::VERSION}"
end
io.on :foo do |data, from|
p data
io.push :foo, data
end
end
| d67cb63abc73abaa60e5efa27de0d3e93bba80d8 | [
"Ruby"
] | 4 | Ruby | shokai/sinatra-cometio-bench | 1d524540d82782b49e5d8b3c90695f83a1f9e3ca | c075580432be13f38378468d6d45516186107caa |
refs/heads/main | <repo_name>kraigspear/DataStructuresAndAlgorithms<file_sep>/Stack/Stack/Stack.swift
//
// Stack.swift
// Stack
//
// Created by <NAME> on 8/21/21.
//
import Foundation
struct Stack<Element: Equatable>: Equatable {
init() {}
init(_ elements: [Element]) {
self.array.append(contentsOf: elements)
}
init(_ elements: Element...) {
self.array.append(contentsOf: elements)
}
private var array: [Element] = []
mutating func push(_ element: Element) {
array.append(element)
}
@discardableResult
mutating func pop() -> Element? {
return array.popLast()
}
func peek() -> Element? {
array.last
}
var isEmpty: Bool {
array.isEmpty
}
}
extension Stack: CustomStringConvertible {
var description: String {
return array.map { "\($0)" }
.joined(separator: ",")
}
}
extension Stack: ExpressibleByArrayLiteral {
init(arrayLiteral elements: Element...) {
self.init(elements)
}
}
<file_sep>/Queue/Queue/QueueArray.swift
//
// QueueArray.swift
// QueueArray
//
// Created by <NAME> on 8/22/21.
//
import Foundation
struct QueueArray<T>: Queue {
typealias Element = T
private var array: [T] = []
mutating func enqueue(_ element: T) {
array.append(element)
}
@discardableResult
mutating func dequeue() -> T? {
isEmpty ? nil : array.removeFirst()
}
var peek: T? {
array.first
}
var isEmpty: Bool { array.isEmpty }
}
<file_sep>/Sorts/Sorts/BubbleSort.swift
//
// BubbleSort.swift
// BubbleSort
//
// Created by <NAME> on 8/22/21.
//
import Foundation
/**
The worst performant of all sorting algorithms
*/
extension Array where Element: Comparable {
func bubbleSort() -> [Element] {
guard count >= 2 else { return self }
var copy = self
// At the end of each iteration, we know the largest value is
// bubbled up to the end.
// The number of elements is now one less because it's already sorted.
for end in (1..<copy.count).reversed() {
print("end: \(end)")
var swapped = false
for currentIndex in 0..<end {
let nextIndex = currentIndex + 1
print("currentIndex: \(currentIndex) nextIndex: \(nextIndex)")
let currentVal = copy[currentIndex]
let nextVal = copy[nextIndex]
if currentVal > nextVal {
print("Need to swipe \(currentVal) \(nextVal)")
print("Before Swipe: \(copy)")
copy.swapAt(currentIndex, nextIndex)
print("After Swipe: \(copy)")
swapped = true
} else {
print("No need to swipe \(currentVal) \(nextVal)")
}
}
if !swapped {
print("Not swapped, we done.")
return copy
}
}
return copy
}
}
<file_sep>/Sorts/Sorts/SelectionSort.swift
//
// SelectionSort.swift
// SelectionSort
//
// Created by <NAME> on 8/22/21.
//
import Foundation
/**
Go thought each element
Find the lowest element, swapping the lowest
Now process the remaining
*/
extension Array where Element: Comparable {
func selectionSort() -> [Element] {
guard count >= 2 else { return self }
var copy = self
for index in 0..<(count - 1) {
var lowestIndex = index
var lowestVal = copy[index]
for compareIndex in (index + 1)..<count {
let compareValue = copy[compareIndex]
if compareValue < lowestVal {
lowestIndex = compareIndex
lowestVal = compareValue
}
}
if lowestIndex != index {
copy.swapAt(lowestIndex, index)
}
}
return copy
}
}
<file_sep>/Stack/Stack/main.swift
//
// main.swift
// Stack
//
// Created by <NAME> on 3/20/21.
//
import Foundation
var myStack = Stack<String>()
assert(myStack.isEmpty)
myStack.push("Kraig")
assert(!myStack.isEmpty)
myStack.push("Christine")
myStack.push("Tippy")
print("Stack: \(myStack)")
print("Peek: \(String(describing: myStack.peek()))")
print("Pop: \(String(describing: myStack.pop()))")
print("Stack: \(myStack)")
func testPassInArray() {
myStack = Stack<String>(["One", "Two", "Three"])
let lastPeek = myStack.peek()
print("lastPeek: \(String(describing: lastPeek))")
assert(lastPeek == "Three")
}
testPassInArray()
func testEquatable() {
let stack1 = Stack<Int>(1,2,3)
let stack2: Stack = [1,2,3]
let stack3: Stack = [3,2,1]
assert(stack1 == stack2)
assert(stack1 != stack3)
}
testEquatable()
func areParensBalanced(_ value: String) -> Bool {
var stack = Stack<Character>()
for c in value {
if c == "(" {
stack.push(c)
} else if c == ")" {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
func areParensBalancedNoStack(_ value: String) -> Bool {
var count = 0
for c in value {
if c == "(" {
count += 1
} else if c == ")" {
count -= 1
if count < 0 { return false }
}
}
return count == 0
}
assert(areParensBalanced("(test) (what) up"))
assert(!areParensBalanced("(test) (what) up)"))
assert(areParensBalancedNoStack("(test) (what) up"))
assert(!areParensBalancedNoStack("(test) (what) up)"))
/*
Interesting that this is one of the go to problems to solve with a stack and it's not
the most efficient.
By using the stack, we take up more memory and have the overhead of adding and removing
to a backing store.
Locally the same thing can be done with a counter, which doesn't use extra memory or
the overhead of using some underlying data structure.
*/
<file_sep>/Sorts/Sorts/InsertionSort.swift
//
// InsertionSort.swift
// InsertionSort
//
// Created by <NAME> on 8/22/21.
//
import Foundation
extension Array where Element: Comparable {
func insertionSort() -> [Element] {
guard count >= 2 else { return self }
var sortingArray = self
// Sort starting with comparing 2 items, adding one more item to compare
// each time through the outer loop
// Walking from left to right, we continue to swipe from highest to lowest
// until the value to the left is not greater than the value we're comparing
for numberOfElementsToCompare in 1..<sortingArray.count {
// Each iteration through this loop we are incrementally comparing one more item
// We are sorting 2 values, then 3 ext.. Left to Right
// until we reach the beginning or we run into a value where the value to the left is <
// then the value to the right.
// What makes this not great is in a worse case scenario if the value at the end of an array
// is less than all other values you are swiping 'n' times and depending on the array
// this could happen often.
let compareRange = (1...numberOfElementsToCompare).reversed()
print("🍀 Outer numberOfElementsToCompare: \(numberOfElementsToCompare) comparing: indexes \(compareRange.first!) to \(compareRange.last!)")
// Swipe all values where the left value is > than the value being compared
// Example:
//
// ☀️ comparingValue: 5 valueLeftOfComparingValue: 1000 Array: [1000, 5, 1, 76, 10, 5, 7, 2, 5, 2]
// Value: 5 is < 1000 need to swap
// Before Swap [1000, 5, 1, 76, 10, 5, 7, 2, 5, 2]
// After Swap [5, 1000, 1, 76, 10, 5, 7, 2, 5, 2]
for comparingIndex in compareRange {
let comparingValue = sortingArray[comparingIndex]
let indexLeftOfComparingValue = comparingIndex - 1
let valueLeftOfComparingValue = sortingArray[indexLeftOfComparingValue]
print("☀️ comparingValue: \(comparingValue) valueLeftOfComparingValue: \(valueLeftOfComparingValue) Array: \(sortingArray) ")
if valueLeftOfComparingValue > comparingValue {
print("Value: \(comparingValue) is < \(valueLeftOfComparingValue) need to swap")
print("Before Swap \(sortingArray)")
sortingArray.swapAt(comparingIndex, indexLeftOfComparingValue)
print("After Swap \(sortingArray)")
} else {
print("⭐️Value: \(comparingValue) is NOT < \(valueLeftOfComparingValue) need to break out of loop")
break
}
}
}
return sortingArray
}
}
<file_sep>/Sorts/Sorts/main.swift
//
// main.swift
// Sorts
//
// Created by <NAME> on 8/22/21.
//
import Foundation
func testSorts() {
let myArray = [1000,5,1,76,10,5,7,2,5,2]
let bubble = myArray.bubbleSort()
print("bubble: \(bubble)")
let selection = myArray.selectionSort()
print("selection: \(bubble)")
assert(bubble == selection)
let insertion = myArray.insertionSort()
print("insertion: \(insertion)")
assert(insertion == selection)
}
testSorts()
<file_sep>/Queue/Queue/QueueStack.swift
//
// QueueStack.swift
// QueueStack
//
// Created by <NAME> on 8/22/21.
//
import Foundation
/**
The point of using a stack is not shifting up all of the array elements.
When you remove first element of an array each element must be copied up
One position.
This overhead can be significant.
This implementation reverses the Queue so that elements are removed
from the bottom, not the top.
Removing from the bottom has little overhead.
When an item is dequeued
The elements are copied to another array in reverse order
This only needs to happen when the queue is empty.
*/
struct QueueStack<T>: Queue {
typealias Element = T
private var enqueueStack: [Element] = []
private var dequeueStack: [Element] = []
var isEmpty: Bool {
enqueueStack.isEmpty && dequeueStack.isEmpty
}
var peek: T? {
dequeueStack.isEmpty == false ? dequeueStack.last : enqueueStack.first
}
mutating func enqueue(_ element: T) {
enqueueStack.append(element)
}
@discardableResult
mutating func dequeue() -> T? {
if dequeueStack.isEmpty {
dequeueStack = enqueueStack.reversed()
enqueueStack.removeAll()
}
return dequeueStack.popLast()
}
}
<file_sep>/Queue/Queue/main.swift
//
// main.swift
// Queue
//
// Created by <NAME> on 8/22/21.
//
import Foundation
func testQueueArray() {
var queueArray = QueueArray<String>()
assert(queueArray.isEmpty)
queueArray.enqueue("Tippy")
assert(!queueArray.isEmpty)
queueArray.enqueue("Toonsis")
queueArray.enqueue("Grumpy")
let dequeue = queueArray.dequeue()!
assert(dequeue == "Tippy")
assert(queueArray.peek == "Toonsis")
queueArray.dequeue()
assert(!queueArray.isEmpty)
queueArray.dequeue()
assert(queueArray.isEmpty)
}
testQueueArray()
func testQueueStack() {
var queueArray = QueueStack<String>()
assert(queueArray.isEmpty)
queueArray.enqueue("Tippy")
assert(!queueArray.isEmpty)
queueArray.enqueue("Toonsis")
queueArray.enqueue("Grumpy")
let dequeue = queueArray.dequeue()!
assert(dequeue == "Tippy")
assert(queueArray.peek == "Toonsis")
queueArray.dequeue()
assert(!queueArray.isEmpty)
queueArray.dequeue()
assert(queueArray.isEmpty)
}
testQueueStack()
| 4a60867969b4d32d915dffdef12a3bad4c8eb9c7 | [
"Swift"
] | 9 | Swift | kraigspear/DataStructuresAndAlgorithms | 7f8b0734676f6d6780eee2f277f4e5a6818168d4 | 0b37d2edde4a6b78ea3763d6ecd5f9da93697042 |
refs/heads/master | <repo_name>marissaorea/woof-woof-js-practice-nyc-web-082718<file_sep>/src/puppy.js
allPups = [];
class Puppy {
constructor(puppyObj){
this.id = puppyObj.id,
this.name = puppyObj.name,
this.isGoodDog = puppyObj.isGoodDog,
this.image = puppyObj.image
allPups.push(this)
}
render() {
return `<span id="puppyName" data-id="${this.id}">${this.name}</span>`
}
renderProfile() {
return `<img src=${this.image}>
<h2>${this.name}</h2>
<button class="toggle" data-id="${this.id}">${this.goodOrBad()}</button>`
}
goodOrBad() {
if(this.isGoodDog === true) {
return `Is Good Dog!`
}
else {
return 'Is Bad Dog!'
}
}
toggle() {
if(this.isGoodDog) {
this.isGoodDog = false
} else {
this.isGoodDog = true
}
}
| 30086b7dc3387ea70a97fb2ebb307468b2d39178 | [
"JavaScript"
] | 1 | JavaScript | marissaorea/woof-woof-js-practice-nyc-web-082718 | b4e1dfc48bb987c249277e5129c4826ff582ac59 | 671489c607b00d57a42f8bd9d695aa33d67d3362 |
refs/heads/master | <repo_name>munetoshi/suggest_reviewer<file_sep>/suggest_reviewer
#! /bin/sh
exec ruby -S -x $0 "$@"
#! ruby
require 'open3'
require 'optparse'
require 'set'
#
# Keeps a list of files to be reviewed and other options to suggest reviewers, which are obtained by
# parsing command line arguments and executing a git command.
# If the command line arguments are invalid, this shows usage, and exits with 1.
#
class SolverParams
attr_reader :file_list, :excluded_authors, :print_mode, :is_quiet,
:history_depth, :candidate_limit
def initialize
@is_path_mode = false # Use arguments as the file path, instead of the diff base.
@excluded_authors = []
@print_mode = :default
@is_quiet = false
@history_depth = 100
@candidate_limit = 10
@includes_myself = false
@option_parser = create_option_parser
argv = ARGV.clone
parse!(argv)
# Use arguments as a file list if is_path_mode is true. Otherwise, use them as the diff base.
@file_list = @is_path_mode ? argv : ExternalCommandExecutor.git_diff_files(argv[0], argv[1])
my_email = ExternalCommandExecutor.git_my_email
@excluded_authors.push(my_email) if !@includes_myself && !my_email.empty?
end
private
BANNER = "Usage:\n" +
" #{$0} [options] DIFF_BASE [DIFF_TARGET]\n" +
" #{$0} [options] -p PATH_0 PATH_1 ... PATH_N\n\n"
def parse!(argv)
@option_parser.parse!(argv)
usage("No commit revision, branch name or file path.") if argv.size == 0
rescue OptionParser::ParseError => e
usage(e.message)
end
def create_option_parser
OptionParser.new do |option|
option.banner = BANNER
option.on(
"-p",
"--path",
"Use a list of file paths instead of the diff target") do |value|
@is_path_mode = value
end
option.on(
"-e AUTHOR1,AUTHOR2,...AUTHORn",
"--exclude-author AUTHOR1,AUTHOR2,...AUTHORn",
Array,
"Comma separated author list to exclude from reviewers") do |authors|
@excluded_authors.concat(authors)
end
option.on(
"-m",
"--include-myself",
"Include myself as a reviewer candidate") do |value|
@includes_myself = value
end
option.on(
"-d",
"--detail",
"Show details for each file. This overrides the preceding '-s' option.") do |value|
@print_mode = :detail if value
end
option.on(
"-s",
"--simple",
"Show only the reviewer list. This overrides the preceding '-d' option.") do |value|
@print_mode = :simple if value
end
option.on(
"-q",
"--quiet",
"Do not show any progress status") do |value|
@is_quiet = value
end
option.on(
"-h DEPTH",
"--history-depth DEPTH",
Integer,
"Depth of history (number of revisions) to find authors") do |depth|
@history_depth = depth
end
option.on(
"-c CANDIDATE_LIMIT",
"--candidate-limit CANDIDATE_LIMIT",
Integer,
"Maximum number of reviewer candidates for each file") do |count|
@candidate_limit = count
end
end
end
def usage(message)
$stderr.puts message
$stderr.puts @option_parser.to_s
exit 1
end
end
#
# Collection of utility methods to call the external commands, "git" and "tput".
#
class ExternalCommandExecutor
def self.window_width
# To prevent the standard input from being overridden, don't use Open3.
`which -s tput && tput cols`.to_i
end
def self.git_my_email
call("git config user.email").chomp
end
def self.git_diff_files(diff_base, diff_target)
call("git diff #{diff_base} #{diff_target} --name-only").lines.map(&:chomp)
end
def self.git_history(file, excluded_authors, history_depth, candidate_limit)
filter_author_command = excluded_authors.empty? ?
"" : "| egrep -v \"" + excluded_authors.join("|") + "\" "
command = "git log --pretty=\"%ae\" #{file} | head -#{history_depth} " +
filter_author_command + "| sort | uniq -c | sort -nr | head -#{candidate_limit}"
call(command).lines.map(&:chomp)
end
private
def self.call(external_command_string)
Open3.capture3(external_command_string)[0]
end
end
#
# IO like class to suppress output like /dev/null.
#
class NilOutput
def puts(obj) end
def print(obj) end
end
#
# Progress bar drawn on the console.
#
class ProgressBar
PERCENTAGE_STR = "%.1f%"
PERCENTAGE_STR_LENGTH = 7
def initialize(window_cols, max, output)
@window_cols = window_cols
@max = max
@output = output
end
def print_bar(progress)
return if @window_cols <= PERCENTAGE_STR_LENGTH
progress = [@max, progress].min.to_f
progress_ratio = progress / @max
bar_area_length = @window_cols - PERCENTAGE_STR_LENGTH
bar_str = ("#" * (progress_ratio * bar_area_length))
@output.print "\r" +
bar_str.ljust(bar_area_length) +
(PERCENTAGE_STR % (progress_ratio * 100)).rjust(PERCENTAGE_STR_LENGTH)
end
end
#
# Author data holding pairs of file names and scores.
#
class AuthorData
attr_reader :files
def initialize
@files = {}
end
def add_file(file, score)
if score > 0
@files[file] = score
else
@files.delete(file)
end
end
def total_score_for(files)
score = 0
files.each do |file|
score += score_for(file)
end
score
end
def elements
@files.keys
end
def score_for(file)
@files[file] || 0
end
end
#
# Solver of the set cover problem which is finding a combination of sets to cover all the elements.
# To avoid confusion with Ruby's "Set", we use the term "group" to mean "set" in this class.
#
class SetCoverProblemSolver
# Solves the set cover problem using the greedy algorithm
# @param elements [Set] :elements Set of element to be covered.
# @param groups [Map] :groups Map of group ID to group data. This data type must have a method.
# total_score_for([element]). The simplest implementation of total_score_for is the count of
# elements in the group.
# @return [Set, Set]
# First value: Set of group IDs to cover elements.
# Second value: Set of elements which is not covered by any group.
def self.solve(elements, groups)
uncovered_elements = elements.clone
uncovering_group_ids = Set.new(groups.keys)
while !uncovered_elements.empty?
candidate_id = nil
candidate_score = 0
# Choose the best group for uncovered elements
uncovering_group_ids.each do |group_id|
group_data = groups[group_id]
next unless group_data
score = group_data.total_score_for(uncovered_elements)
if candidate_score < score
candidate_id = group_id
candidate_score = score
end
end
break unless candidate_id
uncovering_group_ids.delete(candidate_id)
uncovered_elements -= groups[candidate_id].elements
end
return Set.new(groups.keys) - uncovering_group_ids, uncovered_elements
end
end
def puts_files(output, files)
files.each do |file|
output.puts " " + file
end
end
# Script body from here.
# Parse arguments, and get a changed file list.
params = SolverParams.new
e = params.is_quiet ? NilOutput.new : $stderr
if params.file_list.empty?
e.puts "No changed file was found. Check the following items."
e.puts " 1. Confirm the availability of these commands: git, head, uniq, sort, and egrep."
e.puts " 2. Confirm that there are changed files with 'git diff --name-only'."
e.puts " 3. Put the '-p' option to specify files by path."
exit 0
end
# Obtain the git history for each file.
e.puts "Getting the log for each file..."
progress_bar = ProgressBar.new(ExternalCommandExecutor.window_width, params.file_list.size, e)
progress_bar.print_bar(0)
author_email_to_data = {} # Map of author mail String to AuthorData
file_to_authors = {} # Map of file String to the author mail list
params.file_list.each do |file|
file_to_authors[file] = Set.new
top_score = nil
history_results = ExternalCommandExecutor.git_history(
file, params.excluded_authors, params.history_depth, params.candidate_limit)
history_results.each do |result|
match_result = result.match(/(\d+)\s+(\S+)/)
next unless match_result
score = match_result[1].to_f
top_score ||= score
author_email = match_result[2]
author_email_to_data[author_email] ||= AuthorData.new
author_email_to_data[author_email].add_file(file, score / top_score)
file_to_authors[file].add(author_email)
end
progress_bar.print_bar(file_to_authors.size)
end
# The main calculation for finding reviewers.
e.puts "Calculating reviewer candidates..."
reviewers, unreviewable_files =
SetCoverProblemSolver.solve(Set.new(file_to_authors.keys), author_email_to_data)
# Output the result. The flow is as follows.
# - Output reviewers and exit if in simple mode.
# - Output reviewers and the reviewable files.
# - Output files no one can review.
# - Output file details.
e.puts "Finished!"
e.puts ""
o = $stdout
if params.print_mode == :simple
o.puts reviewers.to_a
exit 0
end
reviewers.each do |author_email|
o.puts author_email
puts_files(o, author_email_to_data[author_email].files.keys)
end
if !unreviewable_files.empty?
o.puts "no one can review"
puts_files(o, unreviewable_files)
end
if params.print_mode == :detail
o.puts ""
o.puts "== FILE DETAILS =="
file_to_authors.each_pair do |file, authors|
o.puts file
authors.each do |author_email|
o.puts (" %1.3f, " % author_email_to_data[author_email].score_for(file)) + author_email
end
end
end
<file_sep>/README.md
# suggest_reviewer
Script to suggest reviewers by means of git history
See http://developers.linecorp.com/blog/ja/?p=3832 for more details.
| bbd6beee8da6f6962278eccdbe1eb9335a8ecb97 | [
"Markdown",
"Ruby"
] | 2 | Ruby | munetoshi/suggest_reviewer | f8609b1b115e9b5bc51632ac463e7142fe69b0e6 | 4394221a95472dc3e23f2576bfb4383471e89d42 |
refs/heads/master | <file_sep>import React from 'react';
import Main from './Main';
React.render(<Main />, document.getElementsByTagName('body')[0]);<file_sep># ES6 react starter kit
When starting a new project I found I use a lot of time setting up some sort of build system.
Even though I learn a lot, it left me working on these build systems instead of the prototype I planned to build.
After writing different Grunt, Gulp and Webpack combinations and configs I found a Webpack solution I like.
Having written it more than once and copying from previous projects I decided to make a blank slate.
This is not actually a build system, only a development system, meaning it doesn't save any files.
It is set up to use babeljs to transform the files to ES5, it even takes care of your JSX.
Webpack-dev-server is configured with hot loading and html file generation for easier development.
React is good to go, but I recommend you check the version number and upgrade if needed.
Whenever you need to build your project have a look at [webpack configuration](http://webpack.github.io/docs/configuration.html)
## Getting started
``` bash
# setup
git clone https://github.com/deificx/react-hot-babel-webpack
mv react-hot-babel-webpack your-project-name
cd your-project-name
npm i
# optional
rm -rf .git .gitignore LICENSE README.md
$EDIT package.json
# run
node dev.js
```
Open http://localhost:3000/ and edit src/Main.js to see changes immediately in the browser.
Expand and build as wanted.
## LICENSES
- [babel](https://github.com/babel/babel/blob/master/LICENSE)
- [html-webpack-plugin](https://github.com/ampedandwired/html-webpack-plugin/blob/master/LICENSE)
- [react](https://github.com/facebook/react/blob/master/LICENSE)
- [webpack](https://github.com/webpack/webpack/blob/master/LICENSE)
- [this](https://github.com/deificx/react-hot-babel-webpack/blob/master/LICENSE) | c8cc28c304de83734b2b87682f17f8f599cbac05 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | deificx/react-hot-babel-webpack | 21d57e433e6efc5f39acb131578283d1dbad3057 | 99a53c34280506d761258141772898cdf0105e7d |
refs/heads/master | <file_sep>---
home: true
heroImage: /images/hero.jpeg
actionText: See Experience →
actionLink: /experience
features:
- title: Testing
details: Extensive testing and TDD knowledge covering a wide variety of frameworks including Jest, Chai, Mocha, Sinon, Supertest and Cypress for unit, integration, and end to end testing.
- title: Architecture & DevOps
details: Experience with tooling including a wide variety of AWS services (CloudFormation, ECS, EC2, RDS etc.), Docker, Jenkins and CircleCI with focus on building team practices/culture in this area.
- title: Ways of Working
details: Experienced delivering products using Agile/SCRUM and Lean methodologies and passionate about supporting building teams of great people through knowledge sharing, coaching and mentoring.
footer: MIT Licensed | Copyright © 2019 <NAME>
---
<file_sep># Portfolio
Use `yarn run docs:dev` to view and edit, or `yarn run docs:build` to build into a static folder.
Super helpful markdown reference https://markdown-it.github.io/<file_sep># Education
## University of Southampton
*2013 - 2016, Southampton*
**Bachelor of Science**
| Subject | Grade |
| ------------- | -------------|
| Web Science | 1st |
## Wellsway Sixth Form College
*2012 - 2013, Bristol*
**A Levels**
| Subject | Grade |
| ------------- | -------------|
| Mathematics | A |
| Business Studies | A |
| Media Studies | A* |
| Art | B |
| Extended Project | A* |<file_sep>set -e
git config --global user.email "$GH_EMAIL"
git config --global user.name "$GH_NAME"
git init
git add -f docs/.vuepress/dist
git commit -m 'deploy'
git filter-branch -f --prune-empty --subdirectory-filter docs/.vuepress/dist
git push --force --set-upstream <EMAIL>:elliehamilton3/elliehamilton3.github.io.git master
cd -<file_sep>module.exports = {
title: '<NAME>',
description: 'Full-Stack Javascript Developer (React / NodeJS / Express) experienced in building digital products.',
themeConfig: {
nav: [
{ text: 'About', link: '/' },
{ text: 'Experience', link: '/experience' },
{ text: 'Education', link: '/education' },
{ text: 'GitHub', link: 'https://github.com/elliehamilton3' },
{ text: 'LinkedIn', link: 'https://www.linkedin.com/in/3lliehamilton/' }
],
search: false
},
};
<file_sep>---
layout: projects
projects:
- image: /images/and.webp
rows:
- content: "**AND Digital**"
- content: "Delivery of MVP of a Software as a Service (SaaS) open banking project for Client (Konsentus) to take to market."
- content: "Building architecture to scrape low-quality data from a number of websites and transforming this data into the required format in a performant way which is resilient to error."
- content: "Designing and building a large set of customer-facing API's using JavaScript specifically NodeJS and express with in-depth API documentation in Swagger."
- content: "Unit, integration, and E2E testing the project with a TDD approach."
- content: "Designing and building out the internal microservice architecture, infrastructure, and APIs for the project."
- content: "Introducing more advanced ways of working to move beyond simple SCRUM, introducing kanban and lean to the project and encouraging a collaborative team environment through pairing, mobbing and swarming."
- content: "Mentoring junior team members in JavaScript and the domain of open banking, RegTech and banking regulations in the EU."
- content: "Implementing and supporting other team members in the DevOps for the project including CI/CD pipelines, test automation and various tooling including Docker, AWS and terraform."
- image: /images/noths.png
rows:
- content: "**Not on the High Street**"
- content: "*FULL-STACK DEVELOPER*"
- content: "Building and maintaining features in the Ruby on Rails application but also on the front-end of the site in JavaScript and some ReactJS as well as HTML and CSS, involvement in early research and discussions on GDPR"
- content: "Implementing Facebook Pixel tracking, various analytics, and revenue reporting from emails"
- content: "Software architecture patterns - microservices/monoliths, event-driven programming, request queuing and event workers/listeners"
- content: "CI/CD through tools including Consul, Marathon, Ansible, and Jenkins"
- content: "*QA*"
- content: "Manual testing and writing the regression testing suite for the iOS app"
- content: "Writing user stories and acceptance criteria"
- content: "Accessibility, automated UI testing in XCode, and Apple’s Human Interface Guidelines"
- image: /images/buckle.png
rows:
- content: "**Buckle Consulting**"
- content: "Front and back-end web development for a number of clients, mobile responsive design, and building HTML templates for emails."
- content: "Requirements building through regular communication with clients"
---
# Experience
| 119b551fb17e20013bf678207af26f479e5da8d1 | [
"Markdown",
"JavaScript",
"Shell"
] | 6 | Markdown | elliehamilton3/portfolio | 795eb069cee81845701e3d610e4c94bd1016061d | 8b523dbfbf3c12be4ab7957036bad20d9c5e054f |
refs/heads/master | <repo_name>work-ladder/single-entry-react-template<file_sep>/src/api/getList.jsx
import React, { Component } from 'react';
import axios from 'axios';
export default class GetList extends Component {
constructor() {
super();
this.state = {
student: [],
};
}
componentDidMount() {
axios.get('api/mock/47/test/student')
.then(({ data }) => {
if (data.data && data.data.student) {
this.setState({
student: data.data.student,
});
}
});
}
render() {
const { student } = this.state;
return (
<ul>
{
student.map((item) => <li key={item.name}>{item.name}</li>)
}
</ul>
);
}
}
<file_sep>/README.md
### webpack 4 探索学习
- [x] babel
- [x] less,sass 支持
- [x] 抽离css
- [x] 图片路径支持
- [x] react支持
- [x] eslint
- [x] 别名
- [x] 公共代码
- [x] 编写一个简单的webpack插件
- [x] 热更新
- [x] 编写一个简单的loader
- [ ] 多环境支持
- [ ] 反向代理处理跨域
- [ ] 路由
- [ ] 数据流
- [ ] typescript
...
<file_sep>/src/component/simple-redux/childOne.jsx
import React, { useContext } from "react"
import { Context } from "./context"
export default function ChildOne() {
const { state, dispatch } = useContext(Context)
return (
<div>
<h1>{state}</h1>
<button onClick={() => {
dispatch({type: "increment"})
}}>increment</button>
<button onClick={() => {
dispatch({type: "decrement"})
}}>
decrement
</button>
</div>
)
}
<file_sep>/src/Home.jsx
import React, { useState, useRef } from 'react';
import width from './useWindowWidth';
import UseCallbackComponent from './component/useCallback';
import UseReducerComponent from './component/useReducer';
import UseContextComponent from './component/useContext';
import SimpleRedux from './component/simple-redux/app';
import GetList from './api/getList';
// let countTemp = 0;
export default function Home() {
const [count, setCount] = useState(0);
const ref = useRef(0);
const increment = () => {
setTimeout(() => {
// 1. 短时间点击多次不会增加,每次点击都是执行函数,count 是初始值,不是最新值
// setCount(count + 1);
// 2. 用一个临时变量
// countTemp += 1;
// setCount(countTemp + 1);
// 3. useRef,不管函数组件执行多少次,而 useRef 返回的对象永远都是原来那一个。
// 可以记住当前点击了多少次
setCount(ref.current += 1);
}, 2000);
};
return (
<div>
<div>
当前屏幕宽度:
{width()}
</div>
<div>要nm$l</div>
<button type="button" onClick={increment}>
点击了
{count}
次
</button>
<br />
<h3>UseCallbackComponent</h3>
<UseCallbackComponent />
<br />
<h3>UseReducerComponent</h3>
<UseReducerComponent />
<br />
<h3>UseContextComponent</h3>
<UseContextComponent />
<br />
<h3>SimpleRedux</h3>
<SimpleRedux />
<br />
<h3>api 获取列表</h3>
<GetList />
</div>
);
}
<file_sep>/MyLoader.js
const { getOptions } = require('loader-utils');
module.exports = function (source) {
/*
this指向webpack 不能使用箭头函数,webpack需要对指定this指向
source:打包后的文件内容
this.query options参数
*/
const options = getOptions(this) || {};
// 返回处理后的结果,相当于是打包拦截器
// return source.replace('nm$l', options.name || '和谐');
const result = source.replace('nm$l', options.name || '和谐');
/*
this.callback(
err: Error | null, // error信息
content: string | Buffer, // 要返回的内容
sourceMap?: SourceMap, // source-map
meta?: any // 会被 webpack 忽略,可以是任何东西(例如一些元数据)。
);
*/
// 如果只传这两个参数,效果同上
this.callback(null, result);
// 异步操作
// const callback = this.async();
// setTimeout(() => { // 直接影响打包时间
// const options = getOptions(this);
// const result = source.replace('nm$l', options.name || '和谐');
// callback(null, result); // 这里实际还是调用了this.callback()
// }, 3000);
};
<file_sep>/package.json
{
"name": "webpack4-react-explore",
"version": "1.0.0",
"description": "<%=description%>",
"main": "dist/index.js",
"dependencies": {
"axios": "^0.19.2",
"eslint-plugin-promise": "^4.2.1",
"loader-utils": "^2.0.0",
"react": "^16.13.1",
"react-dom": "^16.13.1"
},
"devDependencies": {
"@babel/core": "^7.10.3",
"@babel/plugin-transform-runtime": "^7.10.3",
"@babel/polyfill": "^7.10.1",
"@babel/preset-env": "^7.10.3",
"@babel/preset-react": "^7.10.1",
"@babel/runtime": "^7.10.3",
"@babel/runtime-corejs2": "^7.10.3",
"autoprefixer": "^9.8.1",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.1.0",
"clean-webpack-plugin": "^3.0.0",
"core-js": "^3.6.5",
"css-loader": "^3.6.0",
"eslint": "^5.3.0",
"eslint-config-airbnb": "^18.2.0",
"eslint-loader": "^4.0.2",
"eslint-plugin-import": "^2.21.2",
"eslint-plugin-jsx-a11y": "^6.3.1",
"eslint-plugin-react": "^7.20.0",
"eslint-plugin-react-hooks": "^4.0.4",
"extract-text-webpack-plugin": "^4.0.0-beta.0",
"file-loader": "^6.0.0",
"html-webpack-plugin": "^3.2.0",
"html-withimg-loader": "^0.1.16",
"less": "^3.11.3",
"less-loader": "^6.1.1",
"mini-css-extract-plugin": "^0.9.0",
"node-sass": "^4.14.1",
"postcss-loader": "^3.0.0",
"sass-loader": "^8.0.2",
"style-loader": "^1.2.1",
"url-loader": "^4.1.0",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --mode=development",
"dev": "wlc dev"
},
"author": "",
"license": "ISC"
}
<file_sep>/prompt.js
module.exports = [
{
type: 'input',
name: 'description',
message: '设置项目描述',
},
];<file_sep>/MyPlugin.js
/* eslint-disable */
// SetScriptTimestampPlugin.js
class MyPlugin {
constructor(options) {
this.options = options
}
apply(compiler) {
compiler.hooks.compilation.tap('SetScriptTimestampPlugin',
(compilation) => {
// 插件逻辑 调用compilation提供的plugin方法
compilation.plugin(
"html-webpack-plugin-before-html-processing",
(htmlPluginData, callback) => {
let result = `
<script>
(${this.options})()
</script>
`;
let resultHTML = htmlPluginData.html.replace(
"<!--MyPlugin inset script-->", result
);
// 返回修改后的结果
htmlPluginData.html = resultHTML;
// 返回修改后的结果
}
);
}
);
}
}
module.exports = MyPlugin;
| 575cfc7adcd1e82dd567b273c82f94ed4b170e35 | [
"JavaScript",
"JSON",
"Markdown"
] | 8 | JavaScript | work-ladder/single-entry-react-template | 9bb237a443236e38321cc2d9c2f203ac490d238e | ba6900d1651cfa695cee78dcefbf60a627eab41e |
refs/heads/master | <file_sep>$(function(){
function show(data){
for(var i=0;i<data.length;i++){
$(".list_ul").append(`
<li>
<img src="${data[i].coverImg}" />
<div class="list_txt">
<h5>${data[i].title}</h5>
<h6>${data[i].creatAt}</h6>
<p>${data[i].describe}</p>
</div>
</li>
`)
}
}
function liHover(){
$('.list_ul li').hover(function() {
$(this).css("border", "1px solid #BAB0C8")
}, function() {
$(this).css("border", "1px solid transparent")
})
}
var data1=listData.listData00.data.list
show(data1)
var click=0
$(".arrow_down").click(function(){
click++;
if(click==1){
var data2=listData.listData01.data.list
show(data2);
}else if(click==2){
var data3=listData.listData02.data.list
show(data3)
$(".mouse_check_more").attr("src","images/list_gomore_bg_nomore.jpg")
}
liHover()
})
liHover()
// $('.list_ul li').click(function(){
// open("列表详情.html")
//
// })
})
<file_sep>$(function() {
$('.nav ul li').hover(function() {
$(this).find('.down').stop().slideDown(700, "bounceOut");
}, function() {
$(this).find('.down').stop().slideUp(); //stop()规范用
}).click(function() {
$(this).addClass('now').find('.down').hide().end().silbings().remove();
//end()清除点击产生的小白点
})
})
<file_sep>var global=global||{} //存储为全局变量
$(function(){
//pageStart 页数 pagesize 每页的条数 count 总条数
getlist();
$(".arrow_down").click(function(){
pageStart++;
if(pageStart<global.page){
getlist();
}else{
$(".arrow_down").hide();
$(".mouse_check_more").attr("src","images/list_gomore_bg_nomore.jpg");
}
})
//跳转详情页
$(".list_ul").delegate(".content_one","click",function(){
var articleId=$(this).attr("articleId");
window.location="列表详情.html?articleId="+articleId;
})
})
var pageStart=0; //页数
function getlist(){
// var pageStart=0; //页数
// $.ajax({
// url:"1.txt",
// type:"get",
// async:false,
// data:{
//
// }
// )}.done(function(result){
//
// })
// console.log(listData);
var result=listData["listData0"+pageStart];
global.count=result.data.count;
var pageSize=result.data.pageSize;
var list=result.data.list;
if(pageStart==0){
$(".list_ul").html("");
}
console.log(result);
for(var i=0;i<list.length;i++){
var htmlmodel=$("#itemHtml").html();//模板
// console.log(htmlmodel)
//拿到模板里的所有节点
htmlmodel=htmlmodel.replace("$articleId$",list[i].sysId)
htmlmodel=htmlmodel.replace("img/list_img02.jpg",list[i].coverImg)
htmlmodel=htmlmodel.replace("$articleTitle$",list[i].title)
htmlmodel=htmlmodel.replace("$articleTime$",list[i].creatAt)
htmlmodel=htmlmodel.replace("$describe$",list[i].describe)
$(".list_ul").append(htmlmodel);
}
global.page=Math.ceil(global.count/pageSize);
}
| bc9d48f5aa0735ac90340833e12dac35a431073d | [
"JavaScript"
] | 3 | JavaScript | inyu1069/project1 | e45f96ec6b9d248d6f8cd61efe60d8a0bdf9f3b0 | d2f1367a2ccebca795209d9845178d40a5debc9a |
refs/heads/master | <repo_name>PauliSpin/Vectors<file_sep>/vectors rods.py
import vpython as vp
import math
# pip install Vpython
# https://www.glowscript.org/docs/VPythonDocs/index.html
class Arrow(object):
'''
Created an arrow using a cyclinder and a cone.
Requires the vector and its position as well as a label
and its position.
'''
def __init__(self, v, v_label, v_label_pos, v_color, v_pos):
self.v = v # Vector
self.v_label = v_label # Label for the vector
self.v_color = v_color # Vector colour
# Position of vector i.e. where its tail is.
self.v_pos = v_pos
# Axis of the cone; same as the vector's
self.cone_axis = 0.1 * vp.norm(self.v)
self.rod_radius = 0.02 # Absolute radius of the rod
self.cone_radius = 0.06 # Absolute radius of the rod
# Reduce the size of the rod by the axial size of the cone
self.rod = vp.cylinder(pos=v_pos, axis=self.v - self.cone_axis,
radius=self.rod_radius, color=v_color)
# Place the base of the cone at the end of rod
# which has been reduced by the cone's axial length
self.cone = vp.cone(pos=self.v - self.cone_axis + v_pos, axis=self.cone_axis,
radius=self.cone_radius, color=v_color)
# Note where the tip of the cone is,
# which will define the starting point of
# of the axis line
self.cone_tip = self.v + v_pos + 0.1 * vp.norm(self.v)
self.axis_text = vp.label(text=v_label, pos=v_pos + v_label_pos * (
self.cone_tip - v_pos), color=v_color, xoffset=3, yoffset=3, box=False)
# self.axis_text.height = 0.6 * self.axis_text.height
# Initialize
o = vp.vector(0, 0, 0)
i = vp.vector(1, 0, 0)
j = vp.vector(0, 1, 0)
k = vp.vector(0, 0, 1)
# Axis colours
x_axis_color = vp.color.red
y_axis_color = vp.color.cyan
z_axis_color = vp.color.green
# Axes Triad
x_axis = Arrow(i, 'x', 1, x_axis_color, o) # Label position is 1 x vector i
y_axis = Arrow(j, 'y', 1, y_axis_color, o)
z_axis = Arrow(k, 'z', 1, z_axis_color, o)
# Define vector A
vec_A = vp.vector(1, 2, 1)
pos_A = vp.vector(0.5, 0.5, 0.5)
col_A = vp.color.magenta
A = Arrow(vec_A, 'A(1, 2, 1)', 0.5, col_A, pos_A) # Label position is 0.5 A
# Define vector B
vec_B = vp.vector(2, 1, 3)
pos_B = vp.vector(0.5, 0.5, 0.5)
col_B = vp.color.orange
A = Arrow(vec_B, 'B(2, 1, 3)', 0.5, col_B, pos_B)
vec_C = vp.cross(vec_A, vec_B)
pos_C = pos_A
col_C = vp.color.purple
C = Arrow(vec_C, f'AxB({vec_C.x}, {vec_C.y}, {vec_C.z})', 0.5, col_C, pos_C)
# vp.scene.camera.pos = vp.vector(-2, -3, 2)
<file_sep>/vector 3.py
import vpython as vp
import math
class Arrow(object):
vec_i = vp.vector(10, 0, 0)
vec_j = vp.vector(0, 10, 0)
vec_k = vp.vector(0, 0, 10)
def __init__(self, axis_label, axis_color, arrow_pos):
if axis_label == 'x':
vec_u = Arrow.vec_i
elif axis_label == 'y':
vec_u = Arrow.vec_j
elif axis_label == 'z':
vec_u = Arrow.vec_k
self.rod_radius = vp.mag(vec_u) * 0.01
self.rod = vp.cylinder(pos=arrow_pos, axis=vec_u,
radius=self.rod_radius, color=axis_color)
self.cone = vp.cone(pos=vec_u, axis=0.1 * vec_u,
radius=vp.mag(vec_u) * 0.03, color=axis_color)
if axis_label in 'xyz':
self.axis_text = vp.text(text=axis_label, pos=self.cone.pos +
0.1 * vec_u, color=axis_color)
vec_o = vp.vector(0, 0, 0)
x_axis = Arrow('x', vp.color.red, vec_o)
y_axis = Arrow('y', vp.color.cyan, vec_o)
z_axis = Arrow('z', vp.color.green, vec_o)
<file_sep>/vectors.py
import vpython as vp
import math
# pip install Vpython
# https://www.glowscript.org/docs/VPythonDocs/index.html
class Arrow(object):
def __init__(self, v, axis_label, axis_color, arrow_pos):
# If we are drawing the axis-triad arrows
# then set the vec_u 'unit vector' accordingley.
# This ignores v in the argument list.
if axis_label == 'x':
self.vec_u = vec_i # Arrow.vec_i
elif axis_label == 'y':
self.vec_u = vec_j # Arrow.vec_j
elif axis_label == 'z':
self.vec_u = vec_k # Arrow.vec_k
else:
# Not drawing the axis triad
# so just set tvec_u to the vector itself
self.vec_u = v
if axis_label in 'xyz':
self.rod_radius = vp.mag(self.vec_u) * 0.01
self.cone_radius = vp.mag(self.vec_u) * 0.03
else:
self.rod_radius = 0.02
self.cone_radius = 0.06
# Reduced Rod length = Rod length - Cone's axial length
# Arrow length = Reduced Rod + Cone Axial Length
# Use a fixed size of axis of the cone
self.cone_axis = 0.1 * vp.norm(self.vec_u)
# Reduce the size of the rod by the axial size of the cone
self.rod = vp.cylinder(pos=arrow_pos, axis=self.vec_u - self.cone_axis,
radius=self.rod_radius, color=axis_color)
# Place the base of the cone at the end of rod
# which has been reduced by the cone's axial length
self.cone = vp.cone(pos=self.vec_u - self.cone_axis + arrow_pos, axis=self.cone_axis,
radius=self.cone_radius, color=axis_color)
# Note where the tip of the cone is,
# which will define the starting point of
# of the axis line
self.cone_tip = self.vec_u + arrow_pos + 0.1 * vp.norm(self.vec_u)
if axis_label in 'xyz':
self.axis_text = vp.label(text=axis_label, pos=self.cone.pos +
0.1 * self.vec_u, color=axis_color, xoffset=3, yoffset=3, box=False)
else:
self.axis_text = vp.label(text=axis_label, pos=arrow_pos +
0.5 * self.vec_u, color=axis_color, xoffset=3, yoffset=3, box=False)
self.axis_text.height = 0.6 * self.axis_text.height
# Initialize
vec_o = vp.vector(0, 0, 0)
vec_i = vp.vector(1, 0, 0)
vec_j = vp.vector(0, 1, 0)
vec_k = vp.vector(0, 0, 1)
# Axis colours
x_axis_color = vp.color.red
y_axis_color = vp.color.cyan
z_axis_color = vp.color.green
# Axes Triad
x_axis = Arrow(vec_o, 'x', x_axis_color, vec_o)
y_axis = Arrow(vec_o, 'y', y_axis_color, vec_o)
z_axis = Arrow(vec_o, 'z', z_axis_color, vec_o)
# Axes
x_axis_line = vp.curve(x_axis.cone_tip, 3 * vec_i,
radius=0.01, color=x_axis_color)
y_axis_line = vp.curve(y_axis.cone_tip, 3 * vec_j,
radius=0.01, color=y_axis_color)
z_axis_line = vp.curve(z_axis.cone_tip, 3 * vec_k,
radius=0.01, color=z_axis_color)
# Define vector A
vec_A = vp.vector(1, 2, 1)
pos_A = vp.vector(0.5, 0.5, 0.5)
col_A = vp.color.magenta
A = Arrow(vec_A, 'A(1, 2, 1)', col_A, pos_A)
# Define vector B
vec_B = vp.vector(2, 1, 3)
pos_B = pos_A + vec_A # vp.vector(0.5, 0.5, 0.5)
col_B = vp.color.orange
A = Arrow(vec_B, 'B(2, 1, 3)', col_B, pos_B)
vec_C = vec_A + vec_B
pos_C = pos_A
col_C = vp.color.purple
C = Arrow(vec_C, f'C({vec_C.x}, {vec_C.y}, {vec_C.z})', col_C, pos_C)
<file_sep>/vector 4.py
import vpython as vp
import math
class Arrow(object):
vec_i = vp.vector(10, 0, 0)
vec_j = vp.vector(0, 10, 0)
vec_k = vp.vector(0, 0, 10)
def __init__(self, v, arrow_label, arrow_color, arrow_pos):
if arrow_label == 'x':
vec_u = Arrow.vec_i
elif arrow_label == 'y':
vec_u = Arrow.vec_j
elif arrow_label == 'z':
vec_u = Arrow.vec_k
else:
vec_u = vp.vector(v.x * Arrow.vec_i.x, v.y *
Arrow.vec_j.y, v.z * Arrow.vec_k.z)
self.rod_radius = vp.mag(vec_u) * 0.01
scaled_arrow_pos = vp.vector(
arrow_pos.x * Arrow.vec_i.x, arrow_pos.y * Arrow.vec_i.y, arrow_pos.z * Arrow.vec_i.z)
self.rod = vp.cylinder(pos=scaled_arrow_pos, axis=vec_u,
radius=self.rod_radius, color=arrow_color)
self.cone = vp.cone(pos=vec_u, axis=0.1 * vec_u,
radius=vp.mag(vec_u) * 0.03, color=arrow_color)
if arrow_label in 'xyz':
self.axis_text = vp.text(text=arrow_label, pos=self.cone.pos +
0.1 * vec_u, color=arrow_color)
i = vp.vector(1, 0, 0)
j = vp.vector(0, 1, 0)
k = vp.vector(0, 0, 1)
vec_o = vp.vector(0, 0, 0)
x_axis = Arrow(i, 'x', vp.color.red, vec_o)
y_axis = Arrow(j, 'y', vp.color.cyan, vec_o)
z_axis = Arrow(k, 'z', vp.color.green, vec_o)
v_pos = vp.vector(2, 2, 2)
v = vp.vector(3, 4, 5)
my_v = Arrow(v, 'a', vp.color.magenta, v_pos)
print(f'Camera Posn Vector = {vp.scene.camera.pos}')
print(f'Camera Axis Vector = {vp.scene.camera.axis}')
vp.scene.camera.pos = vp.vector(10, 10, 7.3205)
<file_sep>/vector 2.py
import vpython as vp
import math
vec_o = vp.vector(0, 0, 0)
vec_i = vp.vector(10, 0, 0)
vec_j = vp.vector(0, 10, 0)
vec_k = vp.vector(0, 0, 10)
rod_radius = vp.mag(vec_i) * 0.01 # 0.01
x_rod = vp.cylinder(pos=vec_o, axis=vec_i,
radius=rod_radius, color=vp.color.red)
x_cone = vp.cone(pos=vec_i, axis=0.1 * vec_i,
radius=vp.mag(vec_i) * 0.03, color=vp.color.red)
x_axis_text = vp.text(text='x', pos=x_cone.pos +
0.1 * vec_i, color=vp.color.red)
y_rod = vp.cylinder(pos=vec_o, axis=vec_j,
radius=rod_radius, color=vp.color.cyan)
y_cone = vp.cone(pos=vec_j, axis=vp.vector(
0, vp.mag(vec_i) * 0.1, 0), radius=vp.mag(vec_j) * 0.03, color=vp.color.cyan)
y_axis_text = vp.text(text='y', pos=y_cone.pos +
0.1 * vec_j, color=vp.color.cyan)
print(f'Camera Posn Vector = {vp.scene.camera.pos}')
print(f'Camera Axis Vector = {vp.scene.camera.axis}')
vp.scene.camera.pos = vp.vector(15, 15, 17.3205)
# z_rod = vp.cylinder(pos=vec_o, axis=vec_k,
# radius=rod_radius, color=vp.color.green)
# z_cone = vp.cone(pos=vec_k, axis=vp.vector(
# 0, 0, vp.mag(vec_i) * 0.1), radius=vp.mag(vec_k) * 0.03, color=vp.color.green)
# print(f'Camera Posn Vector = {vp.scene.camera.pos}')
# print(f'Camera Axis Vector = {vp.scene.camera.axis}')
# print()
# print(f'Camera Posn Vector = {vp.scene.camera.pos}')
# print(f'Camera Axis Vector = {vp.scene.camera.axis}')
# dtheta = 0.05
# theta = 0
# while (True):
# vp.rate(20)
# vec_camera_pos = vp.vector(
# 4 + 1*math.cos(theta), 4 + 1*math.sin(theta), 5)
# vp.scene.camera.pos = vec_camera_pos
# vec_camera_axis = vp.vector(
# math.cos(theta), math.sin(theta), -1.73205)
# vp.scene.camera.axis = vec_camera_axis
# theta += dtheta
<file_sep>/vector 1.py
import vpython as vp
import math
'''
# pip install Vpython
# https://www.glowscript.org/docs/VPythonDocs/index.html
'''
# vp.scene.width = 800
# vp.scene.height = 600
# vp.scene.title = "3D Axes"
vec_o = vp.vector(0, 0, 0)
vec_i = vp.vector(10, 0, 0)
vec_j = vp.vector(0, 10, 0)
vec_k = vp.vector(0, 0, 10)
text_size_scale = 0.1
unit_vec_x = vp.curve(vec_o, vec_i, color=vp.color.red)
x_text = vp.text(text='x', pos=vec_i, color=vp.color.red)
unit_vec_y = vp.curve(vec_o, vec_j, color=vp.color.orange)
y_text = vp.text(text='y', pos=vec_j, color=vp.color.orange)
unit_vec_z = vp.curve(vec_o, vec_k, color=vp.color.green)
z_text = vp.text(text='z', pos=vec_k, color=vp.color.green)
vp.scene.camera.pos = vp.vector(1, 1, 1)
print(f'Camera Axis Vector = {vp.scene.camera.axis}')
# vp.scene.camera.axis = vp.vector(1, 1, -1)
# print(vp.scene.camera.pos)
# print(vp.scene.camera.axis)
# pos <0, 0, 1.73205>
# axis <0, 0, -1.73205>
# dtheta = 0.05
# theta = 0
# while (True):
# vp.rate(20)
# # vp.scene.camera.pos = vp.vector(10*math.cos(theta), 10*math.sin(theta), 5)
# vp.scene.camera.axis = vp.vector(
# 10*math.cos(theta), 10*math.sin(theta), -31)
# theta += dtheta
<file_sep>/vector maths.py
import vpython as vp
# https://www.glowscript.org/docs/VPythonDocs/vector.html
v1 = vp.vector(2, 3, 5)
v2 = vp.vector(4, 7, 1)
v = v1 + v2
print(f' v1 = {v1}')
print(f' v2 = {v2}')
print(f' v1 + v2 = {v}')
print(f' mag(v1) = {vp.mag(v1)} (Magnitude)')
print(f'mag2(v1) = {vp.mag2(v1)} (Magnitude ** 2)')
print(f'norm(v1) = {vp.norm(v1)} (Unit Vector in the direction of v1)')
print(f' hat(v1) = {vp.hat(v1)} (Unit Vector in the direction of v1)')
print()
print(f' dot(v1, v2) = {vp.dot(v1, v2)}')
print(f'cross(v1, v2) = {vp.cross(v1, v2)}')
print()
print(
f'diff_angle(v1, v2) = {vp.diff_angle(v1, v2)} (Angle between v1 and v2 in radians)')
print()
print(f'proj(v1, v2) = {v1.proj(v2)} (Vector projection of v1 along v2)')
print(f'comp(v1, v2) = {v1.comp(v2)} (Scalar projection of v1 onto v2)')
print(f'v1.equals(v2) = {v1.equals(v2)}')
# To normalise a vector i.e. set its length to 1:
v3 = vp.vector(2, 3, 5)
norm_v3 = vp.norm(v3)
print(f'norm(v3) = {norm_v3}')
print(f'Magnitude(norm(v3)) = {vp.mag(norm_v3)}')
# Change the direction of v1 without changing its magnitude
v2.hat = v1 # Changes the direction of v2 to that of v1
# but not its magnitude
# Rotating a Vector
# v2 = vp.rotate(v1, angle=a, axis=vp.vector(x, y, z))
# Angle in radians, The default axis is (0, 0, 1) for a rotation in the xy plane around the z axis
# Equivalent v1.rotate(v1, angle=a, axis=vector(x, y, z))
| ed2b01210ba95e65d07d60f8b584de1f9e011fd5 | [
"Python"
] | 7 | Python | PauliSpin/Vectors | c3d5301fd4180b7c4df56fb8d1626b5bcf722991 | 9d62dbdbfc4aa8d9c3e744625772d14083758fb1 |
refs/heads/master | <repo_name>geow812/towerdefense<file_sep>/myscene.h
#ifndef MYSCENE_H
#define MYSCENE_H
#include "ennemis.h"
#include "defenses.h"
#include "projectiles.h"
#include <QGraphicsScene>
#include <QApplication>
#include <QtGui/QWidget>
#include <QWidget>
#include <QGraphicsItem>
#include <QPixmap>
#include <QFile>
#include <QMouseEvent>
struct structWave
{
QString t;//type
qreal s;//size
qreal n;//nombre
qreal i;//interval
};
struct wave{
QString intitule; // Intitulde la vague
structWave tab[10]; // une vague,possible different type d'ennemis
qreal nb; // Nombre de type d'ennemis
};
class Myscene : public QGraphicsScene
{
Q_OBJECT
public:
explicit Myscene(QObject *parent = 0);
void initScene();
void readMap();
int check[16][16];
Ennemis **ennemis;
wave tabWave[10];//on suppose max dix vague
int maxWave; // Nombre max de vague (=5) //REFAIRE EN PRENANT LE NOMBRE DE VAGUE COMME ARGUMENT DU CONSTRUCTEUR MYSCENE
int maxEnnemis; // Nombre max de Ennemis par vague (=30) // DE MEME EN PASSANT LE NB D'ENNEMI MAX COMME ARG
int EnnemisNumber; //Nombre de Ennemis
int waveCounter ; //num de la vague actuelle
int typeNumber; //numero actuel du type de Ennemis de la vague
int EnnemisNumberType; //nombre actuel de Ennemis d'un certain type dans une vague
int deletedEnnemisNumber; //nombre de Ennemis supprimer pour une vage donne
int nbvague;//nb de vague totale
int smallCafards;
void dieGuepe(int);
void petitCafards(int);
Defenses **defenses;
int DefensesNumber;
int DefensesType;
int nombreCredits;
int selectedDefenses;
int selectedDefensesType;
void infoPanel();
QTimer *t1;
QTimer *t2;
QTimer *createPistoletAEauTimer;
QTimer *createLancePierreTimer;
QTimer *createPaintBallTimer;
QTimer *deleteProjectileTimer;
private:
QString mat[16];
QStringList list[16];
QStringList l;
signals:
void clicked(int,int);
void EnnemisSucceed(int);
void finishedWave();
void ouvrirInfoTour(int);
//signal pr les affichages dans le label
void typeTour(QString);
void porteeTour(int);
void cadenceTour(int);
void degatsTour(int);
void prixTour(int);
void impossibleDeConstruireTour(QString);
void cleanConstruireTour(QString);
void projectileCreer();
void changeCredits(int);
void changeProgressbar(int);
public slots:
void checkEnnemisSucceed();
void killLeftItemsMysceneSlot();
void startWave (); //lance une vague lorsqu'on clique sur le bouton correspondant
void addEnnemis();
void DefensesTypePistoletAEau();
void DefensesTypeLancePierre();
void DefensesTypePaintBall();
void DefensesTypePetanque();
void createDefenses(QPointF pt);
void createPistoletAEauProjectile();
void deleteProjectile();
void createLancePierreProjectile();
void createPaintBallProjectile();
void upgradeDefenses(QPointF qt);
protected:
};
#endif // MYSCENE_H<file_sep>/projectiles.h
#ifndef PROJECTILES_H
#define PROJECTILES_H
#include "ennemis.h"
class Projectiles : public QObject, public QGraphicsPixmapItem
{
Q_OBJECT
Q_PROPERTY(QPointF pos READ pos WRITE setPos)
public:
QPointF p;
int vitesse;
Projectiles(QPointF p,int);
virtual void launch(QPointF d);
int target;
public slots:
virtual void destroy();
};
class EauProjectiles:public Projectiles{
public:
EauProjectiles(QPointF p,int);
};
class PierreProjectiles:public Projectiles{
public:
PierreProjectiles(QPointF p,int);
};
class PaintBallProjectiles:public Projectiles{
public:
PaintBallProjectiles(QPointF p,int);
};
#endif // PROJECTILES_H
<file_sep>/defenses.cpp
#include "defenses.h"
Defenses::Defenses()
{
rayonAction = 120;
focus = 0;
focusNumber = -1;
niveau = 1;
nbProjectiles = 0;
type = 0;
projectile = new Projectiles*[20];
}
QRectF Defenses::boundingRect() const{
return QRect (-15,-15,30,30);
}
void Defenses::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
painter->drawPixmap(-15, -15, *pixmap);
}
PistoletAEauDefenses::PistoletAEauDefenses() : Defenses(){
typeName = "Pistolet A Eau";
type = 1;
pixmap = new QPixmap(":/images/blue_monster.png");
*pixmap=pixmap->scaled(30,30,Qt::KeepAspectRatio);
niveau = 1;
rayonAction = 60 + (niveau/2.0)*30.0;
degat = ( 5 * (pow(niveau,1.5)) );
coutDeBase = 8;
coutUnVersDeux = 20;
coutDeuxVersTrois = 45;
cadence = 4;
}
LancePierreDefenses::LancePierreDefenses() : Defenses(){
typeName = "Lance Pierre";
pixmap = new QPixmap(":/images/yellow_monster.png");
*pixmap=pixmap->scaled(30,30,Qt::KeepAspectRatio);
type = 2;
niveau = 1;
rayonAction = 90 + (niveau/2.0)*30.0;
degat = ( 10 * (pow(niveau,1.5)) );
coutDeBase = 12;
coutUnVersDeux = 25;
coutDeuxVersTrois = 60;
cadence = 1;
}
PaintBallDefenses::PaintBallDefenses(){
typeName = "Paint-ball";
type=3;
pixmap = new QPixmap(":/images/green_monster.png");
*pixmap=pixmap->scaled(30,30,Qt::KeepAspectRatio);
niveau = 1;
rayonAction = 120 + (niveau/2.0)*30.0;
degat = ( 4 * (pow(niveau,1.5)) );
coutDeBase = 12;
coutUnVersDeux = 25;
coutDeuxVersTrois = 60;
cadence = 2;
}
PetanqueDefenses :: PetanqueDefenses() {
typeName = "Joueuer de pétanque";
type=4;
pixmap = new QPixmap(":/images/red_monster.png");
*pixmap=pixmap->scaled(30,30,Qt::KeepAspectRatio);
niveau = 1;
rayonAction = 120 + (niveau/2.0)*30.0;
degat = ( 4 * (pow(niveau,1.5)) );
coutDeBase = 15;
coutUnVersDeux = 40;
coutDeuxVersTrois = 80;
cadence = 2;
}
<file_sep>/projectiles.cpp
#include "projectiles.h"
#include <QGraphicsScene>
#include <QPropertyAnimation>
#include <QSequentialAnimationGroup>
void Projectiles::destroy(){
this->deleteLater();
};
Projectiles::Projectiles(QPointF point,int t):p(point),vitesse(t){
setPos(p.x()-15,p.y()-15);
setZValue(2);
this->scale(0.10,0.10);
};
void Projectiles::launch(QPointF d){
QParallelAnimationGroup *group=new QParallelAnimationGroup;
QPropertyAnimation *anim1=new QPropertyAnimation(this, "pos");
anim1->setDuration(200*vitesse);
anim1->setStartValue(p);
anim1->setEndValue(d);
//anim1->setEasingCurve(QEasingCurve::OutBounce);
anim1->start();
group->addAnimation(anim1);
};
EauProjectiles::EauProjectiles(QPointF point,int t):Projectiles(point,t){
QPixmap *bird=new QPixmap;
bird->load(":/images/ball7.png");
setPixmap(*bird);
};
PierreProjectiles::PierreProjectiles(QPointF point,int t):Projectiles(point,t){
QPixmap *bird=new QPixmap;
bird->load(":/images/ball8.png");
setPixmap(*bird);
};
PaintBallProjectiles::PaintBallProjectiles(QPointF point,int t):Projectiles(point,t){
QPixmap *bird=new QPixmap;
bird->load(":/images/ball4.png");
setPixmap(*bird);
};<file_sep>/myscene.cpp
#include "Myscene.h"
#include <QPropertyAnimation>
Myscene::Myscene(QObject *parent) :
QGraphicsScene(parent)
{
initScene();
readMap();
maxEnnemis=31;
ennemis = new Ennemis*[maxEnnemis];
waveCounter=-1;
EnnemisNumber=0;
DefensesType=0;
DefensesNumber=0;
defenses = new Defenses*[30];
nombreCredits=40;
selectedDefenses = -1;
selectedDefensesType = -1;
t1 = new QTimer();
t1->setSingleShot(false);
// t1->start();
// t1->stop();
t2 = new QTimer();
t2->setSingleShot(false);
// t2->start(20);
//t2->stop();
createPistoletAEauTimer = new QTimer();
createPistoletAEauTimer->start(300);
createPistoletAEauTimer->stop();
createLancePierreTimer = new QTimer;
createLancePierreTimer->start(200);
createLancePierreTimer->stop();
createPaintBallTimer = new QTimer;
createPaintBallTimer->start(200);
createPaintBallTimer->stop();
deleteProjectileTimer=new QTimer;
deleteProjectileTimer->start(200);
deleteProjectileTimer->stop();
}
void Myscene::initScene(){
QPixmap herbe;
herbe.load(":/images/herbe.jpg",0,Qt::AutoColor);
herbe = herbe.scaled(30,30,Qt::KeepAspectRatio);
//scene->setSceneRect(480,480,480,480);
for(int i=0;i<16;i++)
for(int j=0;j<16;j++)
{
QGraphicsItem *background;
background = this->addPixmap(herbe);
background->setPos(i*30,j*30);
}
}
void Myscene::readMap(){
/******************************map***************************/
QFile mapFile(":/txt/map.txt");
if (mapFile.open(QIODevice::ReadOnly| QIODevice::Text))
{
for(int i=0;i<16;i++)
{
mat[i]=mapFile.readLine();
mat[i]=mat[i].simplified();
list[i]=mat[i].split(" ",QString::SkipEmptyParts);
l.append(list[i]);
}
mapFile.close();
}
QPixmap img0;
img0.load(":/images/grass2.png", 0, Qt::AutoColor);
img0=img0.scaled(30,30,Qt::KeepAspectRatio);
QPixmap img1;
img1.load(":/images/soil15.png", 0, Qt::AutoColor);
img1=img1.scaled(30,30,Qt::KeepAspectRatio);
QPixmap img2;
img2.load(":/images/water3.png", 0, Qt::AutoColor);
img2=img2.scaled(30,30,Qt::KeepAspectRatio);
QPixmap img3;
img3.load(":/images/fin.png", 0, Qt::AutoColor);
img3=img3.scaled(30,30,Qt::KeepAspectRatio);
for(int m=0;m<16;m++)
for(int n=0;n<16;n++)
{
check[m][n]=0;
}
for (int i=0;i<16;i++)
{
for (int j=0;j<16;j++)
{
if (list[i][j]=="18" || list[i][j]=="2"|| list[i][j]=="11" || list[i][j]=="6"||list[i][j]=="4"||list[i][j]=="10"||list[i][j]=="8"|| list[i][j]=="7")
{
QGraphicsItem *item1;
item1 = this->addPixmap(img1);
item1->setPos((j)*30,(i)*30);
}
if(list[i][j]=="0"){
QGraphicsItem *item0;
item0 = this->addPixmap(img0);
item0->setPos((j)*30,(i)*30);
check[j][i]=1;
}
if(list[i][j]=="64"){
QGraphicsItem *item2;
item2 = this->addPixmap(img2);
item2->setPos((j)*30,(i)*30);
}
if(list[i][j]=="32"){
QGraphicsItem *item3;
item3 = this->addPixmap(img3);
item3->setPos((j)*30,(i)*30);
}
}
}
/*********************wave Ennemis****************/
QFile waveFile(":/txt/waves.txt");
QString waveread;
if(waveFile.open(QIODevice::ReadOnly| QIODevice::Text)){
waveread=waveFile.readAll();
waveFile.close();
}
else waveread= "Impossible d'ouvrir le fichier !";
QStringList wavelist = waveread.split('\n');
nbvague=wavelist.count();//nb de vague totale
for (int i=0;i<wavelist.count();i++)
{
QStringList partie1;
QStringList partie2;
partie1 = wavelist[i].split(';');
tabWave[i].nb=partie1.count()-1; //renvoie le type d'ennemis dans une vague
tabWave[i].intitule=partie1[0];
for (int j=1;j<partie1.count();j++)
{
partie2 = partie1[j].split(':');
tabWave[i].tab[j-1].t=partie2[0];
tabWave[i].tab[j-1].s=partie2[1].toInt();
tabWave[i].tab[j-1].n=partie2[2].toInt();
tabWave[i].tab[j-1].i=partie2[3].toInt();
}
}
}
void Myscene::checkEnnemisSucceed(){
QPointF b(405,465);
for (int i=0;i<EnnemisNumber;i++){
if (ennemis[i]!= 0){
if (ennemis[i]->pos()==b){
QSound::play("lose.wav");
this->removeItem(ennemis[i]);
delete ennemis[i];
ennemis[i] = 0;
deletedEnnemisNumber++;
emit EnnemisSucceed(1);
if (deletedEnnemisNumber == maxEnnemis+smallCafards)
{
emit finishedWave();
}
}
}
}
}
void Myscene::killLeftItemsMysceneSlot(){
for (int i=deletedEnnemisNumber;i<maxEnnemis;i++) {
this->removeItem(ennemis[i]);
}
}
void Myscene::dieGuepe(int focus){
/* QRectF rectCentre(ennemis[focus]->pos().x(),ennemis[focus]->pos().y(),90,90);
for (int i=0;i<EnnemisNumber;i++)
{
if (ennemis[i] != 0)
{
if (rectCentre.contains(ennemis[i]->pos()))
{
ennemis[i]->hp-=1;
if (ennemis[i]->hp <= 0){
if (dynamic_cast<Guepes*>(ennemis[i])){ dieGuepe(i);}
if ((dynamic_cast<Cafards*>(ennemis[i])) && (ennemis[i]->taille>= 2)){ petitCafards(i);}
this->removeItem(ennemis[i]);
delete ennemis[i];
ennemis[i] = 0;
emit changeCredits(1);
deletedEnnemisNumber++;}
if (deletedEnnemisNumber==maxEnnemis+smallCafards){emit finishedWave();}
}}}*/
};
void Myscene::petitCafards(int focus){
for (int i=0;i<2;i++){
ennemis[EnnemisNumber] = new Cafards(ennemis[focus]->taille-1);
ennemis[EnnemisNumber]->setPos(ennemis[focus]->pos().x(),ennemis[focus]->pos().y());
ennemis[EnnemisNumber]->setway(&l);
this->addItem(ennemis[EnnemisNumber]);
ennemis[EnnemisNumber]->setZValue(2);
ennemis[EnnemisNumber]->casePrecedente = ennemis[focus]->casePrecedente;
if (ennemis[focus]->casePrecedente == 6 || ennemis[focus]->casePrecedente == 4)
{
ennemis[EnnemisNumber]->setRotation(270);
}
if (ennemis[focus]->casePrecedente == 8)
{
ennemis[EnnemisNumber]->setRotation(90);
}
EnnemisNumber+=1;
smallCafards++;
}
};
void Myscene::startWave () //lance une vague lorsqu'on clique sur le bouton correspondant
{
smallCafards=0;
waveCounter+=1;
EnnemisNumber=0;
deletedEnnemisNumber=0;
}
void Myscene::addEnnemis(){
if (EnnemisNumber==0){
maxEnnemis=0;
for (int i=0;i<tabWave[waveCounter].nb;i++){
maxEnnemis+=tabWave[waveCounter].tab[i].n;
}
typeNumber=0;
EnnemisNumberType=0;
}
if (EnnemisNumber==maxEnnemis+smallCafards){
return;}
if (tabWave[waveCounter].tab[typeNumber].n==EnnemisNumberType){
if (tabWave[waveCounter].nb==typeNumber) return;
typeNumber+=1;
EnnemisNumberType=0;
}
if (tabWave[waveCounter].tab[typeNumber].t=="fourmi"){
t1->start(50*tabWave[waveCounter].tab[typeNumber].i);
ennemis[EnnemisNumber] = new Fourmis(tabWave[waveCounter].tab[typeNumber].s);
EnnemisNumberType+=1;
t2->start(6*ennemis[EnnemisNumber]->vitesse);
}
if (tabWave[waveCounter].tab[typeNumber].t=="guepe")
{ t1->start(50*tabWave[waveCounter].tab[typeNumber].i);
ennemis[EnnemisNumber] = new Guepes(tabWave[waveCounter].tab[typeNumber].s);
EnnemisNumberType+=1;
t2->start(6*ennemis[EnnemisNumber]->vitesse);
}
if (tabWave[waveCounter].tab[typeNumber].t=="cafard")
{ t1->start(50*tabWave[waveCounter].tab[typeNumber].i);
ennemis[EnnemisNumber] = new Cafards(tabWave[waveCounter].tab[typeNumber].s);
EnnemisNumberType+=1;
t2->start(6*ennemis[EnnemisNumber]->vitesse);
}
if (tabWave[waveCounter].tab[typeNumber].t=="moustique")
{ t1->start(50*tabWave[waveCounter].tab[typeNumber].i);
ennemis[EnnemisNumber] = new Moustiques(tabWave[waveCounter].tab[typeNumber].s);
EnnemisNumberType+=1;
t2->start(6*ennemis[EnnemisNumber]->vitesse);
}
ennemis[EnnemisNumber]->setPos((2)*30+15,(0)*30+15);
ennemis[EnnemisNumber]->setway(&l);
this->addItem(ennemis[EnnemisNumber]);
ennemis[EnnemisNumber]->setZValue(2);
EnnemisNumber++;
emit changeProgressbar(EnnemisNumber);
};
void Myscene::upgradeDefenses(QPointF pt){
int b=(pt.x())/30;
int c=(pt.y())/30;
int d=b+c*16;
if(l[d]=="0") return;
for(int i=0;i<DefensesNumber;i++){
;
if(defenses[i]->position==QPointF(b,c)){
switch(defenses[i]->niveau){
case 1:
if(nombreCredits-defenses[i]->coutUnVersDeux>=0){
defenses[i]->setniveau(2);
nombreCredits-=defenses[i]->coutUnVersDeux;
qDebug()<<nombreCredits;
qDebug()<<i;
emit changeCredits(-defenses[i]->coutUnVersDeux);
emit typeTour(defenses[i]->typeName);
emit porteeTour(defenses[i]->rayonAction/30.0);
emit cadenceTour(defenses[i]->cadence);
emit degatsTour(defenses[i]->degat);
emit prixTour(defenses[i]->coutUnVersDeux);
return;
}
case 2:
if(nombreCredits-defenses[i]->coutDeuxVersTrois>=0){
defenses[i]->setniveau(2);
nombreCredits-=defenses[i]->coutDeuxVersTrois;
emit changeCredits(-defenses[i]->coutDeuxVersTrois);
emit typeTour(defenses[i]->typeName);
emit porteeTour(defenses[i]->rayonAction/30.0);
emit cadenceTour(defenses[i]->cadence);
emit degatsTour(defenses[i]->degat);
emit prixTour(defenses[i]->coutDeuxVersTrois);
return;
}
case 3:break;
default: return;
}
}
}
};
void Myscene::DefensesTypePistoletAEau(){
DefensesType=1;
};
void Myscene::DefensesTypeLancePierre(){
DefensesType=2;
};
void Myscene::DefensesTypePaintBall(){
DefensesType=3;
};
void Myscene::DefensesTypePetanque(){
DefensesType=4;
};
void Myscene::createDefenses(QPointF pt){
int b=(pt.x())/30;
int c=(pt.y())/30;
int d=b+c*16;
if (DefensesType!=0){
if (l[d]=="0"){
switch(DefensesType){
case 1:
defenses[DefensesNumber] = new PistoletAEauDefenses();
infoPanel();
l[d]="1";
break;
case 2:
defenses[DefensesNumber] = new LancePierreDefenses();
infoPanel();
l[d]="2";
break;
case 3:
defenses[DefensesNumber] = new PaintBallDefenses();
infoPanel();
l[d]="3";
break;
case 4:
defenses[DefensesNumber] = new PetanqueDefenses();
infoPanel();
l[d]="4";
break;
default: break;
}
if ((nombreCredits - defenses[DefensesNumber]->coutDeBase) >= 0){
defenses[DefensesNumber]->setPos(b*30+15,c*30+15);
defenses[DefensesNumber]->position = QPointF(b,c);
this->addItem(defenses[DefensesNumber]);
emit changeCredits(-defenses[DefensesNumber]->coutDeBase);
DefensesType=0;
nombreCredits-=defenses[DefensesNumber]->coutDeBase;
DefensesNumber++;
emit cleanConstruireTour(" ");
qDebug()<<"okokhihihihihi"<<DefensesNumber;
}
else{ qDebug()<<"impossiblehihihihihi";
emit impossibleDeConstruireTour("Pas assez de credits !");
delete defenses[DefensesNumber];
l[d]="0";
DefensesType=0;
}
}
else if (l[d] == "1" || l[d] == "2" || l[d] == "3"){ qDebug()<<"hihihihihi";upgradeDefenses(pt);
}
}
};
void Myscene::infoPanel()
{
emit typeTour(defenses[DefensesNumber]->typeName);
emit porteeTour(defenses[DefensesNumber]->rayonAction/30.0);
emit cadenceTour(defenses[DefensesNumber]->cadence);
emit degatsTour(defenses[DefensesNumber]->degat);
emit prixTour(defenses[DefensesNumber]->coutDeBase);
}
void Myscene::createPistoletAEauProjectile(){
for (int i=0;i<DefensesNumber;i++){
if (defenses[i]->type == 1){
if (defenses[i]->focusNumber == -1){ //Recherche une cible
for (int j=0;j<EnnemisNumber;j++){
if (ennemis[j]!=0){
QPointF vecteur = ennemis[j]->pos() - defenses[i]->pos();
float distance = sqrt( ( vecteur.x() * vecteur.x() ) + ( vecteur.y() * vecteur.y()) );
if (distance < defenses[i]->rayonAction){
defenses[i]->focusNumber = j;
}
}
}
}
else {//On a d'une cible
if (ennemis[defenses[i]->focusNumber] != 0){
QPointF cible= ennemis[defenses[i]->focusNumber]->pos();
QPointF vecteur =cible - defenses[i]->pos();
float distance = sqrt( ( vecteur.x() * vecteur.x() ) + ( vecteur.y() * vecteur.y()) );
if (distance < defenses[i]->rayonAction){
if(defenses[i]->nbProjectiles==20) defenses[i]->nbProjectiles=0;
defenses[i]->projectile[defenses[i]->nbProjectiles] = new EauProjectiles(QPointF(defenses[i]->pos().x()-15,defenses[i]->pos().y()-15),2);
defenses[i]->projectile[defenses[i]->nbProjectiles]->target = defenses[i]->focusNumber;
this->addItem(defenses[i]->projectile[defenses[i]->nbProjectiles]);
defenses[i]->projectile[defenses[i]->nbProjectiles]->launch(QPointF(cible.x()+10,cible.y()-10));
defenses[i]->nbProjectiles++;
QTimer::singleShot(200,this, SLOT(deleteProjectile()));
}
else{
defenses[i]->focusNumber = -1;
}
}
else
{
defenses[i]->focusNumber = -1;
}
}
}
}
};
void Myscene::deleteProjectile(){
for (int i=0;i<DefensesNumber;i++){
for (int j=0;j<defenses[i]->nbProjectiles;j++){
if (defenses[i]->projectile[j] != 0){
QSound::play("collision.wav");
if (ennemis[defenses[i]->projectile[j]->target] != 0){
int focus = defenses[i]->projectile[j]->target;
if (Fourmis *pt = dynamic_cast<Fourmis*>(ennemis[focus])){
if (pt->acc==false) pt->accelerer();
QTimer::singleShot(5000,ennemis[focus],SLOT(accelerer()));
}
ennemis[focus]->hp-=1;
defenses[i]->projectile[j]->destroy();
delete defenses[i]->projectile[j];
defenses[i]->projectile[j] = 0;
if (ennemis[focus]->hp <= 0){
if (dynamic_cast<Guepes*>(ennemis[focus])){ dieGuepe(focus);}
if ((dynamic_cast<Cafards*>(ennemis[focus])) && (ennemis[focus]->taille>= 2)){ petitCafards(focus);}
this->removeItem(ennemis[focus]);
delete ennemis[focus];
ennemis[focus] = 0;
emit changeCredits(1);
deletedEnnemisNumber++;}
if (deletedEnnemisNumber==maxEnnemis+smallCafards){emit finishedWave();}}
else
{
defenses[i]->projectile[j]->target = -1;
defenses[i]->projectile[j]->destroy();
delete defenses[i]->projectile[j];
defenses[i]->projectile[j] = 0;
}
}}}};
void Myscene::createLancePierreProjectile(){
for (int i=0;i<DefensesNumber;i++){
if (defenses[i]->type == 2){
if (defenses[i]->focusNumber == -1){ //Recherche une cible
for (int j=0;j<EnnemisNumber;j++){
if (ennemis[j]!=0){
QPointF vecteur = ennemis[j]->pos() - defenses[i]->pos();
float distance = sqrt( ( vecteur.x() * vecteur.x() ) + ( vecteur.y() * vecteur.y()) );
if (distance < defenses[i]->rayonAction){
defenses[i]->focusNumber = j;
}
}
}
}
else {//On a d'une cible
if (ennemis[defenses[i]->focusNumber] != 0){
QPointF cible= ennemis[defenses[i]->focusNumber]->pos();
QPointF vecteur =cible - defenses[i]->pos();
float distance = sqrt( ( vecteur.x() * vecteur.x() ) + ( vecteur.y() * vecteur.y()) );
if (distance < defenses[i]->rayonAction){
if(defenses[i]->nbProjectiles==20) defenses[i]->nbProjectiles=0;
defenses[i]->projectile[defenses[i]->nbProjectiles] = new PierreProjectiles(QPointF(defenses[i]->pos().x()-15,defenses[i]->pos().y()-15),2);
defenses[i]->projectile[defenses[i]->nbProjectiles]->target = defenses[i]->focusNumber;
this->addItem(defenses[i]->projectile[defenses[i]->nbProjectiles]);
defenses[i]->projectile[defenses[i]->nbProjectiles]->launch(QPointF(cible.x()+10,cible.y()-10));
defenses[i]->nbProjectiles++;
QTimer::singleShot(200,this, SLOT(deleteProjectile()));
}
else{
defenses[i]->focusNumber = -1;
}
}
else
{
defenses[i]->focusNumber = -1;
}
}
}
}
};
void Myscene::createPaintBallProjectile(){
for (int i=0;i<DefensesNumber;i++){
if (defenses[i]->type == 3){
if (defenses[i]->focusNumber == -1){ //Recherche une cible
for (int j=0;j<EnnemisNumber;j++){
if (ennemis[j]!=0){
QPointF vecteur = ennemis[j]->pos() - defenses[i]->pos();
float distance = sqrt( ( vecteur.x() * vecteur.x() ) + ( vecteur.y() * vecteur.y()) );
if (distance < defenses[i]->rayonAction){
defenses[i]->focusNumber = j;
}
}
}
}
else {//On a d'une cible
if (ennemis[defenses[i]->focusNumber] != 0){
QPointF cible= ennemis[defenses[i]->focusNumber]->pos();
QPointF vecteur =cible - defenses[i]->pos();
float distance = sqrt( ( vecteur.x() * vecteur.x() ) + ( vecteur.y() * vecteur.y()) );
if (distance < defenses[i]->rayonAction){
if(defenses[i]->nbProjectiles==20) defenses[i]->nbProjectiles=0;
defenses[i]->projectile[defenses[i]->nbProjectiles] = new PaintBallProjectiles(QPointF(defenses[i]->pos().x()-15,defenses[i]->pos().y()-15),2);
defenses[i]->projectile[defenses[i]->nbProjectiles]->target = defenses[i]->focusNumber;
this->addItem(defenses[i]->projectile[defenses[i]->nbProjectiles]);
defenses[i]->projectile[defenses[i]->nbProjectiles]->launch(QPointF(cible.x()+10,cible.y()-10));
defenses[i]->nbProjectiles++;
QTimer::singleShot(200,this, SLOT(deleteProjectile()));
}
else{
defenses[i]->focusNumber = -1;
}
}
else
{
defenses[i]->focusNumber = -1;
}
}
}
}
};<file_sep>/widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QApplication>
#include <QtGui/QWidget>
#include <QWidget>
#include <QPushButton>
#include <QGridLayout>
#include <QPixmap>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsItem>
#include <QFile>
#include <QGroupBox>
#include <QButtonGroup>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <QLCDNumber>
#include <QProgressBar>
#include <QTextEdit>
#include <QMouseEvent>
#include "myscene.h"
class Myview : public QGraphicsView
{
Q_OBJECT
public:
Myview(Myscene *scene, QWidget *parent = 0);
QPointF mousePoint;
void mousePressEvent(QMouseEvent * mouseEvent )
{
mousePoint = mouseEvent->pos();
emit mouseScenePress(mousePoint);
}
signals:
void mouseScenePress(QPointF);
public slots:
};
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
~Widget();
private:
Myscene* scene;
QGraphicsView* view;
QGridLayout *layout;
//=====================bloc 1
int etatBtn;
QPushButton *btnLancer;
QPushButton *btnArreter;
QPushButton *btnQuitter ;
QHBoxLayout *group1;
//======================bloc 2
QLabel* credit;
QLCDNumber* nbCredit;
QLabel* vie;
QLCDNumber* nbVie;
QGridLayout *box;
QGroupBox* group2;
//========================bloc 3
QProgressBar* group3;
//========================bloc 4
QPushButton *btnEau;
QPushButton *btnPierre;
QPushButton *btnPaintBall;
QPushButton *btnPetanque;
QPushButton *btnMusicien;
QGridLayout *layout3;
QGroupBox* group4 ;
//=========================bloc 5
QLabel*typeTourLabel;
QLabel*porteeTourLabel;
QLabel*cadenceTourLabel;
QLabel*degatsTourLabel;
QLabel*coutTourLabel;
QPushButton *btnAmeliorer;
QPushButton *btnDetruire;
QVBoxLayout *bloc4;
QGroupBox* group5;
//======================regrouper tous les blocs a droite
QVBoxLayout *rightLayout;
signals:
void gameover();
public slots:
void vieLCD(int i){
int vie=nbVie->intValue()-i;
if (vie>0){
nbVie->display(vie);}
else emit gameover();
}
void creditLCD(int i){
int credits=nbCredit->intValue()+i;
if (credits>0){
nbCredit->display(credits);}
//else emit gameover();
}
void avanceProgressbar(int i){
group3->setValue(i);;
}
void buttons(){
if (etatBtn==0){
btnLancer->setEnabled(false);
btnArreter->setEnabled(true);
etatBtn=1;}
else{
btnLancer->setEnabled(true);
btnArreter->setEnabled(false);
etatBtn=0;
}
}
};
#endif // WIDGET_H<file_sep>/ennemis.cpp
#include "ennemis.h"
Ennemis::Ennemis(){
taille = 1;
ralentir = false;
};
Ennemis::Ennemis(float t,int m,float v,int vitalite,int resistance):taille(t),mode(m),vitesse(v),hp(vitalite),resist(resistance)
{
ralentir = false;
};
QRectF Ennemis::boundingRect() const{
return QRect (-30/2,-30/2,30,30);
}
void Ennemis::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
QRectF r(boundingRect());
painter->drawPixmap(-30/2,-15/2,*pixmap);
}
void Ennemis::setway(QStringList *l){
way = QStringList(*l);
img = 0;
}
void Ennemis::advance(int phase){
if (!phase)
return;
img++;
*pixmap = changeimage(img);
QPointF a(this->scenePos());
int b=(a.x()-15)/pixmap->width();
int c=(a.y()-15)/pixmap->height();
qreal m=c*16+b;
if((way[m]=="18") && (QPoint(b*30+15,c*30+15)==this->scenePos())){
casePrecedente=18;
this->moveBy(0,1);
return;
}
if((way[m]=="2") && (QPoint(b*30+15,c*30+15)==this->scenePos())){
casePrecedente=2;
this->moveBy(0,1);
return;
}
if((way[m]=="6") && (QPoint(b*30+15,c*30+15)==this->scenePos())){
casePrecedente=6;
this->setRotation(270);
this->moveBy(1,0);
return;
}
if((way[m]=="4") && (QPoint(b*30+15,c*30+15)==this->scenePos())){
casePrecedente=4;
this->moveBy(1,0);
return;
}
if((way[m]=="7") && (QPoint(b*30+15,c*30+15)==this->scenePos())){
casePrecedente=7;
this->setRotation(0);
this->moveBy(0,1);
return;
}
if((way[m]=="10") && (QPoint(b*30+15,c*30+15)==this->scenePos())){
casePrecedente=10;
this->setRotation(90);
this->moveBy(-1,0);
return;
}
if((way[m]=="8") && (QPoint(b*30+15,c*30+15)==this->scenePos())){
casePrecedente=8;
this->setRotation(90);
this->moveBy(-1,0);
return;
}
if((way[m]=="11") && (QPoint(b*30+15,c*30+15)==this->scenePos())){
casePrecedente=11;
this->setRotation(0);
this->moveBy(0,1);
return;
}
if((way[m]=="32") && (QPoint(b*30+15,c*30+15)==this->scenePos())){
casePrecedente=32;
this->setRotation(0);
this->moveBy(0,0);
return;
}
if (casePrecedente==18){
this->moveBy(0,1);
return;
}
if (casePrecedente==2){
this->moveBy(0,1);
return;
}
if (casePrecedente==6){
this->moveBy(1,0);
return;
}
if (casePrecedente==4){
this->moveBy(1,0);
return;
}
if (casePrecedente==7){
this->moveBy(0,1);
return;
}
if (casePrecedente==10){
this->moveBy(-1,0);
return;
}
if (casePrecedente==8){
this->moveBy(-1,0);
return;
}
if (casePrecedente==11){
this->moveBy(0,1);
return;
}}
void Ennemis::resetvitesse(){
if(ralentir==true){
vitesse=2*vitesse;
ralentir=false;
}
else return;
}
void Ennemis::smallvitesse(){
if(ralentir==false){
ralentir=true;
vitesse=0.5*vitesse;}
else return;
}
Cafards::Cafards(float t):Ennemis(t,0,2,10*t*t,5*t*t){
pixmap = new QPixmap(":/images/cafard1.png");
*pixmap=pixmap->scaled(30,30,Qt::IgnoreAspectRatio);
casePrecedente=18;
img=0;
}
QPixmap Cafards::changeimage(int img){
if (img%15==0)
{
pixmap = new QPixmap(":/images/cafard1.png");
*pixmap=pixmap->scaled(30,30,Qt::KeepAspectRatio);
}
else if (img%10==0)
{
pixmap = new QPixmap(":/images/cafard3.png");
*pixmap=pixmap->scaled(30,30,Qt::KeepAspectRatio);
}
else if (img%5==0)
{
pixmap = new QPixmap(":/images/cafard2.png");
*pixmap=pixmap->scaled(30,30,Qt::KeepAspectRatio);
}
return *pixmap;
}
Fourmis::Fourmis(float t):Ennemis(t,0,(2+t/2),5*t*t,t*t){
pixmap = new QPixmap(":/images/fourmi1.png");
*pixmap=pixmap->scaled(30,30,Qt::IgnoreAspectRatio);
casePrecedente=18;
img=0;
acc=false;
}
QPixmap Fourmis::changeimage(int img){
img++;
if (img%15==0){
pixmap = new QPixmap(":/images/fourmi1.png");
*pixmap=pixmap->scaled(30,30,Qt::KeepAspectRatio);
img=0;
}
else if (img%10==0){
pixmap = new QPixmap(":/images/fourmi3.png");
*pixmap=pixmap->scaled(30,30,Qt::KeepAspectRatio);
}
else if (img%5==0){
pixmap = new QPixmap(":/images/fourmi2.png");
*pixmap=pixmap->scaled(30,30,Qt::KeepAspectRatio);
}
return *pixmap;
}
void Fourmis::accelerer(){
if(acc==false) {vitesse*=1.5;
acc=true;
}
else {vitesse/=1.5;
acc=true;}
};
Guepes::Guepes(float t):Ennemis(t,1,3,7*t*t,4*t*t){
pixmap = new QPixmap(":/images/guepe1.png");
*pixmap=pixmap->scaled(30,30,Qt::IgnoreAspectRatio);
casePrecedente=18;
img=0;
}
QPixmap Guepes::changeimage(int img){
img++;
if (img%10==0){
pixmap = new QPixmap(":/images/guepe2.png");
*pixmap=pixmap->scaled(30,30,Qt::KeepAspectRatio);
img=0;
}
else if (img%5==0){
pixmap = new QPixmap(":/images/guepe1.png");
*pixmap=pixmap->scaled(30,30,Qt::KeepAspectRatio);
}
return *pixmap;
}
void Guepes::die(){
};
Moustiques::Moustiques(float t):Ennemis(t,2,(1+t/2),6*t*t,15*t*t){
pixmap = new QPixmap(":/images/moustiquevolant1.png");
*pixmap=pixmap->scaled(30,30,Qt::IgnoreAspectRatio);
casePrecedente=18;
img=0;
modevol=true;
sol=false;
}
QPixmap Moustiques::changeimage(int img){
img++;
if (img%10==0){
pixmap = new QPixmap(":/images/moustiquevolant2.png");
*pixmap=pixmap->scaled(30,30,Qt::KeepAspectRatio);
}
else if (img%5==0){
pixmap = new QPixmap(":/images/moustiquevolant1.png");
*pixmap=pixmap->scaled(30,30,Qt::KeepAspectRatio);
}
return *pixmap;
}
void Moustiques::changemode(){
};
void Moustiques::cachersol(){
if(sol) {
resist=15*taille*taille;
sol=false; }
else {resist=100*taille*taille;
sol=true;}
};
void Moustiques::moustiquestouche(){
//touche au vol se posent pendant 3 seconds
};<file_sep>/widget.cpp
#include "widget.h"
Myview::Myview(Myscene *scene, QWidget *parent) :
QGraphicsView(scene, parent){
}
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
QSound *begin=new QSound("begin1.wav",this);
begin->play();
scene = new Myscene;
view = new Myview(scene,parent);
//=====================bloc 1
btnLancer = new QPushButton("Begin");
btnLancer->setEnabled(true);
btnArreter = new QPushButton("Pause");
btnArreter->setEnabled(false);
etatBtn=0;
btnQuitter = new QPushButton("Exit");
group1 = new QHBoxLayout;
group1->addWidget(btnLancer,0,Qt::AlignCenter);
group1->addWidget(btnArreter,0,Qt::AlignCenter);
group1->addWidget(btnQuitter,0,Qt::AlignCenter);
//======================bloc 2
credit = new QLabel("Credit");
nbCredit = new QLCDNumber(4);
vie = new QLabel("Vie");
nbVie = new QLCDNumber(4);
box = new QGridLayout;
box->addWidget(credit,0,0,Qt::AlignCenter);
box->addWidget(nbCredit,0,1,Qt::AlignCenter);
box->addWidget(vie,1,0,Qt::AlignCenter);
box->addWidget(nbVie,1,1,Qt::AlignCenter);
group2 = new QGroupBox;
group2->setLayout(box);
//========================bloc 3
group3 = new QProgressBar;
group3->setRange(0,15);
group3->setTextVisible(true);
group3->setValue(0);
//========================bloc 4
btnEau = new QPushButton("Eau");
btnPierre = new QPushButton("Pierre");
btnPaintBall = new QPushButton("Paint-Ball");
btnPetanque = new QPushButton("Petanque");
btnMusicien = new QPushButton("Musicien");
layout3 = new QGridLayout;
layout3->addWidget(btnEau,0,0,Qt::AlignCenter);
layout3->addWidget(btnPierre,0,1,Qt::AlignCenter);
layout3->addWidget(btnPaintBall,1,0,Qt::AlignCenter);
layout3->addWidget(btnPetanque,1,1,Qt::AlignCenter);
layout3->addWidget(btnMusicien,2,0,Qt::AlignCenter);
group4 = new QGroupBox;
group4->setTitle("Type de defenses");
group4->setLayout(layout3);
//=========================bloc 5
typeTourLabel = new QLabel(tr("Type de tour : "));
porteeTourLabel = new QLabel(tr("Portée de Tour : "));
cadenceTourLabel = new QLabel(tr("Cadence de Tour : "));
degatsTourLabel = new QLabel(tr("Dégats de Tour : "));
coutTourLabel = new QLabel(tr("Coût amélioration de Tour : "));
btnAmeliorer = new QPushButton("Ameliorer");
btnDetruire = new QPushButton("Detruire");
btnAmeliorer->setFixedWidth(70);
btnDetruire->setFixedWidth(70);
bloc4 = new QVBoxLayout;
bloc4->addWidget(typeTourLabel,0,Qt::AlignLeft);
bloc4->addWidget(porteeTourLabel,0,Qt::AlignLeft);
bloc4->addWidget(cadenceTourLabel,0,Qt::AlignLeft);
bloc4->addWidget(degatsTourLabel,0,Qt::AlignLeft);
bloc4->addWidget(coutTourLabel,0,Qt::AlignLeft);
bloc4->addWidget(btnAmeliorer,0,Qt::AlignCenter);
bloc4->addWidget(btnDetruire,0,Qt::AlignCenter);
group5 = new QGroupBox;
group5->setLayout(bloc4);
group5->setTitle("Information de Defenses");
//======================regrouper tous les blocs a droite
rightLayout = new QVBoxLayout;
rightLayout->addLayout(group1);
rightLayout->addWidget(group2);
rightLayout->addWidget(group3);
rightLayout->addWidget(group4);
rightLayout->addWidget(group5);
//======================layout global
layout = new QGridLayout;
layout->setColumnMinimumWidth(0,30);
layout->setColumnStretch(0,1);
layout->addWidget(view,0,1,Qt::AlignCenter);
layout->setColumnMinimumWidth(2,40);
layout->setColumnStretch(2,0);
layout->addLayout(rightLayout,0,3,Qt::AlignCenter);
layout->setColumnMinimumWidth(5,30);
layout->setColumnStretch(5,1);
this->setLayout(layout);
QWidget::connect(btnQuitter, SIGNAL(clicked()), qApp, SLOT(quit()));
connect(btnLancer,SIGNAL(clicked()),scene,SLOT(startWave()));
connect(btnLancer,SIGNAL(clicked()),scene->t1,SLOT(start()));
connect(btnLancer,SIGNAL(clicked()),scene->t2,SLOT(start()));
connect(scene->t2,SIGNAL(timeout()),scene,SLOT(advance()));
connect(scene->t1,SIGNAL(timeout()),scene,SLOT(addEnnemis()));
connect(btnLancer,SIGNAL(clicked()),this,SLOT(buttons()));
connect(btnArreter,SIGNAL(clicked()),this,SLOT(buttons()));
connect(scene,SIGNAL(finishedWave()),scene->t1,SLOT(stop()));
connect(scene,SIGNAL(finishedWave()),this,SLOT(buttons()));
//connect(scene,SIGNAL(finishedWave()),scene->t2,SLOT(stop()));
connect(btnLancer,SIGNAL(clicked()),scene->createPistoletAEauTimer,SLOT(start()));
connect(btnLancer,SIGNAL(clicked()),scene->createLancePierreTimer,SLOT(start()));
connect(btnLancer,SIGNAL(clicked()),scene->createPaintBallTimer,SLOT(start()));
connect(btnEau,SIGNAL(clicked()),scene,SLOT(DefensesTypePistoletAEau()));
connect(btnPierre,SIGNAL(clicked()),scene,SLOT(DefensesTypeLancePierre()));
connect(btnPaintBall,SIGNAL(clicked()),scene,SLOT(DefensesTypePaintBall()));
connect(btnPetanque,SIGNAL(clicked()),scene,SLOT(DefensesTypePetanque()));
connect(view,SIGNAL(mouseScenePress(QPointF)),scene,SLOT(upgradeDefenses(QPointF)));
connect(view,SIGNAL(mouseScenePress(QPointF)),scene,SLOT(createDefenses(QPointF)));
connect(scene,SIGNAL(projectileCreer()),scene,SLOT(deleteProjectile()));
connect(scene->createPistoletAEauTimer,SIGNAL(timeout()),scene,SLOT(createPistoletAEauProjectile()));
connect(scene->createLancePierreTimer,SIGNAL(timeout()),scene,SLOT(createLancePierreProjectile()));
connect(scene->createPaintBallTimer,SIGNAL(timeout()),scene,SLOT(createPaintBallProjectile()));
nbCredit->display("40");
nbVie->display("10");
connect(scene,SIGNAL(EnnemisSucceed(int)),this,SLOT(vieLCD(int)));
connect(scene->t2,SIGNAL(timeout()),scene,SLOT(checkEnnemisSucceed()));
connect(this, SIGNAL(gameover()), qApp, SLOT(quit()));
connect(scene, SIGNAL(changeProgressbar(int)), this, SLOT(avanceProgressbar(int)));
connect(scene,SIGNAL(changeCredits(int)),this,SLOT(creditLCD(int)));
connect(scene,SIGNAL(typeTour(QString)),this->typeTourLabel,SLOT(setText(QString)));
connect(scene,SIGNAL(porteeTour(int)),this->typeTourLabel,SLOT(setNum(int)));
connect(scene,SIGNAL(cadenceTour(int)),this->cadenceTourLabel,SLOT(setNum(int)));
connect(scene,SIGNAL(degatsTour(int)),this->degatsTourLabel,SLOT(setNum(int)));
connect(scene,SIGNAL(prixTour(int)),this->coutTourLabel,SLOT(setNum(int)));
/* connect(scene,SIGNAL(creditsTower(int)),this,SLOT(creditsLeft(int)));
connect(scene,SIGNAL(showCreditsLeft(int)),nbCredit,SLOT(display(int)));
connect(nbVie,SIGNAL(displayViesRestantes(int)),nbVie,SLOT(display(int)));
connect(nbVie,SIGNAL(stopTimers()),t1,SLOT(stop()));
connect(nbVie,SIGNAL(stopTimers()),t2,SLOT(stop()));*/
// connect(nbVie,SIGNAL(stopTimers()),panel,SLOT(buttonsDisabled()));//stopTimers <=> il ne reste plus de vie, on arrete donc la vague
}
Widget::~Widget(){
}<file_sep>/defenses.h
#ifndef DEFENSES_H
#define DEFENSES_H
#include "ennemis.h"
#include "projectiles.h"
class Defenses : public QGraphicsItem
{
public:
Defenses();
QPixmap *pixmap;
Ennemis *focus;
int focusNumber;
float rayonAction;
Projectiles **projectile;
int nbProjectiles;
int type;
int niveau;
float degat;
int coutDeBase;
int coutUnVersDeux;
int coutDeuxVersTrois;
int cadence;
QPointF position;
virtual void setniveau(int n) {niveau=n;}
QString typeName;
public slots :
protected:
QRectF boundingRect() const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
};
class PistoletAEauDefenses : public Defenses
{
public :
PistoletAEauDefenses();
};
class LancePierreDefenses : public Defenses{
public :
LancePierreDefenses();
};
class PaintBallDefenses : public Defenses//paintBall
{
public :
PaintBallDefenses();
};
class PetanqueDefenses : public Defenses//paintBall
{
public :
PetanqueDefenses();
};
#endif // Defenses_H<file_sep>/ennemis.h
#ifndef ENNEMIS_H
#define ENNEMIS_H
#include <QSound>
#include <QLabel>
#include <QPixmap>
#include <QPropertyAnimation>
#include <QtGui>
#include <QFile>
#include <QGraphicsView>
#include <math.h>
#include <QWidget>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QDebug>
#include <QGraphicsPixmapItem>
#include <QApplication>
#include <QWidget>
#include <QLabel>
#include <QPixmap>
#include <QPropertyAnimation>
#include <QSequentialAnimationGroup>
#include <QParallelAnimationGroup>
#include <QGraphicsView>
#include <QGraphicsPixmapItem>
#include <QObject>
#include <QGraphicsItem>
#include <QStyleOption>
#include <QStringList>
#include <QList>
#include <QStyleOption>
#include <QWidget>
#include <QDebug>
#include <QTimer>
class Ennemis : public QObject, public QGraphicsItem
{
Q_OBJECT
public:
Ennemis();
Ennemis(float,int,float,int,int);
float taille;
int mode;//mode de deplacement 0 rampant 1 volant 2 rampant et volant
float vitesse;//case par seconde
int hp;//vitalit¨Ĥ
int resist;//resistance aux attaques
QPixmap *pixmap;
int casePrecedente;
int img;
QStringList way;
void setway(QStringList *l);
bool ralentir;
protected:
QRectF boundingRect() const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
virtual QPixmap changeimage(int)=0;
public slots:
virtual void advance(int);
virtual void resetvitesse();
virtual void smallvitesse();
};
class Cafards : public Ennemis{
Q_OBJECT
public:
Cafards(float);
protected:
QPixmap changeimage(int);
public slots:
};
class Fourmis : public Ennemis
{
Q_OBJECT
public:
bool acc;
Fourmis(float);
protected:
QPixmap changeimage(int);
public slots:
void accelerer();
};
class Guepes : public Ennemis
{
Q_OBJECT
public:
Guepes(float);
void die();
protected:
QPixmap changeimage(int);
};
class Moustiques : public Ennemis
{
Q_OBJECT
public:
bool modevol;
bool sol;
Moustiques(float);
void changemode();
void cachersol();
void moustiquestouche();
protected:
QPixmap changeimage(int);
};
#endif // ENNEMIS_H | b88e57733e497c4dc5aab5804cb6ab36e3d8ecb2 | [
"C++"
] | 10 | C++ | geow812/towerdefense | f9444aad51d9a05c99532d18df873491f27c2a8b | 953b7d1d3a52b55370aae675760b89aa7a83de71 |
refs/heads/master | <file_sep>#include <iostream>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include <unistd.h>
using namespace std;
struct character
{
char name[21];
int hp;
int mp;
int attack;
int armor;
int critical;
int avoid;
void set_stat();
void set_monster_stat(const char* mon_name, int hp, int attack, int armor, int critical, int avoid);
void show_stat();
void battle(character &enemy);
int select();
void attack_victim(character &enemy);
void potion(character &enemy);
void skill_attack(character &enemy);
void die();
};
void intro();
void stage1();
void Oreun();
void stage2();
void Sona();
void stage3();
void TwistedFate();
void stage4();
void Cignus();
void stage5();
void Ending();
character my_character;
int main()
{
intro();
my_character.set_stat();
stage1();
Oreun();
stage2();
Sona();
stage3();
TwistedFate();
stage4();
Cignus();
stage5();
Ending();
return 0;
}
void intro()
{
cout << "===========================================================" << endl;
cout << " 메이플 월드에 오신걸 환영합니다." << endl;
cout << " 이 세상을 위협하는 검은 마법사와 그 수하에 있는" << endl;
cout << " 군단장들을 타도하고 메이플 월드를 지켜주세요 !" << endl;
cout << "===========================================================" << endl;
}
void character::set_stat()
{
unsigned int for_while = 1;
char cmd;
cout << endl;
cout << "체력 : 300 + 0~200 에서 설정" << endl;
cout << "마나 : 100 고정" << endl;
cout << "공격력 : 50 + 0~30 에서 설정" << endl;
cout << "방어력 : 5 + 0~10 에서 설정" << endl;
cout << "치명타 확률 : 20% + 0~15% 에서 설정" << endl;
cout << "회피 확률 : 15% + 0~10% 에서 설정" << endl << endl;
strcpy(name, "용사");
mp = 100;
while (for_while)
{
sleep(1);
srand(time(NULL));
hp = 300 + rand() % 201;
srand(time(NULL));
attack = 50 + rand() % 31;
srand(time(NULL));
armor = 5 + rand() % 11;
srand(time(NULL));
critical = 4 + rand() % 4;
srand(time(NULL));
avoid = 3 + rand() % 3;
show_stat();
cout << endl << "이대로 진행할까요 ? (y/n) ";
cin >> cmd;
if (cmd == 'y')
for_while = 0;
cout << endl;
}
}
void character::set_monster_stat(const char* _mon_name_, int _hp_, int _attack_, int _armor_, int _critical_, int _avoid_)
{
strcpy(name, _mon_name_);
hp = _hp_;
mp = 0;
attack = _attack_;
armor = _armor_;
critical = _critical_;
avoid = _avoid_;
}
void character::show_stat()
{
cout << name << "의 스텟 정보" << endl;
cout << "체력 : " << hp << endl;
cout << "마나 : " << mp << endl;
cout << "공격력 : " << attack << endl;
cout << "방어력 : " << armor << endl;
cout << "치명타 확률 : " << critical * 5 << "%" << endl;
cout << "회피 확률 : " << avoid * 5 << "%" << endl;
}
void stage1()
{
character seu_woo;
seu_woo.set_monster_stat("스우", 150, 30, 0, 10, 0);
cout << "공격 : 자신의 공격력 만큼 적의 체력을 감소시킵니다. 간혹 치명타가 발생하면 2배의 공격력이 적용됩니다." << endl;
cout << "물약 : 상대의 공격력만큼 체력을 회복합니다." << endl;
cout << "스킬 사용 : 마나 20을 소모하고 공격력의 +40만큼의 데미지를 입힙니다. 단, 치명타는 발생하지 않습니다." << endl;
cout << "0 ~ 방어력수치만큼 받는 데미지가 감소합니다. 단, 치명타와 스킬 공격은 방어력을 무시하고 적용됩니다." << endl << endl;
cout << "Stage1. 군단장 [스우]" << endl;
my_character.battle(seu_woo);
cout << endl << "스우 처치" << endl << endl;
my_character.show_stat();
}
void stage2()
{
character demian;
demian.set_monster_stat("데미안", 180, 50, 5, 12, 0);
cout << "Stage2. 군단장 [데미안]" << endl;
my_character.battle(demian);
cout << endl << "데미안 처치" << endl << endl;
my_character.show_stat();
}
void stage3()
{
character lucid;
lucid.set_monster_stat("루시드", 200, 50, 20, 4, 5);
cout << "Stage3. 군단장 [루시드]" << endl;
my_character.battle(lucid);
cout << endl << "루시드 처치" << endl << endl;
my_character.show_stat();
}
void stage4()
{
character will;
will.set_monster_stat("윌", 300, 50, 15, 10, 6);
cout << "Stage4. 군단장 [윌]" << endl;
my_character.battle(will);
cout << endl << "윌 처치" << endl << endl;
my_character.show_stat();
}
void stage5()
{
character blackmagician;
blackmagician.set_monster_stat("검은 마법사", 500, 60, 30, 20, 4);
cout << "Stage5. 최종 보스 [검은 마법사]" << endl;
my_character.battle(blackmagician);
cout << endl << "검은 마법사 처치" << endl << endl;
}
void character::battle(character &enemy)
{
unsigned int cmd;
while (enemy.hp > 0)
{
cout << endl;
enemy.show_stat();
cout << endl;
show_stat();
cout << endl;
cmd = select();
switch (cmd)
{
case 1:
attack_victim(enemy);
break;
case 2:
potion(enemy);
break;
case 3:
if (my_character.mp == 0)
{
cout << "마나 부족" << endl;
continue;
}
skill_attack(enemy);
break;
}
sleep(1);
enemy.attack_victim(my_character);
if (hp <= 0)
die();
}
}
int character::select()
{
unsigned int cmd = 0;
cout << "1. 공격" << endl;
cout << "2. 물약" << endl;
cout << "3. 스킬 사용" << endl;
while (cmd != 1 && cmd != 2 && cmd != 3)
{
cout << "명령 : ";
cin >> cmd;
}
return cmd;
}
void character::attack_victim(character &enemy)
{
unsigned int _avoid_, _critical_, _armor_;
srand(time(NULL));
_avoid_ = rand() % 20;
if (_avoid_ < enemy.avoid)
{
cout << enemy.name << "은(는) " << name << "의 공격을 회피하였다." << endl;
return;
}
srand(time(NULL));
_critical_ = rand() % 20;
if (_critical_ < critical)
{
cout << name << "은(는)" << enemy.name << "에게 치명타를 가했다. 데미지 : " << attack * 2 << endl;
enemy.hp -= 2 * attack;
return;
}
_armor_ = rand() % (enemy.armor + 1);
cout << name << "은(는)" << enemy.name << "에게 공격을 가했다. 데미지 : " << attack - _armor_ << endl;
enemy.hp -= attack - _armor_;
}
void character::potion(character &enemy)
{
cout << "포션을 사용하여 " << enemy.attack << "만큼 회복하였다" << endl;
hp += enemy.attack;
}
void character::skill_attack(character &enemy)
{
cout << name << "은(는)" << enemy.name << "에게 스킬 공격을 가했다. 데미지 : " << attack + 40 << endl;
enemy.hp -= attack + 40;
mp -= 20;
}
void character::die()
{
cout << "체력이 0이하로 감소하였기에 사망하였습니다." << endl;
exit(0);
}
void Oreun()
{
char cmd;
unsigned int _armor_;
sleep(1);
cout << endl << "오른 : 내가 만든 이 갑옷은 방어력을 0~30 만큼 늘려주지만 회피능력을 모두 잃는다네 한번 입어보겠나? (y/n) ";
cin >> cmd;
if (cmd == 'y')
{
srand(time(NULL));
_armor_ = rand() % 31;
my_character.armor += _armor_;
my_character.avoid = 0;
cout << "갑옷을 입고 방어력이 " << _armor_ << "만큼 늘었지만 회피능력을 모두 잃었습니다." << endl << endl;
}
}
void Sona()
{
char cmd;
unsigned int random50;
sleep(1);
cout << endl << "소나 : 제 연주를 악한 마음을 가진 자가 듣는다면 체력이 50감소하지만 선한 마음을 가진 자가 듣는다면 체력이 100 상승한답니다. 제 연주를 들어보시겠어요 ? (y/n) ";
cin >> cmd;
if (cmd == 'y')
{
srand(time(NULL));
random50 = rand() % 2;
if (random50 == 1)
{
cout << "용사는 선한 마음을 가졌기에 체력이 100 회복되었다" << endl << endl;
my_character.hp += 100;
}
else
{
cout << "용사는 자신도 모르는 악한 마음을 가졌기에 체력이 50 감소되었다" << endl << endl;
my_character.hp -= 50;
if (my_character.hp <= 0)
my_character.die();
}
}
}
void TwistedFate()
{
char cmd;
unsigned int random100, my_choice;
sleep(1);
cout << endl << "트위스티드 페이트 : 도박 좋아하나 ? 내가 0~100중 하나의 숫자를 선택하지. 만일 자네가 고른 숫자가 내가 고른 숫자보다 작거나 같다면 자네가 선택한 숫자의 3배만큼 체력을 회복시켜주지 만일 자네가 고른 숫자가 더 크다면 그만큼 체력을 감소시킬 것이야. 한번 해보겠나 ? (y/n) ";
cin >> cmd;
if (cmd == 'y')
{
srand(time(NULL));
random100 = rand() % 101;
cout << "당신의 선택은 ? (0 ~ 100) ";
cin >> my_choice;
if (my_choice <= random100)
{
cout << "용사가 고른 숫자가 더 작거나 같았기에 그 수치의 3배(" << my_choice * 3 << ")만큼 체력을 회복하였다." << endl << endl;
my_character.hp += my_choice * 3;
}
else
{
cout << "용사가 고른 숫자가 더 컸기에 그 수치(" << my_choice << ")만큼 체력이 감소되었다." << endl << endl;
my_character.hp -= my_choice;
if (my_character.hp <= 0)
my_character.die();
}
}
}
void Cignus()
{
char cmd;
sleep(1);
cout << endl << "시그너스 : 용사님 드디어 검은 마법사의 눈 앞까지 왔군요, 저희 연합에서 최대한 지원하겠습니다. 지원을 받으시겠습니까 ? (y/n) ";
cin >> cmd;
if (cmd == 'y')
{
my_character.hp += 100;
my_character.attack += 30;
my_character.armor += 10;
cout << "연합의 지원을 받아 더욱 강해진 느낌이 든다." << endl << endl;
}
}
void Ending()
{
system("cat flag");
}
| 016244bd5f2c4f03703fb79370c7bf50ed56e460 | [
"C++"
] | 1 | C++ | eomkyeongho/server | 4d120bff69a26d795b1c5712355cc6d5e8fee061 | e93d0def29063f437eb329ccfe35e8de38e3b9c6 |
refs/heads/master | <file_sep>import axios from "axios";
import config from "../config";
const { protocol, url, port } = config.server;
const getGroups = () => {
return axios.get(`${protocol}://${url}:${port}/api/groups`);
};
const getSchedule = (date, groupId) => {
return axios.get(`${protocol}://${url}:${port}/api/schedule`, {
params: { date, groupId }
});
};
export { getGroups, getSchedule };
<file_sep>import React from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { View } from "react-native";
import { Bars } from "react-native-loader";
import CCurrent from "./Current";
import CButtonGroup from "./ButtonGroup";
import CSchedule from "./Schedule";
class CInfo extends React.PureComponent {
render() {
const { loaderVisible } = this.props.store.face;
return (
<View>
<View
style={{
margin: "40%",
alignItems: "center",
alignSelf: "center",
justifyContent: "center",
display: loaderVisible ? "flex" : "none"
}}
>
<Bars size={15} color="#808080" />
</View>
<View
style={{
display: !loaderVisible ? "flex" : "none"
}}
>
<CCurrent />
<CButtonGroup updateSchedule={this.props.updateSchedule} />
<CSchedule />
</View>
</View>
);
}
}
CInfo.propTypes = {
updateSchedule: PropTypes.func.isRequired
};
export default connect(state => ({ store: state }))(CInfo);
<file_sep>const initialState = [];
export default (state = initialState, action) => {
switch (action.type) {
case "UPDATE_SCHEDULE":
return action.lessons;
default:
return state;
}
};
const testState = {
currentDiscipline: "Физкультура",
schedule: [
{
name: "Физкультура",
teacher: "<NAME>.",
room: 115,
timeStart: 1550390400,
timeEnd: 1550395200
},
{
name: "Базы данных",
teacher: "<NAME>.",
room: 256,
timeStart: 1550395800,
timeEnd: 1550400600
},
{
name: "Экономика",
teacher: "<NAME>.",
room: 351,
timeStart: 1550401200,
timeEnd: 1550406000
},
{
name: "<NAME>",
teacher: "<NAME>.",
room: 351,
timeStart: 1550406600,
timeEnd: 1550411400
},
{
name: "WEB-программирование",
teacher: "<NAME>.",
room: 351,
timeStart: 1550412000,
timeEnd: 1550416800
}
]
};
<file_sep>import React from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { View, Picker, AsyncStorage } from "react-native";
import { Card, Text, Button, Icon } from "react-native-elements";
import { getGroups } from "../services/requests";
class CSetting extends React.Component {
constructor(props) {
super(props);
this.state = {
interface: { settingVisible: false },
settings: {
groupId: this.props.store.settings.groupId
},
groups: []
};
this.renderGroups = this.renderGroups.bind(this);
}
componentDidMount() {
getGroups().then(({ data }) => {
AsyncStorage.getItem("groupId", (error, groupId) => {
if (error && data[0]) {
groupId = data[0].id;
}
this.setState({
...this.state,
settings: {
...this.state.settings,
groupId: Number(groupId)
},
groups: data.sort((groupOne, groupTwo) => {
return groupOne.shortName > groupTwo.shortName;
})
});
this.props.updateGroup(groupId);
this.props.updateSchedule();
});
});
}
renderGroups(groups) {
return groups.map(({ id, shortName, course }, index) => (
<Picker.Item label={`${course}-${shortName}`} value={id} key={id} />
));
}
render() {
return (
<View>
<Button
icon={
<Icon
name="settings"
color="white"
iconStyle={{ marginRight: "5%" }}
size={20}
/>
}
title={
this.state.interface.settingVisible ? "ЗАКРЫТЬ" : "ВЫБРАТЬ ГРУППУ"
}
titleStyle={{ fontSize: 11 }}
containerStyle={{ alignContent: "center" }}
buttonStyle={{
marginLeft: "10%",
marginRight: "10%",
backgroundColor: "#808080"
}}
onPress={() => {
this.setState({
...this.state,
interface: {
...this.state.interface,
settingVisible: !this.state.interface.settingVisible
}
});
}}
/>
<View
nativeID="setting"
style={{
display: this.state.interface.settingVisible ? "flex" : "none"
}}
>
<Card>
<View nativeID="group">
<Text style={{ textAlign: "center", fontWeight: "bold" }}>
Группа
</Text>
<Picker
selectedValue={this.state.settings.groupId}
onValueChange={itemValue => {
AsyncStorage.setItem(
"groupId",
JSON.stringify(itemValue),
() => {
this.setState({
...this.state,
settings: {
...this.state.settings,
groupId: itemValue
}
});
this.props.updateGroup(itemValue);
this.props.updateSchedule();
}
);
}}
>
{this.renderGroups(this.state.groups)}
</Picker>
</View>
</Card>
</View>
</View>
);
}
}
CSetting.propTypes = {
updateSchedule: PropTypes.func.isRequired,
updateGroup: PropTypes.func.isRequired
};
export default connect(
state => ({ store: state }),
dispatchEvent => ({
updateGroup: groupId => {
dispatchEvent({ type: "UPDATE_GROUP", groupId });
}
})
)(CSetting);
<file_sep>import React from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { View, ScrollView } from "react-native";
import CHeader from "./Header";
import CInfo from "./Info";
import CSetting from "./Setting";
import { getSchedule } from "../services/requests";
class CContent extends React.Component {
constructor(props) {
super(props);
this.updateSchedule = this.updateSchedule.bind(this);
}
updateSchedule() {
const { date, groupId } = this.props.store.settings;
const { enableLoader, disableLoader, updateSchedule } = this.props;
enableLoader();
getSchedule(date, groupId)
.then(({ data: { lessons } }) => {
updateSchedule(lessons);
disableLoader();
})
.catch(enableLoader());
}
render() {
return (
<View>
<CHeader updateSchedule={this.updateSchedule} />
<ScrollView>
<CSetting updateSchedule={this.updateSchedule} />
<CInfo updateSchedule={this.updateSchedule} />
</ScrollView>
</View>
);
}
}
CContent.propTypes = {
enableLoader: PropTypes.func.isRequired,
disableLoader: PropTypes.func.isRequired,
updateSchedule: PropTypes.func.isRequired,
store: PropTypes.shape({
setting: PropTypes.shape({
date: PropTypes.string.isRequired,
groupId: PropTypes.string.isRequired
}),
shedule: PropTypes.arrayOf({
id: PropTypes.number,
subject: PropTypes.shape({
name: PropTypes.string,
teacherName: PropTypes.string
}),
beginTime: PropTypes.string,
endTime: PropTypes.string
})
})
};
export default connect(
state => ({ store: state }),
dispatchEvent => ({
enableLoader: () => {
dispatchEvent({ type: "ENABLE_LOADER" });
},
disableLoader: () => {
dispatchEvent({ type: "DISABLE_LOADER" });
},
updateSchedule: lessons => {
dispatchEvent({ type: "UPDATE_SCHEDULE", lessons });
}
})
)(CContent);
<file_sep>const initialState = {
date: new Date().toLocaleDateString("en-US"),
groupId: 0
};
export default (state = initialState, action) => {
switch (action.type) {
case "UPDATE_DATE":
return { ...state, date: action.date };
case "UPDATE_GROUP":
return { ...state, groupId: action.groupId };
default:
return state;
}
};
<file_sep>import React from "react";
import PropTypes from "prop-types";
import { Header, Text, Icon } from "react-native-elements";
class CHeader extends React.PureComponent {
render() {
return (
<Header
centerComponent={<Text><NAME></Text>}
rightComponent={
<Icon name="autorenew" onPress={this.props.updateSchedule} />
}
containerStyle={{ backgroundColor: "#FFFFFF" }}
/>
);
}
}
CHeader.propTypes = {
updateSchedule: PropTypes.func.isRequired
};
export default CHeader;
<file_sep>import { combineReducers } from "redux";
import schedule from "./schedule";
import settings from "./settings";
import face from "./face";
export default combineReducers({ schedule, settings, face });
<file_sep># schedule-client
Приложение (клиентская часть) для просмотра расписания занятий в ЛНУ им. Шевченко.
<file_sep>import React from "react";
import { connect } from "react-redux";
import { View } from "react-native";
import { Text } from "react-native-elements";
class CCurrent extends React.PureComponent {
getCurrentLesson(lessons) {
const currentTimeNumber = Number(
new Date().toLocaleTimeString("ru-RU").replace(/\D+/g, "")
);
for (let count = 0; count < lessons.length; count += 1) {
const {
beginTime,
endTime,
subject: { name }
} = lessons[count];
const beginTimeNumber = Number(beginTime.replace(/\D+/g, ""));
const endTimeNumber = Number(endTime.replace(/\D+/g, ""));
if (beginTimeNumber < currentTimeNumber < endTimeNumber) {
return name;
}
}
return "-";
}
render() {
return (
<View style={{ margin: 10 }}>
<Text style={{ textAlign: "center" }}>Текущая пара:</Text>
<Text style={{ textAlign: "center", fontWeight: "bold" }}>
{this.getCurrentLesson(this.props.store.schedule)}
</Text>
</View>
);
}
}
export default connect(state => ({ store: state }))(CCurrent);
| 1cb1b1c8a9de80eeafe2ced89e0d853860e424c5 | [
"JavaScript",
"Markdown"
] | 10 | JavaScript | ArtReeX/schedule-client | e5fbb491af6bc64f91f76f43fbb4cc464572b870 | 2c8bc634658a8b8bed0184eaacca351265a9cb70 |
refs/heads/master | <repo_name>oggyman/plg.github.io<file_sep>/js/google-map.js
function initialize() {
var mapCanvas = document.getElementById('map');
//const markers = [{lat: 50.452530, lng: 30.508917}, {lat: 50.422796, lng: 30.476854}];
var markers = [{lat: 50.444627, lng: 30.519926}];
var bounds = new google.maps.LatLngBounds();
//var myLatLng = {lat: 50.439661, lng: 30.448177};
var myLatLng = {lat: 50.443421, lng: 30.494963};
var mapOptions = {
mapTypeControl: false,
//center: {50.422796, 30.476854},
center: myLatLng ,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
draggable:false
}
var map = new google.maps.Map(mapCanvas, mapOptions)
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">Prima Leader Group</h1>'+
'<div id="bodyContent">'+
'<p>Ждем Вас в нашем офисе ' +
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow(), marker, i;
for(i = 0; i < markers.length; i += 1) for( i = 0; i < markers.length; i++ ) {
const position = new google.maps.LatLng(markers[i].lat, markers[i].lng);
marker = new google.maps.Marker({
position: position,
map: map,
title: 'Prima Leader Group'
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(contentString);
infoWindow.open(map, marker);
}
})(marker, i));
}
}
google.maps.event.addDomListener(window, 'load', initialize);
<file_sep>/sendMail.php
<?php
$get = $_POST;
$str .= "Телефон - ". $get['phoneNumber']. ';'."\r\n";
mail('<EMAIL>, <EMAIL>', 'Prima Leader Group - Перезвоните мне', $str, "Content-type: text/plain; charset=utf-8");
<file_sep>/ar_chat_main.js
(function(){
$('document').ready(function(){
$('#chat-holder').draggable({
cursor: 'move',
handle: '.dragger, .close-btn',
appendTo: "body"
});
function load_chat(){
document.getElementById('chat-holder')
.innerHTML += '<object id="chat-window" type="text/html" data="http://10.30.0.8/chat_customer/vicidial_chat_customer_side_areon.php" ></object>';
}
load_chat();
});
})();
function changeClass () {
setTimeout(function(){
$('#chat-holder')
.removeClass('dispNone')
.addClass('dispBlock');
}, 2000);
}
function displayNone (){
$('#chat-holder')
.removeClass('dispBlock')
.addClass('dispNone');
}<file_sep>/about-us.html
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Prima Leader Group</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Main CSS -->
<link rel="stylesheet" href="css/main.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">
<!-- Main font -->
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<script src="https://maps.googleapis.com/maps/api/js?key=<KEY>"></script>
<script src="js/google-map.js"></script>
</head>
<body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top">
<!-- Navigation -->
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="row">
<div class="navbar-header page-scroll">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand page-scroll" href="index.html">
<img class="img-responsive" src="plg_logo_06_06_2017.png" alt="logo">
</a>
<div class="number col-xs-4 visible-xs">
<span>050 470 03 89</span>
<a class="callback-link" href="#"><span>Передзвоніть мені</span></a>
</div>
</div>
<div class="number col-sm-offset-3 col-md-offset-4 col-lg-offset-5 col-sm-2 col-md-3 col-lg-2 hidden-xs">
<span>050 470 03 89</span>
<a class="callback-link" href="#"><span>Передзвоніть мені</span></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<!-- Hidden li included to remove active class from about link when scrolled up past about section -->
<li class="hidden">
<a class="page-scroll" href="index.html"></a>
</li>
<li>
<a class="page-scroll" href="about-us.html" target="_blank">Про нас</a>
<!-- отдельная страничка -->
</li>
<li>
<a class="page-scroll" href="news.html" target="_blank">Новини</a>
<!-- отдельная страничка -->
</li>
<li>
<a class="page-scroll" href="#contact">Контакти</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
</div>
<!-- /.container -->
</nav>
<div class="container">
<!-- About Section -->
<section class="about-section">
<div class="row">
<div class="col-lg-12">
<!-- <h1>Про нас</h1> -->
<p><strong>Рrima Leader Group</strong> – це дійсно кваліфіковані юристи, які готові надати професійну
допомогу та консультацію в будь-якій ситуації та за різних умов.</p>
<p>За роки своєї діяльності, починаючи з 2010 року, ми зуміли досягнути значних результатів
та згуртувати навколо себе висококваліфікованих спеціалістів з різноманітних галузей
права. За цей період бувало багато складних моментів та справ, але можна з впевненістю
сказати, що завдяки цим труднощам ми здобули головне – високопрофесійну команду.</p>
<p><u>Головне завдання</u> <strong>Рrima Leader Group</strong> – це надання кваліфікованої правової допомоги
своїм клієнтам у різноманітних ситуаціях.</p>
<p><u>Головна перевага</u> <strong>Рrima Leader Group</strong> – досвід та кваліфікація наших спеціалістів, які
захистять ваші інтереси, позбавлять труднощів при оформленні будь-якої документації та
нададуть правову підтримку в повному обсязі.</p>
<p>Заключаючи договір з компанією <strong>Рrima Leader Group</strong> – ви наймаєте команду
професіоналів, яка завдяки комплексному підходу, вирішує всі справи клієнтів
максимально швидко та ефективно.</p>
<p><u>Головна мета</u> <strong>Рrima Leader Group</strong> – позитивний результат та комфорт наших клієнтів.</p>
<p>Magna et veritas, et praevalebit!</p>
<p>Телефонуйте!</p>
</div>
</div>
<div id="news"></div>
</section>
</div>
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<!-- Scrolling Nav JavaScript -->
<script src="js/jquery.easing.min.js"></script>
<script src="js/scrolling-nav.js"></script>
</body>
</html>
| 2edfb0a89d810666860272b27102b80d5703a499 | [
"JavaScript",
"HTML",
"PHP"
] | 4 | JavaScript | oggyman/plg.github.io | 2f9895f62a568d83a170bface08e10ea5a1f1103 | 864b03ec45e319d63f536d21b15e62a841388309 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.