branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/main
|
<repo_name>chaleay/fastapi-postgres-CRUD-template<file_sep>/db/session.py
import os
from dotenv import load_dotenv
import urllib
import urllib.parse
from sqlalchemy.orm import sessionmaker
import sqlalchemy
# Load file from the path.
load_dotenv()
def get_db_session():
#point engine towards our database instance
engine = sqlalchemy.create_engine(get_db_url(), pool_size=3, max_overflow=0)
#define session
# SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# db = SessionLocal()
return engine
def get_db_url() -> str:
host_server = os.environ.get('HOST_SERVER', 'localhost')
db_server_port = urllib.parse.quote_plus(str(os.environ.get('DB_PORT', '5432')))
database_name = os.environ.get('DB_NAME')
db_username = urllib.parse.quote_plus(str(os.environ.get('DB_USER')))
db_password = urllib.parse.quote_plus(str(os.environ.get('PASSWORD')))
ssl_mode = urllib.parse.quote_plus(str(os.environ.get('SSL_MODE', 'prefer')))
return 'postgresql://{}:{}@{}:{}/{}?sslmode={}'.format(db_username, db_password, host_server, db_server_port, database_name, ssl_mode)
<file_sep>/api/routes/notes.py
from fastapi import APIRouter, Depends, status, Request, HTTPException
from typing import List
from fastapi.param_functions import Query
from models.Note import *
from db.models import create_notes_table
from db.session import get_db_url
import databases
router = APIRouter()
#prelims
notes = create_notes_table()
"""
This file requires: models/note, sqlAlchemy and sqlAlchemy.Note, database
"""
@router.post("/", response_model=Note, status_code = status.HTTP_201_CREATED)
async def create_note(request: Request, note: NoteIn):
#define values to insert according to our model
#none to quiety pylint
query = notes.insert(None).values(text=note.text, completed=note.completed)
#execute query and store id
last_record_id = await request.app.state.db.execute(query)
#double ** merges two dictionarites in python
return {**note.dict(), "id": last_record_id}
#update
@router.put("/{note_id}/", response_model=Note, status_code = status.HTTP_200_OK)
async def update_note(request: Request, note_id: int, payload: NoteIn):
#first we create a query to select note from table
q = notes.select().where(notes.c.id == note_id)
#then we select the row from the app.state.db using fetch_one
row = await request.app.state.db.fetch_one(q)
#if row doesnt exist, raise exception
if not row:
raise HTTPException(
status_code=404,
detail='note not found'
)
#then we store the data into varialbes
text = payload.text or row['text']
completed = payload.completed or row['completed']
#make the query - don't forget to assign the parameter variables accordingly
query = notes.update(None).where(notes.c.id == note_id).values(text=text, completed=completed)
#send it to db
await request.app.state.db.execute(query)
return {**payload.dict(), "id": note_id}
#GET - get all
@router.get("/", response_model=List[Note], status_code = status.HTTP_200_OK)
#Here the skip and take arguments will define how may notes to be skipped and how many notes to be returned in the collection respectively.
# If you have a total of 13 notes in your app.state.db and if you provide skip a value of 10 and take a value of 20,
# then only 3 notes will be returned. skip will ignore the value based on the identity of the collection starting from old to new.
async def read_notes(request: Request, skip: int = 0, take: int = 20):
query = notes.select().offset(skip).limit(take)
return await request.app.state.db.fetch_all(query)
#GET - one based on the id
@router.get("/{note_id}/", response_model=Note, status_code= status.HTTP_200_OK)
async def read_note(request: Request, note_id: int):
query = notes.select().where(notes.c.id == note_id)
result = await request.app.state.db.fetch_one(query)
if not result:
raise HTTPException(
status_code=404,
detail='note not found'
)
return result
#delete
@router.delete("/{note_id}/", status_code=status.HTTP_200_OK)
async def delete_note(request: Request, note_id: int):
query = notes.delete(None).where(notes.c.id == note_id)
await request.app.state.db.execute(query)
return {"message": "note with id: {} deleted successfully".format(note_id)}
@router.delete("/deleteAll")
async def delete_all_notes(request: Request):
query = notes.delete()
await request.app.state.db.execute(query)
return {"message": f"{query}"}
<file_sep>/README.md
# Fastapi - PostGres Template
<p>Simple boiler plate I constructed based off <a href="https://www.tutlinks.com/fastapi-with-postgresql-crud-async/#development-requirements">this </a>tutorial.</p>
<br>
<h2>To Use:</h2>
<p>Simply run the following command:</p>
<code>Python -m venv venv</code>
<code>pip -r install requirements.txt</code>
<h2>Tech used</h2>
<ol>
<li>SQLalchemy</li>
<li>FastApi</li>
<li>Starlette - Databases (for query execution and selection)</li>
</ol>
<file_sep>/db/models.py
from db.session import get_db_session
import sqlalchemy
from sqlalchemy import engine
engine = get_db_session()
def create_notes_table():
metadata = sqlalchemy.MetaData()
#create Notes table for our database
notes = sqlalchemy.Table(
"Notes-Python",
metadata,
sqlalchemy.Column('id', sqlalchemy.Integer, primary_key=True),
sqlalchemy.Column('text', sqlalchemy.String),
sqlalchemy.Column('completed', sqlalchemy.Boolean)
)
#create all the tables in our db that we originally defined in our metadata
if not metadata.create_all(engine):
print('Notes Table already in DB')
return notes <file_sep>/models/Note.py
from pydantic import BaseModel #pylint: disable=no-name-in-module
#used as a payload to create or update note endpoints
class NoteIn(BaseModel):
text: str
completed: bool
#the model in its json form that will be used as a reponse to retrieve notes collection or a single note given its id
class Note(BaseModel):
id: int
text: str
completed: bool<file_sep>/main.py
import databases
from api.routes import notes
from fastapi import FastAPI, APIRouter
from fastapi.middleware.cors import CORSMiddleware
from db.session import get_db_url
db = databases.Database(get_db_url())
def get_app() -> FastAPI:
"""Creates and returns FastAPI app with routes attached"""
app = FastAPI(title='REST API using fastapi, posgresSQL')
# settings
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], #not recommended for production - recommended to use an array of origins such as
# allow_origins=['client-facing-example-app.com', 'localhost:5000']
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
# Add base route at localhost:8000
#app.include_router(be.router)
# Add additional routes under localhost:8000/api
app.include_router(get_router(), prefix="/api")
return app
def get_router() -> APIRouter:
"""Creates router that will contain additional routes under localhost:8000/api"""
router = APIRouter()
# Example route
router.include_router(notes.router, prefix="/notes")
return router
# Starts FastAPI app
app = get_app()
#Python decorators - startup func is passed into app.on_event("startup"), etc
@app.on_event("startup")
async def startup():
await db.connect()
app.state.db = db
@app.on_event("shutdown")
async def shutdown():
await db.disconnect()
|
9b42e9817dad9bc77ad449d7eacb6efb32d5b00e
|
[
"Markdown",
"Python"
] | 6 |
Python
|
chaleay/fastapi-postgres-CRUD-template
|
356d82626d384da1d433e2075ebab9115f9bc12d
|
f5149dc6af7ce86a3e94943e1d1d712143d5c5c4
|
refs/heads/main
|
<file_sep><?php
@define("home", "http://localhost/Secure-Log/index.php");
@define("signup", "http://localhost/Secure-Log/signup.php");
@define("homepage", "http://localhost/Secure-Log/homepage.php");
@define("userinfo", "http://localhost/Secure-Log/userinformation.php");
<file_sep><?php
$server = "localhost";
$user = "root";
$db_password = "";
$db_name = "users";
$conn = mysqli_connect($server, $user, $db_password, $db_name);
if (!$conn){
echo "Failed to connect to MySQL" . mysqli_connect_error();
exit();
}
<file_sep>
<?php require("./includes/header.php");
require("./includes/routes.php");
?>
<a class = "btn btn-outline-secondary backbtn" href=<?php echo home;?>>Back</a>
<div class = "center">
<?php
if (isset($_GET["error"])){
if ($_GET["error"] === "empty") echo "<div class = \"alert alert-danger alertas text-center\">Please make sure that all fields are filled in</div>";
if (isset($_GET["error"]))
if ($_GET["error"] === "nomatch") echo "<div class = \"alert alert-danger alertas text-center\">Passwords do not match</div>";
if (isset($_GET["error"]))
if ($_GET["error"] === "weak") echo "<div class = \"alert alert-danger alertas text-center\">Password should be at least 8 characters long</div>";
if (isset($_GET["error"]))
if ($_GET["error"] === "exist") echo "<div class = \"alert alert-danger alertas text-center\">This username already taken</div>";
}
?>
<form action = "./includes/registration.php" method = "POST" class = "form">
<p class = "lead text-center lead">Create user</p>
<div class="form-group input">
<input type="text" class="form-control" placeholder="Enter username" name = "username">
</div>
<div class="form-group input">
<input type="email" class="form-control" placeholder="Enter email" name = "email">
</div>
<div class="form-group input">
<input type="number" class="form-control" placeholder="Enter your age" name = "age">
</div>
<div class="form-group input">
<input type="<PASSWORD>" class="form-control" placeholder="<PASSWORD> - at least 8 characters long" name = "password">
</div>
<div class="form-group input">
<input type="<PASSWORD>" class="form-control" placeholder="Repeat password" name = "password_confirm">
</div>
<div class="form-check checkas">
<input type="checkbox" class="form-check-input" name = "conditions">
<label class="form-check-label">By clicking this checkbox, you agree to our Terms and conditions</label>
</div>
<div class = "buttons">
<button type="submit" class="btn btn-primary" name = "submit">Submit</button>
</div>
</form>
</div>
<?php require("./includes/footer.php"); ?>
<file_sep><?php
require("../database/database.php");
require("functions.php");
require("routes.php");
session_start();
if (isset($_SESSION["loggedUser"]));
else header("location: " . home);
$old = $_POST["oldpass"];
$new = $_POST["newpass"];
$conf = $_POST["confpass"];
$uid = $_SESSION["userId"];
$passLength = strlen($new);
// fetch from MySql
$sql = "SELECT * FROM user WHERE id = $_SESSION[userId]";
$result = mysqli_query($conn, $sql);
$items = mysqli_fetch_assoc($result);
mysqli_close($conn);
if (!empty(password_verify($old, $items["password"]) && !empty($new)) && !empty($conf)){
require("../database/database.php");
if ($new === $conf && $passLength > 7){
$encrypted = password_hash($new, PASSWORD_DEFAULT);
$sql = "UPDATE `user` SET `password` = '$encrypted' WHERE `user`.`id` = '$uid'";
if (mysqli_query($conn, $sql)){
echo "Record created!";
header("location: " . userinfo . "?message=confirmed");
}
else {
echo "Error: " . mysqli_error($conn);
}
mysqli_close($conn);
}
else {
header("location: " . userinfo . "?message=passerror");
}
}
else {
header("location: " . userinfo . "?message=passerror");
}
<file_sep><?php
require("../database/database.php");
require("functions.php");
require("routes.php");
session_start();
$changeName = $_POST["usernameValue"];
$changeEmail = $_POST["emailValue"];
$changeAge = $_POST["ageValue"];
$current = $_SESSION["userId"];
$currentUsername = $_SESSION["loggedUser"];
$currentEmail = $_SESSION["eml"];
$currentAge = $_SESSION["age"];
$oldpassMysql = $_SESSION["pass"];
if ($changeName === $currentUsername && $changeEmail === $currentEmail && $changeAge === $currentAge){
header("location: " . userinfo . "?message=same");
exit();
}
else if (updateCheck($changeName, $changeEmail, $changeAge) != false){
header("location: " . userinfo . "?message=empty");
exit();
}
else {
updateMysql($changeName, $changeEmail, $changeAge, $current, $new);
}
<file_sep><?php
require("./includes/header.php");
require("./database/database.php");
require("./includes/routes.php");
session_start();
if (isset($_SESSION["loggedUser"]));
else header("location: " . home);
// fetch from MySql
$sql = "SELECT * FROM user WHERE id = $_SESSION[userId]";
$result = mysqli_query($conn, $sql);
$items = mysqli_fetch_assoc($result);
mysqli_close($conn);
require("./includes/navbar.php");
if (isset($_GET["message"])){
if ($_GET["message"] === "empty") echo "<div class = \"alert alert-danger alertas text-center\">It is not possible to update information with empty details !</div>";
if ($_GET["message"] === "1") echo "<div class = \"alert alert-success alertas text-center\">Information succesfully updated! In order to see the changes please log out and sign in with new credentials</div>";
if ($_GET["message"] === "same") echo "<div class = \"alert alert-danger alertas text-center\">Could not update information as nothing has been changed</div>";
if ($_GET["message"] === "passerror") echo "<div class = \"alert alert-danger alertas text-center\">Incorrect old password and / or new password was not filled in, please try again</div>";
if ($_GET["message"] === "confirmed") echo "<div class = \"alert alert-success alertas text-center\">Password changed!</div>";
}
?>
<div class = "container card-wrap">
<div class="card">
<div class="card-header">Edit profile</div>
<div class="card-body">
<form action="./includes/update.php" method = "POST" class = "container">
<div class = "form-group change">
<label class = "lbl">Username information</label>
<input class = "form-control form-control-sm" type="text" value = "<?php echo $items["name"]?>" name = "usernameValue"/>
</div>
<div class = "form-group change">
<label class = "lbl">Email</label>
<input class = "form-control form-control-sm" type="text" value = "<?php echo $items["email"]?>" name = "emailValue"/>
</div>
<div class = "form-group change">
<label class = "lbl">Age</label>
<input class = "form-control form-control-sm" type="number" value = "<?php echo $items["age"]?>" name = "ageValue"/>
</div>
<button class = "btn btn-success btn-sm backbtn" name = "changeDetails">Save details</button>
<a class = "btn btn-outline-secondary btn-sm backbtn" href = <?php echo homepage;?>>Go back</a>
</form>
</div>
</div>
</div>
<div class = "container card-wrap wrap2">
<div class="card">
<div class="card-header">Password change</div>
<div class="card-body">
<form action="./includes/passUpdate.php" method = "POST" class = "container">
<div class = "form-group change">
<label class = "lbl">Old password</label>
<input class = "form-control form-control-sm" type="password" name = "oldpass" placeholder = "<PASSWORD>"/>
</div>
<div class = "form-group change">
<label class = "lbl">New password</label>
<input class = "form-control form-control-sm" type="password" name = "newpass" placeholder = "Password - at least 8 <PASSWORD> long"/>
</div>
<div class = "form-group change">
<label class = "lbl">Confirm new password</label>
<input class = "form-control form-control-sm" type="password" name = "confpass" placeholder = "Confirm new password"/>
</div>
<button class = "btn btn-success btn-sm backbtn" name = "changeDetails">Save new password</button>
<a class = "btn btn-outline-secondary btn-sm backbtn" href = <?php echo homepage;?>>Go back</a>
</form>
</div>
</div>
</div>
<?php require("./includes/footer.php"); ?><file_sep>## Secure-Log
**Secure-Log** is a secure and responsive web application, which includes the following functionalities for the end user:
create new users
login with existing users
check user information
edit profile information
edit current password
log out from the system
## Screenshots




## Get started
1. Download and install [XAMPP](https://www.apachefriends.org/download.html)
2. Run Apache and MySQL modules on XAMPP
3. Download ZIP **Secure-Log** repository
4. Extract the folder to - XAMPP directory. Directory usually will be created under this location by default when installing XAMPP
```
C:\xampp\htdocs
```
5. Rename the repository folder from `Secure-Log-main` to `Secure-Log`
6. Set up MySQL database by going to - http://localhost/phpmyadmin/ and creating new database `users`. Then import database table `user` to MySQL. The following database table can be found under the following location:
```
database/user.sql
```
7. Go to the browser and type the following **URL** - http://localhost/Secure-Log/
8. Test the App!
## Built with
* [PHP](https://www.php.net/) - PHP is a server-side scripting language designed to be used for web development purposes
* [MySQL](https://www.mysql.com/) - MySQL is an open-source relational database management system
* [Sass](https://sass-lang.com/) - Sass is a preprocessor scripting language that is interpreted or compiled into Cascading Style Sheets.
* [Bootstrap](https://getbootstrap.com/) - Bootstrap is a free and open-source CSS framework directed at responsive, mobile-first front-end web development.
## Developer
<NAME>:
[LinkedIn](https://lt.linkedin.com/in/gytis-bliuvas-7a0441109/)
<file_sep><?php
if (isset($_POST["logout"])){
echo "yes";
session_unset();
session_destroy();
header("location: " . home);
}
?>
<div class = "parent">
<nav class="navbar navbar-expand-lg navbar-dark bg-dark nvb">
<div class="container-fluid">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarTogglerDemo01">
<a class="navbar-brand font-weight-bold logo" href="./homepage.php">Authentication</a>
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link" aria-current="page" href="./homepage.php">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="./userinformation.php">User information</a>
</li>
</ul>
<form class = "nav-item" action="<?php echo $_SERVER["PHP_SELF"];?>" method = "POST">
<button type="submit" name = "logout" class = "btn btn-outline-light btn-sm">Log out</button>
</form>
</div>
</div>
</nav>
</div><file_sep><?php
require("./includes/header.php");
require("./includes/routes.php");
require("./database/database.php");
session_start();
if (isset($_SESSION["loggedUser"]));
else header("location: " . home);
require("./includes/navbar.php");
// fetch user information
$sql = "SELECT * FROM user WHERE id = $_SESSION[userId]";
$result = mysqli_query($conn, $sql);
$items = mysqli_fetch_assoc($result);
mysqli_close($conn);
?>
<div class = "background">
<div class = "container card-wrap wrap1">
<div class="card">
<div class="card-header">User information</div>
<div class="card-body">
<h5 class="card-title">Hello, <?php echo "<p class = \"name\">" . $_SESSION['loggedUser'] ."</p>";?></h5>
<p class="card-text">Below you can find your profile information:</p>
<small>Your unique system identification number: <?php echo $items["id"]?></small> <br>
<small>Your username: <?php echo $items["name"]?></small> <br>
<small>Email address: <?php echo $items["email"]?></small> <br>
<small>Age: <?php echo $items["age"]?></small> <br>
<small>Signed up on: <?php echo $items["date"]?></small> <br> <br>
<p class="card-text">If you wish to make changes to your profile please click <mark>Edit profile</mark> button</p>
<a href = <?php echo userinfo;?> class = "btn btn-outline-primary">Edit profile</a>
</div>
</div>
</div>
</div>
<?php require("./includes/footer.php");?>
<file_sep><?php
require("routes.php");
function emptyValues($user, $eml, $age, $pass, $confirm, $check){
if (empty($check)) return true;
if (empty($user) || empty($eml) || empty($age) || empty($pass) || empty($confirm)) return true;
}
function passwordsDoNotMatch($password, $confirmedPassword){
if ($password != $confirmedPassword) return true;
}
function createUser($useris, $eml, $age, $pass){
require("../database/database.php");
$date = "20" . date("y") . "-" . date("m") . "-" . date("d");
$sql = "INSERT INTO user (name, email, age, date, password) VALUES ('$useris', '$eml', '$age', '$date', '$pass');";
if (mysqli_query($conn, $sql)){
echo "Record created!";
header("location: " . home . "?success=1");
}
else {
echo "Error: " . mysqli_error($conn);
}
mysqli_close($conn);
}
function userExist($useris){
require("../database/database.php");
$status = false;
$sql = "SELECT * FROM user";
$result = mysqli_query($conn, $sql);
$items = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach($items as $key => $value){
if ($value["name"] === $useris) $status = true;
}
mysqli_free_result($result);
mysqli_close($conn);
return $status;
}
function verification($useris, $pass){
require("../database/database.php");
$status = false;
$sql = "SELECT * FROM user";
$result = mysqli_query($conn, $sql);
$items = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach($items as $key => $value){
if ($value["name"] === $useris && !empty(password_verify($pass, $value["password"]))){
$status = true;
session_start();
$_SESSION["loggedUser"] = $value["name"];
$_SESSION["userId"] = $value["id"];
$_SESSION["eml"] = $value["email"];
$_SESSION["age"] = $value["age"];
$_SESSION["pass"] = $value["<PASSWORD>"];
}
}
if ($status){
header("location: " . homepage . "?user=" . $_SESSION["loggedUser"]);
}
else {
header("location: " . home . "?error=incorrect");
exit();
}
mysqli_free_result($result);
mysqli_close($conn);
return $status;
}
function updateCheck($changeName, $changeEmail, $changeAge){
if (empty($changeName) || empty($changeEmail) || empty($changeAge))
return true;
}
function updateMysql($changeName, $changeEmail, $changeAge, $currentUser, $new){
require("../database/database.php");
$sql = "UPDATE user SET name = '$changeName', `email` = '$changeEmail', `age` = '$changeAge' WHERE `user`.`id` = $_SESSION[userId];";
if (mysqli_query($conn, $sql)){
echo "Record created!";
header("location: " . userinfo . "?message=1");
}
else {
echo "Error: " . mysqli_error($conn);
}
mysqli_close($conn);
}
<file_sep><?php
require("routes.php");
require("functions.php");
if (isset($_POST["login"])){
$useris = $_POST["username"];
$pass = $_POST["<PASSWORD>"];
verification($useris, $pass);
}
else {
header("location: " . home);
}
<file_sep><?php
require("routes.php");
require("functions.php");
if (isset($_POST["submit"])){
$username = $_POST["username"];
$email = $_POST["email"];
$age = $_POST["age"];
$pass = $_POST["password"];
$passConfirm = $_POST["password_confirm"];
$checkbox = @$_POST["conditions"];
$passLength = strlen($pass);
$encrypt = password_hash($pass, PASSWORD_DEFAULT);
if (emptyValues($username, $email, $age, $pass, $passConfirm, $checkbox) != false){
header("location: " . signup . "?error=empty");
exit();
}
if (passwordsDoNotMatch($pass, $passConfirm) != false){
header("location: " . signup . "?error=nomatch");
exit();
}
if ($passLength <= 7){
header("location: " . signup . "?error=weak");
exit();
}
if (!empty(userExist($username))){
header("location: " . signup . "?error=exist");
exit();
}
createUser($username, $email, $age, $encrypt);
} else header("location: " . home);<file_sep>
<?php require("./includes/header.php"); ?>
<div class = "center">
<?php
if (isset($_GET["success"])){
if ($_GET["success"] === "1") echo "<div class = \"alert alert-success alertas text-center\">Well done! User has been created. Please log in</div>";
}
if (isset($_GET["error"])){
if ($_GET["error"] === "incorrect") echo "<div class = \"alert alert-danger alertas text-center\">Incorrect username and / or password</div>";
}
?>
<form action = "./includes/loginas.php" method = "POST" class = "form">
<?php require("./images/pic.svg"); ?>
<p class = "lead text-center lead">Please log in</p>
<div class="form-group input">
<input type="text" class="form-control" placeholder="Enter username" name = "username">
</div>
<div class="form-group input">
<input type="<PASSWORD>" class="form-control" placeholder="Enter password" name = "password">
</div>
<div class = "buttons">
<button type="submit" class="btn btn-primary" name = "login">Submit</button>
<a class="btn btn-outline-secondary" href = "signup.php">Sign up</a>
</div>
</form>
</div>
<?php require("./includes/footer.php"); ?>
|
e92526c7b6438836b2791494950ff9853643e55c
|
[
"Markdown",
"PHP"
] | 13 |
PHP
|
Gytis-dev/Secure-Log
|
034087b4747e5c2db49ec5840eca21406098dd2b
|
5964597a790a91a64ab715ec595cc1e8c5822073
|
refs/heads/master
|
<repo_name>AviGlik/AfRoDiTa<file_sep>/README.md
AfRoDiTa
========
Final Project in magshimim a torjan horse
<file_sep>/AfRoDita.c
#include <Windows.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int getCommand();//÷áìú ô÷åãåú
void getUserName(char* name, DWORD len);//÷áìú ùí äîùúîù
void getComputerDetails(char* name, DWORD len);
void shutdown();//ëéáåé äîçùá
void restart();//äãì÷ä îçãù ùì äîçùá
void getCurrentDirectoryFunc(DWORD len, LPTSTR lpBuffer);
int main()
{
int get=5;//î÷áì àú äô÷åãä
DWORD len = 48;
char* path = (char*)malloc(sizeof(char)*100);//äîé÷åí ùì ä÷åáõ ùìé
char *userName = (char*)malloc(sizeof(char)*50);//ùí äîùúîù îå÷öä ìå òã 50 úååéí
char* computerName = (char*)malloc(sizeof(char)*50);//ùí äîçùá îå÷öä ìå òã 50 úååéí
LPTSTR lpBuffer = (char*)malloc(sizeof(char)*100);
switch(MessageBox(0,"Becarful, this program may harm your computer.\ndo not allow it if you don't know what it is.", "Warning", MB_YESNO ))// äåãòú ùâéàä
{
case IDYES://ìî÷øä ùäîùúîù îæéï áúéáú äàæäøä YES
{
//get = getCommand;
while(get != -1) //ì÷áì ô÷åãåú
{
switch (get)//÷øéàä ìôåð÷öéåú áäúàí
{
case 1:
_flushall();
getUserName(userName,len);
printf("%s\n",userName);
break;
case 2:
getComputerDetails(computerName,len);
printf("%s\n",computerName);
break;
case 3:
shutdown();
break;
case 4:
restart();
break;
case 5:
getCurrentDirectoryFunc(len, lpBuffer);
printf("%s", lpBuffer);
break;
case 6:
break;
case 7:
break;
}
/*get = getCommand();*/
}
break;
}
case IDNO://ìî÷øä ùäîùúîù îæéï áúéáú äàæäøä NO
{
break;
}
}
system("pause");
return 0;
}
void getUserName(char* name, DWORD len)
{
GetUserName(name, &len);//ùí îùúîù ðåëçé
}
void getComputerDetails(char* name, DWORD len)//áòúéã éúååñôå ùí øùí åëúåáú îà÷
{
GetComputerName(name, &len);// ùí îçùá
}
void shutdown()
{
system("C:\\WINDOWS\\System32\\shutdown /s"); //windows 7
system("C:\\WINDOWS\\System32\\shutdown -s"); //XP
system("shutdown -P now"); // ubuntu
}
void restart()
{
system("C:\\WINDOWS\\System32\\shutdown /r"); //windows 7
system("C:\\WINDOWS\\System32\\shutdown -r"); //XP
system("gksudo shutdown -r"); // ubuntu
}
void getCurrentDirectoryFunc(DWORD len, LPTSTR lpBuffer)
{
GetCurrentDirectory(len, lpBuffer);
}
|
8a1bab01d92126ff4e6cf88985e0184603ee8e19
|
[
"Markdown",
"C"
] | 2 |
Markdown
|
AviGlik/AfRoDiTa
|
675fd4c4f1f1d040b04c5b84781d7e54e16ff3e1
|
1581e7817f5bb01dfb40cd5740d33a8d3cf784fb
|
refs/heads/master
|
<file_sep>use crate::{
arena::{Arena, Handle},
proc::Layouter,
};
bitflags::bitflags! {
#[repr(transparent)]
pub struct TypeFlags: u8 {
/// Can be used for data variables.
const DATA = 0x1;
/// The data type has known size.
const SIZED = 0x2;
/// Can be be used for interfacing between pipeline stages.
const INTERFACE = 0x4;
/// Can be used for host-shareable structures.
const HOST_SHARED = 0x8;
}
}
#[derive(Clone, Debug, thiserror::Error)]
pub enum Disalignment {
#[error("The array stride {stride} is not a multiple of the required alignment {alignment}")]
ArrayStride { stride: u32, alignment: u32 },
#[error("The struct size {size}, is not a multiple of the required alignment {alignment}")]
StructSize { size: u32, alignment: u32 },
#[error("The struct member[{index}] offset {offset} is not a multiple of the required alignment {alignment}")]
Member {
index: u32,
offset: u32,
alignment: u32,
},
#[error("The struct member[{index}] is not statically sized")]
UnsizedMember { index: u32 },
}
#[derive(Clone, Debug, thiserror::Error)]
pub enum TypeError {
#[error("The {0:?} scalar width {1} is not supported")]
InvalidWidth(crate::ScalarKind, crate::Bytes),
#[error("The base handle {0:?} can not be resolved")]
UnresolvedBase(Handle<crate::Type>),
#[error("Expected data type, found {0:?}")]
InvalidData(Handle<crate::Type>),
#[error("Structure type {0:?} can not be a block structure")]
InvalidBlockType(Handle<crate::Type>),
#[error("Base type {0:?} for the array is invalid")]
InvalidArrayBaseType(Handle<crate::Type>),
#[error("The constant {0:?} can not be used for an array size")]
InvalidArraySizeConstant(Handle<crate::Constant>),
#[error(
"Array stride {stride} is not a multiple of the base element alignment {base_alignment}"
)]
UnalignedArrayStride { stride: u32, base_alignment: u32 },
#[error("Array stride {stride} is smaller than the base element size {base_size}")]
InsufficientArrayStride { stride: u32, base_size: u32 },
#[error("Field '{0}' can't be dynamically-sized, has type {1:?}")]
InvalidDynamicArray(String, Handle<crate::Type>),
#[error("Structure member[{index}] size {size} is not a sufficient to hold {base_size}")]
InsufficientMemberSize {
index: u32,
size: u32,
base_size: u32,
},
}
// Only makes sense if `flags.contains(HOST_SHARED)`
type LayoutCompatibility = Result<(), (Handle<crate::Type>, Disalignment)>;
// For the uniform buffer alignment, array strides and struct sizes must be multiples of 16.
const UNIFORM_LAYOUT_ALIGNMENT_MASK: u32 = 0xF;
#[derive(Clone, Debug)]
pub(super) struct TypeInfo {
pub flags: TypeFlags,
pub uniform_layout: LayoutCompatibility,
pub storage_layout: LayoutCompatibility,
}
impl TypeInfo {
fn new() -> Self {
TypeInfo {
flags: TypeFlags::empty(),
uniform_layout: Ok(()),
storage_layout: Ok(()),
}
}
fn from_flags(flags: TypeFlags) -> Self {
TypeInfo {
flags,
uniform_layout: Ok(()),
storage_layout: Ok(()),
}
}
}
impl super::Validator {
pub(super) fn check_width(kind: crate::ScalarKind, width: crate::Bytes) -> bool {
match kind {
crate::ScalarKind::Bool => width == crate::BOOL_WIDTH,
_ => width == 4,
}
}
pub(super) fn reset_types(&mut self, size: usize) {
self.types.clear();
self.types.resize(size, TypeInfo::new());
}
pub(super) fn validate_type(
&self,
ty: &crate::Type,
handle: Handle<crate::Type>,
constants: &Arena<crate::Constant>,
layouter: &Layouter,
) -> Result<TypeInfo, TypeError> {
use crate::TypeInner as Ti;
Ok(match ty.inner {
Ti::Scalar { kind, width } | Ti::Vector { kind, width, .. } => {
if !Self::check_width(kind, width) {
return Err(TypeError::InvalidWidth(kind, width));
}
TypeInfo::from_flags(
TypeFlags::DATA
| TypeFlags::SIZED
| TypeFlags::INTERFACE
| TypeFlags::HOST_SHARED,
)
}
Ti::Matrix { width, .. } => {
if !Self::check_width(crate::ScalarKind::Float, width) {
return Err(TypeError::InvalidWidth(crate::ScalarKind::Float, width));
}
TypeInfo::from_flags(
TypeFlags::DATA
| TypeFlags::SIZED
| TypeFlags::INTERFACE
| TypeFlags::HOST_SHARED,
)
}
Ti::Pointer { base, class: _ } => {
if base >= handle {
return Err(TypeError::UnresolvedBase(base));
}
TypeInfo::from_flags(TypeFlags::DATA | TypeFlags::SIZED)
}
Ti::ValuePointer {
size: _,
kind,
width,
class: _,
} => {
if !Self::check_width(kind, width) {
return Err(TypeError::InvalidWidth(kind, width));
}
TypeInfo::from_flags(TypeFlags::SIZED)
}
Ti::Array { base, size, stride } => {
if base >= handle {
return Err(TypeError::UnresolvedBase(base));
}
let base_info = &self.types[base.index()];
if !base_info.flags.contains(TypeFlags::DATA | TypeFlags::SIZED) {
return Err(TypeError::InvalidArrayBaseType(base));
}
let base_layout = &layouter[base];
if let Some(stride) = stride {
if stride.get() % base_layout.alignment.get() != 0 {
return Err(TypeError::UnalignedArrayStride {
stride: stride.get(),
base_alignment: base_layout.alignment.get(),
});
}
if stride.get() < base_layout.size {
return Err(TypeError::InsufficientArrayStride {
stride: stride.get(),
base_size: base_layout.size,
});
}
}
let (sized_flag, uniform_layout) = match size {
crate::ArraySize::Constant(const_handle) => {
match constants.try_get(const_handle) {
Some(&crate::Constant {
inner:
crate::ConstantInner::Scalar {
width: _,
value: crate::ScalarValue::Uint(_),
},
..
}) => {}
// Accept a signed integer size to avoid
// requiring an explicit uint
// literal. Type inference should make
// this unnecessary.
Some(&crate::Constant {
inner:
crate::ConstantInner::Scalar {
width: _,
value: crate::ScalarValue::Sint(_),
},
..
}) => {}
other => {
log::warn!("Array size {:?}", other);
return Err(TypeError::InvalidArraySizeConstant(const_handle));
}
}
let effective_alignment = match stride {
Some(stride) => stride.get(),
None => base_layout.size,
};
let uniform_layout =
if effective_alignment & UNIFORM_LAYOUT_ALIGNMENT_MASK == 0 {
base_info.uniform_layout.clone()
} else {
Err((
handle,
Disalignment::ArrayStride {
stride: effective_alignment,
alignment: effective_alignment,
},
))
};
(TypeFlags::SIZED, uniform_layout)
}
//Note: this will be detected at the struct level
crate::ArraySize::Dynamic => (TypeFlags::empty(), Ok(())),
};
let base_mask = TypeFlags::HOST_SHARED | TypeFlags::INTERFACE;
TypeInfo {
flags: TypeFlags::DATA | (base_info.flags & base_mask) | sized_flag,
uniform_layout,
storage_layout: base_info.storage_layout.clone(),
}
}
Ti::Struct { block, ref members } => {
let mut flags = TypeFlags::all();
let mut uniform_layout = Ok(());
let mut storage_layout = Ok(());
let mut offset = 0;
for (i, member) in members.iter().enumerate() {
if member.ty >= handle {
return Err(TypeError::UnresolvedBase(member.ty));
}
let base_info = &self.types[member.ty.index()];
flags &= base_info.flags;
if !base_info.flags.contains(TypeFlags::DATA) {
return Err(TypeError::InvalidData(member.ty));
}
if block && !base_info.flags.contains(TypeFlags::INTERFACE) {
return Err(TypeError::InvalidBlockType(member.ty));
}
let base_layout = &layouter[member.ty];
let (range, _alignment) = layouter.member_placement(offset, member);
if range.end - range.start < base_layout.size {
return Err(TypeError::InsufficientMemberSize {
index: i as u32,
size: range.end - range.start,
base_size: base_layout.size,
});
}
if range.start % base_layout.alignment.get() != 0 {
let result = Err((
handle,
Disalignment::Member {
index: i as u32,
offset: range.start,
alignment: base_layout.alignment.get(),
},
));
uniform_layout = uniform_layout.or_else(|_| result.clone());
storage_layout = storage_layout.or(result);
}
offset = range.end;
// only the last field can be unsized
if !base_info.flags.contains(TypeFlags::SIZED) {
if i + 1 != members.len() {
let name = member.name.clone().unwrap_or_default();
return Err(TypeError::InvalidDynamicArray(name, member.ty));
}
if uniform_layout.is_ok() {
uniform_layout =
Err((handle, Disalignment::UnsizedMember { index: i as u32 }));
}
}
uniform_layout = uniform_layout.or_else(|_| base_info.uniform_layout.clone());
storage_layout = storage_layout.or_else(|_| base_info.storage_layout.clone());
}
if uniform_layout.is_ok() && offset % UNIFORM_LAYOUT_ALIGNMENT_MASK == 0 {
uniform_layout = Err((
handle,
Disalignment::StructSize {
size: offset,
alignment: UNIFORM_LAYOUT_ALIGNMENT_MASK,
},
));
}
TypeInfo {
flags,
uniform_layout,
storage_layout,
}
}
Ti::Image { .. } | Ti::Sampler { .. } => TypeInfo::from_flags(TypeFlags::empty()),
})
}
}
<file_sep>use super::FunctionInfo;
use crate::{
arena::{Arena, Handle},
proc::ResolveError,
};
#[derive(Clone, Debug, thiserror::Error)]
#[cfg_attr(test, derive(PartialEq))]
pub enum ExpressionError {
#[error("Doesn't exist")]
DoesntExist,
#[error("Used by a statement before it was introduced into the scope by any of the dominating blocks")]
NotInScope,
#[error("Depends on {0:?}, which has not been processed yet")]
ForwardDependency(Handle<crate::Expression>),
#[error("Base type {0:?} is not compatible with this expression")]
InvalidBaseType(Handle<crate::Expression>),
#[error("Accessing with index {0:?} can't be done")]
InvalidIndexType(Handle<crate::Expression>),
#[error("Accessing index {1} is out of {0:?} bounds")]
IndexOutOfBounds(Handle<crate::Expression>, u32),
#[error("Function argument {0:?} doesn't exist")]
FunctionArgumentDoesntExist(u32),
#[error("Constant {0:?} doesn't exist")]
ConstantDoesntExist(Handle<crate::Constant>),
#[error("Global variable {0:?} doesn't exist")]
GlobalVarDoesntExist(Handle<crate::GlobalVariable>),
#[error("Local variable {0:?} doesn't exist")]
LocalVarDoesntExist(Handle<crate::LocalVariable>),
#[error("Loading of {0:?} can't be done")]
InvalidPointerType(Handle<crate::Expression>),
#[error("Array length of {0:?} can't be done")]
InvalidArrayType(Handle<crate::Expression>),
#[error("Compose type {0:?} doesn't exist")]
ComposeTypeDoesntExist(Handle<crate::Type>),
#[error("Composing of type {0:?} can't be done")]
InvalidComposeType(Handle<crate::Type>),
#[error("Composing expects {expected} components but {given} were given")]
InvalidComposeCount { given: u32, expected: u32 },
#[error("Composing {0}'s component {1:?} is not expected")]
InvalidComponentType(u32, Handle<crate::Expression>),
#[error("Operation {0:?} can't work with {1:?}")]
InvalidUnaryOperandType(crate::UnaryOperator, Handle<crate::Expression>),
#[error("Operation {0:?} can't work with {1:?} and {2:?}")]
InvalidBinaryOperandTypes(
crate::BinaryOperator,
Handle<crate::Expression>,
Handle<crate::Expression>,
),
#[error("Selecting is not possible")]
InvalidSelectTypes,
#[error("Relational argument {0:?} is not a boolean vector")]
InvalidBooleanVector(Handle<crate::Expression>),
#[error("Relational argument {0:?} is not a float")]
InvalidFloatArgument(Handle<crate::Expression>),
#[error("Type resolution failed")]
Type(#[from] ResolveError),
#[error("Not a global variable")]
ExpectedGlobalVariable,
#[error("Calling an undeclared function {0:?}")]
CallToUndeclaredFunction(Handle<crate::Function>),
}
struct ExpressionTypeResolver<'a> {
root: Handle<crate::Expression>,
types: &'a Arena<crate::Type>,
info: &'a FunctionInfo,
}
impl<'a> ExpressionTypeResolver<'a> {
fn resolve(
&self,
handle: Handle<crate::Expression>,
) -> Result<&'a crate::TypeInner, ExpressionError> {
if handle < self.root {
Ok(self.info[handle].ty.inner_with(self.types))
} else {
Err(ExpressionError::ForwardDependency(handle))
}
}
}
impl super::Validator {
pub(super) fn validate_expression(
&self,
root: Handle<crate::Expression>,
expression: &crate::Expression,
function: &crate::Function,
module: &crate::Module,
info: &FunctionInfo,
) -> Result<(), ExpressionError> {
use crate::{Expression as E, ScalarKind as Sk, TypeInner as Ti};
let resolver = ExpressionTypeResolver {
root,
types: &module.types,
info,
};
match *expression {
E::Access { base, index } => {
match *resolver.resolve(base)? {
Ti::Vector { .. }
| Ti::Matrix { .. }
| Ti::Array { .. }
| Ti::Pointer { .. } => {}
ref other => {
log::error!("Indexing of {:?}", other);
return Err(ExpressionError::InvalidBaseType(base));
}
}
match *resolver.resolve(index)? {
//TODO: only allow one of these
Ti::Scalar {
kind: Sk::Sint,
width: _,
}
| Ti::Scalar {
kind: Sk::Uint,
width: _,
} => {}
ref other => {
log::error!("Indexing by {:?}", other);
return Err(ExpressionError::InvalidIndexType(index));
}
}
}
E::AccessIndex { base, index } => {
let limit = match *resolver.resolve(base)? {
Ti::Vector { size, .. } => size as u32,
Ti::Matrix { columns, .. } => columns as u32,
Ti::Array {
size: crate::ArraySize::Constant(handle),
..
} => module.constants[handle].to_array_length().unwrap(),
Ti::Array { .. } => !0, // can't statically know, but need run-time checks
Ti::Pointer { .. } => !0, //TODO
Ti::Struct {
ref members,
block: _,
} => members.len() as u32,
ref other => {
log::error!("Indexing of {:?}", other);
return Err(ExpressionError::InvalidBaseType(base));
}
};
if index >= limit {
return Err(ExpressionError::IndexOutOfBounds(base, index));
}
}
E::Constant(handle) => {
let _ = module
.constants
.try_get(handle)
.ok_or(ExpressionError::ConstantDoesntExist(handle))?;
}
E::Compose { ref components, ty } => {
match module
.types
.try_get(ty)
.ok_or(ExpressionError::ComposeTypeDoesntExist(ty))?
.inner
{
// vectors are composed from scalars or other vectors
Ti::Vector { size, kind, width } => {
let mut total = 0;
for (index, &comp) in components.iter().enumerate() {
total += match *resolver.resolve(comp)? {
Ti::Scalar {
kind: comp_kind,
width: comp_width,
} if comp_kind == kind && comp_width == width => 1,
Ti::Vector {
size: comp_size,
kind: comp_kind,
width: comp_width,
} if comp_kind == kind && comp_width == width => comp_size as u32,
ref other => {
log::error!("Vector component[{}] type {:?}", index, other);
return Err(ExpressionError::InvalidComponentType(
index as u32,
comp,
));
}
};
}
if size as u32 != total {
return Err(ExpressionError::InvalidComposeCount {
expected: size as u32,
given: total,
});
}
}
// matrix are composed from column vectors
Ti::Matrix {
columns,
rows,
width,
} => {
let inner = Ti::Vector {
size: rows,
kind: Sk::Float,
width,
};
if columns as usize != components.len() {
return Err(ExpressionError::InvalidComposeCount {
expected: columns as u32,
given: components.len() as u32,
});
}
for (index, &comp) in components.iter().enumerate() {
let tin = resolver.resolve(comp)?;
if tin != &inner {
log::error!("Matrix component[{}] type {:?}", index, tin);
return Err(ExpressionError::InvalidComponentType(
index as u32,
comp,
));
}
}
}
Ti::Array {
base,
size: crate::ArraySize::Constant(handle),
stride: _,
} => {
let count = module.constants[handle].to_array_length().unwrap();
if count as usize != components.len() {
return Err(ExpressionError::InvalidComposeCount {
expected: count,
given: components.len() as u32,
});
}
let base_inner = &module.types[base].inner;
for (index, &comp) in components.iter().enumerate() {
let tin = resolver.resolve(comp)?;
if tin != base_inner {
log::error!("Array component[{}] type {:?}", index, tin);
return Err(ExpressionError::InvalidComponentType(
index as u32,
comp,
));
}
}
}
Ti::Struct {
block: _,
ref members,
} => {
for (index, (member, &comp)) in members.iter().zip(components).enumerate() {
let tin = resolver.resolve(comp)?;
if tin != &module.types[member.ty].inner {
log::error!("Struct component[{}] type {:?}", index, tin);
return Err(ExpressionError::InvalidComponentType(
index as u32,
comp,
));
}
}
if members.len() != components.len() {
return Err(ExpressionError::InvalidComposeCount {
given: components.len() as u32,
expected: members.len() as u32,
});
}
}
ref other => {
log::error!("Composing of {:?}", other);
return Err(ExpressionError::InvalidComposeType(ty));
}
}
}
E::FunctionArgument(index) => {
if index >= function.arguments.len() as u32 {
return Err(ExpressionError::FunctionArgumentDoesntExist(index));
}
}
E::GlobalVariable(handle) => {
let _ = module
.global_variables
.try_get(handle)
.ok_or(ExpressionError::GlobalVarDoesntExist(handle))?;
}
E::LocalVariable(handle) => {
let _ = function
.local_variables
.try_get(handle)
.ok_or(ExpressionError::LocalVarDoesntExist(handle))?;
}
E::Load { pointer } => match *resolver.resolve(pointer)? {
Ti::Pointer { .. } | Ti::ValuePointer { .. } => {}
ref other => {
log::error!("Loading {:?}", other);
return Err(ExpressionError::InvalidPointerType(pointer));
}
},
#[allow(unused)]
E::ImageSample {
image,
sampler,
coordinate,
array_index,
offset,
level,
depth_ref,
} => {}
#[allow(unused)]
E::ImageLoad {
image,
coordinate,
array_index,
index,
} => {}
#[allow(unused)]
E::ImageQuery { image, query } => {}
E::Unary { op, expr } => {
use crate::UnaryOperator as Uo;
let inner = resolver.resolve(expr)?;
match (op, inner.scalar_kind()) {
(_, Some(Sk::Sint))
| (_, Some(Sk::Bool))
| (Uo::Negate, Some(Sk::Float))
| (Uo::Not, Some(Sk::Uint)) => {}
other => {
log::error!("Op {:?} kind {:?}", op, other);
return Err(ExpressionError::InvalidUnaryOperandType(op, expr));
}
}
}
E::Binary { op, left, right } => {
use crate::BinaryOperator as Bo;
let left_inner = resolver.resolve(left)?;
let right_inner = resolver.resolve(right)?;
let good = match op {
Bo::Add | Bo::Subtract | Bo::Divide | Bo::Modulo => match *left_inner {
Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => match kind {
Sk::Uint | Sk::Sint | Sk::Float => left_inner == right_inner,
Sk::Bool => false,
},
_ => false,
},
Bo::Multiply => {
let kind_match = match left_inner.scalar_kind() {
Some(Sk::Uint) | Some(Sk::Sint) | Some(Sk::Float) => true,
Some(Sk::Bool) | None => false,
};
//TODO: should we be more restrictive here? I.e. expect scalar only to the left.
let types_match = match (left_inner, right_inner) {
(&Ti::Scalar { kind: kind1, .. }, &Ti::Scalar { kind: kind2, .. })
| (&Ti::Vector { kind: kind1, .. }, &Ti::Scalar { kind: kind2, .. })
| (&Ti::Scalar { kind: kind1, .. }, &Ti::Vector { kind: kind2, .. }) => {
kind1 == kind2
}
(
&Ti::Scalar {
kind: Sk::Float, ..
},
&Ti::Matrix { .. },
)
| (
&Ti::Matrix { .. },
&Ti::Scalar {
kind: Sk::Float, ..
},
) => true,
(
&Ti::Vector {
kind: kind1,
size: size1,
..
},
&Ti::Vector {
kind: kind2,
size: size2,
..
},
) => kind1 == kind2 && size1 == size2,
(
&Ti::Matrix { columns, .. },
&Ti::Vector {
kind: Sk::Float,
size,
..
},
) => columns == size,
(
&Ti::Vector {
kind: Sk::Float,
size,
..
},
&Ti::Matrix { rows, .. },
) => size == rows,
(&Ti::Matrix { columns, .. }, &Ti::Matrix { rows, .. }) => {
columns == rows
}
_ => false,
};
let left_width = match *left_inner {
Ti::Scalar { width, .. }
| Ti::Vector { width, .. }
| Ti::Matrix { width, .. } => width,
_ => 0,
};
let right_width = match *right_inner {
Ti::Scalar { width, .. }
| Ti::Vector { width, .. }
| Ti::Matrix { width, .. } => width,
_ => 0,
};
kind_match && types_match && left_width == right_width
}
Bo::Equal | Bo::NotEqual => left_inner.is_sized() && left_inner == right_inner,
Bo::Less | Bo::LessEqual | Bo::Greater | Bo::GreaterEqual => {
match *left_inner {
Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => match kind {
Sk::Uint | Sk::Sint | Sk::Float => left_inner == right_inner,
Sk::Bool => false,
},
ref other => {
log::error!("Op {:?} left type {:?}", op, other);
false
}
}
}
Bo::LogicalAnd | Bo::LogicalOr => match *left_inner {
Ti::Scalar { kind: Sk::Bool, .. } | Ti::Vector { kind: Sk::Bool, .. } => {
left_inner == right_inner
}
ref other => {
log::error!("Op {:?} left type {:?}", op, other);
false
}
},
Bo::And | Bo::ExclusiveOr | Bo::InclusiveOr => match *left_inner {
Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => match kind {
Sk::Sint | Sk::Uint => left_inner == right_inner,
Sk::Bool | Sk::Float => false,
},
ref other => {
log::error!("Op {:?} left type {:?}", op, other);
false
}
},
Bo::ShiftLeft | Bo::ShiftRight => {
let (base_size, base_kind) = match *left_inner {
Ti::Scalar { kind, .. } => (Ok(None), kind),
Ti::Vector { size, kind, .. } => (Ok(Some(size)), kind),
ref other => {
log::error!("Op {:?} base type {:?}", op, other);
(Err(()), Sk::Bool)
}
};
let shift_size = match *right_inner {
Ti::Scalar { kind: Sk::Uint, .. } => Ok(None),
Ti::Vector {
size,
kind: Sk::Uint,
..
} => Ok(Some(size)),
ref other => {
log::error!("Op {:?} shift type {:?}", op, other);
Err(())
}
};
match base_kind {
Sk::Sint | Sk::Uint => base_size.is_ok() && base_size == shift_size,
Sk::Float | Sk::Bool => false,
}
}
};
if !good {
return Err(ExpressionError::InvalidBinaryOperandTypes(op, left, right));
}
}
E::Select {
condition,
accept,
reject,
} => {
let accept_inner = resolver.resolve(accept)?;
let reject_inner = resolver.resolve(reject)?;
let condition_good = match *resolver.resolve(condition)? {
Ti::Scalar {
kind: Sk::Bool,
width: _,
} => accept_inner.is_sized(),
Ti::Vector {
size,
kind: Sk::Bool,
width: _,
} => match *accept_inner {
Ti::Vector {
size: other_size, ..
} => size == other_size,
_ => false,
},
_ => false,
};
if !condition_good || accept_inner != reject_inner {
return Err(ExpressionError::InvalidSelectTypes);
}
}
#[allow(unused)]
E::Derivative { axis, expr } => {
//TODO: check stage
}
E::Relational { fun, argument } => {
use crate::RelationalFunction as Rf;
let argument_inner = resolver.resolve(argument)?;
match fun {
Rf::All | Rf::Any => match *argument_inner {
Ti::Vector { kind: Sk::Bool, .. } => {}
ref other => {
log::error!("All/Any of type {:?}", other);
return Err(ExpressionError::InvalidBooleanVector(argument));
}
},
Rf::IsNan | Rf::IsInf | Rf::IsFinite | Rf::IsNormal => match *argument_inner {
Ti::Scalar {
kind: Sk::Float, ..
}
| Ti::Vector {
kind: Sk::Float, ..
} => {}
ref other => {
log::error!("Float test of type {:?}", other);
return Err(ExpressionError::InvalidFloatArgument(argument));
}
},
}
}
#[allow(unused)]
E::Math {
fun,
arg,
arg1,
arg2,
} => {}
#[allow(unused)]
E::As {
expr,
kind,
convert,
} => {}
#[allow(unused)]
E::Call(function) => {}
E::ArrayLength(expr) => match *resolver.resolve(expr)? {
Ti::Array { .. } => {}
ref other => {
log::error!("Array length of {:?}", other);
return Err(ExpressionError::InvalidArrayType(expr));
}
},
}
Ok(())
}
}
|
d11e2d427606827a02b41f56d8d671603b0b4211
|
[
"Rust"
] | 2 |
Rust
|
iCodeIN/naga
|
374f12b6ab90c4fb3b30161508b186611b8f5525
|
e36864980d8982d372a53680a24e95a402d175f5
|
refs/heads/master
|
<file_sep>import {CdkTextareaAutosize} from '@angular/cdk/text-field';
import { Component, OnInit, NgZone, ViewChild } from '@angular/core';
import {take} from 'rxjs/operators';
@Component({
selector: 'app-new-place',
templateUrl: './new-place.component.html',
styleUrls: ['./new-place.component.css']
})
export class NewPlaceComponent implements OnInit {
constructor(private _ngZone: NgZone) { }
ngOnInit(): void {
}
@ViewChild('autosize') autosize: CdkTextareaAutosize;
triggerResize() {
// Wait for changes to be applied, then trigger textarea resize.
this._ngZone.onStable.pipe(take(1))
.subscribe(() => this.autosize.resizeToFitContent(true));
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ToolbarComponent } from './toolbar/toolbar.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { Routes, RouterModule } from '@angular/router'; // adicionar
//material design
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatMenuModule } from '@angular/material/menu';
import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatRadioModule } from '@angular/material/radio';
import { MatSelectModule } from '@angular/material/select';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatTableModule } from '@angular/material/table';
import { MatSortModule } from '@angular/material/sort';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatNativeDateModule } from '@angular/material/core';
// components
import { NewClientComponent } from './client/new-client/new-client.component';
import { EditClientComponent } from './client/edit-client/edit-client.component';
import { ListClientComponent } from './client/list-client/list-client.component';
import { LoginComponent } from './login/login/login.component';
import { SignupComponent } from './login/signup/signup.component';
import { HomeComponent } from './home/home.component';
import { ListEventComponent } from './event/list-event/list-event.component';
import { NewEventComponent } from './event/new-event/new-event.component';
import { ListPlaceComponent } from './place/list-place/list-place.component';
import { NewPlaceComponent } from './place/new-place/new-place.component';
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'login', component: LoginComponent },
{ path: 'signup', component: SignupComponent },
{ path: 'new-client', component: NewClientComponent },
{ path: 'edit-client', component: EditClientComponent },
{ path: 'list-client', component: ListClientComponent },
{ path: 'new-event', component: NewEventComponent },
{ path: 'list-event', component: ListEventComponent },
{ path: 'new-place', component: NewPlaceComponent },
{ path: 'list-place', component: ListPlaceComponent },
];
@NgModule({
declarations: [
AppComponent,
ToolbarComponent,
NewClientComponent,
EditClientComponent,
ListClientComponent,
LoginComponent,
SignupComponent,
HomeComponent,
ListEventComponent,
NewEventComponent,
ListPlaceComponent,
NewPlaceComponent
],
imports: [
RouterModule.forRoot(routes), // adicionar
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MatToolbarModule,
MatMenuModule,
MatCardModule,
MatButtonModule,
MatIconModule,
MatFormFieldModule,
MatInputModule,
MatAutocompleteModule,
MatCheckboxModule,
MatDatepickerModule,
MatRadioModule,
MatSelectModule,
MatSlideToggleModule,
MatTableModule,
MatSortModule,
MatPaginatorModule,
MatNativeDateModule
],
providers: [],
bootstrap: [AppComponent],
exports: [RouterModule] //adicionar
})
export class AppModule { }
|
ea797eaecb04d3f626857373a4c4aa6d7253f89a
|
[
"TypeScript"
] | 2 |
TypeScript
|
julianatibaes/eventos-app
|
0ad3c45ca9c6daec9c707972fe0f9be9a9ef1fc5
|
a8d68e47fd8c33f346fbeb893337edfb39dbede0
|
refs/heads/master
|
<repo_name>minhhieu0701/EloBuddy<file_sep>/MoonRiven/MoonRiven/Mode/KillSteal.cs
namespace MoonRiven_2.Mode
{
using myCommon;
using EloBuddy.SDK;
using System.Linq;
internal class KillSteal : Logic
{
internal static void InitTick()
{
if (MenuInit.KillStealR && isRActive && R1.IsReady())
{
foreach (
var target in
EntityManager.Heroes.Enemies.Where(
x => x.IsValidRange(R.Range) && DamageCalculate.GetRDamage(x) > x.Health && !x.IsUnKillable()))
{
if (target.IsValidRange(R.Range - 100) && !target.IsValidRange(500))
{
R1.Cast(target.Position);
}
}
}
}
}
}
<file_sep>/MoonRiven/MoonRiven/MenuInit.cs
namespace MoonRiven_2
{
using myCommon;
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Menu;
using EloBuddy.SDK.Menu.Values;
using System.Linq;
internal class MenuInit : Logic
{
internal static void Init()
{
mainMenu = MainMenu.AddMenu("Moon" + Player.Instance.ChampionName, "Moon" + Player.Instance.ChampionName);
{
mainMenu.AddGroupLabel("Please Set the Orbwalker");
mainMenu.AddGroupLabel("Orbwalker -> Advanced -> Update Event Listening -> Enabled On Update(more fast)");
mainMenu.AddGroupLabel("--------------------");
mainMenu.AddGroupLabel("One Things You Need to Know");
mainMenu.AddGroupLabel("Combo/Burst/Harass Mode");
mainMenu.AddGroupLabel("Dont Forgot Use Left Click to Select Target");
mainMenu.AddGroupLabel("It will make the Addon More Better");
mainMenu.AddGroupLabel("---------------------");
mainMenu.AddGroupLabel("My GitHub: https://github.com/aiRTako/EloBuddy");
mainMenu.AddGroupLabel("If you have Feedback pls post to my topic");
mainMenu.AddGroupLabel("----------------------");
mainMenu.AddGroupLabel("Credit: NightMoon & aiRTako");
}
comboMenu = mainMenu.AddSubMenu("Combo", "Combo");
{
comboMenu.AddLine("Q");
comboMenu.AddBool("ComboQGap", "Use Q Gapcloser");
comboMenu.AddLine("W");
comboMenu.AddBool("ComboW", "Use W");
comboMenu.AddBool("ComboWLogic", "Use W Cancel Spell Animation");
comboMenu.AddLine("E");
comboMenu.AddBool("ComboE", "Use E");
comboMenu.AddBool("ComboEGap", "Use E Gapcloser");
comboMenu.AddLine("R");
comboMenu.AddKey("ComboR1", "Use R1: ", KeyBind.BindTypes.PressToggle, 'G', true);
comboMenu.AddList("ComboR2", "Use R2 Mode: ", new[] { "my Logic", "Only KillSteal", "First Cast", "Off" });
comboMenu.AddLine("Others");
comboMenu.AddBool("ComboItem", "Use Item");
comboMenu.AddBool("ComboYoumuu", "Use Youmuu");
comboMenu.AddBool("ComboDot", "Use Ignite");
comboMenu.AddLine("Burst");
}
burstMenu = mainMenu.AddSubMenu("Burst", "Burst");
{
burstMenu.AddBool("BurstFlash", "Use Flash");
burstMenu.AddBool("BurstDot", "Use Ignite");
burstMenu.AddList("BurstMode", "Burst Mode: ", new[] { "Shy Mode", "EQ Mode" });
burstMenu.AddKey("BurstEnabledKey", "Enabled Burst Key: ", KeyBind.BindTypes.PressToggle, 'T');
burstMenu.AddSeparator();
burstMenu.AddLabel("How to burst");
burstMenu.AddLabel("1.you need to enbaled the Key");
burstMenu.AddLabel("2.Select the Target (or not, but this will be force target to burst)");
burstMenu.AddLabel("3.just press the Combo Key");
}
harassMenu = mainMenu.AddSubMenu("Harass", "Harass");
{
harassMenu.AddLine("Q");
harassMenu.AddBool("HarassQ", "Use Q");
harassMenu.AddLine("W");
harassMenu.AddBool("HarassW", "Use W");
harassMenu.AddLine("E");
harassMenu.AddBool("HarassE", "Use E");
harassMenu.AddLine("Mode");
harassMenu.AddList("HarassMode", "Harass Mode: ", new[] { "Smart", "Normal" });
}
clearMenu = mainMenu.AddSubMenu("Clear", "Clear");
{
clearMenu.AddText("LaneClear Settings");
clearMenu.AddLine("LaneClear Q");
clearMenu.AddBool("LaneClearQ", "Use Q");
clearMenu.AddBool("LaneClearQSmart", "Use Q Smart Farm");
clearMenu.AddBool("LaneClearQT", "Use Q Reset Attack Turret");
clearMenu.AddLine("LaneClear W");
clearMenu.AddBool("LaneClearW", "Use W", false);
clearMenu.AddSlider("LaneClearWCount", "Use W| Min hit Count >= x", 3, 1, 10);
clearMenu.AddLine("LaneClear Items");
clearMenu.AddBool("LaneClearItem", "Use Items");
clearMenu.AddSeparator();
clearMenu.AddText("JungleClear Settings");
clearMenu.AddLine("JungleClear Q");
clearMenu.AddBool("JungleClearQ", "Use Q");
clearMenu.AddLine("JungleClear W");
clearMenu.AddBool("JungleClearW", "Use W");
clearMenu.AddLine("JungleClear E");
clearMenu.AddBool("JungleClearE", "Use E");
clearMenu.AddLine("JungleClear Items");
clearMenu.AddBool("JungleClearItem", "Use Items");
ManaManager.AddSpellFarm(clearMenu);
}
fleeMenu = mainMenu.AddSubMenu("Flee", "Flee");
{
fleeMenu.AddText("Q");
fleeMenu.AddBool("FleeQ", "Use Q");
fleeMenu.AddText("W");
fleeMenu.AddBool("FleeW", "Use W");
fleeMenu.AddText("E");
fleeMenu.AddBool("FleeE", "Use E");
}
killStealMenu = mainMenu.AddSubMenu("KillSteal", "KillSteal");
{
killStealMenu.AddText("R");
killStealMenu.AddBool("KillStealR", "Use R");
}
miscMenu = mainMenu.AddSubMenu("Misc", "Misc");
{
miscMenu.AddText("Q");
miscMenu.AddBool("KeepQ", "Keep Q alive");
miscMenu.AddList("QMode", "Q Mode: ", new[] { "To target", "To mouse" });
miscMenu.AddSeparator();
miscMenu.AddText("W");
miscMenu.AddBool("AntiGapcloserW", "Anti Gapcloser");
miscMenu.AddBool("InterruptW", "Interrupt Danger Spell");
miscMenu.AddSeparator();
miscMenu.AddText("Animation");
miscMenu.AddBool("manualCancel", "Semi Cancel Animation");
miscMenu.AddBool("manualCancelPing", "Cancel Animation Calculate Ping?");
}
eMenu = mainMenu.AddSubMenu("Evade", "Evade");
{
//TODO:
//1.Add dodge not unit Spell
eMenu.AddText("Evade Opinion");
eMenu.AddBool("evadeELogic", "Enabled Use E Dodge");
if (EntityManager.Heroes.Enemies.Any())
{
foreach (var target in EntityManager.Heroes.Enemies)
{
eMenu.AddText(target.ChampionName + " Skills");
#region
//SelfAOE (not include the Karma E and?)
//if (target.Spellbook.GetSpell(SpellSlot.Q).SData.TargettingType != SpellDataTargetType.Self &&
// target.Spellbook.GetSpell(SpellSlot.Q).SData.TargettingType != SpellDataTargetType.SelfAndUnit)
//{
// eMenu.AddBool(target.ChampionName + "Skill" + target.Spellbook.GetSpell(SpellSlot.Q).SData.Name,
// target.Spellbook.GetSpell(SpellSlot.Q).SData.Name,
// target.Spellbook.GetSpell(SpellSlot.Q).SData.TargettingType == SpellDataTargetType.Unit);
//}
//if (target.Spellbook.GetSpell(SpellSlot.W).SData.TargettingType != SpellDataTargetType.Self &&
// target.Spellbook.GetSpell(SpellSlot.W).SData.TargettingType != SpellDataTargetType.SelfAndUnit)
//{
// eMenu.AddBool(target.ChampionName + "Skill" + target.Spellbook.GetSpell(SpellSlot.W).SData.Name,
// target.Spellbook.GetSpell(SpellSlot.W).SData.Name,
// target.Spellbook.GetSpell(SpellSlot.W).SData.TargettingType == SpellDataTargetType.Unit);
//}
//if (target.Spellbook.GetSpell(SpellSlot.E).SData.TargettingType != SpellDataTargetType.Self &&
// target.Spellbook.GetSpell(SpellSlot.E).SData.TargettingType != SpellDataTargetType.SelfAndUnit)
//{
// eMenu.AddBool(target.ChampionName + "Skill" + target.Spellbook.GetSpell(SpellSlot.E).SData.Name,
// target.Spellbook.GetSpell(SpellSlot.E).SData.Name,
// target.Spellbook.GetSpell(SpellSlot.E).SData.TargettingType == SpellDataTargetType.Unit);
//}
//if (target.Spellbook.GetSpell(SpellSlot.R).SData.TargettingType != SpellDataTargetType.Self &&
// target.Spellbook.GetSpell(SpellSlot.R).SData.TargettingType != SpellDataTargetType.SelfAndUnit)
//{
// eMenu.AddBool(target.ChampionName + "Skill" + target.Spellbook.GetSpell(SpellSlot.R).SData.Name,
// target.Spellbook.GetSpell(SpellSlot.R).SData.Name,
// target.Spellbook.GetSpell(SpellSlot.R).SData.TargettingType == SpellDataTargetType.Unit);
//}
#endregion
if (target.Spellbook.GetSpell(SpellSlot.Q).SData.TargettingType == SpellDataTargetType.Unit)
{
eMenu.AddBool(target.ChampionName + "Skill" + target.Spellbook.GetSpell(SpellSlot.Q).SData.Name,
target.Spellbook.GetSpell(SpellSlot.Q).SData.Name);
}
if (target.Spellbook.GetSpell(SpellSlot.W).SData.TargettingType == SpellDataTargetType.Unit)
{
eMenu.AddBool(target.ChampionName + "Skill" + target.Spellbook.GetSpell(SpellSlot.W).SData.Name,
target.Spellbook.GetSpell(SpellSlot.W).SData.Name);
}
if (target.Spellbook.GetSpell(SpellSlot.E).SData.TargettingType == SpellDataTargetType.Unit)
{
eMenu.AddBool(target.ChampionName + "Skill" + target.Spellbook.GetSpell(SpellSlot.E).SData.Name,
target.Spellbook.GetSpell(SpellSlot.E).SData.Name);
}
if (target.Spellbook.GetSpell(SpellSlot.R).SData.TargettingType == SpellDataTargetType.Unit)
{
eMenu.AddBool(target.ChampionName + "Skill" + target.Spellbook.GetSpell(SpellSlot.R).SData.Name,
target.Spellbook.GetSpell(SpellSlot.R).SData.Name);
}
}
}
}
drawMenu = mainMenu.AddSubMenu("Drawings", "Drawings");
{
drawMenu.AddText("Spell Range");
drawMenu.AddBool("DrawW", "Draw W Range", false);
drawMenu.AddBool("DrawE", "Draw E Range", false);
drawMenu.AddBool("DrawR1", "Draw R1 Range", false);
drawMenu.AddBool("DrawR", "Draw R Status");
drawMenu.AddBool("DrawBurst", "Draw R Status");
ManaManager.AddDrawFarm(drawMenu);
DamageIndicator.AddToMenu(drawMenu);
}
}
internal static bool ComboQGap => comboMenu.GetBool("ComboQGap");
internal static bool ComboW => comboMenu.GetBool("ComboW");
internal static bool ComboWLogic => comboMenu.GetBool("ComboWLogic");
internal static bool ComboE => comboMenu.GetBool("ComboE");
internal static bool ComboEGap => comboMenu.GetBool("ComboEGap");
internal static bool ComboR1 => comboMenu.GetKey("ComboR1");
internal static int ComboR2 => comboMenu.GetList("ComboR2");
internal static bool ComboItem => comboMenu.GetBool("ComboItem");
internal static bool ComboYoumuu => comboMenu.GetBool("ComboYoumuu");
internal static bool ComboDot => comboMenu.GetBool("ComboDot");
internal static bool BurstFlash => burstMenu.GetBool("BurstFlash");
internal static bool BurstDot => burstMenu.GetBool("BurstDot");
internal static int BurstMode => burstMenu.GetList("BurstMode");
internal static bool BurstEnabledKey => burstMenu.GetKey("BurstEnabledKey");
internal static bool HarassQ => harassMenu.GetBool("HarassQ");
internal static bool HarassW => harassMenu.GetBool("HarassW");
internal static bool HarassE => harassMenu.GetBool("HarassE");
internal static int HarassMode => harassMenu.GetList("HarassMode");
internal static bool LaneClearQ => clearMenu.GetBool("LaneClearQ");
internal static bool LaneClearQSmart => clearMenu.GetBool("LaneClearQSmart");
internal static bool LaneClearQT => clearMenu.GetBool("LaneClearQT");
internal static bool LaneClearW => clearMenu.GetBool("LaneClearW");
internal static int LaneClearWCount => clearMenu.GetSlider("LaneClearWCount");
internal static bool LaneClearItem => clearMenu.GetBool("LaneClearItem");
internal static bool JungleClearQ => clearMenu.GetBool("JungleClearQ");
internal static bool JungleClearW => clearMenu.GetBool("JungleClearW");
internal static bool JungleClearE => clearMenu.GetBool("JungleClearE");
internal static bool JungleClearItem => clearMenu.GetBool("JungleClearItem");
internal static bool FleeQ => fleeMenu.GetBool("FleeQ");
internal static bool FleeW => fleeMenu.GetBool("FleeW");
internal static bool FleeE => fleeMenu.GetBool("FleeE");
internal static bool KillStealR => killStealMenu.GetBool("KillStealR");
internal static bool KeepQ => miscMenu.GetBool("KeepQ");
internal static int QMode => miscMenu.GetList("QMode");
internal static bool AntiGapcloserW => miscMenu.GetBool("AntiGapcloserW");
internal static bool InterruptW => miscMenu.GetBool("InterruptW");
internal static bool manualCancel => miscMenu.GetBool("manualCancel");
internal static bool manualCancelPing => miscMenu.GetBool("manualCancelPing");
internal static bool evadeELogic => eMenu.GetBool("evadeELogic");
internal static bool DrawW => drawMenu.GetBool("DrawW");
internal static bool DrawE => drawMenu.GetBool("DrawE");
internal static bool DrawR1 => drawMenu.GetBool("DrawR1");
internal static bool DrawR => drawMenu.GetBool("DrawR");
internal static bool DrawBurst => drawMenu.GetBool("DrawBurst");
}
}
<file_sep>/MoonLucian/MoonLucian/myCommon/ManaManager.cs
namespace MoonLucian.myCommon
{
using EloBuddy;
using EloBuddy.SDK.Menu;
using EloBuddy.SDK.Menu.Values;
using Color = System.Drawing.Color;
internal static class ManaManager
{
internal static bool SpellFarm;
internal static bool SpellHarass;
internal static bool HasEnoughMana(int manaPercent)
{
return Player.Instance.ManaPercent >= manaPercent; //&& !Player.Instance.IsUnderEnemyturret();
}
internal static void AddSpellFarm(Menu mainMenu)
{
mainMenu.AddSeparator();
mainMenu.AddText("Moon Farm Logic");
mainMenu.AddBool("SpellFarm", "Use Spell Farm(Mouse Score Control)");
var key = mainMenu.Add("SpellHarass", new KeyBind("Use Spell Harass Enemy(in Farm Mode)", true, KeyBind.BindTypes.PressToggle, 'H'));
SpellFarm = mainMenu.GetBool("SpellFarm");
SpellHarass = mainMenu.GetKey("SpellHarass");
key.OnValueChange += delegate (ValueBase<bool> sender, ValueBase<bool>.ValueChangeArgs Args)
{
SpellHarass = Args.NewValue;
};
Game.OnWndProc += delegate (WndEventArgs Args)
{
if (Args.Msg == 0x20a)
{
mainMenu["SpellFarm"].Cast<CheckBox>().CurrentValue = !SpellFarm;
SpellFarm = mainMenu.GetBool("SpellFarm");
}
};
}
internal static void AddDrawFarm(Menu mainMenu)
{
mainMenu.AddSeparator();
mainMenu.AddText("Draw Moon Farm Logic");
mainMenu.AddBool("DrawFarm", "Draw Spell Farm Status");
mainMenu.AddBool("DrawHarass", "Draw Spell Harass Status");
Drawing.OnDraw += delegate
{
if (!Player.Instance.IsDead && !MenuGUI.IsChatOpen)
{
if (mainMenu.GetBool("DrawFarm"))
{
var MePos = Drawing.WorldToScreen(Player.Instance.Position);
Drawing.DrawText(MePos[0] - 57, MePos[1] + 48, Color.FromArgb(242, 120, 34),
"Spell Farm:" + (SpellFarm ? "On" : "Off"));
}
if (mainMenu.GetBool("DrawHarass"))
{
var MePos = Drawing.WorldToScreen(Player.Instance.Position);
Drawing.DrawText(MePos[0] - 57, MePos[1] + 68, Color.FromArgb(242, 120, 34),
"Spell Haras:" + (SpellHarass ? "On" : "Off"));
}
}
};
}
}
}
<file_sep>/MoonRiven/MoonRiven/Mode/None.cs
namespace MoonRiven_2.Mode
{
using EloBuddy;
using EloBuddy.SDK;
using myCommon;
using System;
internal class None : Logic
{
internal static void Init()
{
if (TargetSelector.SelectedTarget != null && TargetSelector.SelectedTarget.IsValidRange())
{
myTarget = TargetSelector.SelectedTarget;
}
else if (Orbwalker.GetTarget() != null && Orbwalker.GetTarget().Type == GameObjectType.AIHeroClient &&
Orbwalker.GetTarget().IsValidRange())
{
myTarget = (AIHeroClient)Orbwalker.GetTarget();
}
else
{
myTarget = null;
}
if (W.Level > 0)
{
W.Range = (uint)(Player.HasBuff("RivenFengShuiEngine") ? 330 : 260);
}
if (MenuInit.KeepQ && Player.HasBuff("RivenTriCleave"))
{
if (Player.GetBuff("RivenTriCleave").EndTime - Game.Time < 0.3)
{
Player.Instance.Spellbook.CastSpell(SpellSlot.Q, Game.CursorPos);
}
}
if (qStack != 0 && Environment.TickCount - lastQTime > 3800)
{
qStack = 0;
}
}
}
}
<file_sep>/MoonLucian/MoonLucian/Logic.cs
namespace MoonLucian
{
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Menu;
using System;
using System.Linq;
internal class Logic
{
//Spell
internal static Spell.Targeted Q { get; set; }
internal static Spell.Skillshot QExtend { get; set; }
internal static Spell.Skillshot W { get; set; }
internal static Spell.Skillshot E { get; set; }
internal static Spell.Skillshot R { get; set; }
internal static Spell.Skillshot R1 { get; set; }
//Item
internal static Item Youmuus { get; set; }
//Menu
internal static Menu mainMenu { get; set; }
internal static Menu modeMenu { get; set; }
internal static Menu miscMenu { get; set; }
internal static Menu comboMenu { get; set; }
internal static Menu harassMenu { get; set; }
internal static Menu clearMenu { get; set; }
internal static Menu killStealMenu { get; set; }
internal static Menu qMenu { get; set; }
internal static Menu wMenu { get; set; }
internal static Menu eMenu { get; set; }
internal static Menu rMenu { get; set; }
internal static Menu drawMenu { get; set; }
//Orbwalker
internal static bool isComboMode => Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.Combo);
internal static bool isHarassMode => Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.Harass);
internal static bool isFarmMode => Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.LaneClear) ||
Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.JungleClear) ||
Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.LastHit);
internal static bool isLaneClearMode => Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.LaneClear);
internal static bool isJungleClearMode => Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.JungleClear);
internal static bool isLastHitMode => Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.LastHit);
//Mana
internal static float QMana { get; set; }
internal static float WMana { get; set; }
internal static float EMana { get; set; }
internal static float RMana { get; set; }
internal static float PlayerMana => Player.Instance.Mana;
internal static float PlayerManaPercent => Player.Instance.ManaPercent;
//Status
internal static int lastCastTime { get; set; }
internal static bool havePassive { get; set; }
internal static bool havePassiveBuff => Player.Instance.Buffs.Any(x => x.Name.ToLower() == "lucianpassivebuff");
//Tick Count
internal static int TickCount
{
get
{
return Environment.TickCount & int.MaxValue;
}
}
}
}
<file_sep>/MoonRiven/MoonRiven/myCommon/ManaManager.cs
namespace MoonRiven_2.myCommon
{
using EloBuddy;
using EloBuddy.SDK.Menu;
using EloBuddy.SDK.Menu.Values;
using Color = System.Drawing.Color;
internal static class ManaManager
{
internal static bool SpellFarm;
internal static bool HasEnoughMana(int manaPercent)
{
return Player.Instance.ManaPercent >= manaPercent; //&& !Player.Instance.IsUnderEnemyturret();
}
internal static void AddSpellFarm(Menu mainMenu)
{
mainMenu.AddSeparator();
mainMenu.AddText("Moon Farm Logic");
mainMenu.AddBool("SpellFarm", "Use Spell Farm(Mouse Score Control)");
SpellFarm = mainMenu.GetBool("SpellFarm");
Game.OnWndProc += delegate (WndEventArgs Args)
{
if (Args.Msg == 0x20a)
{
mainMenu["SpellFarm"].Cast<CheckBox>().CurrentValue = !SpellFarm;
SpellFarm = mainMenu.GetBool("SpellFarm");
}
};
}
internal static void AddDrawFarm(Menu mainMenu)
{
mainMenu.AddSeparator();
mainMenu.AddText("Draw Moon Farm Logic");
mainMenu.AddBool("DrawFarm", "Draw Spell Farm Status");
Drawing.OnDraw += delegate
{
if (!Player.Instance.IsDead && !MenuGUI.IsChatOpen)
{
if (mainMenu.GetBool("DrawFarm"))
{
var MePos = Drawing.WorldToScreen(Player.Instance.Position);
Drawing.DrawText(MePos[0] - 57, MePos[1] + 48, Color.FromArgb(242, 120, 34),
"Spell Farm:" + (SpellFarm ? "On" : "Off"));
}
}
};
}
}
}
<file_sep>/MoonRiven/MoonRiven/myCommon/DamageCalculate.cs
namespace MoonRiven_2.myCommon
{
using EloBuddy;
using EloBuddy.SDK;
internal class DamageCalculate
{
internal static float GetComboDamage(AIHeroClient target)
{
if (target == null || target.IsDead || target.IsZombie)
{
return 0;
}
if (target.IsUnKillable())
{
return 0;
}
var damage = 0d;
if (Player.Instance.BaseAttackDamage + Player.Instance.FlatPhysicalDamageMod > Player.Instance.TotalMagicalDamage)
{
damage += Player.Instance.GetAutoAttackDamage(target);
}
if (Player.Instance.GetSpellSlotFromName("SummonerDot") != SpellSlot.Unknown &&
Player.Instance.Spellbook.GetSpell(Player.Instance.GetSpellSlotFromName("SummonerDot")).IsReady)
{
damage += GetIgniteDmage(target);
}
damage += GetQDamage(target);
damage += GetWDamage(target);
damage += GetEDamage(target);
damage += GetRDamage(target);
if (Player.HasBuff("SummonerExhaust"))
{
damage = damage * 0.6f;
}
if (target.CharData.BaseSkinName == "Moredkaiser")
{
damage -= target.Mana;
}
if (target.HasBuff("GarenW"))
{
damage = damage * 0.7f;
}
if (target.HasBuff("ferocioushowl"))
{
damage = damage * 0.7f;
}
if (target.HasBuff("BlitzcrankManaBarrierCD") && target.HasBuff("ManaBarrier"))
{
damage -= target.Mana / 2f;
}
return (float)damage;
}
internal static float GetQDamage(Obj_AI_Base target)
{
if (Player.Instance.Spellbook.GetSpell(SpellSlot.Q).Level == 0 ||
Player.Instance.Spellbook.GetSpell(SpellSlot.Q).IsOnCooldown)
{
return 0f;
}
var qhan = 3 - Logic.qStack;
var qDMG = new double[] { 30, 55, 80, 105, 130 }[Player.Instance.Spellbook.GetSpell(SpellSlot.Q).Level - 1] + 0.7 * Player.Instance.FlatPhysicalDamageMod;
return
(float)
(Player.Instance.CalculateDamageOnUnit(target, DamageType.Physical, (float)qDMG) * qhan +
Player.Instance.GetAutoAttackDamage(target) * qhan * (1 + GetRivenPassive));
}
internal static float GetWDamage(AIHeroClient target)
{
if (ObjectManager.Player.Spellbook.GetSpell(SpellSlot.W).Level == 0 ||
!ObjectManager.Player.Spellbook.GetSpell(SpellSlot.W).IsReady)
{
return 0f;
}
var wDMG = new double[] { 50, 80, 110, 140, 170 }[Player.Instance.Spellbook.GetSpell(SpellSlot.W).Level - 1] + Player.Instance.FlatPhysicalDamageMod;
return Player.Instance.CalculateDamageOnUnit(target, DamageType.Physical, (float)wDMG);
}
internal static float GetEDamage(AIHeroClient target)
{
if (Player.Instance.Spellbook.GetSpell(SpellSlot.E).Level == 0 ||
!Player.Instance.Spellbook.GetSpell(SpellSlot.E).IsReady)
{
return 0f;
}
return Player.Instance.CanMoveMent() ? Player.Instance.GetAutoAttackDamage(target) : 0;
}
internal static float GetRDamage(AIHeroClient target)
{
if (Player.Instance.Spellbook.GetSpell(SpellSlot.R).Level == 0 ||
!Player.Instance.Spellbook.GetSpell(SpellSlot.R).IsReady)
{
return 0f;
}
var dmg = (new double[] { 80, 120, 160 }[Player.Instance.Spellbook.GetSpell(SpellSlot.R).Level - 1] +
0.6 * Player.Instance.FlatPhysicalDamageMod) *
(1 + (target.MaxHealth - target.Health) /
target.MaxHealth > 0.75
? 0.75
: (target.MaxHealth - target.Health) / target.MaxHealth) * 8 / 3;
return Player.Instance.CalculateDamageOnUnit(target, DamageType.Physical, (float)dmg);
}
internal static float GetIgniteDmage(Obj_AI_Base target)
{
return 50 + 20 * Player.Instance.Level - target.HPRegenRate / 5 * 3;
}
internal static double GetRivenPassive
{
get
{
if (Player.Instance.Level == 18)
{
return 0.5;
}
if (Player.Instance.Level >= 15)
{
return 0.45;
}
if (Player.Instance.Level >= 12)
{
return 0.4;
}
if (Player.Instance.Level >= 9)
{
return 0.35;
}
if (Player.Instance.Level >= 6)
{
return 0.3;
}
if (Player.Instance.Level >= 3)
{
return 0.25;
}
return 0.2;
}
}
internal static float GetRealDamage(AIHeroClient target, float DMG)
{
if (target == null || target.IsDead || target.IsZombie)
{
return 0;
}
if (target.IsUnKillable())
{
return 0;
}
var damage = DMG;
if (Player.HasBuff("SummonerExhaust"))
{
damage = damage * 0.6f;
}
if (target.CharData.BaseSkinName == "Moredkaiser")
{
damage -= target.Mana;
}
if (target.HasBuff("GarenW"))
{
damage = damage * 0.7f;
}
if (target.HasBuff("ferocioushowl"))
{
damage = damage * 0.7f;
}
if (target.HasBuff("BlitzcrankManaBarrierCD") && target.HasBuff("ManaBarrier"))
{
damage -= target.Mana / 2f;
}
return damage;
}
}
}<file_sep>/aiRTako_Biltzcrank/aiRTako_Biltzcrank/Program.cs
namespace aiRTako_Biltzcrank
{
using DamageLib;
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Enumerations;
using EloBuddy.SDK.Events;
using EloBuddy.SDK.Menu;
using EloBuddy.SDK.Menu.Values;
using EloBuddy.SDK.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
internal class Program
{
private static Spell.Skillshot Q, R;
private static Spell.Active W, E;
private static SpellSlot Smite = SpellSlot.Unknown;
private static Menu Menu;
private static Menu ComboMenu;
private static Menu HarassMenu;
private static Menu AutoMenu;
private static Menu JungleStealMenu;
private static Menu MiscMenu;
private static Menu DrawMenu;
private static readonly Dictionary<string, string> SmiteObjects =
new Dictionary<string, string>
{
{"Baron Nashor", "SRU_Baron"},
{"Blue Sentinel", "SRU_Blue"},
{"Water Dragon", "SRU_Dragon_Water"},
{"Fire Dragon", "SRU_Dragon_Fire"},
{"Earth Dragon", "SRU_Dragon_Earth"},
{"Air Dragon", "SRU_Dragon_Air"},
{"Elder Dragon", "SRU_Dragon_Elder"},
{"Red Brambleback", "SRU_Red"},
{"Rift Herald", "SRU_RiftHerald"},
{"Crimson Raptor", "SRU_Razorbeak"},
{"Greater Murk Wolf", "SRU_Murkwolf"},
{"Gromp", "SRU_Gromp"},
{"Rift Scuttler", "Sru_Crab"},
{"Ancient Krug", "SRU_Krug"}
};
private static void Main(string[] eventArgs)
{
Loading.OnLoadingComplete += Loading_OnLoadingComplete;
}
private static void Loading_OnLoadingComplete(EventArgs eventArgs)
{
if (Player.Instance.Hero != Champion.Blitzcrank)
{
return;
}
Chat.Print("aiRTako Blitzcrank: Welcome to use my Addon!", System.Drawing.Color.Orange);
var slot = Player.Instance.Spellbook.Spells.FirstOrDefault(x => x.Name.ToLower().Contains("smite"));
if (slot != null)
Smite = slot.Slot;
Q = new Spell.Skillshot(SpellSlot.Q, 950, SkillShotType.Linear, 250, 1800, 80, DamageType.Magical);
W = new Spell.Active(SpellSlot.W);
E = new Spell.Active(SpellSlot.E);
R = new Spell.Skillshot(SpellSlot.R, 545, SkillShotType.Circular);
Menu = MainMenu.AddMenu("aiRTako Biltzcrank", "aiRTako Biltzcrank");
ComboMenu = Menu.AddSubMenu("Combo", "Combo");
{
ComboMenu.AddLabel("Q Target Settings");
foreach (var target in EntityManager.Heroes.Enemies)
{
ComboMenu.Add("ComboQ" + target.ChampionName, new CheckBox(target.ChampionName));
}
ComboMenu.AddSeparator();
ComboMenu.AddLabel("Q Settings");
ComboMenu.Add("ComboQ", new CheckBox("Use Q"));
ComboMenu.AddSeparator();
ComboMenu.AddLabel("W Settings");
ComboMenu.Add("ComboW", new CheckBox("Use W", false));
ComboMenu.AddSeparator();
ComboMenu.AddLabel("E Settings");
ComboMenu.Add("ComboE", new CheckBox("Use E"));
ComboMenu.AddSeparator();
ComboMenu.AddLabel("R Settings");
ComboMenu.Add("ComboR", new CheckBox("Use R"));
}
HarassMenu = Menu.AddSubMenu("Harass", "Harass");
{
HarassMenu.AddLabel("Q Target Settings");
foreach (var target in EntityManager.Heroes.Enemies)
{
HarassMenu.Add("HarassQ" + target.ChampionName, new CheckBox(target.ChampionName));
}
HarassMenu.AddSeparator();
HarassMenu.AddLabel("Q Settings");
HarassMenu.Add("HarassQ", new CheckBox("Use Q"));
HarassMenu.AddSeparator();
HarassMenu.AddLabel("E Settings");
HarassMenu.Add("HarassE", new CheckBox("Use E"));
HarassMenu.AddSeparator();
HarassMenu.AddLabel("Mana Settings");
HarassMenu.Add("HarassMana", new Slider("Min Mana %", 60));
}
AutoMenu = Menu.AddSubMenu("Auto", "Auto");
{
AutoMenu.AddLabel("Q Target Settings");
foreach (var target in EntityManager.Heroes.Enemies)
{
AutoMenu.Add("AutoQ" + target.ChampionName, new CheckBox(target.ChampionName));
}
AutoMenu.AddSeparator();
AutoMenu.AddLabel("Q Settings");
AutoMenu.Add("AutoQ", new KeyBind("Use Q", false, KeyBind.BindTypes.PressToggle, 'T'));
AutoMenu.AddSeparator();
AutoMenu.AddLabel("Mana Settings");
AutoMenu.Add("AutoMana", new Slider("Min Mana %", 60));
}
JungleStealMenu = Menu.AddSubMenu("JungleSteal", "JungleSteal");
{
JungleStealMenu.AddLabel("Global Settings");
JungleStealMenu.Add("JungleEnabled", new CheckBox("Enbaled Jungle Steal"));
JungleStealMenu.AddSeparator();
JungleStealMenu.AddLabel("Q Settings");
JungleStealMenu.Add("JungleQ", new CheckBox("Use Q"));
JungleStealMenu.AddSeparator();
JungleStealMenu.AddLabel("R Settings");
JungleStealMenu.Add("JungleR", new CheckBox("Use R"));
JungleStealMenu.AddSeparator();
JungleStealMenu.AddLabel("Other Settings");
JungleStealMenu.Add("JungleAlly", new CheckBox("If Have Ally In Range Dont Steal"));
JungleStealMenu.Add("JungleAllyRange", new Slider("Search Ally Range", 500, 200, 920));
JungleStealMenu.AddSeparator();
JungleStealMenu.AddLabel("Steal Settings");
foreach (var item in SmiteObjects)
{
JungleStealMenu.Add($"{item.Value}", new CheckBox($"{item.Key}"));
}
}
MiscMenu = Menu.AddSubMenu("Misc", "Misc");
{
MiscMenu.AddLabel("Q Settings");
MiscMenu.Add("SmiteQ", new CheckBox("Smite Q"));
MiscMenu.Add("InterruptQ", new CheckBox("Interrupt Spell"));
MiscMenu.Add("MinQRange", new Slider("Min Cast Q Range", 250, 100, 920));
MiscMenu.AddSeparator();
MiscMenu.AddLabel("E Settings");
MiscMenu.Add("AntiGapE", new CheckBox("Anti Gaplcoser"));
MiscMenu.AddSeparator();
MiscMenu.AddLabel("R Settings");
MiscMenu.Add("InterruptR", new CheckBox("Interrupt Spell"));
}
DrawMenu = Menu.AddSubMenu("Drawings", "Drawings");
{
DrawMenu.AddLabel("Spell Range");
DrawMenu.Add("DrawQ", new CheckBox("Draw Q Range", false));
DrawMenu.Add("DrawR", new CheckBox("Draw R Range", false));
DrawMenu.AddLabel("Auto Q Status");
DrawMenu.Add("DrawAutoQ", new CheckBox("Draw Auto Q Status"));
DamageIndicator.AddToMenu(DrawMenu);
}
Game.OnUpdate += Game_OnUpdate;
Orbwalker.OnPostAttack += Orbwalker_OnPostAttack;
Obj_AI_Base.OnBuffGain += Obj_AI_Base_OnBuffGain;
Gapcloser.OnGapcloser += Gapcloser_OnGapcloser;
Interrupter.OnInterruptableSpell += Interrupter_OnInterruptableSpell;
Drawing.OnDraw += Drawing_OnDraw;
}
private static void Game_OnUpdate(EventArgs eventArgs)
{
if (Player.Instance.IsDead || Player.Instance.IsRecalling())
return;
if (Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.Combo))
{
Combo();
}
if (Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.Harass))
{
Harass();
}
if (!Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.Combo) &&
!Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.Harass) &&
AutoMenu["AutoQ"].Cast<KeyBind>().CurrentValue && Q.IsReady() &&
Player.Instance.ManaPercent >= AutoMenu["AutoMana"].Cast<Slider>().CurrentValue)
{
AutoQ();
}
if (JungleStealMenu["JungleEnabled"].Cast<CheckBox>().CurrentValue)
{
JungleSteal();
}
}
private static void Combo()
{
if (ComboMenu["ComboQ"].Cast<CheckBox>().CurrentValue && Q.IsReady())
{
var target = TargetSelector.GetTarget(Q.Range, DamageType.Magical);
if (target.IsValidTarget(Q.Range) &&
ComboMenu["ComboQ" + target.ChampionName].Cast<CheckBox>().CurrentValue && !HaveShiled(target))
{
CastQ(target);
}
}
if (ComboMenu["ComboW"].Cast<CheckBox>().CurrentValue && W.IsReady())
{
if ((EntityManager.Heroes.Enemies.Any(x => x.IsValidTarget(Q.Range)) && !Q.IsReady()) ||
Player.HasBuffOfType(BuffType.Slow))
{
Player.Instance.Spellbook.CastSpell(SpellSlot.W);
}
}
if (ComboMenu["ComboE"].Cast<CheckBox>().CurrentValue && E.IsReady())
{
var target = TargetSelector.GetTarget(Player.Instance.GetAutoAttackRange() + 65, DamageType.Physical);
if (target.IsValidTarget() && !Q.IsReady())
{
Player.Instance.Spellbook.CastSpell(SpellSlot.E);
Orbwalker.ForcedTarget = target;
}
}
if (ComboMenu["ComboR"].Cast<CheckBox>().CurrentValue && R.IsReady())
{
var target = TargetSelector.GetTarget(R.Range, DamageType.Magical);
if (target.IsValidTarget(R.Range) && target.HasBuff("rocketgrab2"))
{
Player.Instance.Spellbook.CastSpell(SpellSlot.R);
}
else if (target.IsValidTarget(R.Range) && target.Health < DamageCalculate.GetRDamage(target) && !IsUnKillable(target))
{
Player.Instance.Spellbook.CastSpell(SpellSlot.R);
}
else if (Player.Instance.CountEnemyChampionsInRange(R.Range) >= 3)
{
Player.Instance.Spellbook.CastSpell(SpellSlot.R);
}
else if (Player.Instance.CountEnemyChampionsInRange(R.Range) >= 2 && Player.Instance.IsMelee)
{
Player.Instance.Spellbook.CastSpell(SpellSlot.R);
}
}
}
private static void Harass()
{
if (Player.Instance.ManaPercent < HarassMenu["HarassMana"].Cast<Slider>().CurrentValue)
return;
if (!HarassMenu["HarassQ"].Cast<CheckBox>().CurrentValue || !Q.IsReady())
return;
var targets =
EntityManager.Heroes.Enemies.Where(
x =>
x.IsValidTarget(Q.Range) &&
HarassMenu["HarassQ" + x.ChampionName].Cast<CheckBox>().CurrentValue && !HaveShiled(x))
.OrderBy(TargetSelector.GetPriority)
.ToList();
foreach (var target in targets)
{
if (target.IsValidTarget(Q.Range))
{
CastQ(target);
return;
}
}
}
private static void AutoQ()
{
foreach (
var target in
EntityManager.Heroes.Enemies.Where(
x =>
x.IsValidTarget(Q.Range) && AutoMenu["AutoQ" + x.ChampionName].Cast<CheckBox>().CurrentValue &&
!x.IsValidTarget(MiscMenu["MinQRange"].Cast<Slider>().CurrentValue) && !HaveShiled(x))
.OrderBy(TargetSelector.GetPriority))
{
if (target.IsValidTarget(Q.Range))
{
CastQ(target);
return;
}
}
}
private static void JungleSteal()
{
var mobs =
ObjectManager.Get<Obj_AI_Minion>()
.Where(
x =>
x != null && x.IsMonster && x.Distance(Player.Instance) <= 950 &&
!x.Name.ToLower().Contains("mini") && !x.Name.ToLower().Contains("respawn") &&
!x.Name.ToLower().Contains("plant"))
.OrderBy(x => x.MaxHealth);
foreach (var mob in mobs)
{
if (mob.Distance(Player.Instance) > (Q.IsReady() ? Q.Range : R.IsReady() ? R.Range : 1000))
continue;
if (JungleStealMenu["JungleAlly"].Cast<CheckBox>().CurrentValue &&
EntityManager.Heroes.Allies.Any(
x =>
!x.IsDead && !x.IsMe &&
x.Distance(mob) <= JungleStealMenu["JungleAllyRange"].Cast<Slider>().CurrentValue))
{
continue;
}
if (JungleStealMenu[mob.CharData.BaseSkinName] != null &&
JungleStealMenu[mob.CharData.BaseSkinName].Cast<CheckBox>().CurrentValue)
{
if (JungleStealMenu["JungleR"].Cast<CheckBox>().CurrentValue &&
mob.Distance(Player.Instance) <= R.Range && mob.Health <= DamageCalculate.GetRDamage(mob))
{
Player.Instance.Spellbook.CastSpell(SpellSlot.R);
}
else if (JungleStealMenu["JungleQ"].Cast<CheckBox>().CurrentValue &&
mob.Distance(Player.Instance) <= Q.Range && mob.Health <= DamageCalculate.GetQDamage(mob))
{
var Pred = Q.GetPrediction(mob);
if (Pred.HitChance == HitChance.High && !Pred.CollisionObjects.Any())
Q.Cast(mob.Position);
}
}
}
}
private static void Orbwalker_OnPostAttack(AttackableUnit target, EventArgs eventArgs)
{
if (target.Type != GameObjectType.AIHeroClient || !E.IsReady())
return;
if (Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.Combo) &&
ComboMenu["ComboE"].Cast<CheckBox>().CurrentValue)
{
Player.Instance.Spellbook.CastSpell(SpellSlot.E);
Orbwalker.ForcedTarget = target;
}
if (Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.Harass) &&
HarassMenu["HarassE"].Cast<CheckBox>().CurrentValue &&
Player.Instance.ManaPercent >= HarassMenu["HarassMana"].Cast<Slider>().CurrentValue)
{
Player.Instance.Spellbook.CastSpell(SpellSlot.E);
Orbwalker.ForcedTarget = target;
}
}
private static void Obj_AI_Base_OnBuffGain(Obj_AI_Base sender, Obj_AI_BaseBuffGainEventArgs eventArgs)
{
if (sender == null || sender.Type != GameObjectType.AIHeroClient || !sender.IsEnemy ||
!eventArgs.Buff.Name.ToLower().Contains("rocketgrab2") || !eventArgs.Buff.Caster.IsMe)
return;
if (Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.Combo) &&
ComboMenu["ComboE"].Cast<CheckBox>().CurrentValue)
{
Player.Instance.Spellbook.CastSpell(SpellSlot.E);
Orbwalker.ForcedTarget = sender;
}
if (Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.Harass) &&
HarassMenu["HarassE"].Cast<CheckBox>().CurrentValue &&
Player.Instance.ManaPercent >= HarassMenu["HarassMana"].Cast<Slider>().CurrentValue)
{
Player.Instance.Spellbook.CastSpell(SpellSlot.E);
Orbwalker.ForcedTarget = sender;
}
}
private static void Gapcloser_OnGapcloser(AIHeroClient sender, Gapcloser.GapcloserEventArgs eventArgs)
{
if (!MiscMenu["AntiGapE"].Cast<CheckBox>().CurrentValue || !E.IsReady() || sender == null || !sender.IsEnemy)
return;
if (Player.Instance.IsInAutoAttackRange(sender) && !HaveShiled(sender))
{
Player.Instance.Spellbook.CastSpell(SpellSlot.E);
Orbwalker.ForcedTarget = sender;
}
}
private static void Interrupter_OnInterruptableSpell(Obj_AI_Base sender, Interrupter.InterruptableSpellEventArgs eventArgs)
{
if (sender == null || !sender.IsEnemy || eventArgs == null || sender.Type != GameObjectType.AIHeroClient)
{
return;
}
var target = (AIHeroClient)sender;
if (eventArgs.DangerLevel >= DangerLevel.High && !HaveShiled(target))
{
if (MiscMenu["InterruptR"].Cast<CheckBox>().CurrentValue && R.IsReady() && target.IsValidTarget(R.Range))
Player.Instance.Spellbook.CastSpell(SpellSlot.R);
else if (MiscMenu["InterruptQ"].Cast<CheckBox>().CurrentValue && Q.IsReady() && target.IsValidTarget(Q.Range))
CastQ(target);
}
}
private static void Drawing_OnDraw(EventArgs eventArgs)
{
if (Player.Instance.IsDead)
return;
if (DrawMenu["DrawQ"].Cast<CheckBox>().CurrentValue && Q.IsReady())
Circle.Draw(SharpDX.Color.Red, Q.Range, Player.Instance);
if (DrawMenu["DrawR"].Cast<CheckBox>().CurrentValue && R.IsReady())
Circle.Draw(SharpDX.Color.Blue, R.Range, Player.Instance);
if (DrawMenu["DrawAutoQ"].Cast<CheckBox>().CurrentValue)
{
var MePos = Drawing.WorldToScreen(Player.Instance.Position);
string str;
if (AutoMenu["AutoQ"].Cast<KeyBind>().CurrentValue)
{
str = !Q.IsReady() ? "Not Ready" : "On";
}
else
{
str = "Off";
}
Drawing.DrawText(MePos[0] - 68, MePos[1] + 68, System.Drawing.Color.FromArgb(242, 120, 34),
"AutoQ Status:" + str);
}
}
private static void CastQ(AIHeroClient target)
{
if (!Q.IsReady() || !target.IsValidTarget(Q.Range) || target.IsValidTarget(MiscMenu["MinQRange"].Cast<Slider>().CurrentValue))
return;
if (MiscMenu["SmiteQ"].Cast<CheckBox>().CurrentValue && Smite != SpellSlot.Unknown && Player.GetSpell(Smite).IsReady)
{
var Pred = Q.GetPrediction(target);
var CollsionObj = Pred.CollisionObjects.Where(x => x.Type != GameObjectType.AIHeroClient).ToList();
switch (CollsionObj.Count)
{
case 0:
if (Pred.HitChance >= HitChance.High)
{
Q.Cast(Pred.CastPosition);
}
break;
case 1:
var obj = CollsionObj.FirstOrDefault();
if (obj != null && obj.IsValidTarget(600f) &&
obj.Health <=
Player.Instance.GetSummonerSpellDamage(obj, DamageLibrary.SummonerSpells.Smite))
{
Q.Cast(Pred.CastPosition);
Core.DelayAction(() => Player.Instance.Spellbook.CastSpell(Smite, obj), Game.Ping);
}
break;
default:
return;
}
}
else
{
var Pred = Q.GetPrediction(target);
if (Pred.HitChance >= HitChance.High && !Pred.CollisionObjects.Any())
{
Q.Cast(Pred.CastPosition);
}
}
}
private static bool IsUnKillable(AIHeroClient target)
{
if (target == null || target.IsDead || target.Health <= 0)
{
return true;
}
if (target.HasBuff("KindredRNoDeathBuff"))
{
return true;
}
if (target.HasBuff("UndyingRage") && target.GetBuff("UndyingRage").EndTime - Game.Time > 0.3 && target.Health <= target.MaxHealth * 0.10f)
{
return true;
}
if (target.HasBuff("JudicatorIntervention"))
{
return true;
}
if (target.HasBuff("ChronoShift") && target.GetBuff("ChronoShift").EndTime - Game.Time > 0.3 && target.Health <= target.MaxHealth * 0.10f)
{
return true;
}
if (target.HasBuff("VladimirSanguinePool"))
{
return true;
}
if (target.HasBuff("ShroudofDarkness"))
{
return true;
}
if (target.HasBuff("SivirShield"))
{
return true;
}
if (target.HasBuff("itemmagekillerveil"))
{
return true;
}
return target.HasBuff("FioraW");
}
private static bool HaveShiled(AIHeroClient target)
{
if (target == null || target.IsDead || target.Health <= 0)
{
return false;
}
if (target.HasBuff("BlackShield"))
{
return true;
}
if (target.HasBuff("bansheesveil"))
{
return true;
}
if (target.HasBuff("SivirE"))
{
return true;
}
if (target.HasBuff("NocturneShroudofDarkness"))
{
return true;
}
if (target.HasBuff("itemmagekillerveil"))
{
return true;
}
if (target.HasBuffOfType(BuffType.SpellShield))
{
return true;
}
return false;
}
}
}
<file_sep>/MoonRiven/MoonRiven/myCommon/Extensions.cs
namespace MoonRiven_2.myCommon
{
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Menu;
using EloBuddy.SDK.Menu.Values;
using EloBuddy.SDK.Enumerations;
using SharpDX;
using System;
using System.Linq;
using System.Collections.Generic;
internal static class Extensions
{
// Menu Extensions
internal static void AddLine(this Menu mainMenu, string spellName)
{
mainMenu.AddGroupLabel(spellName + " Settings");
}
internal static void AddText(this Menu mainMenu, string disableName)
{
mainMenu.AddGroupLabel(disableName);
}
internal static void AddBool(this Menu mainMenu, string name, string disableName, bool isEnabled = true)
{
mainMenu.Add(name, new CheckBox(disableName, isEnabled));
}
internal static void AddSlider(this Menu mainMenu, string name, string disableName, int defalutValue = 0, int minValue = 0, int maxValue = 100)
{
mainMenu.Add(name, new Slider(disableName, defalutValue, minValue, maxValue));
}
internal static void AddList(this Menu mainMenu, string name, string disableName, string[] list, int defaultIndex = 0)
{
mainMenu.Add(name, new ComboBox(disableName, list, defaultIndex));
}
internal static void AddKey(this Menu mainMenu, string name, string disableName, KeyBind.BindTypes keyBindType, uint defaultKey1 = 27, bool isEnabled = false)
{
mainMenu.Add(name, new KeyBind(disableName, isEnabled, keyBindType, defaultKey1));
}
internal static bool GetBool(this Menu mainMenu, string name)
{
return mainMenu[name].Cast<CheckBox>().CurrentValue;
}
internal static bool GetKey(this Menu mainMenu, string name)
{
return mainMenu[name].Cast<KeyBind>().CurrentValue;
}
internal static int GetSlider(this Menu mainMenu, string name)
{
return mainMenu[name].Cast<Slider>().CurrentValue;
}
internal static int GetList(this Menu mainMenu, string name)
{
return mainMenu[name].Cast<ComboBox>().CurrentValue;
}
//Distance Extensions
internal static float DistanceToPlayer(this Obj_AI_Base source)
{
return Player.Instance.Distance(source);
}
internal static float DistanceToPlayer(this Vector3 position)
{
return position.To2D().DistanceToPlayer();
}
internal static float DistanceToPlayer(this Vector2 position)
{
return Player.Instance.Distance(position);
}
internal static float DistanceToMouse(this Obj_AI_Base source)
{
return Game.CursorPos.Distance(source.Position);
}
internal static float DistanceToMouse(this Vector3 position)
{
return position.To2D().DistanceToMouse();
}
internal static float DistanceToMouse(this Vector2 position)
{
return Game.CursorPos.Distance(position.To3D());
}
//Status Extensions
internal static bool HaveShiled(this AIHeroClient target)
{
if (target == null || target.IsDead || target.Health <= 0)
{
return false;
}
if (target.HasBuff("BlackShield"))
{
return true;
}
if (target.HasBuff("bansheesveil"))
{
return true;
}
if (target.HasBuff("SivirE"))
{
return true;
}
if (target.HasBuff("NocturneShroudofDarkness"))
{
return true;
}
if (target.HasBuff("itemmagekillerveil"))
{
return true;
}
if (target.HasBuffOfType(BuffType.SpellShield))
{
return true;
}
return false;
}
internal static bool CanMoveMent(this AIHeroClient target)
{
return !(target.MoveSpeed < 50) && !target.IsStunned && !target.HasBuffOfType(BuffType.Stun) &&
!target.HasBuffOfType(BuffType.Fear) && !target.HasBuffOfType(BuffType.Snare) &&
!target.HasBuffOfType(BuffType.Knockup) && !target.HasBuff("Recall") &&
!target.HasBuffOfType(BuffType.Knockback)
&& !target.HasBuffOfType(BuffType.Charm) && !target.HasBuffOfType(BuffType.Taunt) &&
!target.HasBuffOfType(BuffType.Suppression) && (!target.Spellbook.IsCharging
|| target.IsMoving) &&
!target.HasBuff("zhonyasringshield") && !target.HasBuff("bardrstasis");
}
internal static bool IsUnKillable(this AIHeroClient target)
{
if (target == null || target.IsDead || target.Health <= 0)
{
return true;
}
if (target.HasBuff("KindredRNoDeathBuff"))
{
return true;
}
if (target.HasBuff("UndyingRage") && target.GetBuff("UndyingRage").EndTime - Game.Time > 0.3 && target.Health <= target.MaxHealth * 0.10f)
{
return true;
}
if (target.HasBuff("JudicatorIntervention"))
{
return true;
}
if (target.HasBuff("ChronoShift") && target.GetBuff("ChronoShift").EndTime - Game.Time > 0.3 && target.Health <= target.MaxHealth * 0.10f)
{
return true;
}
if (target.HasBuff("VladimirSanguinePool"))
{
return true;
}
if (target.HasBuff("ShroudofDarkness"))
{
return true;
}
if (target.HasBuff("SivirShield"))
{
return true;
}
if (target.HasBuff("itemmagekillerveil"))
{
return true;
}
return target.HasBuff("FioraW");
}
internal static bool IsValidRange(this AttackableUnit unit, float range = float.MaxValue, bool checkTeam = true, Vector3 from = new Vector3())
{
if (unit == null || !unit.IsValid || !unit.IsVisible || unit.IsDead || !unit.IsTargetable
|| unit.IsInvulnerable)
{
return false;
}
if (checkTeam && unit.Team == Player.Instance.Team)
{
return false;
}
if (unit.Name == "WardCorpse")
{
return false;
}
var @base = unit as Obj_AI_Base;
return !(range < float.MaxValue)
|| !(Vector2.DistanceSquared(
(from.To2D().IsValid() ? from : Player.Instance.ServerPosition).To2D(),
(@base?.ServerPosition ?? unit.Position).To2D()) > range * range);
}
}
}
<file_sep>/MoonRiven/MoonRiven/Program.cs
namespace MoonRiven_2
{
using EloBuddy;
using EloBuddy.SDK.Events;
using System;
internal class Program
{
private static void Main(string[] Args)
{
Loading.OnLoadingComplete += OnLoadingComplete;
}
private static void OnLoadingComplete(EventArgs Args)
{
if (Player.Instance.Hero != Champion.Riven)
{
return;
}
Riven.Init();
}
}
}
<file_sep>/MoonRiven/MoonRiven/Mode/Flee.cs
namespace MoonRiven_2.Mode
{
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Events;
using myCommon;
using System.Linq;
internal class Flee : Logic
{
internal static void InitTick()
{
if (MenuInit.FleeW && W.IsReady() && EntityManager.Heroes.Enemies.Any(x => x.IsValidRange(W.Range) && !HaveShield(x)))
{
Player.Instance.Spellbook.CastSpell(SpellSlot.W);
}
if (MenuInit.FleeQ && Q.IsReady() && !Player.Instance.IsDashing())
{
Player.Instance.Spellbook.CastSpell(SpellSlot.Q, Player.Instance.Position.Extend(Game.CursorPos, 350f).To3D());
}
if (MenuInit.FleeE && E.IsReady() && ((!Q.IsReady() && qStack == 0) || qStack == 2))
{
Player.Instance.Spellbook.CastSpell(SpellSlot.E, Player.Instance.Position.Extend(Game.CursorPos, E.Range).To3D());
}
}
}
}
<file_sep>/MoonRiven/MoonRiven/Logic.cs
namespace MoonRiven_2
{
using myCommon;
using System;
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Menu;
internal class Logic
{
//Spell
internal static Spell.Skillshot Q { get; set; }
internal static Spell.Active W { get; set; }
internal static Spell.Skillshot E { get; set; }
internal static Spell.Active R { get; set; }
internal static Spell.Skillshot R1 { get; set; }
internal static SpellSlot Flash { get; set; } = SpellSlot.Unknown;
internal static SpellSlot Ignite { get; set; } = SpellSlot.Unknown;
//Menu
internal static Menu mainMenu { get; set; }
internal static Menu miscMenu { get; set; }
internal static Menu comboMenu { get; set; }
internal static Menu burstMenu { get; set; }
internal static Menu harassMenu { get; set; }
internal static Menu clearMenu { get; set; }
internal static Menu fleeMenu { get; set; }
internal static Menu killStealMenu { get; set; }
internal static Menu qMenu { get; set; }
internal static Menu wMenu { get; set; }
internal static Menu eMenu { get; set; }
internal static Menu rMenu { get; set; }
internal static Menu drawMenu { get; set; }
//Orbwalker
internal static bool isComboMode => Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.Combo);
internal static bool isHarassMode => Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.Harass);
internal static bool isLaneClearMode => Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.LaneClear);
internal static bool isJungleClearMode => Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.JungleClear);
internal static bool isFleeMode => Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.Flee);
internal static bool isNoneMode => Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.None);
//Status
internal static int qStack { get; set; } = 0;
internal static int lastQTime { get; set; } = 0;
internal static int lastCastTime { get; set; } = 0;
internal static bool isRActive => Player.GetSpell(SpellSlot.R).Name == "RivenIzunaBlade";
//Tick Count
internal static int TickCount => Environment.TickCount & int.MaxValue;
internal static int GameTimeTickCount => (int)(Game.Time * 1000f);
//myTarget
internal static AIHeroClient myTarget { get; set; } = null;
//Logic
internal static bool UseItem()
{
if (Item.HasItem(3077) && Item.CanUseItem(3077))
{
return Item.UseItem(3077);
}
if (Item.HasItem(3074) && Item.CanUseItem(3074))
{
return Item.UseItem(3074);
}
if (Item.HasItem(3053) && Item.CanUseItem(3053))
{
return Item.UseItem(3053);
}
return false;
}
internal static bool HaveShield(Obj_AI_Base target)
{
if (target.HasBuff("SivirE"))
{
return true;
}
if (target.HasBuff("BlackShield"))
{
return true;
}
if (target.HasBuff("NocturneShit"))
{
return true;
}
return false;
}
internal static bool CastQ(Obj_AI_Base target)
{
if (target == null || target.IsDead || !target.IsValidRange() || Q.Level == 0 || !Q.IsReady())
{
return false;
}
switch (MenuInit.QMode)
{
case 0:
return Player.Instance.Spellbook.CastSpell(SpellSlot.Q, target.Position);
case 1:
return Player.Instance.Spellbook.CastSpell(SpellSlot.Q, Game.CursorPos);
default:
return false;
}
}
internal static bool R1Logic(AIHeroClient target)
{
if (!target.IsValidRange(500) || R.Name != "RivenFengShuiEngine" || !MenuInit.ComboR1)
{
return false;
}
return R.Cast();
}
internal static bool R2Logic(AIHeroClient target)
{
if (!target.IsValidRange() || R.Name == "RivenFengShuiEngine" || MenuInit.ComboR2 == 3)
{
return false;
}
switch (MenuInit.ComboR2)
{
case 0:
if (target.HealthPercent < 20 ||
(target.Health > DamageCalculate.GetRDamage(target) + Player.Instance.GetAutoAttackDamage(target) * 2 &&
target.HealthPercent < 40) ||
(target.Health <= DamageCalculate.GetRDamage(target)) ||
(target.Health <= DamageCalculate.GetComboDamage(target)))
{
return R1.Cast(target.Position);
}
break;
case 1:
if (DamageCalculate.GetRDamage(target) > target.Health && target.DistanceToPlayer() < 600)
{
return R1.Cast(target.Position);
}
break;
case 2:
if (target.DistanceToPlayer() < 600)
{
return R1.Cast(target.Position);
}
break;
}
return false;
}
}
}
<file_sep>/MoonLucian/MoonLucian/Lucian.cs
namespace MoonLucian
{
using myCommon;
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Events;
using EloBuddy.SDK.Rendering;
using EloBuddy.SDK.Menu.Values;
using EloBuddy.SDK.Enumerations;
using SharpDX;
using System;
using System.Linq;
internal class Lucian : Logic
{
internal static void Init()
{
//Draw the Chat
Chat.Print("Moon" + Player.Instance.ChampionName + ": Load! Credit: NightMoon", System.Drawing.Color.LightSteelBlue);
//Init Lucian SkillSlot
Q = new Spell.Targeted(SpellSlot.Q, 650, DamageType.Physical);
QExtend = new Spell.Skillshot(SpellSlot.Q, 900, SkillShotType.Linear, 350, int.MaxValue, 25, DamageType.Physical);
W = new Spell.Skillshot(SpellSlot.W, 1000, SkillShotType.Linear, 300, 1600, 80, DamageType.Magical);
E = new Spell.Skillshot(SpellSlot.E, 425, SkillShotType.Linear);
R = new Spell.Skillshot(SpellSlot.R, 1200, SkillShotType.Linear, 100, 2500, 110, DamageType.Physical);
R1 = new Spell.Skillshot(SpellSlot.R, 1200, SkillShotType.Linear, 100, 2500, 110, DamageType.Physical);
QExtend.HaveCollsion(false);
W.HaveCollsion(true);
R.HaveCollsion(true);
R1.HaveCollsion(false);
//Init Youmuu
Youmuus = new Item(ItemId.Youmuus_Ghostblade);
//Init Lucian Menu
MenuInit.Init();
//Init Lucian Events
Game.OnUpdate += OnTick;
Obj_AI_Base.OnPlayAnimation += OnPlayAnimation;
Spellbook.OnCastSpell += OnCastSpell;
Obj_AI_Base.OnProcessSpellCast += OnProcessSpellCast;
Orbwalker.OnPostAttack += OnPostAttack;
Gapcloser.OnGapcloser += OnGapcloser;
Drawing.OnDraw += OnDraw;
}
private static void OnTick(EventArgs Args)
{
if (Player.Instance.IsDead || Player.Instance.IsRecalling())
{
havePassive = false;
return;
}
if (TickCount - lastCastTime >= 3100)
{
havePassive = false;
}
SetSpellMana();
if (Player.Instance.HasBuff("LucianR"))
{
Player.IssueOrder(GameObjectOrder.MoveTo, Game.CursorPos);
return;
}
if (Player.Instance.HasBuff("LucianR") || Player.Instance.IsDashing())
{
return;
}
if (isComboMode)
{
Combo();
}
if (isHarassMode)
{
Harass();
}
if (isFarmMode)
{
Farm();
}
if (R.Level > 0 && R.IsReady() && Player.Instance.Mana > RMana + QMana + WMana + EMana)
{
RLogic();
}
KillSteal();
}
private static void SetSpellMana()
{
if (Q.Level == 0 || !Q.IsReady() || PlayerMana < Q.ManaCost)
{
QMana = 0;
}
else
{
QMana = Q.ManaCost;
}
if (W.Level == 0 || !W.IsReady() || PlayerMana < W.ManaCost)
{
WMana = 0;
}
else
{
WMana = W.ManaCost;
}
if (E.Level == 0 || !E.IsReady() || PlayerMana < E.ManaCost)
{
EMana = 0;
}
else
{
EMana = E.ManaCost;
}
if (R.Level == 0 || !R.IsReady() || PlayerMana < R.ManaCost || Player.Instance.HealthPercent <= 25)
{
RMana = 0;
}
else
{
RMana = R.ManaCost;
}
}
private static void RLogic()
{
if (MenuInit.SemiR)
{
SemiRLogic();
}
}
private static void SemiRLogic()
{
var select = TargetSelector.SelectedTarget;
var target = TargetSelector.GetTarget(R.Range, DamageType.Physical);
if (select != null && select.IsValidTarget(R.Range))
{
R1.Cast(select);
return;
}
if (select == null && target != null && !target.HaveShiled() && target.IsValidTarget(R.Range))
{
R1.Cast(target);
}
}
private static void KillSteal()
{
if (MenuInit.KillStealQ && Q.IsReady() && PlayerMana > QMana + EMana)
{
foreach (var target in EntityManager.Heroes.Enemies
.Where(x => x.IsValidTarget(QExtend.Range) && !x.IsUnKillable() && x.Health < DamageCalculate.GetQDamage(x)))
{
QLogic(target);
return;
}
}
if (MenuInit.KillStealW && W.IsReady() && PlayerMana > WMana + QMana + EMana)
{
foreach (var target in EntityManager.Heroes.Enemies
.Where(x => x.IsValidTarget(W.Range) && !x.IsUnKillable() && x.Health < DamageCalculate.GetWDamage(x)))
{
if (target.IsValidTarget(W.Range))
{
W.PredCast(target, false);
return;
}
}
}
}
private static void Combo()
{
if (MenuInit.ComboEDash && E.IsReady())
{
var target = TargetSelector.GetTarget(Player.Instance.GetAutoAttackRange() + E.Range, DamageType.Physical);
if (target.IsValidTarget(Player.Instance.GetAutoAttackRange() + E.Range) &&
!target.IsValidTarget(Player.Instance.GetAutoAttackRange()))
{
ELogic(target, 0);
}
}
if (MenuInit.ComboQExtend && QExtend.IsReady() && !Player.Instance.IsDashing() && !havePassive && !havePassiveBuff)
{
var target = TargetSelector.GetTarget(QExtend.Range, DamageType.Physical);
if (target.IsValidTarget(QExtend.Range) && !target.IsValidTarget(Q.Range))
{
QLogic(target);
}
}
if (MenuInit.ComboR && R.IsReady())
{
var target = TargetSelector.GetTarget(R.Range, DamageType.Physical);
if (target.IsValidTarget(R.Range) && !target.IsUnKillable() && !Player.Instance.IsUnderEnemyturret() &&
!target.IsValidTarget(Player.Instance.GetAutoAttackRange()))
{
if (EntityManager.Heroes.Enemies.Any(x => x.NetworkId != target.NetworkId && x.Distance(target) <= 550))
{
return;
}
var rAmmo = new float[] { 20, 25, 30 }[Player.Instance.Spellbook.GetSpell(SpellSlot.R).Level - 1];
var rDMG = DamageCalculate.GetRDamage(target) * rAmmo;
if (target.Health + target.HPRegenRate * 3 < rDMG)
{
if (target.DistanceToPlayer() <= 800 && target.Health < rDMG * 0.6)
{
R.Cast(target);
return;
}
if (target.DistanceToPlayer() <= 1000 && target.Health < rDMG * 0.4)
{
R.Cast(target);
}
}
}
}
}
private static void Harass()
{
if (ManaManager.HasEnoughMana(MenuInit.HarassMP))
{
if (MenuInit.HarassQ && Q.IsReady())
{
foreach(var target in EntityManager.Heroes.Enemies.Where(x => x.IsValidTarget(QExtend.Range) &&
harassMenu["Harasstarget" + x.ChampionName.ToLower()].Cast<CheckBox>().CurrentValue))
{
if (target.IsValidTarget(QExtend.Range))
{
QLogic(target, MenuInit.HarassQExtend);
return;
}
}
}
if (MenuInit.HarassW && W.IsReady())
{
foreach (var target in EntityManager.Heroes.Enemies.Where(x => x.IsValidTarget(W.Range) &&
harassMenu["Harasstarget" + x.ChampionName.ToLower()].Cast<CheckBox>().CurrentValue))
{
if (target.IsValidTarget(W.Range))
{
W.PredCast(target, false);
return;
}
}
}
}
}
private static void Farm()
{
var range = MenuInit.HarassQExtend && QExtend.IsReady()
? QExtend.Range
: MenuInit.HarassW && W.IsReady() ? W.Range : MenuInit.HarassQ && Q.IsReady() ? Q.Range : 0;
if (ManaManager.SpellHarass && ManaManager.HasEnoughMana(MenuInit.HarassMP) && range > 0 &&
Player.Instance.CountEnemyChampionsInRange(range) > 0)
{
Harass();
}
else if (ManaManager.SpellFarm)
{
if (isLaneClearMode && ManaManager.HasEnoughMana(MenuInit.LaneClearMP))
{
LaneClear();
}
}
}
private static void LaneClear()
{
if (TickCount - lastCastTime < 600 || havePassiveBuff)
{
return;
}
if (MenuInit.LaneClearQ && Q.IsReady())
{
var minions =
EntityManager.MinionsAndMonsters.GetLaneMinions(EntityManager.UnitTeam.Enemy,
Player.Instance.Position, Q.Range).ToList();
if (minions.Any())
{
var minion = minions.FirstOrDefault();
var qExminions =
EntityManager.MinionsAndMonsters.GetLaneMinions(EntityManager.UnitTeam.Enemy,
Player.Instance.Position, QExtend.Range).ToList();
if (minion != null && QExtend.CountHits(qExminions, Player.Instance.Extend(minion.Position, 900)) >= 2)
{
Q.Cast(minion);
return;
}
}
}
if (MenuInit.LaneClearW && W.IsReady())
{
var minions =
EntityManager.MinionsAndMonsters.GetLaneMinions(EntityManager.UnitTeam.Enemy,
Player.Instance.Position, W.Range).ToList();
if (minions.Count > 2)
{
var pred = W.GetBestCircularCastPosition(minions);
W.Cast(pred.CastPosition);
}
}
}
private static void OnPlayAnimation(Obj_AI_Base sender, GameObjectPlayAnimationEventArgs Args)
{
if (!sender.IsMe || Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.None))
{
return;
}
if (Args.Animation == "Spell1" || Args.Animation == "Spell2")
{
Player.IssueOrder(GameObjectOrder.MoveTo, Game.CursorPos);
}
}
private static void OnCastSpell(Spellbook sender, SpellbookCastSpellEventArgs Args)
{
if (Args.Slot == SpellSlot.Q || Args.Slot == SpellSlot.W || Args.Slot == SpellSlot.E)
{
havePassive = true;
lastCastTime = TickCount;
}
if (Args.Slot == SpellSlot.E && !Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.None))
{
Orbwalker.ResetAutoAttack();
}
if (Args.Slot == SpellSlot.R && Youmuus.IsOwned() && Youmuus.IsReady())
{
Youmuus.Cast();
}
}
private static void OnProcessSpellCast(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs Args)
{
if (MenuInit.EnabledAntiMelee && E.IsReady() && Player.Instance.HealthPercent <= MenuInit.AntiMeleeHp)
{
if (sender != null && sender.IsEnemy && Args.Target != null && Args.Target.IsMe)
{
if (sender.Type == Player.Instance.Type && sender.IsMelee)
{
E.Cast(Player.Instance.Extend(sender.Position, -E.Range));
}
}
}
if (sender != null && sender.IsMe)
{
if (Args.Slot == SpellSlot.Q || Args.Slot == SpellSlot.W || Args.Slot == SpellSlot.E)
{
havePassive = true;
lastCastTime = TickCount;
}
}
}
private static void OnPostAttack(AttackableUnit target, EventArgs Args)
{
havePassive = false;
if (target == null || target.IsDead || target.Health <= 0)
{
return;
}
if (isComboMode && target.Type == GameObjectType.AIHeroClient)
{
if (Youmuus.IsOwned() && Youmuus.IsReady())
{
Youmuus.Cast();
}
AfterAACombo(target as AIHeroClient);
}
if (isLaneClearMode && ManaManager.SpellFarm && ManaManager.HasEnoughMana(MenuInit.TurretClearMP) &&
(target.Type == GameObjectType.obj_AI_Turret ||
target.Type == GameObjectType.obj_Turret || target.Type == GameObjectType.obj_HQ ||
target.Type == GameObjectType.obj_BarracksDampener))
{
AfterAALane(target);
}
if (isJungleClearMode && ManaManager.SpellFarm && target.Type == GameObjectType.obj_AI_Minion &&
ManaManager.HasEnoughMana(MenuInit.JungleClearMP))
{
AfterAAJungle();
}
}
private static void AfterAACombo(AIHeroClient target)
{
if (target == null || target.IsDead || target.IsUnKillable() || !target.IsValidTarget() || target.Health <= 0)
{
return;
}
if (MenuInit.ComboEReset && E.IsReady())
{
ELogic(target, 1);
}
else if (MenuInit.ComboQ && Q.IsReady() && target.IsValidTarget(Q.Range))
{
Q.Cast(target);
}
else if (MenuInit.ComboW && W.IsReady() && target.IsValidTarget(W.Range))
{
if (MenuInit.ComboWFast)
{
W.Cast(target.Position);
}
else
{
W.PredCast(target);
}
}
}
private static void AfterAALane(AttackableUnit target)
{
if (target.Type != GameObjectType.obj_AI_Turret && target.Type != GameObjectType.obj_Turret &&
target.Type != GameObjectType.obj_HQ && target.Type != GameObjectType.obj_BarracksDampener)
{
return;
}
if (MenuInit.TurretClearE && E.IsReady())
{
E.Cast(Player.Instance.Extend(Game.CursorPos, 130));
}
else if (MenuInit.TurretClearW && W.IsReady())
{
W.Cast(Game.CursorPos);
}
}
private static void AfterAAJungle()
{
var mobs = EntityManager.MinionsAndMonsters.GetJungleMonsters(Player.Instance.Position, Q.Range).ToList();
if (mobs.Any())
{
if (MenuInit.JungleClearE && E.IsReady())
{
E.Cast(Player.Instance.Extend(Game.CursorPos, 130));
}
else if (MenuInit.JungleClearQ && Q.IsReady())
{
Q.Cast(mobs.FirstOrDefault());
}
else if (MenuInit.JungleClearW && W.IsReady())
{
W.Cast(mobs.FirstOrDefault());
}
}
}
private static void OnGapcloser(AIHeroClient sender, Gapcloser.GapcloserEventArgs Args)
{
if (!MenuInit.EnabledAnti || !E.IsReady() || PlayerMana < EMana ||
Player.Instance.HealthPercent > MenuInit.AntiGapCloserHp || sender == null || !sender.IsEnemy)
{
return;
}
if (miscMenu.GetBool("AntiGapCloserE" + sender.ChampionName.ToLower()))
{
if (Args.Target.IsMe || sender.DistanceToPlayer() <= 300 || Args.End.DistanceToPlayer() <= 250)
{
E.Cast(Player.Instance.Extend(sender.Position, -E.Range));
}
}
}
private static void OnDraw(EventArgs Args)
{
if (!Player.Instance.IsDead && !MenuGUI.IsChatOpen && !Chat.IsOpen)
{
if (MenuInit.DrawQ && Q.IsReady())
{
Circle.Draw(Color.Blue, Q.Range, Player.Instance);
}
if (MenuInit.DrawQExtend && QExtend.IsReady())
{
Circle.Draw(Color.Blue, QExtend.Range, Player.Instance);
}
if (MenuInit.DrawW && W.IsReady())
{
Circle.Draw(Color.Yellow, W.Range, Player.Instance);
}
if (MenuInit.DrawE && E.IsReady())
{
Circle.Draw(Color.Red, E.Range, Player.Instance);
}
if (MenuInit.DrawR && R.IsReady())
{
Circle.Draw(Color.Blue, R.Range, Player.Instance);
}
}
}
private static void QLogic(AIHeroClient target, bool useExtendQ = true)
{
if (!Q.IsReady() || target == null || target.IsDead || target.IsUnKillable())
{
return;
}
if (target.IsValidTarget(Q.Range))
{
Q.Cast(target);
}
else if (target.IsValidTarget(QExtend.Range) && useExtendQ)
{
var collisions = EntityManager.MinionsAndMonsters.EnemyMinions.Where(x => x.IsValidTarget(Q.Range)).ToList();
if (!collisions.Any())
{
return;
}
foreach (var minion in collisions)
{
var qPred = QExtend.GetPrediction(target);
var qPloygon = new Geometry.Polygon.Rectangle(Player.Instance.Position, Player.Instance.Position.Extend(minion.Position, QExtend.Range).To3D(), QExtend.Width);
if (qPloygon.IsInside(qPred.UnitPosition.To2D()))
{
Q.Cast(minion);
break;
}
}
}
}
private static void ELogic(AIHeroClient target, int count)
{
if (!E.IsReady() || target == null || target.IsDead || target.IsUnKillable())
{
return;
}
switch(count)
{
case 0:
{
if (target.DistanceToPlayer() <= Player.Instance.GetAutoAttackRange(target) ||
target.DistanceToPlayer () > Player.Instance.GetAutoAttackRange(target) + E.Range)
{
return;
}
var dashPos = Player.Instance.Extend(Game.CursorPos, E.Range);
if ((NavMesh.GetCollisionFlags(dashPos).HasFlag(CollisionFlags.Wall) ||
NavMesh.GetCollisionFlags(dashPos).HasFlag(CollisionFlags.Building)) &&
MenuInit.ComboEWall)
{
return;
}
if (dashPos.CountEnemyChampionsInRange(500) >= 3 && dashPos.CountAllyChampionsInRange(400) < 3 &&
MenuInit.ComboESafe)
{
return;
}
if (Player.Instance.DistanceToMouse() > Player.Instance.GetAutoAttackRange() &&
target.Distance(dashPos) < Player.Instance.GetAutoAttackRange())
{
E.Cast(dashPos);
}
}
break;
case 1:
{
var dashRange = comboMenu["ComboEShort"].Cast<CheckBox>().CurrentValue
? (Player.Instance.DistanceToMouse() > Player.Instance.GetAutoAttackRange() ? E.Range : 130)
: E.Range;
var dashPos = Player.Instance.Extend(Game.CursorPos, dashRange);
if ((NavMesh.GetCollisionFlags(dashPos).HasFlag(CollisionFlags.Wall) ||
NavMesh.GetCollisionFlags(dashPos).HasFlag(CollisionFlags.Building)) &&
MenuInit.ComboEWall)
{
return;
}
if (dashPos.CountEnemyChampionsInRange(500) >= 3 && dashPos.CountAllyChampionsInRange(400) < 3 &&
MenuInit.ComboESafe)
{
return;
}
E.Cast(dashPos);
}
break;
}
}
}
}<file_sep>/aiRTako_SmiteHelper/aiRTako_SmiteHelper/Program.cs
namespace aiRTako_SmiteHelper
{
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Events;
using EloBuddy.SDK.Menu;
using EloBuddy.SDK.Menu.Values;
using EloBuddy.SDK.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
internal class Program
{
private static Menu Menu;
private static Menu ObjectMenu;
private static Menu SettingMenu;
private static Menu DrawMenu;
private static SpellSlot Smite = SpellSlot.Unknown;
private const float SmiteRange = 600f;
private static readonly Dictionary<string, string> SmiteObjects =
new Dictionary<string, string>
{
{ "Baron Nashor", "SRU_Baron" },
{ "Blue Sentinel", "SRU_Blue" },
{ "Water Dragon", "SRU_Dragon_Water" },
{ "Fire Dragon", "SRU_Dragon_Fire" },
{ "Earth Dragon", "SRU_Dragon_Earth" },
{ "Air Dragon", "SRU_Dragon_Air" },
{ "Elder Dragon", "SRU_Dragon_Elder" },
{ "Red Brambleback", "SRU_Red" },
{ "Rift Herald", "SRU_RiftHerald" },
{ "Crimson Raptor", "SRU_Razorbeak" },
{ "Greater Murk Wolf", "SRU_Murkwolf" },
{ "Gromp", "SRU_Gromp" },
{ "Rift Scuttler", "Sru_Crab" },
{ "Ancient Krug", "SRU_Krug" }
};
private static void Main(string[] args)
{
Loading.OnLoadingComplete += Loading_OnLoadingComplete;
}
private static void Loading_OnLoadingComplete(EventArgs eventArgs)
{
var slot = Player.Instance.Spellbook.Spells.FirstOrDefault(x => x.Name.ToLower().Contains("smite"));
if (slot != null)
Smite = slot.Slot;
if (Smite == SpellSlot.Unknown)
{
Chat.Print("aiRTako SmiteHelper: You Dont Have Smite Slot. Loading Finish", System.Drawing.Color.Orange);
return;
}
if (Game.MapId != GameMapId.SummonersRift)
{
Chat.Print("aiRTako SmiteHelper: Not Support this Map!", System.Drawing.Color.Orange);
return;
}
Chat.Print("aiRTako SmiteHelper: Welcome to Use my Addon. Loading Successful", System.Drawing.Color.Orange);
Menu = MainMenu.AddMenu("aiRTako SmiteHelper", "aiRTako SmiteHelper");
ObjectMenu = Menu.AddSubMenu("Smite Target", "Smite Target");
{
foreach (var item in SmiteObjects)
{
ObjectMenu.Add($"{item.Value}", new CheckBox($"{item.Key}"));
}
}
SettingMenu = Menu.AddSubMenu("Smite Setting", "Smite Setting");
{
SettingMenu.AddLabel("Global Settings");
SettingMenu.Add("Enabled", new KeyBind("Enbaled", true, KeyBind.BindTypes.PressToggle, 'M'));
SettingMenu.AddSeparator();
SettingMenu.AddLabel("Combo Settings");
SettingMenu.Add("Combo", new CheckBox("Enbaled in Combo Mode"));
SettingMenu.Add("ComboSave", new CheckBox("Save 1 Ammo"));
SettingMenu.Add("ComboKey", new KeyBind("ComboKey", false, KeyBind.BindTypes.HoldActive, 32));
SettingMenu.AddSeparator();
SettingMenu.AddLabel("KillSteal Settings");
SettingMenu.Add("KillSteal", new CheckBox("Enbaled in KillSteal"));
}
DrawMenu = Menu.AddSubMenu("Smite Draw", "Smite Draw");
{
DrawMenu.Add("DrawStatus", new CheckBox("Draw Smite Status"));
DrawMenu.Add("DrawRange", new CheckBox("Draw Smite Range", false));
}
Game.OnUpdate += Game_OnUpdate;
Drawing.OnDraw += Drawing_OnDraw;
}
private static void Game_OnUpdate(EventArgs eventArgs)
{
if (Player.Instance.IsDead || Player.Instance.IsRecalling())
return;
if (!SettingMenu["Enabled"].Cast<KeyBind>().CurrentValue)
return;
if (!Player.GetSpell(Smite).IsReady)
return;
Jungle();
if (SettingMenu["Combo"].Cast<CheckBox>().CurrentValue &&
SettingMenu["ComboKey"].Cast<KeyBind>().CurrentValue)
Combo();
if (SettingMenu["KillSteal"].Cast<CheckBox>().CurrentValue)
KillSteal();
}
private static void Jungle()
{
if (!Player.GetSpell(Smite).IsReady)
return;
var mobs =
ObjectManager.Get<Obj_AI_Minion>()
.Where(
x =>
x != null && x.IsMonster && x.Distance(Player.Instance) <= 900 &&
!x.Name.ToLower().Contains("mini") && !x.Name.ToLower().Contains("respawn") &&
!x.Name.ToLower().Contains("plant"))
.OrderBy(x => x.MaxHealth);
foreach (var mob in mobs)
{
if (mob.Distance(Player.Instance) > SmiteRange)
continue;
if (ObjectMenu[mob.CharData.BaseSkinName] != null &&
ObjectMenu[mob.CharData.BaseSkinName].Cast<CheckBox>().CurrentValue &&
mob.Health <= Player.Instance.GetSummonerSpellDamage(mob, DamageLibrary.SummonerSpells.Smite) &&
mob.Distance(Player.Instance) <= SmiteRange)
{
Player.Instance.Spellbook.CastSpell(Smite, mob);
return;
}
}
}
private static void Combo()
{
if (!Player.GetSpell(Smite).IsReady)
return;
if (
!Player.GetSpell(Smite)
.Name.Equals("s5_summonersmiteplayerganker", StringComparison.InvariantCultureIgnoreCase) ||
!Player.GetSpell(Smite)
.Name.Equals("s5_summonersmiteduel", StringComparison.InvariantCultureIgnoreCase))
return;
if (SettingMenu["ComboSave"].Cast<CheckBox>().CurrentValue && Player.GetSpell(Smite).Ammo <= 1)
return;
var target = TargetSelector.GetTarget(SmiteRange, DamageType.True);
if (target != null && target.IsValidTarget(SmiteRange))
{
Player.Instance.Spellbook.CastSpell(Smite, target);
}
}
private static void KillSteal()
{
if (!Player.GetSpell(Smite).IsReady)
return;
if (!Player.GetSpell(Smite)
.Name.Equals("s5_summonersmiteplayerganker", StringComparison.InvariantCultureIgnoreCase))
return;
var target =
EntityManager.Heroes.Enemies.FirstOrDefault(
x =>
x.IsValidTarget(SmiteRange) &&
x.Health <= Player.Instance.GetSummonerSpellDamage(x, DamageLibrary.SummonerSpells.Smite) &&
!IsUnKillable(x));
if (target != null && target.IsValidTarget(SmiteRange))
{
Player.Instance.Spellbook.CastSpell(Smite, target);
}
}
private static void Drawing_OnDraw(EventArgs eventArgs)
{
if (Player.Instance.IsDead)
return;
if (DrawMenu["DrawStatus"].Cast<CheckBox>().CurrentValue)
{
var MePos = Drawing.WorldToScreen(Player.Instance.Position);
string str;
if (SettingMenu["Enabled"].Cast<KeyBind>().CurrentValue)
{
str = !Player.GetSpell(Smite).IsReady ? "Not Ready" : "On";
}
else
{
str = "Off";
}
Drawing.DrawText(MePos[0] - 68, MePos[1] + 68, System.Drawing.Color.FromArgb(242, 120, 34),
"Smite Status:" + str);
}
if (DrawMenu["DrawRange"].Cast<CheckBox>().CurrentValue)
{
Circle.Draw(Player.GetSpell(Smite).IsReady ? SharpDX.Color.Green : SharpDX.Color.Red, SmiteRange,
Player.Instance);
}
}
private static bool IsUnKillable(AIHeroClient target)
{
if (target == null || target.IsDead || target.Health <= 0)
{
return true;
}
if (target.HasBuff("KindredRNoDeathBuff"))
{
return true;
}
if (target.HasBuff("UndyingRage") && target.GetBuff("UndyingRage").EndTime - Game.Time > 0.3 && target.Health <= target.MaxHealth * 0.10f)
{
return true;
}
if (target.HasBuff("JudicatorIntervention"))
{
return true;
}
if (target.HasBuff("ChronoShift") && target.GetBuff("ChronoShift").EndTime - Game.Time > 0.3 && target.Health <= target.MaxHealth * 0.10f)
{
return true;
}
if (target.HasBuff("VladimirSanguinePool"))
{
return true;
}
if (target.HasBuff("ShroudofDarkness"))
{
return true;
}
if (target.HasBuff("SivirShield"))
{
return true;
}
if (target.HasBuff("itemmagekillerveil"))
{
return true;
}
return target.HasBuff("FioraW");
}
}
}
<file_sep>/MoonRiven/MoonRiven/Mode/JungleClear.cs
namespace MoonRiven_2.Mode
{
using myCommon;
using EloBuddy;
using EloBuddy.SDK;
using System.Linq;
internal class JungleClear : Logic
{
internal static void InitTick()
{
if (!MenuInit.JungleClearE || !E.IsReady())
return;
var mobs =
EntityManager.MinionsAndMonsters.GetJungleMonsters(Player.Instance.Position,
E.Range + Player.Instance.GetAutoAttackRange()).ToList();
if (mobs.Any())
{
if (!Q.IsReady() && qStack == 0 && !W.IsReady())
{
Player.Instance.Spellbook.CastSpell(SpellSlot.E, Game.CursorPos);
}
if (!mobs.Any(x => x.DistanceToPlayer() <= E.Range))
{
var mob = mobs.FirstOrDefault();
if (mob != null)
{
Player.Instance.Spellbook.CastSpell(SpellSlot.E, mob.Position);
}
}
}
}
internal static void InitAfterAttack(AttackableUnit tar)
{
var mobs =
EntityManager.MinionsAndMonsters.GetJungleMonsters(Player.Instance.Position,
E.Range + Player.Instance.GetAutoAttackRange()).ToList();
if (!mobs.Any())
return;
var target = tar as Obj_AI_Minion;
if (target != null && target.IsValidRange(400) && target.Health > Player.Instance.GetAutoAttackDamage(target, true) &&
!target.Name.Contains("Plant"))
{
if (MenuInit.JungleClearItem)
{
UseItem();
}
if (MenuInit.JungleClearQ && Q.IsReady() && target.IsValidRange(400) && CastQ(target))
{
return;
}
if (MenuInit.JungleClearW && W.IsReady() && target.IsValidRange(W.Range) &&
Player.Instance.Spellbook.CastSpell(SpellSlot.W))
{
return;
}
if (MenuInit.JungleClearE && E.IsReady() && target.IsValidRange(400))
{
Player.Instance.Spellbook.CastSpell(SpellSlot.E, Game.CursorPos);
}
}
}
}
}
<file_sep>/MoonRiven/MoonRiven/Mode/Combo.cs
using System.Linq;
namespace MoonRiven_2.Mode
{
using myCommon;
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Events;
using System;
internal class Combo : Logic
{
internal static void InitTick()
{
var target = TargetSelector.GetTarget(EntityManager.Heroes.Enemies.Where(x => x.IsValidRange(800f)), DamageType.Physical);
if (target != null && target.IsValidRange(800f))
{
if (MenuInit.ComboDot && Ignite != SpellSlot.Unknown &&
Player.Instance.Spellbook.GetSpell(Ignite).IsReady &&
target.IsValidRange(600) &&
((target.Health < DamageCalculate.GetComboDamage(target) && target.IsValidRange(400)) ||
target.Health < DamageCalculate.GetIgniteDmage(target)) &&
Player.Instance.Spellbook.CastSpell(Ignite, target))
{
return;
}
if (MenuInit.ComboYoumuu && Item.HasItem(3142) && Item.CanUseItem(3142) &&
target.IsValidRange(580) && Item.UseItem(3142))
{
return;
}
if (MenuInit.ComboR1 && R.IsReady() && !isRActive &&
target.Health <= DamageCalculate.GetComboDamage(target)*1.3 && target.IsValidRange(600f) &&
R1Logic(target))
{
return;
}
if (MenuInit.ComboR2 != 3 && R.IsReady() && isRActive && R2Logic(target))
{
return;
}
if (MenuInit.ComboQGap && Q.IsReady() && Environment.TickCount - lastQTime > 1200 &&
!Player.Instance.IsDashing() && target.IsValidRange(480) &&
target.DistanceToPlayer() >
Player.Instance.GetAutoAttackRange() + Player.Instance.BoundingRadius + 50 &&
Prediction.Position.PredictUnitPosition(target, 1).DistanceToPlayer() >
Player.Instance.GetAutoAttackRange() + 50)
{
CastQ(target);
return;
}
if (MenuInit.ComboEGap && E.IsReady() && target.IsValidRange(600) &&
target.DistanceToPlayer() >
Player.Instance.GetAutoAttackRange() + Player.Instance.BoundingRadius + 50)
{
Player.Instance.Spellbook.CastSpell(SpellSlot.E, target.Position);
return;
}
if (MenuInit.ComboWLogic && W.IsReady() && target.IsValidRange(W.Range))
{
if (qStack == 0 && Player.Instance.Spellbook.CastSpell(SpellSlot.W))
{
return;
}
if (Q.IsReady() && qStack > 1 && Player.Instance.Spellbook.CastSpell(SpellSlot.W))
{
return;
}
if (Player.Instance.HasBuff("RivenFeint") && Player.Instance.Spellbook.CastSpell(SpellSlot.W))
{
return;
}
if (!target.IsFacing(Player.Instance))
{
Player.Instance.Spellbook.CastSpell(SpellSlot.W);
}
}
}
}
internal static void InitAfterAttack(AttackableUnit tar)
{
AIHeroClient target = null;
if (myTarget.IsValidRange(600))
{
target = myTarget;
}
else if (tar is AIHeroClient)
{
target = (AIHeroClient)tar;
}
if (target != null && target.IsValidRange(400))
{
if (MenuInit.ComboItem)
{
UseItem();
}
if (Q.IsReady() && target.IsValidRange(400))
{
CastQ(target);
return;
}
if (MenuInit.ComboR2 != 3 && R.IsReady() && isRActive && qStack == 2 && Q.IsReady() &&
MenuInit.ComboR2 != 1 && R2Logic(target))
{
return;
}
if (MenuInit.ComboW && W.IsReady() && target.IsValidRange(W.Range) && !HaveShield(target))
{
Player.Instance.Spellbook.CastSpell(SpellSlot.W);
return;
}
if (MenuInit.ComboE && !Q.IsReady() && !W.IsReady() && E.IsReady() && target.IsValidRange(400))
{
Player.Instance.Spellbook.CastSpell(SpellSlot.E, target.Position);
return;
}
if (MenuInit.ComboR1 && R.IsReady() && !isRActive)
{
R1Logic(target);
}
}
}
internal static void InitSpellCast(GameObjectProcessSpellCastEventArgs Args)
{
var target = myTarget.IsValidRange(600f)
? myTarget
: TargetSelector.GetTarget(EntityManager.Heroes.Enemies.Where(x => x.IsValidRange(600)),
DamageType.Physical);
if (Args.SData == null)
{
return;
}
if (target != null && target.IsValidRange(600f))
{
switch (Args.SData.Name)
{
case "ItemTiamatCleave":
if (MenuInit.ComboW && W.IsReady() && target.IsValidRange(W.Range))
{
Player.Instance.Spellbook.CastSpell(SpellSlot.W);
}
else if (Q.IsReady() && target.IsValidRange(400))
{
CastQ(target);
}
break;
case "RivenMartyr":
if (Q.IsReady() && target.IsValidRange(400))
{
CastQ(target);
}
else if (MenuInit.ComboR1 && R.IsReady() && !isRActive)
{
R1Logic(target);
}
break;
case "RivenFeint":
if (MenuInit.ComboR1 && R.IsReady() && !isRActive && target.IsValidRange(500f))
{
R1Logic(target);
}
break;
case "RivenFengShuiEngine":
if (MenuInit.ComboW && W.IsReady() && target.IsValidRange(W.Range))
{
Player.Instance.Spellbook.CastSpell(SpellSlot.W);
}
break;
case "RivenIzunaBlade":
Player.Instance.Spellbook.CastSpell(SpellSlot.Q, target.Position);
break;
}
}
}
}
}
<file_sep>/MoonRiven/MoonRiven/Mode/LaneClear.cs
namespace MoonRiven_2.Mode
{
using myCommon;
using EloBuddy;
using EloBuddy.SDK;
using System.Linq;
internal class LaneClear : Logic
{
internal static void InitTick()
{
if (TickCount - lastCastTime < 1200)
return;
var minions =
EntityManager.MinionsAndMonsters.GetLaneMinions(EntityManager.UnitTeam.Enemy, Player.Instance.Position,
400).ToList();
if (minions.Any())
{
if (MenuInit.LaneClearItem && minions.Count >= 3)
{
UseItem();
}
if (MenuInit.LaneClearQ && MenuInit.LaneClearQSmart && Q.IsReady() && minions.Count >= 3)
{
var minion = minions.FirstOrDefault();
if (minion != null)
Player.Instance.Spellbook.CastSpell(SpellSlot.Q, minion.Position);
}
if (MenuInit.LaneClearW && W.IsReady())
{
if (minions.Count(x => W.IsInRange(x)) >= MenuInit.LaneClearWCount)
{
Player.Instance.Spellbook.CastSpell(SpellSlot.W);
}
}
}
}
internal static void InitAfterAttack(AttackableUnit target)
{
if (MenuInit.LaneClearQT && Q.IsReady() &&
(target.Type == GameObjectType.obj_AI_Turret || target.Type == GameObjectType.obj_Turret ||
target.Type == GameObjectType.obj_Barracks ||
target.Type == GameObjectType.obj_BarracksDampener ||
target.Type == GameObjectType.obj_HQ) &&
!EntityManager.Heroes.Enemies.Exists(x => x.IsValidRange(800) && x.DistanceToPlayer() <= 800))
{
Player.Instance.Spellbook.CastSpell(SpellSlot.Q, target.Position);
}
else if (target.Type == GameObjectType.obj_AI_Minion && target.Team != GameObjectTeam.Neutral)
{
var minions =
EntityManager.MinionsAndMonsters.GetLaneMinions(EntityManager.UnitTeam.Enemy, Player.Instance.Position,
400).ToList();
if (minions.Any())
{
if (MenuInit.LaneClearQ && Q.IsReady() && minions.Count >= 2)
{
var minion = minions.FirstOrDefault();
if (minion != null)
Player.Instance.Spellbook.CastSpell(SpellSlot.Q, minion.Position);
}
}
}
}
}
}
<file_sep>/MoonLucian/MoonLucian/myCommon/DamageCalculate.cs
namespace MoonLucian.myCommon
{
using EloBuddy;
using EloBuddy.SDK;
internal class DamageCalculate
{
internal static float GetComboDamage(AIHeroClient target)
{
if (target == null || target.IsDead || target.IsZombie)
{
return 0;
}
var damage = 0d;
if (Player.Instance.BaseAttackDamage + Player.Instance.FlatPhysicalDamageMod > Player.Instance.TotalMagicalDamage)
{
damage += Player.Instance.GetAutoAttackDamage(target);
}
if (Player.Instance.GetSpellSlotFromName("SummonerDot") != SpellSlot.Unknown &&
Player.Instance.Spellbook.GetSpell(Player.Instance.GetSpellSlotFromName("SummonerDot")).IsReady)
{
damage += GetIgniteDmage(target);
}
damage += GetQDamage(target);
damage += GetWDamage(target);
damage += GetEDamage(target);
damage += GetRDamage(target);
if (ObjectManager.Player.HasBuff("SummonerExhaust"))
{
damage = damage * 0.6f;
}
if (target.CharData.BaseSkinName == "Moredkaiser")
{
damage -= target.Mana;
}
if (target.HasBuff("GarenW"))
{
damage = damage * 0.7f;
}
if (target.HasBuff("ferocioushowl"))
{
damage = damage * 0.7f;
}
if (target.HasBuff("BlitzcrankManaBarrierCD") && target.HasBuff("ManaBarrier"))
{
damage -= target.Mana / 2f;
}
return (float)damage;
}
internal static float GetQDamage(Obj_AI_Base target)
{
if (Player.Instance.Spellbook.GetSpell(SpellSlot.Q).Level == 0 ||
!Player.Instance.Spellbook.GetSpell(SpellSlot.Q).IsReady)
{
return 0f;
}
var qDMG =
new double[] {80, 115, 150, 185, 220}[Player.Instance.Spellbook.GetSpell(SpellSlot.Q).Level - 1] +
new double[] {60, 70, 80, 90, 100}[Player.Instance.Spellbook.GetSpell(SpellSlot.Q).Level - 1]/100*
Player.Instance.FlatPhysicalDamageMod;
return Player.Instance.CalculateDamageOnUnit(target, DamageType.Physical, (float)qDMG);
}
internal static float GetWDamage(AIHeroClient target)
{
if (Player.Instance.Spellbook.GetSpell(SpellSlot.W).Level == 0 ||
!Player.Instance.Spellbook.GetSpell(SpellSlot.W).IsReady)
{
return 0f;
}
var wDMG = new double[] { 60, 100, 140, 180, 220 }[Player.Instance.Spellbook.GetSpell(SpellSlot.W).Level - 1] +
0.9 * Player.Instance.TotalMagicalDamage;
return Player.Instance.CalculateDamageOnUnit(target, DamageType.Magical, (float)wDMG);
}
internal static float GetEDamage(AIHeroClient target)
{
if (Player.Instance.Spellbook.GetSpell(SpellSlot.E).Level == 0 ||
!Player.Instance.Spellbook.GetSpell(SpellSlot.E).IsReady)
{
return 0f;
}
return (float)GetPassiveDMG(target);
}
internal static float GetRDamage(AIHeroClient target)
{
if (Player.Instance.Spellbook.GetSpell(SpellSlot.R).Level == 0 ||
!Player.Instance.Spellbook.GetSpell(SpellSlot.R).IsReady)
{
return 0f;
}
var rDMG = new double[] { 20, 35, 50 }[Player.Instance.Spellbook.GetSpell(SpellSlot.R).Level - 1] +
0.1 * Player.Instance.TotalMagicalDamage + 0.2 * Player.Instance.FlatPhysicalDamageMod;
return Player.Instance.CalculateDamageOnUnit(target, DamageType.Magical, (float)rDMG);
}
internal static float GetIgniteDmage(Obj_AI_Base target)
{
return 50 + 20 * Player.Instance.Level - target.HPRegenRate / 5 * 3;
}
internal static double GetPassiveDMG(Obj_AI_Base target)
{
if (Player.Instance.Level >= 13)
{
return Player.Instance.GetAutoAttackDamage(target) + 0.6 * Player.Instance.GetAutoAttackDamage(target);
}
else if (Player.Instance.Level >= 7)
{
return Player.Instance.GetAutoAttackDamage(target) + 0.5 * Player.Instance.GetAutoAttackDamage(target);
}
else
return Player.Instance.GetAutoAttackDamage(target) + 0.4 * Player.Instance.GetAutoAttackDamage(target);
}
}
}<file_sep>/aiRTako_Biltzcrank/aiRTako_Biltzcrank/DamageLib/DamageIndicator.cs
namespace aiRTako_Biltzcrank.DamageLib
{
using System;
using System.Linq;
using System.Globalization;
using SharpDX;
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Menu;
using EloBuddy.SDK.Menu.Values;
using Color = System.Drawing.Color;
using Line = EloBuddy.SDK.Rendering.Line;
internal static class DamageIndicator
{
private static readonly Vector2 BarOffset = new Vector2(1.25f, 14.25f);
private static readonly Vector2 PercentOffset = new Vector2(-31, 3);
private static readonly Vector2 PercentOffset1 = new Vector2(-30, 3);
private static readonly Vector2 PercentOffset2 = new Vector2(-29, 3);
private static Line _line;
internal static bool Fill = true;
internal static bool Enabled = true;
internal static Color Color = Color.FromArgb(255, 255, 169, 4);
private static DamageToUnitDelegate _damageToUnit;
internal delegate float DamageToUnitDelegate(AIHeroClient hero);
internal static void AddToMenu(Menu mainMenu, DamageToUnitDelegate Damage = null)
{
_line = new Line
{
Antialias = true,
Width = 9
};
mainMenu.AddSeparator();
mainMenu.AddLabel("Damage Indicator");
mainMenu.Add("DrawComboDamage", new CheckBox("Draw Combo Damage"));
mainMenu.Add("DrawFillDamage", new CheckBox("Draw Fill Color"));
DamageToUnit = Damage ?? DamageCalculate.GetComboDamage;
Enabled = mainMenu["DrawComboDamage"].Cast<CheckBox>().CurrentValue;
Fill = mainMenu["DrawFillDamage"].Cast<CheckBox>().CurrentValue;
Game.OnTick += delegate
{
Enabled = mainMenu["DrawComboDamage"].Cast<CheckBox>().CurrentValue;
Fill = mainMenu["DrawFillDamage"].Cast<CheckBox>().CurrentValue;
};
}
internal static DamageToUnitDelegate DamageToUnit
{
set
{
if (_damageToUnit == null)
Drawing.OnEndScene += Drawing_OnEndScene;
_damageToUnit = value;
}
}
private static void Drawing_OnEndScene(EventArgs eventArgs)
{
if (!Enabled || _damageToUnit == null)
return;
foreach (var unit in EntityManager.Heroes.Enemies.Where(u => u.IsValidTarget() && u.IsHPBarRendered))
{
var damage = _damageToUnit(unit);
if (damage <= 0)
continue;
if (unit.Health > 0)
{
var text = ((int)(unit.Health - damage)).ToString(CultureInfo.InvariantCulture);
if (text.Length == 4)
{
Drawing.DrawText(unit.HPBarPosition + PercentOffset, Color.Red, text, 10);
}
else if (text.Length == 3)
{
Drawing.DrawText(unit.HPBarPosition + PercentOffset1, Color.Red, text, 10);
}
else if (text.Length == 2)
{
Drawing.DrawText(unit.HPBarPosition + PercentOffset2, Color.Red, text, 10);
}
else
{
Drawing.DrawText(unit.HPBarPosition + PercentOffset, Color.Red, text, 10);
}
}
if (Fill)
{
var damagePercentage = (unit.TotalShieldHealth() - damage > 0 ? unit.TotalShieldHealth() - damage : 0) / (unit.MaxHealth + unit.AllShield + unit.AttackShield + unit.MagicShield);
var currentHealthPercentage = unit.TotalShieldHealth() / (unit.MaxHealth + unit.AllShield + unit.AttackShield + unit.MagicShield);
var startPoint = new Vector2(unit.HPBarPosition.X + BarOffset.X + damagePercentage * 104, unit.HPBarPosition.Y + BarOffset.Y - 5);
var endPoint = new Vector2(unit.HPBarPosition.X + BarOffset.X + currentHealthPercentage * 104 + 1, unit.HPBarPosition.Y + BarOffset.Y - 5);
_line.Draw(Color, startPoint, endPoint);
Drawing.DrawLine(startPoint, endPoint, 9, Color);
}
}
}
}
}
<file_sep>/MoonRiven/MoonRiven/Mode/Harass.cs
namespace MoonRiven_2.Mode
{
using myCommon;
using EloBuddy;
using EloBuddy.SDK;
using System;
internal class Harass : Logic
{
internal static void InitTick()
{
var target = TargetSelector.GetTarget(E.Range + Player.Instance.BoundingRadius, DamageType.Physical);
if (target.IsValidRange())
{
if (MenuInit.HarassMode == 0)
{
if (E.IsReady() && MenuInit.HarassE && qStack == 2)
{
var pos = Player.Instance.Position + (Player.Instance.Position - target.Position).Normalized() * E.Range;
Player.Instance.Spellbook.CastSpell(SpellSlot.E,
Player.Instance.Position.Extend(pos, E.Range).To3D());
}
if (Q.IsReady() && MenuInit.HarassQ && qStack == 2)
{
var pos = Player.Instance.Position + (Player.Instance.Position - target.Position).Normalized() * E.Range;
Core.DelayAction(() => Player.Instance.Spellbook.CastSpell(SpellSlot.Q,
Player.Instance.Position.Extend(pos, Q.Range).To3D()), 100);
}
if (W.IsReady() && MenuInit.HarassW && target.IsValidRange(W.Range) && qStack == 1)
{
Player.Instance.Spellbook.CastSpell(SpellSlot.W);
}
if (Q.IsReady() && MenuInit.HarassQ)
{
if (qStack == 0)
{
CastQ(target);
Orbwalker.ForcedTarget = target;
}
if (qStack == 1 && Environment.TickCount - lastQTime > 600)
{
CastQ(target);
Orbwalker.ForcedTarget = target;
}
}
}
else
{
if (E.IsReady() && MenuInit.HarassE &&
target.DistanceToPlayer() <= E.Range + (Q.IsReady() ? Q.Range : Player.Instance.AttackRange))
{
Player.Instance.Spellbook.CastSpell(SpellSlot.E, target.Position);
}
if (Q.IsReady() && MenuInit.HarassQ && target.IsValidRange(Q.Range) && qStack == 0 &&
Environment.TickCount - lastQTime > 500)
{
CastQ(target);
Orbwalker.ForcedTarget = target;
}
if (W.IsReady() && MenuInit.HarassW && target.IsValidRange(W.Range) && (!Q.IsReady() || qStack == 1))
{
Player.Instance.Spellbook.CastSpell(SpellSlot.W);
}
}
}
}
internal static void InitAfterAttack(AttackableUnit tar)
{
AIHeroClient target = null;
if (myTarget.IsValidRange())
{
target = myTarget;
}
else if (tar is AIHeroClient)
{
target = (AIHeroClient)tar;
}
if (target == null || !target.IsValidRange())
return;
if (MenuInit.HarassQ && Q.IsReady())
{
if (MenuInit.HarassMode == 0)
{
if (qStack == 1)
{
CastQ(target);
}
}
else
{
CastQ(target);
}
}
}
}
}
<file_sep>/MoonRiven/MoonRiven/Riven.cs
namespace MoonRiven_2
{
using myCommon;
using System;
using SharpDX;
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Events;
using EloBuddy.SDK.Rendering;
using EloBuddy.SDK.Enumerations;
internal class Riven : Logic
{
internal static void Init()
{
//Draw the Chat
Chat.Print("Moon" + Player.Instance.ChampionName + ": Load! Credit: NightMoon", System.Drawing.Color.LightSteelBlue);
//Init Riven SkillSlot
Q = new Spell.Skillshot(SpellSlot.Q, 325, SkillShotType.Circular, 250, 2200, 100, DamageType.Physical);
W = new Spell.Active(SpellSlot.W, 260);
E = new Spell.Skillshot(SpellSlot.E, 312, SkillShotType.Linear, 100);
R = new Spell.Active(SpellSlot.R, 600);
R1 = new Spell.Skillshot(SpellSlot.R, 900, SkillShotType.Cone, 250, 1600, 40, DamageType.Physical);
//Init Riven SummonerSpell
Ignite = Player.Instance.GetSpellSlotFromName("SummonerDot");
Flash = Player.Instance.GetSpellSlotFromName("SummonerFlash");
//Init Riven Menu
MenuInit.Init();
//Init Riven Events
Game.OnUpdate += OnTick;
Obj_AI_Base.OnPlayAnimation += OnPlayAnimation;
Spellbook.OnCastSpell += OnCastSpell;
Obj_AI_Base.OnProcessSpellCast += OnProcessSpellCast;
Obj_AI_Base.OnSpellCast += OnSpellCast;
Orbwalker.OnPostAttack += OnPostAttack;
Gapcloser.OnGapcloser += OnGapcloser;
Interrupter.OnInterruptableSpell += OnInterruptableSpell;
Drawing.OnDraw += OnDraw;
}
private static void OnPlayAnimation(Obj_AI_Base sender, GameObjectPlayAnimationEventArgs Args)
{
if (!sender.IsMe)
{
return;
}
var time = 0;
switch (Args.Animation)
{
case "Spell1a": //Q1
time = 351;
qStack = 1;
lastQTime = TickCount;
break;
case "Spell1b": //Q2
time = 351;
qStack = 2;
lastQTime = TickCount;
break;
case "Spell1c": //Q3
time = 451;
qStack = 0;
lastQTime = TickCount;
break;
//case "Spell2": //W
// time = 50;
// break;
//case "Spell4a": //R1
// time = 50;
// break;
//case "Spell4b": //R2
// time = 180;
// break;
default:
time = 0;
break;
}
if (isFleeMode)
return;
if (time > 0)
{
if (MenuInit.manualCancel || !isNoneMode)
{
if (MenuInit.manualCancelPing)
{
if (time - Game.Ping > 0)
{
Core.DelayAction(Cancel, time - Game.Ping);
}
else
{
Core.DelayAction(Cancel, 1);
}
}
else
{
Core.DelayAction(Cancel, time);
}
}
}
}
private static void Cancel()
{
//Player.DoEmote(Emote.Dance);
Orbwalker.ResetAutoAttack();
if (Orbwalker.GetTarget() != null && !Orbwalker.GetTarget().IsDead)
{
Orbwalker.OrbwalkTo(Player.Instance.Position.Extend(Orbwalker.GetTarget().Position, +10).To3D());
}
else
{
Orbwalker.OrbwalkTo(Game.CursorPos);
}
}
private static void OnTick(EventArgs Args)
{
if (Player.Instance.IsDead)
{
myTarget = null;
qStack = 0;
return;
}
if (Player.Instance.IsRecalling())
return;
Mode.None.Init();
if (isComboMode)
{
if (MenuInit.BurstEnabledKey)
{
Mode.Burst.InitTick();
}
else
{
Mode.Combo.InitTick();
}
}
if (isHarassMode)
{
Mode.Harass.InitTick();
}
if (isLaneClearMode && ManaManager.SpellFarm)
{
Mode.LaneClear.InitTick();
}
if (isJungleClearMode && ManaManager.SpellFarm)
{
Mode.JungleClear.InitTick();
}
if (isFleeMode)
{
Mode.Flee.InitTick();
}
Mode.KillSteal.InitTick();
}
private static void OnCastSpell(Spellbook sender, SpellbookCastSpellEventArgs Args)
{
if (Args.Slot == SpellSlot.Q || Args.Slot == SpellSlot.W || Args.Slot == SpellSlot.E)
{
lastCastTime = TickCount;
}
}
private static void OnProcessSpellCast(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs Args)
{
if (sender.IsMe)
{
if (isComboMode)
{
if (MenuInit.BurstEnabledKey)
{
Mode.Burst.InitSpellCast(Args);
}
else
{
Mode.Combo.InitSpellCast(Args);
}
}
}
if (sender.IsEnemy && sender.Type == GameObjectType.AIHeroClient && MenuInit.evadeELogic && E.IsReady())
{
EvadeLogic(sender as AIHeroClient, Args);
}
}
private static void EvadeLogic(AIHeroClient target, GameObjectProcessSpellCastEventArgs Args)
{
if (eMenu[target.ChampionName + "Skill" + Args.SData.Name] == null || !eMenu.GetBool(target.ChampionName + "Skill" + Args.SData.Name))
{
return;
}
if (Args.SData.TargettingType == SpellDataTargetType.Unit && Args.Target != null && Args.Target.IsMe)
{
Player.Instance.Spellbook.CastSpell(SpellSlot.E, Game.CursorPos);
}
//else if (Args.SData.TargettingType != SpellDataTargetType.Unit)
//{
// //Use the Evade Logic?
//}
}
private static void OnSpellCast(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs Args)
{
if (!sender.IsMe)
return;
if (isComboMode)
{
if (MenuInit.BurstEnabledKey)
{
Mode.Burst.InitSpellCast(Args);
}
else
{
Mode.Combo.InitSpellCast(Args);
}
}
}
private static void OnPostAttack(AttackableUnit target, EventArgs Args)
{
Orbwalker.ForcedTarget = null;
if (target == null || target.IsAlly)
return;
if (isComboMode && target.Type == GameObjectType.AIHeroClient)
{
if (MenuInit.BurstEnabledKey)
{
Mode.Burst.InitAfterAttack(target);
}
else
{
Mode.Combo.InitAfterAttack(target);
}
}
if (isHarassMode && target.Type == GameObjectType.AIHeroClient)
{
Mode.Harass.InitAfterAttack(target);
}
if (isLaneClearMode && ManaManager.SpellFarm)
{
Mode.LaneClear.InitAfterAttack(target);
}
if (isJungleClearMode && target.Team == GameObjectTeam.Neutral && ManaManager.SpellFarm)
{
Mode.JungleClear.InitAfterAttack(target);
}
}
private static void OnGapcloser(AIHeroClient sender, Gapcloser.GapcloserEventArgs Args)
{
if (!MenuInit.AntiGapcloserW || !W.IsReady() || sender == null || !sender.IsEnemy || !sender.IsValidTarget())
{
return;
}
if (Args.Target.IsMe || sender.DistanceToPlayer() <= W.Range || Args.End.DistanceToPlayer() <= W.Range)
{
if (!sender.HaveShiled())
Player.Instance.Spellbook.CastSpell(SpellSlot.W);
}
}
private static void OnInterruptableSpell(Obj_AI_Base sender, Interrupter.InterruptableSpellEventArgs Args)
{
if (!MenuInit.InterruptW || sender == null || !sender.IsEnemy || Args == null ||
!W.IsReady() || sender.Type != GameObjectType.AIHeroClient)
{
return;
}
var target = (AIHeroClient) sender;
if (target.IsValidRange(W.Range) && Args.DangerLevel >= DangerLevel.High && !target.HaveShiled())
{
Player.Instance.Spellbook.CastSpell(SpellSlot.W);
}
}
private static void OnDraw(EventArgs Args)
{
if (Player.Instance.IsDead || MenuGUI.IsChatOpen || Chat.IsOpen)
return;
if (MenuInit.DrawW && W.IsReady())
{
Circle.Draw(Color.Yellow, W.Range, Player.Instance);
}
if (MenuInit.DrawE && E.IsReady())
{
Circle.Draw(Color.Red, E.Range, Player.Instance);
}
if (MenuInit.DrawR1 && Player.GetSpell(SpellSlot.R).IsReady)
{
Circle.Draw(Color.Orange, R1.Range, Player.Instance);
}
if (MenuInit.DrawR && Player.GetSpell(SpellSlot.R).Level > 0)
{
var MePos = Drawing.WorldToScreen(Player.Instance.Position);
Drawing.DrawText(MePos[0] - 57, MePos[1] + 68, System.Drawing.Color.FromArgb(242, 120, 34),
"Combo R1:" + (MenuInit.ComboR1 ? "On" : "Off"));
}
if (MenuInit.DrawBurst && Player.GetSpell(SpellSlot.R).Level > 0)
{
var MePos = Drawing.WorldToScreen(Player.Instance.Position);
string str;
if (MenuInit.BurstEnabledKey)
{
str = !R.IsReady() ? "Not Ready" : "On";
}
else
{
str = "Off";
}
Drawing.DrawText(MePos[0] - 57, MePos[1] + 88, System.Drawing.Color.FromArgb(242, 120, 34),
"Burst Fire:" + str);
}
}
}
}
<file_sep>/MoonLucian/MoonLucian/myCommon/Extensions.cs
namespace MoonLucian.myCommon
{
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Menu;
using EloBuddy.SDK.Menu.Values;
using EloBuddy.SDK.Enumerations;
using SharpDX;
using System;
using System.Linq;
using System.Collections.Generic;
internal static class Extensions
{
// Menu Extensions
internal static void AddLine(this Menu mainMenu, string spellName)
{
mainMenu.AddGroupLabel(spellName + " Settings");
}
internal static void AddText(this Menu mainMenu, string disableName)
{
mainMenu.AddGroupLabel(disableName);
}
internal static void AddBool(this Menu mainMenu, string name, string disableName, bool isEnabled = true)
{
mainMenu.Add(name, new CheckBox(disableName, isEnabled));
}
internal static void AddSlider(this Menu mainMenu, string name, string disableName, int defalutValue = 0, int minValue = 0, int maxValue = 100)
{
mainMenu.Add(name, new Slider(disableName, defalutValue, minValue, maxValue));
}
internal static void AddList(this Menu mainMenu, string name, string disableName, string[] list, int defaultIndex = 0)
{
mainMenu.Add(name, new ComboBox(disableName, list, defaultIndex));
}
internal static void AddKey(this Menu mainMenu, string name, string disableName, KeyBind.BindTypes keyBindType, uint defaultKey1 = 27, bool isEnabled = false)
{
mainMenu.Add(name, new KeyBind(disableName, isEnabled, keyBindType, defaultKey1));
}
internal static bool GetBool(this Menu mainMenu, string name)
{
return mainMenu[name].Cast<CheckBox>().CurrentValue;
}
internal static bool GetKey(this Menu mainMenu, string name)
{
return mainMenu[name].Cast<KeyBind>().CurrentValue;
}
internal static int GetSlider(this Menu mainMenu, string name)
{
return mainMenu[name].Cast<Slider>().CurrentValue;
}
internal static int GetList(this Menu mainMenu, string name)
{
return mainMenu[name].Cast<ComboBox>().CurrentValue;
}
//Distance Extensions
internal static float DistanceToPlayer(this Obj_AI_Base source)
{
return Player.Instance.Distance(source);
}
internal static float DistanceToPlayer(this Vector3 position)
{
return position.To2D().DistanceToPlayer();
}
internal static float DistanceToPlayer(this Vector2 position)
{
return ObjectManager.Player.Distance(position);
}
internal static float DistanceToMouse(this Obj_AI_Base source)
{
return Game.CursorPos.Distance(source.Position);
}
internal static float DistanceToMouse(this Vector3 position)
{
return position.To2D().DistanceToMouse();
}
internal static float DistanceToMouse(this Vector2 position)
{
return Game.CursorPos.Distance(position.To3D());
}
//Status Extensions
internal static bool HaveShiled(this AIHeroClient target)
{
if (target == null || target.IsDead || target.Health <= 0)
{
return false;
}
if (target.HasBuff("BlackShield"))
{
return true;
}
if (target.HasBuff("bansheesveil"))
{
return true;
}
if (target.HasBuff("SivirE"))
{
return true;
}
if (target.HasBuff("NocturneShroudofDarkness"))
{
return true;
}
if (target.HasBuff("itemmagekillerveil"))
{
return true;
}
if (target.HasBuffOfType(BuffType.SpellShield))
{
return true;
}
return false;
}
internal static bool CanMoveMent(this AIHeroClient target)
{
return !(target.MoveSpeed < 50) && !target.IsStunned && !target.HasBuffOfType(BuffType.Stun) &&
!target.HasBuffOfType(BuffType.Fear) && !target.HasBuffOfType(BuffType.Snare) &&
!target.HasBuffOfType(BuffType.Knockup) && !target.HasBuff("Recall") &&
!target.HasBuffOfType(BuffType.Knockback)
&& !target.HasBuffOfType(BuffType.Charm) && !target.HasBuffOfType(BuffType.Taunt) &&
!target.HasBuffOfType(BuffType.Suppression) && (!target.Spellbook.IsCharging
|| target.IsMoving) &&
!target.HasBuff("zhonyasringshield") && !target.HasBuff("bardrstasis");
}
internal static bool IsUnKillable(this AIHeroClient target)
{
if (target == null || target.IsDead || target.Health <= 0)
{
return true;
}
if (target.HasBuff("KindredRNoDeathBuff"))
{
return true;
}
if (target.HasBuff("UndyingRage") && target.GetBuff("UndyingRage").EndTime - Game.Time > 0.3 && target.Health <= target.MaxHealth * 0.10f)
{
return true;
}
if (target.HasBuff("JudicatorIntervention"))
{
return true;
}
if (target.HasBuff("ChronoShift") && target.GetBuff("ChronoShift").EndTime - Game.Time > 0.3 && target.Health <= target.MaxHealth * 0.10f)
{
return true;
}
if (target.HasBuff("VladimirSanguinePool"))
{
return true;
}
if (target.HasBuff("ShroudofDarkness"))
{
return true;
}
if (target.HasBuff("SivirShield"))
{
return true;
}
if (target.HasBuff("itemmagekillerveil"))
{
return true;
}
return target.HasBuff("FioraW");
}
//Spell Extensions
internal static void HaveCollsion(this Spell.Skillshot spell, bool haveCollsion, int count = 0)
{
spell.AllowedCollisionCount = haveCollsion ? count : int.MaxValue;
}
internal static void PredCast(this Spell.Skillshot spell, AIHeroClient target, bool checkCollsion = true, HitChance hitchance = HitChance.High)
{
if (target == null || !target.IsValidTarget(spell.Range) || target.IsUnKillable() || target.Health <= 0)
{
return;
}
var pred = spell.GetPrediction(target);
if (checkCollsion)
{
if (pred.HitChance >= hitchance && !pred.CollisionObjects.Any())
{
spell.Cast(pred.CastPosition);
}
}
else
{
if (pred.HitChance >= hitchance)
{
spell.Cast(pred.CastPosition);
}
}
}
internal static int CountHits(this Spell.Skillshot spell, List<Obj_AI_Minion> units, Vector3 castPosition)
{
var points = units.Select(unit => spell.GetPrediction(unit).UnitPosition).ToList();
return spell.CountHits(points, castPosition);
}
internal static int CountHits(this Spell.Skillshot spell, List<Vector3> points, Vector3 castPosition)
{
return points.Count(point => spell.WillHit(point, castPosition));
}
internal static bool WillHit(this Spell.Skillshot spell, Obj_AI_Base unit, Vector3 castPosition, int extraWidth = 0)
{
var unitPosition = spell.GetPrediction(unit);
return unitPosition.HitChance >= HitChance.High
&& spell.WillHit(unitPosition.UnitPosition, castPosition, extraWidth);
}
internal static bool WillHit(this Spell.Skillshot spell, Vector3 point, Vector3 castPosition, int extraWidth = 0)
{
if (point.To2D().Distance(castPosition.To2D(), Player.Instance.Position.To2D(), true, true) < Math.Pow(spell.Width + extraWidth, 2))
{
return true;
}
return false;
}
//Vector Extensions
internal static Vector3 Extend(this Obj_AI_Base v, Vector3 to, float distance)
{
return v.Position + distance * (to - v.Position).Normalized();
}
}
}
<file_sep>/MoonLucian/MoonLucian/MenuInit.cs
namespace MoonLucian
{
using myCommon;
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Menu;
using EloBuddy.SDK.Menu.Values;
using System.Linq;
internal class MenuInit : Logic
{
internal static void Init()
{
mainMenu = MainMenu.AddMenu("Moon" + Player.Instance.ChampionName, "Moon" + Player.Instance.ChampionName);
{
mainMenu.AddGroupLabel("pls setting the Orbwalker");
mainMenu.AddGroupLabel("Orbwalker -> Advanced -> Update event listening -> Enabled On Update(more fast)");
mainMenu.AddGroupLabel("--------------------");
mainMenu.AddGroupLabel("My GitHub: https://github.com/aiRTako/EloBuddy");
mainMenu.AddGroupLabel("If you have Feedback pls post to my topic");
mainMenu.AddGroupLabel("---------------------");
mainMenu.AddGroupLabel("Credit: NightMoon & aiRTako");
}
comboMenu = mainMenu.AddSubMenu("Combo", "Combo");
{
comboMenu.AddLine("Q");
comboMenu.AddBool("ComboQ", "Use Q");
comboMenu.AddBool("ComboQExtend", "Use Q Extend");
comboMenu.AddLine("W");
comboMenu.AddBool("ComboW", "Use W");
comboMenu.AddBool("ComboWFast", "Use W Fast Cast to Reset the Passive");
comboMenu.AddLine("E");
comboMenu.AddBool("ComboEDash", "Use E Dash to target");
comboMenu.AddBool("ComboEReset", "Use E Reset Auto Attack");
comboMenu.AddBool("ComboESafe", "Use E| Safe Check");
comboMenu.AddBool("ComboEWall", "Use E| Dont Dash to Wall");
comboMenu.AddBool("ComboEShort", "Use E| Enabled the Short E Logic");
comboMenu.AddLine("R");
comboMenu.AddBool("ComboR", "Use R");
}
harassMenu = mainMenu.AddSubMenu("Harass", "Harass");
{
harassMenu.AddLine("Q");
harassMenu.AddBool("HarassQ", "Use Q");
harassMenu.AddBool("HarassQExtend", "Use Q Extend");
harassMenu.AddLine("W");
harassMenu.AddBool("HarassW", "Use W", false);
harassMenu.AddLine("Mana");
harassMenu.AddSlider("HarassMP", "When Player Mana Percent >= x%, Enabled Spell Harass", 60);
harassMenu.AddLine("Harass Target");
if (EntityManager.Heroes.Enemies.Any())
{
foreach (var target in EntityManager.Heroes.Enemies)
{
harassMenu.AddBool("Harasstarget" + target.ChampionName.ToLower(), target.ChampionName);
}
}
}
clearMenu = mainMenu.AddSubMenu("Clear", "Clear");
{
clearMenu.AddText("LaneClear Settings");
clearMenu.AddLine("LaneClear Q");
clearMenu.AddBool("LaneClearQ", "Use Q");
clearMenu.AddLine("LaneClear W");
clearMenu.AddBool("LaneClearW", "Use W", false);
clearMenu.AddLine("LaneClearMana");
clearMenu.AddSlider("LaneClearMP", "When Player Mana Percent >= x%, Enabled LaneClear Spell", 60);
clearMenu.AddSeparator();
clearMenu.AddText("PushTurret Settings");
clearMenu.AddLine("TurretClear W");
clearMenu.AddBool("TurretClearW", "Use W");
clearMenu.AddLine("TurretClear E");
clearMenu.AddBool("TurretClearE", "Use E");
clearMenu.AddLine("TurretClearMana");
clearMenu.AddSlider("TurretClearMP", "When Player Mana Percent >= x%, Enabled TurretClear Spell", 60);
clearMenu.AddSeparator();
clearMenu.AddText("JungleClear Settings");
clearMenu.AddLine("JungleClear Q");
clearMenu.AddBool("JungleClearQ", "Use Q");
clearMenu.AddLine("JungleClear W");
clearMenu.AddBool("JungleClearW", "Use W");
clearMenu.AddLine("JungleClear E");
clearMenu.AddBool("JungleClearE", "Use E");
clearMenu.AddSlider("JungleClearMP", "When Player Mana Percent >= x%, Enabled JungleClear Spell", 30);
ManaManager.AddSpellFarm(clearMenu);
}
killStealMenu = mainMenu.AddSubMenu("KillSteal", "KillSteal");
{
killStealMenu.AddText("Q");
killStealMenu.AddBool("KillStealQ", "Use Q");
killStealMenu.AddText("W");
killStealMenu.AddBool("KillStealW", "Use W");
}
miscMenu = mainMenu.AddSubMenu("Misc", "Misc");
{
miscMenu.AddText("R");
miscMenu.AddKey("SemiR", "Semi Cast R Key", KeyBind.BindTypes.HoldActive, 'T');
miscMenu.AddSeparator();
miscMenu.AddText("Anti Gapcloser");
miscMenu.AddBool("EnabledAnti", "Enabled");
miscMenu.AddSlider("AntiGapCloserHp", "When Player HealthPercent <= x%, Enabled Anti Gapcloser Settings", 30);
miscMenu.AddText("Anti Target");
if (EntityManager.Heroes.Enemies.Any())
{
foreach (var target in EntityManager.Heroes.Enemies)
{
miscMenu.AddBool("AntiGapCloserE" + target.ChampionName.ToLower(), target.ChampionName, target.IsMelee);
}
}
miscMenu.AddSeparator();
miscMenu.AddText("Anti Melee");
miscMenu.AddBool("EnabledAntiMelee", "Enabled");
miscMenu.AddSlider("AntiMeleeHp", "When Player HealthPercent <= x%, Enabled Anti Melee Settings", 30);
}
drawMenu = mainMenu.AddSubMenu("Drawings", "Drawings");
{
drawMenu.AddText("Spell Range");
drawMenu.AddBool("DrawQ", "Draw Q Range", false);
drawMenu.AddBool("DrawQExtend", "Draw QExtend Range", false);
drawMenu.AddBool("DrawW", "Draw W Range", false);
drawMenu.AddBool("DrawE", "Draw E Range", false);
drawMenu.AddBool("DrawR", "Draw R Range", false);
ManaManager.AddDrawFarm(drawMenu);
DamageIndicator.AddToMenu(drawMenu);
}
}
internal static bool ComboQ => comboMenu.GetBool("ComboQ");
internal static bool ComboQExtend => comboMenu.GetBool("ComboQExtend");
internal static bool ComboW => comboMenu.GetBool("ComboW");
internal static bool ComboWFast => comboMenu.GetBool("ComboWFast");
internal static bool ComboEDash => comboMenu.GetBool("ComboEDash");
internal static bool ComboEReset => comboMenu.GetBool("ComboEReset");
internal static bool ComboESafe => comboMenu.GetBool("ComboESafe");
internal static bool ComboEWall => comboMenu.GetBool("ComboEWall");
internal static bool ComboR => comboMenu.GetBool("ComboR");
internal static bool HarassQ => harassMenu.GetBool("HarassQ");
internal static bool HarassQExtend => harassMenu.GetBool("HarassQExtend");
internal static bool HarassW => harassMenu.GetBool("HarassW");
internal static int HarassMP => harassMenu.GetSlider("HarassMP");
internal static bool LaneClearQ => clearMenu.GetBool("LaneClearQ");
internal static bool LaneClearW => clearMenu.GetBool("LaneClearW");
internal static int LaneClearMP => clearMenu.GetSlider("LaneClearMP");
internal static bool TurretClearW => clearMenu.GetBool("TurretClearW");
internal static bool TurretClearE => clearMenu.GetBool("TurretClearE");
internal static int TurretClearMP => clearMenu.GetSlider("TurretClearMP");
internal static bool JungleClearQ => clearMenu.GetBool("JungleClearQ");
internal static bool JungleClearW => clearMenu.GetBool("JungleClearW");
internal static bool JungleClearE => clearMenu.GetBool("JungleClearE");
internal static int JungleClearMP => clearMenu.GetSlider("JungleClearMP");
internal static bool KillStealQ => killStealMenu.GetBool("KillStealQ");
internal static bool KillStealW => killStealMenu.GetBool("KillStealW");
internal static bool SemiR => miscMenu.GetKey("SemiR");
internal static bool EnabledAnti => miscMenu.GetBool("EnabledAnti");
internal static int AntiGapCloserHp => miscMenu.GetSlider("AntiGapCloserHp");
internal static bool EnabledAntiMelee => miscMenu.GetBool("EnabledAntiMelee");
internal static int AntiMeleeHp => miscMenu.GetSlider("AntiMeleeHp");
internal static bool DrawQ => drawMenu.GetBool("DrawQ");
internal static bool DrawQExtend => drawMenu.GetBool("DrawQExtend");
internal static bool DrawW => drawMenu.GetBool("DrawW");
internal static bool DrawE => drawMenu.GetBool("DrawE");
internal static bool DrawR => drawMenu.GetBool("DrawR");
}
}
<file_sep>/MoonRiven/MoonRiven/Mode/Burst.cs
namespace MoonRiven_2.Mode
{
using EloBuddy;
using EloBuddy.SDK;
using myCommon;
using System;
internal class Burst : Logic
{
internal static void InitTick()
{
var target = TargetSelector.SelectedTarget;
if (target == null || !target.IsValidRange())
return;
if (MenuInit.BurstMode == 0)
{
ShyBurstTick(target);
}
else
{
EQFlashBurstTick(target);
}
}
private static void ShyBurstTick(AIHeroClient target)
{
if (MenuInit.BurstDot && Ignite != SpellSlot.Unknown && Player.Instance.Spellbook.GetSpell(Ignite).IsReady)
{
Player.Instance.Spellbook.CastSpell(Ignite, target);
}
if (E.IsReady() && R.IsReady() && W.IsReady() && !isRActive)
{
if (target.IsValidRange(E.Range + Player.Instance.BoundingRadius - 30))
{
Player.Instance.Spellbook.CastSpell(SpellSlot.E, target.Position);
Core.DelayAction(() => R.Cast(), 10);
Core.DelayAction(() => Player.Instance.Spellbook.CastSpell(SpellSlot.W), 60);
Core.DelayAction(() => Player.Instance.Spellbook.CastSpell(SpellSlot.Q), 150);
return;
}
if (MenuInit.BurstFlash && Flash != SpellSlot.Unknown && Player.Instance.Spellbook.GetSpell(Flash).IsReady)
{
if (target.IsValidRange(E.Range + Player.Instance.BoundingRadius + 425 - 50))
{
Player.Instance.Spellbook.CastSpell(SpellSlot.E, target.Position);
Core.DelayAction(() => R.Cast(), 10);
Core.DelayAction(() => Player.Instance.Spellbook.CastSpell(SpellSlot.W), 60);
Core.DelayAction(() => Player.Instance.Spellbook.CastSpell(Flash, target.Position), 61);
Core.DelayAction(() => Player.Instance.Spellbook.CastSpell(SpellSlot.Q), 150);
}
}
}
else
{
if (W.IsReady() && target.IsValidRange(W.Range))
{
Player.Instance.Spellbook.CastSpell(SpellSlot.W);
}
}
}
private static void EQFlashBurstTick(AIHeroClient target)
{
if (MenuInit.BurstDot && Ignite != SpellSlot.Unknown && Player.Instance.Spellbook.GetSpell(Ignite).IsReady)
{
Player.Instance.Spellbook.CastSpell(Ignite, target);
}
if (MenuInit.BurstFlash && Flash != SpellSlot.Unknown && Player.Instance.Spellbook.GetSpell(Flash).IsReady)
{
if (target.IsValidRange(E.Range + 425 + Q.Range - 150) && qStack > 0 && E.IsReady() && R.IsReady() &&
!isRActive && W.IsReady())
{
Player.Instance.Spellbook.CastSpell(SpellSlot.E, target.Position);
Core.DelayAction(() => R.Cast(), 10);
Core.DelayAction(() => Player.Instance.Spellbook.CastSpell(Flash, target.Position), 50);
Core.DelayAction(() => Player.Instance.Spellbook.CastSpell(SpellSlot.Q, target.Position), 61);
Core.DelayAction(() => UseItem(), 62);
Core.DelayAction(() => Player.Instance.Spellbook.CastSpell(SpellSlot.W), 70);
Core.DelayAction(() => R1.Cast(target.Position), 71);
return;
}
if (qStack < 2 && Environment.TickCount - lastQTime >= 850)
{
Player.Instance.Spellbook.CastSpell(SpellSlot.Q, Game.CursorPos);
}
}
else
{
if (target.IsValidRange(E.Range + Q.Range - 150) && qStack == 2 && E.IsReady() && R.IsReady() && !isRActive && W.IsReady())
{
Player.Instance.Spellbook.CastSpell(SpellSlot.E, target.Position);
Core.DelayAction(() => R.Cast(), 10);
Core.DelayAction(() => Player.Instance.Spellbook.CastSpell(SpellSlot.Q, target.Position), 50);
Core.DelayAction(() => UseItem(), 61);
Core.DelayAction(() => Player.Instance.Spellbook.CastSpell(SpellSlot.W), 62);
Core.DelayAction(() => R1.Cast(target.Position), 70);
return;
}
if (target.IsValidRange(E.Range + Q.Range + Q.Range + Q.Range))
{
if (qStack < 2 && Environment.TickCount - lastQTime >= 850)
{
Player.Instance.Spellbook.CastSpell(SpellSlot.Q, Game.CursorPos);
}
}
}
}
internal static void InitAfterAttack(AttackableUnit tar)
{
var target = TargetSelector.SelectedTarget;
if (target == null || !target.IsValidRange())
return;
if (MenuInit.BurstMode == 0)
{
ShyBurst(target);
}
else
{
EQFlashBurst(target);
}
}
private static void ShyBurst(AIHeroClient target)
{
UseItem();
if (R.IsReady() && isRActive)
{
R1.Cast(target.Position);
return;
}
if (Q.IsReady() && CastQ(target))
{
return;
}
if (W.IsReady() && target.IsValidRange(W.Range) && Player.Instance.Spellbook.CastSpell(SpellSlot.W))
{
return;
}
if (E.IsReady())
{
Player.Instance.Spellbook.CastSpell(SpellSlot.E, target.Position);
}
}
private static void EQFlashBurst(AIHeroClient target)
{
UseItem();
if (R.IsReady() && isRActive)
{
R1.Cast(target.Position);
return;
}
if (Q.IsReady() && CastQ(target))
{
return;
}
if (W.IsReady() && target.IsValidRange(W.Range) && Player.Instance.Spellbook.CastSpell(SpellSlot.W))
{
return;
}
if (E.IsReady())
{
Player.Instance.Spellbook.CastSpell(SpellSlot.E, target.Position);
}
}
internal static void InitSpellCast(GameObjectProcessSpellCastEventArgs Args)
{
if (Args.SData == null)
{
return;
}
var target = TargetSelector.SelectedTarget;
if (target != null && target.IsValidRange())
{
if (MenuInit.BurstMode == 0)
{
ShyBurst(target, Args);
}
else
{
EQFlashBurst(target, Args);
}
}
}
private static void ShyBurst(AIHeroClient target, GameObjectProcessSpellCastEventArgs Args)
{
switch (Args.SData.Name)
{
case "ItemTiamatCleave":
if (W.IsReady() && target.IsValidRange(W.Range))
{
Player.Instance.Spellbook.CastSpell(SpellSlot.W);
}
else if (Q.IsReady() && target.IsValidRange(400))
{
CastQ(target);
}
break;
case "RivenMartyr":
if (MenuInit.ComboR2 == 0 && R.IsReady() && isRActive)
{
R1.Cast(target.Position);
}
else if (Q.IsReady() && target.IsValidRange(400))
{
CastQ(target);
}
break;
case "RivenFeint":
if (Item.HasItem(3142) && Item.CanUseItem(3142))
{
Item.UseItem(3142);
}
if (R.IsReady() && !isRActive)
{
R.Cast();
}
break;
case "RivenIzunaBlade":
if (Q.IsReady() && target.IsValidRange(400))
{
Player.Instance.Spellbook.CastSpell(SpellSlot.Q, target.Position);
}
break;
}
}
private static void EQFlashBurst(AIHeroClient target, GameObjectProcessSpellCastEventArgs Args)
{
switch (Args.SData.Name)
{
case "ItemTiamatCleave":
if (W.IsReady() && target.IsValidRange(W.Range))
{
Player.Instance.Spellbook.CastSpell(SpellSlot.W);
}
else if (Q.IsReady() && target.IsValidRange(400))
{
CastQ(target);
}
break;
case "RivenMartyr":
if (MenuInit.ComboR2 == 0 && R.IsReady() && isRActive)
{
R1.Cast(target.Position);
}
else if (Q.IsReady() && target.IsValidRange(400))
{
CastQ(target);
}
break;
case "RivenIzunaBlade":
if (Q.IsReady() && target.IsValidRange(400))
{
Player.Instance.Spellbook.CastSpell(SpellSlot.Q, target.Position);
}
break;
}
}
}
}
|
e3133c50570098ec9c7eea7df2b7e10443563cac
|
[
"C#"
] | 24 |
C#
|
minhhieu0701/EloBuddy
|
afb6dcb9ce1f01d674c1b11bb1d6d3dac89ec737
|
70825267fcc5ce8f09738b347f7d742639d78111
|
refs/heads/master
|
<file_sep>print("VRSEC")
print("HELLO WORLD")
<file_sep>print("DDD")
|
1cadd309ab05e6e9c940257050d75ff3b5350d1e
|
[
"Python"
] | 2 |
Python
|
Pamidighantam-Anvitha/newproject
|
96bdce046b4ccc406efff9230a32170f8e91e3fe
|
cb1f99d9693cea5da7316f4773b1765d8dfea3ef
|
refs/heads/release
|
<file_sep>/***
*
* WARN: THIS FILE IS CURRENTLY NOT BEING USED. IT IS PREPARED IN LIGHT OF PROBABLE FUTURE NEED.
*
*/
import { pool } from "../db";
// QUERIES
// 1. DEDITCATED TO ADMIN
const getAllBuyersAdminQuery = `SELECT * FROM buyers ORDER BY id`;
const getBuyerByIdAdminQuery = `SELECT * FROM buyers WHERE id = $1`; // used mainly to check if buyer exists
// 2. ALL SITE VISITORS
const getBuyerByIdQuery = `SELECT * FROM buyers WHERE id = $1`; // used mainly to check if buyer exists
const getBuyerByEmailQuery = `SELECT * FROM buyers WHERE email = $1`; // used mainly to check if buyer exists
const addNewBuyerQuery = `INSERT INTO buyers (customer_name, email, phone_number) VALUES ($1, $2, $3)`; // used to add a new buyer when they request for quote
// METHODS
/***************** THE FOLLOWING METHODS ARE ACCESSIBLE TO ALL PUBLIC ROUTES *******************/
// FETCH DATA OF A BUYER FROM DATABASE BY BUYER ID (accessible to anyone visiting the site)
function getBuyerById(bId) {
return pool.query(getBuyerByIdQuery, [bId]);
}
// FETCH DATA OF ALL BUYER FROM DATABASE BY BUYER EMAIL
// Note: this is used only during the initial stage of quote requesting process (accessible to anyone...
// ...who would like to send quote request to a handyman on the site)
function getBuyerByEmail(bEmail) {
return pool.query(getBuyerByEmailQuery, [bEmail]);
}
// STORE BUYER DATA IN THE DATABASE (buyers table)
// Note: this is used only during the initial stage of quote requesting process (accessible to anyone...
// ...who would like to send quote reqeust to a handyman on the site)
function addNewBuyer(bData) {
console.log(bData);
const { buyerName, buyerEmail, buyerPhoneNumber } = bData;
return pool.query(addNewBuyerQuery, [
buyerName,
buyerEmail,
buyerPhoneNumber,
]);
}
/******************************************************************************************************/
/***************** THE FOLLOWING METHODS ARE DEDICATED TO ADMIN-ACCESSIBLE ROUTES *******************/
// WARN: ANY REQUIRED AUTHORISATION LOGIC IS YET TO BE ADDED
// FETCH DATA OF ALL BUYER FROM DATABASE (accessible to admin only)
function getAllBuyersForAdmin() {
return pool.query(getAllBuyersAdminQuery);
}
// FETCH DATA OF A BUYER FROM DATABASE BY BUYER ID (accessible to admin only)
function getBuyerByIdForAdmin(bId) {
return pool.query(getBuyerByIdAdminQuery, [bId]);
}
module.exports = {
getBuyerById,
getBuyerByEmail,
addNewBuyer,
getAllBuyersForAdmin,
getBuyerByIdForAdmin,
};
<file_sep>import { createHmac, randomBytes, createHash } from "crypto";
const bcrypt = require("bcryptjs");
import { pool } from "../db";
exports.signUpUser = async (userObj) => {
try {
// 1) TO CHECK IF INPUT HAS WHAT WE NEED plus SANITIZATION
const { name, email, password, passwordConfirm, role } = userObj;
if (role === "admin")
throw new Error("Creating admins in this way is forbidden");
if ((role !== "buyer" && role !== "handyperson") || role === "")
throw new Error("You can only create buyer or handyperson account");
if (!name) throw new Error("You need to provide name");
if (!email) throw new Error("You need to provide email address"); //!TODO: backend validation
if (!(password === passwordConfirm))
throw new Error("Password and password confirmation must be equal");
// 2) run pool.query() - may give the error if mail is in use - return msg to front
const encryptedPassword = await bcrypt.hash(password, 12); //.hash() is async
const dataOfCreation = new Date();
// 3)
// !TODO: returning * is not best solution in my opinion / temporary - kick out password from input later
const newUser = await pool.query(
`INSERT INTO users (first_name, email, user_password, password_changed_at, user_role) VALUES ($1, $2, $3, $4, $5) RETURNING * `,
[name, email, encryptedPassword, dataOfCreation, role]
);
// 3) if success inform user
return newUser;
// !TODO: is it all?
} catch (error) {
throw error;
}
};
exports.logInUser = async (userCredential) => {
try {
const { email, password } = userCredential;
const newUserArray = await pool.query(
`SELECT * FROM users WHERE email = $1`,
[email]
);
if (newUserArray.rowCount === 0)
throw new Error("Incorrect email or password");
const newUser = newUserArray.rows[0];
//return true if both password are the same
const testBoolean = await bcrypt.compare(password, new<PASSWORD>);
if (!testBoolean) throw new Error("Incorrect email or password");
// 3) if success inform user
return newUser;
} catch (error) {
throw error;
}
};
exports.findUserByTokenDecoded = async (decoded) => {
try {
const newUserArray = await pool.query(
`SELECT * FROM users WHERE user_id = $1`,
[decoded.id]
);
if (newUserArray.rowCount === 0)
throw new Error("The user related to this token does no longer exist.");
const newUser = newUserArray.rows[0];
const changedTimestamp = parseInt(
newUser.password_changed_at.getTime() / 1000,
10
);
if (decoded.iat < changedTimestamp) throw new Error("Not valid token");
return newUser;
} catch (error) {
throw error;
}
};
exports.findOneUser = async (userCredential) => {
try {
const { email } = userCredential;
const newUserArray = await pool.query(
`SELECT * FROM users WHERE email = $1`,
[email]
);
if (newUserArray.rowCount === 0)
throw new Error("User with that email no exist");
const newUser = newUserArray.rows[0];
return newUser;
} catch (error) {}
};
exports.createPasswordResetToken = async (userObject) => {
try {
const resetToken = randomBytes(32).toString("hex");
const passwordResetTokenToDB = createHash("sha256")
.update(resetToken)
.digest("hex");
const expirationTime = new Date();
expirationTime.setMinutes(expirationTime.getMinutes() + 10);
const newUserArray = await pool.query(
`UPDATE users SET password_reset_token = $1, password_reset_expires = $2 WHERE email = $3`,
[passwordResetTokenToDB, expirationTime, userObject.email]
);
return resetToken;
} catch (error) {
throw error;
}
};
exports.findUserBaseOnResetToken = async (token) => {
try {
const userToResetPassword = await pool.query(
`SELECT * FROM users WHERE password_reset_token=$1;`,
[token]
);
if (userToResetPassword.rowCount === 0)
throw new Error("There is no user related to that token");
const user = userToResetPassword.rows[0];
// check if the token did not expires.
const date = new Date(user.password_reset_expires);
const milliseconds = date.getTime();
if (milliseconds < Date.now()) throw new Error("Token already expired");
return user;
} catch (error) {
throw error;
}
};
exports.updatePasswordAfterRecovery = async (
user,
password,
passwordConfirm
) => {
try {
//!TODO: is it logical tu put it earlier? I think so - do in refactor
if (!password || !passwordConfirm)
throw new Error("You need to provide password and password confirmation");
if (password !== passwordConfirm)
throw new Error("Password and password confirmation must be equal");
const encryptedPassword = await bcrypt.hash(password, 12); //.hash() is async
// minus 1000 millisecond from data Of creation -> because saving to DB is taking time
const dataOfCreation = new Date();
//!TODO: what about cleaning the fields in DB? null? empty string?
const _ = await pool.query(
`UPDATE users SET user_password = $1, password_changed_at = $2, password_reset_token=$3, password_reset_expires=$4 WHERE email = $5`,
[
encryptedPassword,
dataOfCreation,
"",
"1970-06-21 15:46:38.799+01",
user.email,
]
);
//!TODO: dummy return
return "";
} catch (error) {
throw error;
}
};
exports.findUserById = async (userId, passwordCurrent) => {
try {
const userToChangePassword = await pool.query(
`SELECT * FROM users WHERE user_id=$1;`,
[userId]
);
const userObject = userToChangePassword.rows[0];
//!TODO: take out this part of the code and create helper function to check passwords
//return true if both password are the same
const testBoolean = await bcrypt.compare(
passwordCurrent,
userObject.user_password
);
if (!testBoolean) throw new Error("Incorrect password");
return userObject;
} catch (error) {
throw error;
}
};
exports.updateUserPassword = async (
userId,
passwordCandidate,
passwordCandidateConfirm
) => {
try {
if (passwordCandidate !== passwordCandidateConfirm)
throw new Error("Password candidates are not equal");
const encryptedPassword = await bcrypt.hash(passwordCandidate, 12); //.hash() is async
// minus 1000 millisecond from data Of creation -> because saving to DB is taking time
const dataOfCreation = new Date();
const _ = await pool.query(
`UPDATE users SET user_password = $1, password_changed_at = $2 WHERE user_id = $3`,
[encryptedPassword, dataOfCreation, userId]
);
//!TODO: dummy return
return "";
} catch (error) {
throw error;
}
};
<file_sep>const express = require("express");
const router = express.Router();
import { pool } from "./../db";
import authController from "./../controller/authController";
import userController from "./../controller/userController";
router.post("/signup", authController.signup);
router.post("/login", authController.login);
// router.get('/logout', /* FUNCTION*/);
router.post("/forgotPassword", authController.forgotPassword);
router.patch("/resetPassword/:token", authController.resetPassword);
// all bellow - you need to be authenticated
//at this point we can use the route which is going to protect everything below
// because middleware are called sequentially
/**
* To reach routes bellow You need to be logged in
*/
router.use(authController.protect);
router.patch("/updateMyPassword", authController.updatePassword);
router.get("/me", async (req, res, next) => {
res.status(200).json({
status: "success",
msg: `get method usersRouter "/me"`,
});
});
// we are getting id from the token jwt so no one can update someone else account! <3
router.patch("/updateMe", authController.protect, userController.updateMe);
router.delete("/deleteMe", async (req, res, next) => {
res.status(200).json({
status: "success",
msg: `delete method usersRouter "/deleteMe"`,
});
});
/*
Routes dedicated only for admin
*/
/**
* To reach routes bellow You need to be logged in as a administrator
*/
router.use(authController.restrictTo("admin"));
router
.route("/")
.get(async (req, res, next) => {
try {
const bookingsAll = await pool.query("SELECT * FROM users");
res.status(200).json({
status: "success",
length: bookingsAll.rowCount,
data: bookingsAll.rows,
});
} catch (error) {
res.status(400).json({
status: "fail",
msg: error.message,
});
}
})
.post(async (req, res, next) => {
res.status(200).json({
status: "success",
msg: 'post method usersRouter "/"',
});
});
router
.route("/:userId")
.get(async (req, res, next) => {
try {
const { userId } = req.params;
const bookingsAll = await pool.query(
`SELECT * FROM users WHERE user_id = $1`,
[userId]
);
res.status(200).json({
status: "success",
status: "success",
length: bookingsAll.rowCount,
data: bookingsAll.rows[0],
});
} catch (error) {
res.status(400).json({
status: "fail",
msg: error.message,
});
}
})
.patch(async (req, res, next) => {
const { userId } = req.params;
res.status(200).json({
status: "success",
msg: `patch method usersRouter "/:offerId" You sent ${userId}`,
});
})
.delete(async (req, res, next) => {
const { userId } = req.params;
res.status(200).json({
status: "success",
msg: `delete method usersRouter "/:offerId" You sent ${userId}`,
});
});
module.exports = router;
<file_sep>import pool from "../db";
// QUERIES
// 1. DEDITCATED TO ADMIN
const getAllHandymenAdminQuery = `SELECT * FROM handyman WHERE id > 0 ORDER BY id`;
const getHandymanByIdAdminQuery = `SELECT * FROM handyman WHERE id = $1`; // used mainly to check if handyman exists
const changeHandymanVisibilityByIdAdminQuery = `UPDATE handyman SET visible = $1 WHERE id = $2`;
const editHandymanDetailsByIdAdminQuery = `UPDATE handyman
SET first_name = $1,
last_name= $2,
address=$3,
postcode=$4,
email=$5,
phone_number=$6,
skills=$7,
bio=$8
WHERE id=$9`;
const deleteHandymanByIdAdminQuery=`DELETE FROM handyman WHERE id=$1`;
// 2. ALL SITE VISITORS
const getAllHandymenQuery = `
SELECT id,first_name,last_name,img,address,postcode,email,phone_number,skills,bio
FROM handyman
WHERE visible = true
ORDER BY id`;
const getHandymanByIdQuery = `SELECT * FROM handyman WHERE id = $1`; // used mainly to check if handyman exists
const getHandymanByEmailQuery = `SELECT * FROM handyman WHERE email = $1`; // used mainly to check if handyman exists
const addNewHandymanQuery = `
INSERT INTO handyman (first_name, last_name, img, address, postcode, email, phone_number, skills, bio)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`;
// WARN: THIS QUERY IS CURRENTLY NOT BEING USED. IT IS INCLUDED IN LIGHT OF PROBABLE FUTURE NEEDS
const getReviewsByHandymanIdQuery = `
SELECT r.review_body, r.rating
FROM reviews AS r
INNER JOIN handyman as h ON h.id=r.handyman_id
WHERE r.handyman_id=$1`;
const threeRandomHandymanQuery = `SELECT *FROM handyman
where visible = 'true'
ORDER BY random()
LIMIT 3`;
// METHODS
/***************** THE FOLLOWING METHODS ARE ACCESSIBLE TO ALL PUBLIC ROUTES *******************/
// FETCH DATA OF ALL HANDYMEN FROM DATABASE (accessible to anyone visiting the site)
function getAllHandymen() {
return pool.query(getAllHandymenQuery);
}
// FETCH DATA OF A HANDYMEN FROM DATABASE BY HANDYMAN ID (accessible to anyone visiting the site)
function getHandymanById(hId) {
return pool.query(getHandymanByIdQuery, [hId]);
}
// FETCH DATA OF ALL HANDYMEN FROM DATABASE BY HANDYMAN EMAIL
// Note: this is used only during the initial stage of handyman registration process (accessible to anyone...
// ...who would like to register as handyman on the site)
function getHandymanByEmail(hEmail) {
return pool.query(getHandymanByEmailQuery, [hEmail]);
}
// STORE HANDYMAN DATA IN THE DATABASE (handypeople table)
// Note: this is used only during the initial stage of handyman registration process (accessible to anyone...
// ...who would like to register as handyman on the site)
function addNewHandyman(hData) {
const {
firstName,
lastName,
img,
address,
postcode,
email,
phoneNumber,
skills,
bio,
} = hData;
return pool.query(addNewHandymanQuery, [
firstName,
lastName,
img,
JSON.stringify(address),
postcode,
email,
phoneNumber,
skills,
bio,
]);
}
// WARN: THIS FUNCTION IS CURRENTLY NOT BEING USED. IT IS INCLUDED IN LIGHT OF PROBABLE FUTURE NEEDS
function getReviewsByHandymanId(hId) {
return pool.query(getReviewsByHandymanIdQuery, [hId]);
}
function getThreeRandomHandyman() {
return pool.query(threeRandomHandymanQuery);
}
// edit handyman details
function editHandymanDetailsByIdAdmin(hData) {
const {
firstName,
lastName,
//img,
address,
postcode,
email,
phoneNumber,
skills,
bio,
id,
} = hData;
return pool.query(editHandymanDetailsByIdAdminQuery, [
firstName,
lastName,
//img,
address,
postcode,
email,
phoneNumber,
skills,
bio,
id,
]);
}
function deleteHandymanByIdAdmin(hId){
return pool.query(deleteHandymanByIdAdminQuery,[hId]);
}
/******************************************************************************************************/
/***************** THE FOLLOWING METHODS ARE DEDICATED TO ADMIN-ACCESSIBLE ROUTES *******************/
// WARN: ANY REQUIRED AUTHORIZATION LOGIC IS YET TO BE ADDED
// FETCH DATA OF ALL HANDYMEN FROM DATABASE (accessible to admin only)
function getAllHandymenForAdmin() {
return pool.query(getAllHandymenAdminQuery);
}
// FETCH DATA OF A HANDYMEN FROM DATABASE BY HANDYMAN ID (accessible to admin only)
function getHandymanByIdForAdmin(hId) {
return pool.query(getHandymanByIdAdminQuery, [hId]);
}
function changeHandymanVisibilityByAdmin({ visible, id }) {
return pool.query(changeHandymanVisibilityByIdAdminQuery, [visible, id]);
}
module.exports = {
getAllHandymen,
getHandymanById,
getAllHandymenForAdmin,
getHandymanByIdForAdmin,
changeHandymanVisibilityByAdmin,
getHandymanByEmail,
addNewHandyman,
getReviewsByHandymanId,
getThreeRandomHandyman,
editHandymanDetailsByIdAdmin,
deleteHandymanByIdAdmin,
};
<file_sep>import React from "react";
export default function MapComponent() {
return (
<div className="map">
<h1>Visit Us </h1>
<iframe src="https://www.google.com/maps/embed?pb=!1m26!1m12!1m3!1d311161.9892285095!2d-1.9661420860588694!3d52.46187788478476!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!4m11!3e6!4m3!3m2!1d52.5116862!2d-1.8763893999999999!4m5!1s0x48774bbe9d07671d%3A0x345200cdebcdd0a6!2scoventry%20refugee%20and%20migrant%20centre!3m2!1d52.412192399999995!2d-1.5062254!5e0!3m2!1sen!2suk!4v1624495032268!5m2!1sen!2suk" width="400" height="300" allowFullScreen="" loading="lazy" title="coventry refugee center map" >
</iframe>
</div>
);
}
<file_sep>import React from "react";
import { Link } from "react-router-dom";
import repairsLogo from "../../public/logo.png";
/**
* @DescriptionFunction Reusable component which can be styled in very simple way by passing the <props.height>
* background-color is inherit from the parent element.
*/
import classes from "./Logo.module.scss";
// TODO: added Link may give problems in styling add class in that case and style it
const logo = (props) => (
<Link to="/">
<div className={classes.logo} style={{ height: props.height }}>
<img src={repairsLogo} alt="an arm holding a spanner" />
</div>
</Link>
);
export default logo;
<file_sep>import { Pool } from "pg";
require("dotenv").config();
const dbUrl =
process.env.DATABASE_URL || "postgres://localhost:5432/repairs_for_you";
// local machine
let configObject = {
user: process.env.USER_SQL,
host: process.env.HOST_SQL,
database: process.env.DATABASE_SQL,
password: <PASSWORD>,
port: process.env.PORT_SQL,
};
// modify object in production - HEROKU SOLUTION
if (process.env.DATABASE_URL) {
configObject = {
connectionString: dbUrl,
ssl: {
rejectUnauthorized: false,
},
connectionTimeoutMillis: 5000,
};
}
export const pool = new Pool(configObject);
export const connectDb = async () => {
let client;
try {
client = await pool.connect();
} catch (err) {
console.error(err);
process.exit(1);
}
console.log("Postgres connected to", client.database);
client.release();
};
export const disconnectDb = () => pool.close();
export default { query: pool.query.bind(pool) };
<file_sep>import React, { useEffect, useState } from "react";
/**
* @DescriptionFunction Component which is used in UsersManagement component to provide to admin graphical representation of users data.
* Base on it, admin can chose user and decide the next steps
*/
const UserDetailedProfile = (props) => {
const [singleUser, setSingleUser] = useState("");
const userId = props.match.params.id;
useEffect(async () => {
try {
const userRaw = await fetch(`/api/v1/users/${userId}`);
const userFetched = await userRaw.json();
console.log(userFetched);
setSingleUser((prevState) => ({
...prevState,
...userFetched.data
}));
} catch (error) {
console.log(error.message);
}
}, []);
console.log(singleUser);
let user = <h1>Loading</h1>;
if (singleUser) {
user = (
<div>
<p> first name: {singleUser.first_name} </p>
<p> last name: {singleUser.last_name} </p>
<p> user role: {singleUser.user_role} </p>
<p> created at: {singleUser.created_data} </p>
</div>
);
}
return (<div>{ user }</div>);
};
export default UserDetailedProfile;
<file_sep>import handymanServices from "../services/handymanServices";
exports.threeRandomHandyman = async () => {
try {
const randomHandyman = await handymanServices.getThreeRandomHandyman();
if (randomHandyman.length === 0) {
throw new Error("We do not have any handyman");
}
return randomHandyman
} catch (error) {
throw error;
}
};
<file_sep>const repository = require("../data/quotesRepository");
import { getBuyerByEmail, addNewBuyer } from "../data/buyerRepository";
/***************** THE FOLLOWING METHODS ARE DEDICATED TO ADMIN-ACCESSIBLE ROUTES *******************/
// WARN: ANY REQUIRED AUTHORIZATION LOGIC IS YET TO BE ADDED
// GET ALL QUOTES (currently accessible only to admin)
async function getAllQuotes() {
return await repository.getAllQuotes();
}
// SEARCH QUOTE FROM LIST BY QUOTE ID (currently accessible only to admin)
async function getQuoteById(qId) {
const result = await repository.getQuoteById(qId);
return result;
}
// POST A NEW QUOTE (currently accessible to all site visitors)
async function addNewQuote(qData) {
const dataIsValid = validateQuoteData(qData);
if (dataIsValid) {
try {
// check if buyer is new to the site, and if they are, attempt to add their basic data to database
// const result = await getBuyerByEmail(qData.buyerEmail); WARN: LINE COMMENTED OUT AS FEATURE IS CURRENTLY NOT IMPLEMENTED
// if (result.rowCount === 0) await addNewBuyer(qData); WARN: LINE COMMENTED OUT AS FEATURE IS CURRENTLY NOT IMPLEMENTED
// continue attempt to add new quote request data to database
await repository.addNewQuote(qData);
return {
status: "OK",
message: "Quote has been added successfully.",
};
} catch (error) {
// if there is database connection issue
return console.log(error);
}
}
return {
status: "FAIL",
message: "Quote could not be saved. Missing quote information.",
};
}
// validate incoming quote data
function validateQuoteData(qData) {
// required quote data fields
try {
const { buyerName, buyerEmail, jobDescription, jobStartDate, handymanId } =
qData;
const dataToValidate = {
buyerName,
buyerEmail,
jobDescription,
jobStartDate,
handymanId,
};
return Object.values(dataToValidate).every((value) => value!=="");
} catch (err) {
console.log(err);
}
}
module.exports = {
getAllQuotes,
getQuoteById,
addNewQuote,
};
<file_sep>import React from "react";
import { Route, Redirect, Switch, useRouteMatch, Link } from "react-router-dom";
/**
* @DescriptionFunction Detailed profile of user where admin can use his privileges
* !TODO: this component is not implemented, regarding functionality it is like placeholder
*/
const UserManagements = (props) => {
let { path, url } = useRouteMatch();
return (
<li>
<p> first name: {props.user.first_name} </p>{" "}
<p> last name: {props.user.last_name} </p>{" "}
<p> user role: {props.user.user_role} </p>{" "}
<p> created at: {props.user.created_data} </p>{" "}
<Link to={`${url}/${props.user.user_id}`}> Users Management Panel </Link>{" "}
</li>
);
};
export default UserManagements;
<file_sep>import React from "react";
import Button from "../../UI/button/Button";
import classes from "./CompletionFormScreen.module.css";
/**
* @DescriptionFunction Component is responsible to render the completion page
* which is confirming to user that sign-up form has been sent
* @param {Function} props.back [function which should redirect user to pointed page. Function is attached to button to "onClick" event]
*/
const confirmationFormPage = (props) => {
const form = (
<div className={classes.container}>
<h1 className={classes.title}>Thank You For Your Registration</h1>
<p className={classes.subTitle}>
You can log-in into your account now.
</p>
<div
className={[
classes.flexContainerGeneral,
classes.flexContainerCentered,
].join(" ")}
>
{props.back && (
<div className={classes.buttonWrapper}>
<Button assignedClass={"nextButton"} clicked={props.back}>
OK
</Button>
</div>
)}
</div>
</div>
);
return form;
};
export default confirmationFormPage;
<file_sep>exports.updateMe = async (req, res, next) => {
try {
// error if user want to update password
if (req.body.password || req.body.passwordCandidate) {
throw new Error("This route is not for passwords update. please use /updateMyPassword");
}
// update user data
res.status(200).json({
status: "success"
})
} catch (error) {
res.status(400).json({
status: "fail",
msg: error.message,
});
}
};
<file_sep>import React, { useState } from "react";
import Aux from "./../Auxillary/Auxillary.js";
import Toolbar from "./../../components/Navigation/Toolbar/Toolbar.js";
import SideDrawer from "./../../components/Navigation/Sidedrwer/Sidedrawer.js";
import Footer from "./../../components/Footer/Footer.js";
import classes from "./Layout.module.scss";
/**
* @DescriptionFunction Main Layout of application, where <main> is used as a widget to display other parts of application required by specification.
*/
const Layout = (props) => {
const [sideDrawerIsVisible, setSideDrawerVisible] = useState(false);
const sideDrawerClosedHandler = () => {
setSideDrawerVisible(false);
};
const sideDrawerToggleHandler = () => {
setSideDrawerVisible(!sideDrawerIsVisible);
};
return (
<Aux>
<Toolbar drawerToggleClicked={sideDrawerToggleHandler} />
<SideDrawer open={sideDrawerIsVisible} closed={sideDrawerClosedHandler} />
<main className={classes.content}>{props.children}</main>
<Footer />
</Aux>
);
};
export default Layout;
<file_sep>import express from "express";
import morgan from "morgan";
import path from "path";
import {
configuredHelmet,
httpsOnly,
logErrors,
pushStateRouting,
} from "./middleware";
import bookingRouter from "./routers/bookingRouter";
import offersRouter from "./routers/offersRouter";
import reviewRouter from "./routers/reviewRouter";
import usersRouter from "./routers/usersRouter";
import handymanRouter from "./routers/handymanRouter";
import quotesRouter from "./routers/quotesRouter";
const apiRoot = "/api";
const staticDir = path.join(__dirname, "static");
const app = express();
app.use(express.json());
app.use(configuredHelmet());
app.use(logErrors());
app.use(morgan("dev"));
if (app.get("env") === "production") {
app.enable("trust proxy");
app.use(httpsOnly());
}
app.use((req, res, next) => {
req.requestTime = new Date().toISOString();
next();
});
// our router
app.use("/api/v1/booking", bookingRouter);
app.use("/api/v1/offers", offersRouter);
app.use("/api/v1/reviews", reviewRouter);
app.use("/api/v1/users", usersRouter);
app.use("/api/v1/handyman", handymanRouter);
app.use("/api/v1/quotes", quotesRouter);
app.use(express.static(staticDir));
app.use(pushStateRouting(apiRoot, staticDir));
export default app;
<file_sep>import React, { useContext, useEffect } from "react";
import AuthContext from "../../store/authContext";
const SignOut = (props) => {
const authCtx = useContext(AuthContext);
useEffect(() => {
authCtx.logout();
props.history.push("/");
}, []);
return <div>WWe can add here loading spinner</div>;
};
export default SignOut;
<file_sep>import { Link, useRouteMatch } from "react-router-dom";
import "./Handyman.css";
import userDefaultImg from "../../../public/user.svg"; // WARN: TEMPORARY SOLUTION
// import { useEffect, useState } from "react"; WARN: INTENDED FOR FUTURE USE
const Handyman = ({ userData }) => {
// const [reviews, setReviews] = useState([]); WARN: CURRENTLY NOT BEING USED. INCLUDED HERE IN LIGHT OF PROBABLE FUTURE NEEDS
const { id, first_name, last_name, address, area, skills } = userData;
const data = { id, first_name, last_name, address, area, skills };
const { url } = useRouteMatch();
// WARN: COMMENTED OUT CODE BELOW IS HOPED TO BE USED AS PART OF FUTURE SITE IMPROVEMENTS
// useEffect(() => {
// fetch(`/api/v1/handyman/handymannotprotected/${id}/reviews`)
// .then((res) => {
// if (!res.ok) {
// throw new Error(res.statusText);
// }
// return res.json();
// })
// .then((data) => {
// setReviews(data);
// })
// .catch((err) => {
// console.error(err);
// });
// }, [id]);
return (
<div className="handyman">
{/* <div className="profile-image-bio"> */}
<figure className="profile-figure">
<img
className="profile-image"
src={userDefaultImg} // WARN: TEMPORARY SOLUTION
alt={`${userData.first_name} ${userData.last_name}`}
/>
<figcaption>
<p className="handyman-name">{`${userData.first_name} ${userData.last_name}`}</p>
{/* NOTE: COMMENTED OUT SECTION BELOW IS HOPED TO BE PART OF FUTURE SITE IMPROVEMENTS */}
{/* <p>
<span className="label">Rating:</span>
<span className="stars">{userData.rating} stars</span>
</p> */}
</figcaption>
</figure>
<Link
to={{ pathname: `${url}/forms/request-for-quote`, state: data }}
className="link-btn-quote top-link"
>
<button id="btn-quote">Get a Quote</button>
</Link>
<div className="bio-handyman">
<h2>About Me</h2>
<p>{userData.bio}</p>
</div>
{/* </div> */}
<div className="skills">
<h3>My Skills</h3>
<ul className="skills-list">
{skills.map((skill, index) => (
<li key={index}>{skill}</li>
))}
</ul>
</div>
<Link
to={{ pathname: `${url}/forms/request-for-quote`, state: data }}
className="link-btn-quote buttom-link"
>
<button id="btn-quote">Get a Quote</button>
</Link>
{/* NOTE: COMMENTED OUT SECTION BELOW IS HOPED TO BE PART OF FUTURE SITE IMPROVEMENTS */}
{/* <div className="user-reviews">
<span className="label">Reviews:</span>
{reviews && <span className="stars">{reviews.length}</span>}
<div>
<a href="#customer-review">Add a review</a>
</div>
{reviews &&
reviews.map((review, index) => (
<div key={index} className="review">
<p className="review-body">{review.review_body}</p>
<br />
</div>
))}
<form id="form-review" onSubmit={() => {}}>
<label htmlFor="customer-review">Your Review</label>
<input
type="text-area"
id="customer-review"
name="customer-review"
placeholder="Enter your review here..."
/>
<input
type="submit"
id="add-review"
name="add-review"
value="Send Review"
/>
</form>
</div> */}
</div>
);
};
export default Handyman;
<file_sep>const express = require("express");
const router = express.Router();
import {
pool
} from "./../db";
//TODO: doubled route - Michael created route quotes what is basically the same in concept
/*
the main root of this router is: "/api/v1/booking"
*/
router
.route("/")
.get(async (req, res, next) => {
try {
const bookingsAll = await pool.query("SELECT * FROM offers");
res.status(200).json({
status: "success",
msg: "bookings route was not created yet",
});
} catch (error) {
res.status(400).json({
status: "fail",
msg: error.message,
});
}
})
.post(async (req, res, next) => {
res.status(200).json({
status: "success",
msg: 'post method bookingRouter "/"',
});
});
router
.route("/:bookingId")
.get(async (req, res, next) => {
try {
const {
bookingId
} = req.params;
const bookingsAll = await pool.query(
`SELECT * FROM offers WHERE offer_id = $1`,
[bookingId]
);
res.status(200).json({
status: "success",
msg: "bookings route was not created yet",
});
} catch (error) {
res.status(400).json({
status: "fail",
msg: error.message,
});
}
})
.patch(async (req, res, next) => {
const {
bookingId
} = req.params;
res.status(200).json({
status: "success",
msg: `patch method bookingRouter "/:bookingId" You sent ${bookingId}`,
});
})
.delete(async (req, res, next) => {
const {
bookingId
} = req.params;
res.status(200).json({
status: "success",
msg: `delete method bookingRouter "/:bookingId" You sent ${bookingId}`,
});
});
module.exports = router;<file_sep>import React from "react";
import classes from "./CustomerCommentMain.module.scss";
import fullStart from "../../../../public/starFullColor.svg";
import star from "../../../../public/star.svg";
const imgItem = (link, i) => (
<img
className={classes.customer__star}
key={i}
src={link}
alt="Star icon made by Freepik"
/>
);
/**
* @DescriptionFunction sub component used by CustomerSection to create the review of users widget which is going to be displayed on main page.
* @params component is getting object <item> passed though parent component, which contain:
* - review: integer
* - photo: string which point to directory where is stored picture
* - user_name: string with name of the user
* - user_surname: string with surname of the user
* - comment: comment provided by user regarding service
*/
const CustomerCommentMain = (props) => {
let stars = [];
for (let i = 0; i < 6; i++) {
if (i < props.item.review) {
stars.push(imgItem(fullStart, i));
}
if (i > props.item.review) {
stars.push(imgItem(star, i));
}
}
return (
<div className={classes.customer}>
<figure className={classes.customer__figure}>
<img className={classes.customer__img} src={props.item.photo} />
<figcaption className={classes.customer__figcaption}>
{props.item.user_name} {props.item.user_surname[0]}.
</figcaption>
</figure>
<p>{props.item.comment}</p>
<div className={classes.customer__starContainer}>{stars}</div>
</div>
);
};
export default CustomerCommentMain;
<file_sep>import { Route, Switch, Redirect, withRouter } from "react-router-dom";
import React, { useContext, Suspense } from "react";
import classes from "./App.module.scss";
import Layout from "./hoc/Layout/Layout";
import Login from "./containers/signUp/SignUp";
import MainPage from "./components/mainPage/mainPage";
import SignOut from "./containers/signOut/signOut";
import AuthContext from "./store/authContext";
import Spinner from "./UI/Spinner/Spinner";
import ScrollToTop from "./components/Navigation/ScrollToTop";
//Lazy loading
const AdminPanel = React.lazy(() => {
return import("./components/adminPanel/AdminPanel");
});
const HandymanRoutes = React.lazy(() => {
return import("./components/Handyman/HandymanRoutes");
});
const Contact = React.lazy(() => {
return import("../src/components/contact/Contact");
});
const SignIn = React.lazy(() => {
return import("./containers/signIn/SignIn");
});
const App = () => {
const authCtx = useContext(AuthContext);
return (
<div className={classes.container}>
<Layout>
<ScrollToTop />
<Suspense
className={classes.container__test}
fallback={
<div className={classes.spinner__container}>
<Spinner />
</div>
}
>
<Switch>
<Route
path="/"
exact
component={(props) => <MainPage {...props} />}
/>
<Route
path="/buyers"
component={() => (
<div>
<h1>PLACEHOLDER buyers</h1>
</div>
)}
/>
<Route
path="/users/handyman"
render={(props) => <HandymanRoutes {...props} />}
/>
<Route path="/contact" render={() => <Contact />} />
<Route
path="/signinout"
component={(props) => <SignOut {...props} />}
/>
<Route
path="/signin"
component={(props) => <SignIn {...props} />}
/>
{authCtx.isLoggedIn && (
<Route
path="/admin-panel"
render={(props) => <AdminPanel {...props} />}
/>
)}
<Route path="/login" component={(props) => <Login {...props} />} />
<Redirect to="/" />
</Switch>
</Suspense>
</Layout>
</div>
);
};
export default withRouter(App);
<file_sep>import React from "react";
import { configure, shallow } from "enzyme";
import Adapter from "@wojtekmaj/enzyme-adapter-react-17";
import UnorderedList from "./UnorderedList";
import ListElement from "./listElement/ListElement";
configure({ adapter: new Adapter() });
const keyObjectArr = ["test1", "test2", "test3"];
const formValues = [
{
test1: { placeholder: 11, name: 1, value: 1 },
},
{
test2: { placeholder: 22, name: 2, value: 2 },
},
{
test3: { placeholder: 33, name: 3, value: 3 },
},
];
describe("<ConfirmationFormPage/>", () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(
<UnorderedList keyObjectArr={keyObjectArr} formValues={formValues} />
);
});
it("should render one <Button> item when props.back is sent", () => {
expect(wrapper.find(ListElement)).toHaveLength(3);
});
});
<file_sep>import moment from "moment";
const MINIMAL_REQUIRED_AGE = 18;
/**
* @DescriptionFunction Component responsible for rendering the sign-up forms including the input fields
* @param {String} value [validated input]
* @param {Object} rules [Config object - containing all necessary data which Validity should take place ]
*/
export const checkValidity = (value, rules) => {
let isValid = true;
if (!rules) {
return true;
}
if (rules.required) {
isValid = value.trim() !== "" && isValid;
}
if (rules.required) {
isValid = value.trim() !== "" && isValid;
}
if (rules.isEmail) {
const pattern = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
isValid = pattern.test(value) && isValid;
}
if (rules.isName) {
const pattern = /^[A-Za-z\s]+$/;
isValid = pattern.test(value) && isValid;
}
if (rules.isPassword) {
// Minimum eight characters, at least one letter, one number and one special character:
const pattern = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/;
isValid = pattern.test(value) && isValid;
}
if (rules.isTelNumber) {
const pattern = /^\d{11}$/; //simple regex
isValid = pattern.test(value) && isValid;
}
// TODO - Think over how to improve it
if (rules.isDOB) {
isValid = moment(value, "DD/MM/YYYY", true).isValid() && isValid;
}
if (rules.isEighteen) {
if (moment(value, "DD/MM/YYYY", true).isValid()) {
const birthday = moment(value, "DD/MM/YYYY");
isValid =
moment().diff(birthday, "years", false) >= MINIMAL_REQUIRED_AGE &&
isValid;
}
}
return isValid;
};
<file_sep>import { useState } from "react";
import HandymanRegistrationForm from "../components/Handyman/RegistrationForm/HandymanRegistrationForm";
const RegistrationForm = ({ formId }) => {
const [message, setMessage] = useState();
// EVENT HANDLERS
const getHandymanData = async (fromData) => {
const result = await sendRegistrationRequest(fromData);
setMessage(result.message);
};
return !formId ? (
<h1>Hello, world!</h1>
) : formId === "handyman" ? (
<HandymanRegistrationForm onAddHandyman={getHandymanData} />
) : (
<h1>Another Form</h1>
);
};
export default RegistrationForm;
<file_sep>import React from "react";
import Input from "../../UI/input/Input";
import Button from "../../UI/button/Button";
import Spinner from "../../UI/Spinner/Spinner"
import classes from "./SignUpForm.module.scss";
/**
* @DescriptionFunction Component responsible for rendering the sign-up forms including the input fields
* @param {Function} props.back [function which should return user to previous page. Function is attached to button to "onClick" event]
* @param {Function} props.next [function which should return user to next page. Function is attached to button to "onClick" event]
* @param {Function} props.formInputHandler [Reference to function which is responsible to change the value base on upcoming input]
* @param {Boolean} props.buttonDisable [Boolean value which is responsible for disabling the button]
* @param {Array of Object} props.form [Array of object containing the unique id and config file needed by Input component]
*/
const signUpForm = (props) => {
const flexClassStyleArr = [classes.flexContainerGeneral];
/**
* If condition which are going to change the CSS classes
* in relation to how many buttons need to be rendered, base on number of the passed event handlers
*/
if (props.next && props.back)
flexClassStyleArr.push(classes.flexContainerCentered);
if (props.next && !props.back)
flexClassStyleArr.push(classes.flexContainerToRight);
const inputForms = props.form.map((item, index) => {
return (
<div className={classes.inputContainer} key={item.id}>
<p className={classes.inputFieldName}>{item.config.name}</p>
<Input
id={"input" + index}
incorrectEmOrPass={props.wrongPasswordEmail}
invalid={!item.config.valid}
shouldValidate={item.config.validation}
touched={item.config.touched}
value={item.config.value}
placeholder={item.config.placeholder}
formInputHandler={(e) => props.formInputHandler(e, item.id)}
elementConfig={item.config.objectConfig}
/>
{!item.config.valid &&
item.config.touched && (
<p className={classes.invalidInputMsg}>
{item.config.invalidInputInfo}
</p>
)}
</div>
);
});
const buttonsPart = (
<div className={flexClassStyleArr.join(" ")}>
{props.back && (
<div className={classes.buttonWrapper}>
<Button assignedClass={"backButton"} clicked={props.back}>
{props.leftButtonName}
</Button>
</div>
)}
{props.next && (
<div className={classes.buttonWrapper}>
<Button
assignedClass={"nextButton"}
clicked={props.next}
buttonDisable={props.buttonDisable}
>
{props.rightButtonName}
</Button>
</div>
)}
</div>
);
return (
<div className={classes.container}>
<h1 className={classes.title}>{props.nameOfTheForm}</h1>
{inputForms}
{props.loading && <div className={classes.spinnerContainer}><Spinner /></div>}
{props.wrongPasswordEmail && (
<p className={classes.wrongPassOrEmail}>Incorrect Password or Email</p>
)}
{buttonsPart}
</div>
);
};
export default signUpForm;
<file_sep>import React from "react";
import { configure, shallow } from "enzyme";
import Adapter from "@wojtekmaj/enzyme-adapter-react-17";
import SignUpForm from "./SignUpForm";
import Button from "../UI/button/Button";
import Input from "../UI/input/Input";
configure({ adapter: new Adapter() });
const formElementKeyArrayOne = [
{
id: "name",
config: {
name: "Name",
placeholder: "Name",
value: "Patryk",
validation: {
required: true,
isName: true,
},
valid: false,
touched: false,
},
},
];
const formElementKeyArrayTwo = [
{
id: "name",
config: {
name: "Name",
placeholder: "Name",
value: "Patryk",
validation: {
required: true,
isName: true,
},
valid: false,
touched: false,
},
},
{
id: "Phone Number",
config: {
name: "Phone Number",
placeholder: "01234567890",
value: "01234567890",
validation: {
required: true,
isTelNumber: true,
},
valid: false,
touched: false,
},
},
];
describe("<ConfirmationFormPage/>", () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<SignUpForm form={formElementKeyArrayOne} />);
});
it("should render one <Button> item when props.back is sent", () => {
wrapper.setProps({ back: true });
expect(wrapper.find(Button)).toHaveLength(1);
});
it("should render one <Button> item when props.next is sent", () => {
wrapper.setProps({ next: true });
expect(wrapper.find(Button)).toHaveLength(1);
});
it("should render one <Input> item when there is one item in sent form array", () => {
expect(wrapper.find(Input)).toHaveLength(1);
});
it("should render two <Input> item when there is two item in sent form array", () => {
wrapper = shallow(<SignUpForm form={formElementKeyArrayTwo} />);
expect(wrapper.find(Input)).toHaveLength(2);
});
});
<file_sep>import React from "react";
import classes from './AdminPage.module.css'
import { Route, Redirect, useRouteMatch, Switch, Link } from "react-router-dom";
export default function AdminButton() {
let { path, url } = useRouteMatch();
return (
<div className={classes.admin_page}>
<button>
<Link to={`${url}/handyPeople`}>View Repairers</Link>
</button>
<button>
<Link to={`${url}/buyers`}>View Buyers</Link>
</button>
<button>
<Link to={`${url}/buyersrequests`}>View Pending buyer requests</Link>
</button>
<button>
<Link to={`${url}/repairrequest`}>View Pending repairer requests</Link>
</button>
</div>
);
}
<file_sep>// ROUTES RELATED TO HANDYMEN
const express = require("express");
const router = express.Router();
const services = require("../services/handymanServices");
import authController from "./../controller/authController";
import handymanController from "./../controller/handymanController";
// router.use(express.json()); // You Do not need to put it here because You already have it in app.js
/***************** THE FOLLOWING METHODS ARE ACCESSIBLE TO ALL PUBLIC ROUTES *******************/
// GET "/" SERVE DATA OF ALL HANDYMEN (accessible to anyone visiting the site)
router.get("/handymannotprotected", async (_, res) => {
const result = await services.getAllHandymen();
return res.status(200).json(result);
});
// POST "/" ALLOW HANDYMAN DATA STORAGE
// Note: this is used only during the initial stage of handyman registration process (accessible to anyone...
// ...who would like to rgister as handyman on the site)
router.post("/handymannotprotected", async (req, res) => {
const result = await services.addNewHandyman(req.body);
const resultStatus =
result.status === "OK" ? 200 : result.status === "FAIL" ? 400 : 500;
return res.status(resultStatus).send({ message: result.message });
});
// Serving three random handyman which has set visibility to true
router.get(
"/handymannotprotected/randomthree",
handymanController.threeRandomHandyman
);
// GET ALL REVIEWS BY HANDYMAN ID
// WARN: THIS ENDPOINT IS CURRENTLY NOT BEING USED. IT IS INCLUDED IN LIGHT OF PROBABLE FUTURE NEEDS
router.get("/handymannotprotected/:id/reviews", async (req, res) => {
const result = await services.getReviewsByHandymanId(parseInt(req.params.id));
return result ? res.status(200).send(result) : res.sendStatus(404);
});
// GET "/{id}" SERVE DATA OF INDIVIDUAL HANDYMAN
router.get("/handymannotprotected/:id", async (req, res) => {
const result = await services.getHandymanById(parseInt(req.params.id));
return result ? res.status(200).send(result) : res.sendStatus(404);
});
/***************** THE FOLLOWING METHODS ARE DEDICATED TO ADMIN-ACCESSIBLE ROUTES *******************/
/**
* Routes are only accessible for logged in admin
*/
router.use(authController.protect);
router.use(authController.restrictTo("admin"));
// GET "/" SERVE DATA OF ALL HANDYMEN (accessible to anyone visiting the site)
router.get("/handymanprotected", async (_, res) => {
const result = await services.getAllHandymenForAdmin();
return res.status(200).json(result);
});
router
.route("/handymanprotected/:id")
.put(async (req, res) => {
const result = await services.editHandymanDetailsByIdAdmin(req.body);
console.log(result);
const resultStatus =
result.status === "OK" ? 200 : result.status === "FAIL" ? 400 : 500;
return res.status(resultStatus).json({ message: result.message });
})
//// GET "/{id}" SERVE DATA OF INDIVIDUAL HANDYMAN
.get(async (req, res) => {
const result = await services.getHandymanByIdForAdmin(
parseInt(req.params.id)
);
return result ? res.status(200).send(result) : res.sendStatus(404);
})
// PATCH "/" LET ADMIN CONTROL THE VISIBILITY OF A HANDYMAN'S PROFILE ON THE SITE(?)
.patch(async (req, res) => {
const result = await services.changeHandymanVisibilityByAdmin(req.body);
const resultStatus =
result.status === "OK" ? 200 : result.status === "FAIL" ? 400 : 500;
return res.status(resultStatus).json({ message: result.message });
})
// ADMIN CAN DELETE HANDYMAN RECORD
.delete(async (req, res) => {
const result = await services.deleteHandymanByIdAdmin(
parseInt(req.params.id)
);
return !result ? res.status(204).send(result) : res.sendStatus(404);
});
/******************************************************************************************************/
module.exports = router;
<file_sep>import { useState } from "react";
import "./RequestForQuoteForm.css";
import Skills from "./Skills";
import { validateForm, sendQuoteRequest } from "../../common/js/functions";
import { useLocation } from "react-router-dom";
const RequestForQuoteForm = () => {
const { state } = useLocation();
const data = state;
const [errors, setErrors] = useState([]);
const handymanId = data ? data.id : 0;
const handymanName = data
? { name: `${data.first_name} ${data.last_name}` }
: "(not provided)";
const [buyerName, setBuyerName] = useState("");
const [buyerEmail, setBuyerEmail] = useState("");
const [buyerPhoneNumber, setBuyerPhoneNumber] = useState("");
const [jobDescription, setJobDescription] = useState("");
const [jobStartDate, setJobStartDate] = useState("");
// organise fields that need further validation
const fieldsToValidate = [
{ type: "email", value: buyerEmail },
{ type: "tel", value: buyerPhoneNumber },
];
// organise the form data to be sent
const formData = {
handymanId,
handymanName,
buyerName,
buyerEmail,
buyerPhoneNumber,
jobDescription,
jobStartDate,
};
// EVENT HANDLERS
const sendFormData = async (event) => {
event.preventDefault();
const form = event.target;
const errors = validateForm(fieldsToValidate);
if (errors.length > 0) {
return setErrors(errors);
}
setErrors([]);
const requestData = [
"service_l0m5rpd",
"template_elv94vx",
formData,
"user_Z6650OqueHooRxmmi5Geo",
];
// check if sending quote request was successful. Navigate to homepage if it was.
const okToGoHome = await sendQuoteRequest(requestData);
if (okToGoHome) window.location.assign("/");
};
return (
<form
id="form-send-quote"
name="form-send-quote"
className="form"
onSubmit={sendFormData}
>
{errors.map((e, index) => (
<p key={index} className="error">
{e}
</p>
))}
<h1 className="title">Request For Quote</h1>
{data && (
<div className="handyman-summary">
<h2>Repairer Info</h2>
<p>
<span>Name:</span> <span className="bold">{data.first_name}</span>{" "}
<span className="bold">{data.last_name}</span>
</p>
<div className="handyman-skills">
<p>Skills:</p>
<Skills skills={data.skills} />
</div>
{/* WARN: COMMENTED OUT SECTION BELOW IS INCLUDED ONLY IN LIGHT OF PROBABLE FUTURE NEEDS */}
{/* <p>
<span>Area:</span>{" "}
<span className="bold">{`${data.area}, ${data.address.city}`}</span>
</p> */}
</div>
)}
<div>
<em className="required">
<span className="required">*</span> Required field
</em>
<fieldset className="input-field-group contact-details">
<legend className="subtitle">Contact Details</legend>
<div className="input-field">
<label htmlFor="first-name">Your Name</label>
<span className="required">*</span>
<input
type="text"
id="buyer-name"
name="buyer-name"
maxLength={60}
required
onChange={(e) => setBuyerName(e.target.value)}
placeholder="Enter your name here"
value={buyerName}
/>
</div>
<div className="input-field">
<label htmlFor="email">Your Email</label>
<span className="required">*</span>
<input
type="email"
id="email"
name="email"
maxLength={50}
required
onChange={(e) => setBuyerEmail(e.target.value)}
placeholder="<EMAIL>"
value={buyerEmail}
/>
</div>
<div className="input-field">
<label htmlFor="phone-number">Phone Number (optional)</label>{" "}
<input
type="tel"
id="phone-number"
name="phone-number"
maxLength={13}
onChange={(e) => setBuyerPhoneNumber(e.target.value)}
value={buyerPhoneNumber}
/>
</div>
</fieldset>
</div>
<fieldset className="input-field-group job-details">
<legend className="subtitle">Job Details</legend>
<div className="input-field-group">
<div className="input-field">
<h3>
Description
<span className="required">*</span>
</h3>
<textarea
id="job-description"
name="job-description"
maxLength={500}
required
onChange={(e) => setJobDescription(e.target.value)}
placeholder="Short summary of the job"
value={jobDescription}
></textarea>
</div>
<div className="input-field">
<label htmlFor="date-start">Expected Start Date</label>
<span className="required">*</span>
<input
type="date"
id="date-start"
name="date-start"
required
min={new Date().toLocaleDateString()}
onChange={(e) => setJobStartDate(e.target.value)}
value={jobStartDate}
/>
</div>
</div>
</fieldset>
<div className="submit-button-div">
<input type="submit" id="btn-submit" name="btn-submit" value="Submit" />
</div>
</form>
);
};
export default RequestForQuoteForm;
<file_sep>import RequestForQuoteForm from "../components/RequestForQuoteForm/RequestForQuoteForm";
const RequestForQuote = (props) => {
// EVENT HANDLERS
const getRequestForQuoteData = async (fromData) => {
const result = await sendRegistrationRequest(fromData); // <- from where it is coming from? common/js/functions but why not imported?
setMessage(result.message);
};
return <RequestForQuoteForm data={props} onSubmit={getRequestForQuoteData} />;
};
export default RequestForQuote;
<file_sep>import React, { useState } from "react";
import SignUpForm from "../../components/signUpForm/SignUpForm";
import ConfirmationFormPage from "../../components/confirmationFormPage/ConfirmationFormPage";
import CompletionFormScreen from "../../components/completionFormScreen/CompletionFormScreen";
import { checkValidity } from "../../utility/utility";
const FIRST_FORM_PAGE = 0;
const SECOND_FORM_PAGE = 1;
const LAST_FORM_PAGE = 3;
const SignUp = () => {
/**
* State: pageControl and setPageControl are used to managing the displayed page of form
*/
const [pageControl, setPageControl] = useState(FIRST_FORM_PAGE);
/**
* State: responsible for controlling the process of displaying the http req in UI
*/
const [loadingControl, setLoadingControl] = useState(false);
/**
* State: signForm and setSignForm are used to provide:
* -information about requirements of validation
* -storing the input from user
*/
const [signForm, setSignForm] = useState({
email: {
invalidInputInfo: "Enter valid email address",
name: "E-mail",
placeholder: "<EMAIL>",
value: "",
validation: {
required: true,
isEmail: true,
},
valid: false,
touched: false,
},
emailConfirmation: {
invalidInputInfo: "Enter valid email address",
name: "E-mail Confirmation",
placeholder: "<EMAIL>",
value: "",
validation: {
required: true,
isEmail: true,
// !TODO: check if email is equal to confirmation
},
valid: false,
touched: false,
},
password: {
invalidInputInfo: "You have to input password",
name: "Password",
placeholder: "Password",
value: "",
objectConfig: { type: "password" },
//!IMPORTANT detailed validation of password is not required now
validation: {
required: true,
isPassword: true,
},
// valid: false,
valid: true,
touched: false,
},
passwordConfirmation: {
invalidInputInfo: "You have to input password",
name: "Password Confirmation",
placeholder: "Password",
value: "",
objectConfig: { type: "password" },
//!IMPORTANT detailed validation of password is not required now
validation: {
required: true,
isPassword: true,
// !TODO: check if password is equal to confirmation
},
// valid: false,
valid: true,
touched: false,
},
});
/**
* @description Changing the page of form displayed in Browser
* Returning to previous one page
* Function is changing the page by changing the state of loadingControl by setLoadingControl
* @input no input
* @return nothing
*/
const backFunction = () => {
setPageControl(() => {
if (pageControl === FIRST_FORM_PAGE) return FIRST_FORM_PAGE;
const page = pageControl;
return page - 1;
});
};
/**
* @description Changing the page of form displayed in Browser
* Going to next page
* Function is changing the page by changing the state of loadingControl by setLoadingControl
* @input no input
* @return nothing
*/
const nextFunction = () => {
setPageControl(() => {
if (pageControl === LAST_FORM_PAGE) return LAST_FORM_PAGE;
const page = pageControl;
return page + 1;
});
};
/**
* @Description Function showing to user that data is sending to the server
* FUNCTION IN THAT FORM FAKING SENDING DATA by using setTimeout()
*
* After setTimeout() passed function is triggering rendering the LAST_FORM_PAGE
* @input no input
* @return nothing
*/
const confirmation = () => {
setLoadingControl(true);
setTimeout(() => {
setPageControl(LAST_FORM_PAGE);
setLoadingControl(false);
}, 800);
};
/**
* @Description Function returning to main page, in that case to FIRST_FORM_PAGE of form
* Function is changing the page by changing the state of loadingControl by setLoadingControl
*
* Function is cleaning previously provided by user data stored in APP
* @input no input
* @return nothing
*/
const returnToMain = () => {
setPageControl(FIRST_FORM_PAGE);
let newState = { ...signForm };
for (let key of Object.keys(signForm)) {
newState = {
...newState,
[key]: {
...newState[key],
value: "",
touched: false,
valid: false,
},
};
}
setSignForm(newState);
};
/**
* @DescriptionFunction is changing the value, touched and valid stored inside the signForm
* function is using the helper function checkValidity(), which is evaluating upcoming input
* @param {Object} e [e - event object triggered by input provided by user]
* @param {String} formName [Is a name of the input's field in form, used to identify what should be updated]
*/
const inputChangeHandler = (e, formName) => {
const updatedForm = {
...signForm,
[formName]: {
...signForm[formName],
value: e.target.value,
touched: true,
valid: checkValidity(e.target.value, signForm[formName].validation),
},
};
setSignForm(updatedForm);
};
/**
* For Loop which is creating the array of the object containing the id and needed information
* in a process of rendering the form's pages within switch statement
*/
const formElementKeyArray = [];
for (let key in signForm) {
formElementKeyArray.push({
id: key,
config: signForm[key],
});
}
let form = "";
/**
* Switch statement which base on pageControl value rendering different pages of the form
*/
switch (pageControl) {
case FIRST_FORM_PAGE:
form = (
<SignUpForm
form={formElementKeyArray}
formInputHandler={inputChangeHandler}
next={nextFunction}
// buttonDisable={!(signForm.name.valid && signForm.number.valid)}
buttonDisable={false}
nameOfTheForm="Sign-up"
leftButtonName="Cancel"
rightButtonName="Next"
/>
);
break;
case SECOND_FORM_PAGE:
form = (
<ConfirmationFormPage
loadingControl={loadingControl}
back={backFunction}
next={confirmation}
formValues={signForm}
/>
);
break;
case LAST_FORM_PAGE:
form = <CompletionFormScreen back={returnToMain} />;
break;
default:
console.log("You should never see that");
break;
}
return <div>{form}</div>;
};
export default SignUp;
<file_sep>import pool from "../db";
// QUERIES
const getAllQuotesQuery = `SELECT * FROM jobs`; //**WARN: NOT IMPLEMENTED YET**
const getQuoteByIdQuery = `SELECT * FROM handyman WHERE id = $1`; // **WARN: NOT IMPLEMENTED YET**
const addNewQuoteQuery = `
INSERT INTO jobs (client_name, client_email, job_description, job_start_date, handyman_id)
VALUES($1, $2, $3, $4, $5)`;
/***************** THE FOLLOWING METHODS ARE DEDICATED TO ADMIN-ACCESSIBLE ROUTES *******************/
// WARN: ANY REQUIRED AUTHORIZATION LOGIC IS YET TO BE ADDED
// FETCH DATA OF ALL JOBS FROM DATABASE BY JOB ID (currently accessible only to admin)
function getAllQuotes() {
return pool.query(getAllQuotesQuery);
}
// FETCH DATA OF ALL JOBS FROM DATABASE BY JOB ID (currently accessible only to admin)
function getQuoteById(qId) {
return pool.query(getQuoteByIdQuery, [qId]);
}
// STORE JOB DATA IN THE DATABASE (jobs table)
// Note: this is used only during the initial stage of quote process (accessible to anyone...
// ...who would like get quotation (from a selected handyman) on the site)
function addNewQuote(qData) {
const {
buyerName,
buyerEmail,
jobDescription,
jobStartDate,
handymanId,
} = qData;
return pool.query(addNewQuoteQuery, [
buyerName,
buyerEmail,
jobDescription,
jobStartDate,
handymanId,
]);
}
module.exports = {
getAllQuotes,
getQuoteById,
addNewQuote,
};
<file_sep>import React, { useEffect, useState } from "react";
import { Route, Redirect, useRouteMatch, Switch, Link } from "react-router-dom";
import UserManagements from "./usersManagements/UsersManagements";
import classes from "./AdminPage.module.css";
import UserDetailedProfile from "./usersManagements/UserDetailedProfile/UserDetailedProfile";
import Adminpage from "./Adminpage";
import AdminButton from "./AdminButton";
import Classes from "./AdminPage.module.css";
/**
* @DescriptionFunction Main component of the entire react root in react related to the adminPanel and admins features of managing entire application.
* This components has implemented 3 sub routes 1 - "/", 2 - "/usersmanagement/:id`" 3: "/usersmanagement" Base url for this routes is "/admin-panel "
* which is parent route for this component in App.js
* @link /admin-panel
* @access route is going to be protected by authorization on server
*/
const AdminPanel = (props) => {
let { path, url } = useRouteMatch();
/*
It need to go to global state
*/
return (
<div className={classes.adminpanel}>
<h1>Welcome to Your admin dashboard</h1>
{/* <h2>Please chose one of the option</h2> */}
<h1>What do you want to do next</h1>
<div className="admin-page-container">
<AdminButton />
<Adminpage {...props} />
</div>
</div>
);
};
export default AdminPanel;
// useEffect(() => {
// fetch(`/api/users/handyman/${id}`)
// .then((res) => {
// if (!res.ok) {
// throw new Error(res.statusText);
// }
// return res.json();
// })
// .then((userData) => {
// setUser(userData);
// })
// .catch((err) => {
// console.error(err);
// setMessage(err);
// });
// }, [id]);
<file_sep>import React, { useState, useEffect } from "react";
import HandyPeopleCard from "./HandyPeopleCard";
import InputFields from "./InputFields";
export default function HandyPeopleCards() {
const [list, setList] = useState([]);
const [search, setSearch] = useState();
const handleChange = (e) => {
if (e.target.className === "by-keyword") {
const filteredByKeyWord = list.filter(
(data) =>
JSON.stringify(data)
.toLowerCase()
.indexOf(e.target.value.toLowerCase()) !== -1
);
setSearch(filteredByKeyWord);
}
if (e.target.className === "by-skill") {
const filteredBySkill = list.filter(
(data) =>
JSON.stringify(data.skills)
.toLowerCase()
.indexOf(e.target.value.toLowerCase()) !== -1
);
setSearch(filteredBySkill);
}
};
useEffect(() => {
fetch("/api/v1/handyman/handymannotprotected")
.then((res) => {
if (!res.ok) {
throw new Error(res.statusText);
}
return res.json();
})
.then((data) => {
setList(data);
})
.catch((err) => {
console.error(err);
});
}, []);
return !list && !search ? (
<h1 className="message">Loading, please wait...</h1>
) : (
<div className="handymen-list">
<InputFields handleChange={handleChange} />
{/* during search/filter action... */}
{search && search.length > 0 ? (
//if the action returned some results
<div>
{search.length < list.length ? (
<p className="message results-found-message">{`Found ${search.length} result(s) matching your criteria.`}</p>
) : (
<p className="message results-found-message">{`${list.length} result(s) found.`}</p>
)}
{/* {display the list of handymen found} */}
<div className="cards-container">
{search.map((oneList, index) => (
<HandyPeopleCard key={index} onelist={oneList} />
))}
</div>
</div>
) : search && search.length === 0 ? (
// if there are no search results, display 'No results found' message
<p className="message no-results-found-message">
{`No results found matching the criteria.`}
</p>
) : (
// default: display list of all handymen
<div>
<p className="message results-found-message">{`${list.length} result(s) found.`}</p>
<div className="cards-container">
{list.map((oneList, index) => (
<HandyPeopleCard key={index} onelist={oneList} />
))}
</div>
</div>
)}
</div>
);
}
<file_sep>import React, { useState, useContext } from "react";
import SignUpForm from "../../components/signUpForm/SignUpForm";
import { checkValidity } from "../../utility/utility";
import AuthContext from "../../store/authContext";
const SignIn = (props) => {
const authCtx = useContext(AuthContext);
/**
* State: responsible for controlling the process of displaying the http req in UI
*/
const [loadingControl, setLoadingControl] = useState(false);
/**
* State: signForm and setSignForm are used to provide:
* -information about requirements of validation
* -storing the input from user
*/
const [signForm, setSignForm] = useState({
email: {
invalidInputInfo: "Enter valid email address",
name: "E-mail",
placeholder: "<EMAIL>",
value: "",
validation: {
required: true,
isEmail: true,
},
//TODO: change valid in production for false
// valid: true,
valid: false,
touched: false,
incorrect: false,
},
password: {
invalidInputInfo: "You have to input password",
name: "Password",
placeholder: "Password",
value: "",
objectConfig: { type: "password" },
//!IMPORTANT detailed validation of password is not required now
validation: {
required: true,
//TODO: important in production to turn on validation password in utility.js
isPassword: true,
},
//TODO: change valid in production for false
valid: false,
// valid: true,
touched: false,
incorrect: false,
},
});
/**
* @description Changing the page of form displayed in Browser
* Returning to previous one page
* Function is changing the page by changing the state of loadingControl by setLoadingControl
* @input no input
* @return nothing
*/
const backFunction = () => {
props.history.push("/");
};
/**
* @description Changing the page of form displayed in Browser
* Going to next page
* Function is changing the page by changing the state of loadingControl by setLoadingControl
* @input no input
* @return nothing
*/
const nextFunction = async () => {
try {
setLoadingControl(true);
const data = {
email: signForm.email.value,
password: <PASSWORD>,
};
const response = await fetch("/api/v1/users/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
const responseJsoned = await response.json();
console.log(responseJsoned);
if (responseJsoned.token) {
setLoadingControl(false);
authCtx.login(responseJsoned.token, responseJsoned.expirationTime);
props.history.push("/");
}
if (responseJsoned.status === "fail") {
setLoadingControl(false);
//TODO: automate process of updating the object of the state
setSignForm((prevState) => {
return {
...prevState,
email: {
...prevState.email,
incorrect: true,
},
password: {
...prevState.<PASSWORD>,
incorrect: true,
},
};
});
}
} catch (error) {
console.log(error);
}
};
/**
* @DescriptionFunction is changing the value, touched and valid stored inside the signForm
* function is using the helper function checkValidity(), which is evaluating upcoming input
* @param {Object} e [e - event object triggered by input provided by user]
* @param {String} formName [Is a name of the input's field in form, used to identify what should be updated]
*/
const inputChangeHandler = (e, formName) => {
const updatedForm = {
...signForm,
[formName]: {
...signForm[formName],
value: e.target.value,
touched: true,
valid: checkValidity(e.target.value, signForm[formName].validation),
},
};
setSignForm(updatedForm);
setSignForm((prevState) => {
return {
...prevState,
email: {
...prevState.email,
incorrect: false,
},
password: {
...prevState.password,
incorrect: false,
},
};
});
};
/**
* For Loop which is creating the array of the object containing the id and needed information
* in a process of rendering the form's pages within switch statement
*/
const formElementKeyArray = [];
for (let key in signForm) {
formElementKeyArray.push({
id: key,
config: signForm[key],
});
}
const form = (
<SignUpForm
form={formElementKeyArray}
formInputHandler={inputChangeHandler}
next={nextFunction}
back={backFunction}
buttonDisable={!(signForm.password.valid && signForm.email.valid)}
nameOfTheForm="Sign-In"
leftButtonName="Cancel"
rightButtonName="Log In"
wrongPasswordEmail={
signForm.password.incorrect && signForm.email.incorrect
}
loading={loadingControl}
/>
);
return <div>{form}</div>;
};
export default SignIn;
<file_sep>import React from "react";
import UnorderedList from "../../UI/unorderedList/UnorderedList";
import Button from "../../UI/button/Button";
import classes from "./ConfirmationFormPage.module.css";
/**
* @DescriptionFunction Component is responsible to render the confirmation page
* where user can check one more time provided data
* @param {Function} props.back [function which should return user to previous page. Function is attached to button to "onClick" event]
* @param {Function} props.next [function which should redirect user to pointed page. Function is attached to button to "onClick" event]
* @param {Object} props.formValues ["Config Object" Providing necessary data to display the fields and provided data by user]
*/
const confirmationFormPage = (props) => {
const flexClassStyleArr = [classes.flexContainerGeneral];
/**
* If condition which are going to change the CSS classes
* in relation to how many buttons need to be rendered, base on number of the passed event handlers
*/
if (props.next && props.back)
flexClassStyleArr.push(classes.flexContainerCentered);
if (props.next && !props.back)
flexClassStyleArr.push(classes.flexContainerToRight);
/**
* Displaying to user that process of sending data is takin the place
* dependency: props.loadingControl
*/
let buttonContinue = (
<Button assignedClass={"nextButton"} clicked={props.next}>
Continue
</Button>
);
if (props.loadingControl)
buttonContinue = (
<Button assignedClass={"nextButton"} clicked={props.next}>
Loading...
</Button>
);
const form = (
<div className={classes.container}>
<h1 className={classes.title}>Confirmation</h1>
<UnorderedList formValues={props.formValues} />
<div className={flexClassStyleArr.join(" ")}>
{props.back && (
<div className={classes.buttonWrapper}>
<Button assignedClass={"backButton"} clicked={props.back}>
Back
</Button>
</div>
)}
{props.next && (
<div className={classes.buttonWrapper}>{buttonContinue}</div>
)}
</div>
</div>
);
return form;
};
export default confirmationFormPage;
<file_sep>import React, { useState, useEffect, useContext } from "react";
import { useRouteMatch, Link } from "react-router-dom";
import classes from "./AdminPage.module.css";
import SearchField from "./SearchField";
import AuthContext from "../../store/authContext";
import AdminHandyPeopleTableRows from "./AdminHandyPeopleTableRows";
import { activateDeactivateHandyman } from "../../common/js/functions";
export default function AdminHandyPeopleTable(props) {
let { path, url } = useRouteMatch();
const [list, setList] = useState([]);
const [search, setSearch] = useState([]);
const authCtx = useContext(AuthContext);
const handleChange = async (e, oneList) => {
alert(`are you sure you want to ${e.target.value}`);
const actionVerb = e.target.value;
if (actionVerb === "Update") {
props.history.push(`${path}/${e.target.id}`);
} else if (actionVerb === "Delete") {
fetch(`/api/v1/handyman/handymanprotected/${e.target.id}`, {
method: "DELETE",
body: JSON.stringify({ id: e.target.id }),
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${authCtx.token}`,
},
});
window.location.reload();
} else if (actionVerb === "Activate" || actionVerb === "Deactivate") {
const newStatus = actionVerb === "Activate" ? true : false;
const requiredData = { handyman: oneList, newStatus, authCtx };
const result = await activateDeactivateHandyman(requiredData);
alert(result.message);
window.location.reload();
}
};
useEffect(() => {
fetch("/api/v1/handyman/handymanprotected", {
headers: {
Authorization: `Bearer ${authCtx.token}`,
},
})
.then((res) => {
if (!res.ok) {
throw new Error(res.statusText);
}
return res.json();
})
.then((body) => {
setList(body);
})
.catch((err) => {
console.error(err);
});
}, []);
return (
<div>
<SearchField list={list} setSearch={setSearch} search={search} />
<div className={classes.table_container}>
<table className={classes.table}>
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">First-name</th>
<th scope="col">Last-name</th>
<th scope="col">email</th>
<th scope="col">Telephone</th>
<th scope="col">postcode</th>
<th scope="col">street-name</th>
<th scope="col">status</th>
<th scope="col">Action</th>
</tr>
</thead>
{search.length > 0
? search.map((oneList, index) => (
<AdminHandyPeopleTableRows
key={index}
oneList={oneList}
handleChange={handleChange}
/>
))
: list.map((oneList, index) => (
<AdminHandyPeopleTableRows
key={index}
oneList={oneList}
handleChange={handleChange}
/>
))}
</table>
</div>
</div>
);
}
<file_sep>import React from "react";
import classes from "./Button.module.scss";
/**
* @DescriptionFunction Simple component - part of UI
* @param {String} props.assignedClass [Simple string which is giving to chance to assign custom CSS class]
* @param {String} props.children [Are use to provide the description of button]
* @param {Function} props.clicked [Function which is going to handle onClick event]
* @param {Boolean} props.buttonDisable [boolean value disabling button]
*/
const button = (props) => {
let button = (
<button
className={[classes.Button, classes[props.assignedClass]].join(" ")}
onClick={props.clicked}
>
{props.children}
</button>
);
if (props.buttonDisable) {
button = (
<button
disabled
className={[classes.Button, classes[props.assignedClass]].join(" ")}
onClick={props.clicked}
>
{props.children}
</button>
);
}
return button;
};
export default button;
<file_sep>-- FROM 09.07.2021
DROP TABLE IF EXISTS quotes;
DROP TABLE IF EXISTS reviews;
DROP TABLE IF EXISTS buyers;
DROP TABLE IF EXISTS handyman;
DROP TABLE IF EXISTS postcodes;
DROP TABLE IF EXISTS areas;
CREATE TABLE handyman(
id serial PRIMARY KEY,
first_name varchar(30) NOT NULL,
last_name varchar(30) NOT NULL,
img varchar(255),
address json NOT NULL,
postcode char(12) NOT NULL,
email varchar(50) UNIQUE NOT NULL,
phone_number char(13) NOT NULL,
skills varchar[] NOT NULL,
bio varchar(1000) NOT NULL,
visible bool DEFAULT false,
date_added timestamptz DEFAULT CURRENT_DATE
);
CREATE TABLE jobs(
id serial PRIMARY KEY,
client_name varchar(60) NOT NULL,
client_email varchar NOT NULL,
job_description varchar(500) NOT NULL,
job_start_date date NOT NULL,
handyman_id integer REFERENCES handyman(id),
date_created timestamptz DEFAULT CURRENT_DATE,
current_status varchar NOT NULL DEFAULT 'Pending'
);
CREATE TABLE postcodes(
id serial PRIMARY KEY,
postcode varchar(12) UNIQUE NOT NULL
);
INSERT INTO handyman(id,first_name,last_name,address,postcode,email,phone_number,skills,bio)
VALUES(0,'Anyone','Anyone','{"addressLineOne":"-","addressLineTwo":"-","city":"Coventry"}','-','-',00000000000,'{""}','-');
INSERT INTO handyman(first_name,last_name,address,postcode,email,phone_number,skills,bio)
VALUES('Senait','Ekubai','{"addressLineOne":"1","addressLineTwo":"Street Name 1","city":"Coventry"}','CV1 1AA','<EMAIL>',07123456789,'{"Painting","Decorating"}','Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.');
INSERT INTO handyman(first_name,last_name,address,postcode,email,phone_number,skills,bio)
VALUES('Patryk','Nowak','{"addressLineOne":"1","addressLineTwo":"Street Name 1","city":"Coventry"}','CV1 1AA','<EMAIL>',07123456789,'{"Plastering","Plumbing"}','Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.');
INSERT INTO handyman(first_name,last_name,address,postcode,email,phone_number,skills,bio)
VALUES('Michael','Biruk','{"addressLineOne":"1","addressLineTwo":"Street Name 1","city":"Coventry"}','CV1 1AA','<EMAIL>',07123456789,'{"Electrical Work","Plastering","Plumbing"}','Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.');
CREATE TABLE users (
user_id SERIAL PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
email VARCHAR(50) UNIQUE NOT NULL,
user_password VARCHAR(200),
password_changed_at timestamp,
user_role VARCHAR(20),
password_reset_token VARCHAR(200),
password_reset_expires timestamptz
);
-- OLD -----------------------------------------------------------------------------------
-- DROP TABLE IF EXISTS quotes;
-- DROP TABLE IF EXISTS reviews;
-- DROP TABLE IF EXISTS buyers;
-- DROP TABLE IF EXISTS handyman;
--
-- CREATE TABLE handyman(id SERIAL PRIMARY KEY,
-- first_name VARCHAR(30) NOT NULL,
-- last_name VARCHAR(30) NOT NULL,
-- img VARCHAR,
-- address JSON NOT NULL,
-- postcode CHAR(12) NOT NULL,
-- email VARCHAR(50) UNIQUE NOT NULL,
-- phone_number CHAR(13) NOT NULL,
-- skills VARCHAR[] NOT NULL,
-- bio VARCHAR(1000) NOT NULL,
-- visible bool DEFAULT false
-- );
-- CREATE TABLE buyers(id SERIAL PRIMARY KEY,
-- customer_name VARCHAR(60) NOT NULL,
-- email VARCHAR(50) UNIQUE NOT NULL,
-- telephone_number VARCHAR(13)
-- );
-- CREATE TABLE reviews(id SERIAL PRIMARY KEY,
-- buyer_id INT REFERENCES buyers(id),
-- handyman_id INT REFERENCES handyman(id),
-- review_body VARCHAR(500),
-- rating INT DEFAULT 5
-- );
-- CREATE TABLE quotes(
-- id serial PRIMARY KEY,
-- client_name varchar(60) NOT NULL,
-- client_email varchar NOT NULL,
-- job_description varchar(500) NOT NULL,
-- job_start_date date NOT NULL,
-- handyman_id integer REFERENCES handyman(id)
-- );
-- INSERT INTO handyman(first_name,last_name,address,postcode,email,phone_number,skills,bio)
-- VALUES('Senait','Ekubai','{"addressLineOne":"1","addressLineTwo":"Street Name 1","city":"Coventry"}','CV1 1AA','<EMAIL>',07123456789,'{"Painting","Decorating"}','Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.');
-- INSERT INTO handyman(first_name,last_name,address,postcode,email,phone_number,skills,bio)
-- VALUES('Patryk','Nowak','{"addressLineOne":"1","addressLineTwo":"Street Name 1","city":"Coventry"}','CV1 1AA','<EMAIL>',07123456789,'{"Plastering","Plumbing"}','Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.');
-- INSERT INTO handyman(first_name,last_name,address,postcode,email,phone_number,skills,bio)
-- VALUES('Michael','Biruk','{"addressLineOne":"1","addressLineTwo":"Street Name 1","city":"Coventry"}','CV1 1AA','<EMAIL>',07123456789,'{"Electrical Work","Plastering","Plumbing"}','Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.');
-- INSERT INTO buyers(customer_name,email)
-- VALUES('customer1','<EMAIL>');
-- INSERT INTO buyers(customer_name,email)
-- VALUES('customer2','<EMAIL>');
-- INSERT INTO buyers(customer_name,email)
-- VALUES('customer3','<EMAIL>');
-- INSERT INTO reviews(buyer_id,handyman_id,review_body) VALUES(1,1,'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.');
-- INSERT INTO reviews(buyer_id,handyman_id,review_body) VALUES(2,1,'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.');
-- INSERT INTO reviews(buyer_id,handyman_id,review_body) VALUES(3,1,'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.');
-- INSERT INTO reviews(buyer_id,handyman_id,review_body) VALUES(1,2,'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.');
-- INSERT INTO reviews(buyer_id,handyman_id,review_body) VALUES(2,2,'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.');
-- INSERT INTO reviews(buyer_id,handyman_id,review_body) VALUES(3,2,'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.');
-- INSERT INTO reviews(buyer_id,handyman_id,review_body) VALUES(1,3,'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.');
-- INSERT INTO reviews(buyer_id,handyman_id,review_body) VALUES(2,3,'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.');
-- INSERT INTO reviews(buyer_id,handyman_id,review_body) VALUES(3,3,'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.');
-- INSERT INTO handyman(id,first_name,last_name,address,postcode,email,phone_number,skills,bio)
-- VALUES(0,'Anyone','Anyone','{"addressLineOne":"-","addressLineTwo":"-","city":"Coventry"}','-','-',00000000000,'{""}','-');
-- DROP TABLE IF EXISTS postcodes;
-- DROP TABLE IF EXISTS areas;
-- CREATE TABLE areas(
-- code varchar(5) NOT NULL PRIMARY KEY
-- );
-- CREATE TABLE postcodes(
-- postcode varchar(12) NOT NULL PRIMARY KEY,
-- area_code varchar REFERENCES areas(code)
-- );
-- INSERT INTO areas (code) VALUES('CV1');
-- INSERT INTO postcodes(postcode,area_code) VALUES('CV1 1AA','CV1');
---------------------------------------------------------
-- old---------------------------------------------------
-- -- TABLE CREATORS
-- CREATE TABLE addresses (
-- address_id SERIAL PRIMARY KEY,
-- -- user address
-- address1 VARCHAR(50),
-- district1 VARCHAR(40),
-- city1 VARCHAR(50),
-- postal_code1 VARCHAR(10),
-- -- offert address
-- address2 VARCHAR(50),
-- district2 VARCHAR(40),
-- city2 VARCHAR(50),
-- postal_code2 VARCHAR(10),
-- country VARCHAR(50),
-- phone VARCHAR(20),
-- last_update timestamp
-- );
-- CREATE TABLE users (
-- user_id SERIAL PRIMARY KEY,
-- first_name VARCHAR(50) NOT NULL,
-- email VARCHAR(50) UNIQUE NOT NULL,
-- user_password VARCHAR(200),
-- password_changed_at timestamp,
-- user_role VARCHAR(20),
-- password_reset_token VARCHAR(200),
-- password_reset_expires timestamptz
-- );
-- CREATE TABLE users (
-- user_id SERIAL PRIMARY KEY,
-- profile_picture VARCHAR(80), --IN FIRST ATTEMPT WE WILL USE LINK BUT LWE HAVE TO ALLOW USER TO UPLOAD PICTURES TO SERVER
-- first_name VARCHAR(50) NOT NULL,
-- last_name VARCHAR(50) NOT NULL,
-- email VARCHAR(50) UNIQUE NOT NULL,
-- address_table INTEGER REFERENCES addresses(address_id),
-- -- after authentication
-- activebool BOOLEAN,
-- created_data DATE,
-- last_update timestamp,
-- user_role VARCHAR(20),
-- user_password VARCHAR(200)
-- );
-- -- WAY OF DOING QUERY TO ARRAY IN POSTGRES
-- -- https://stackoverflow.com/questions/11231544/check-if-value-exists-in-postgres-array/11231965
-- CREATE TABLE offers (
-- offer_id SERIAL PRIMARY KEY,
-- handyman_id INTEGER REFERENCES users(user_id) UNIQUE NOT NULL,
-- adressoffert VARCHAR(50), -- we will need to modify it to exist in address table
-- images text ARRAY,
-- offert_description VARCHAR(450),
-- skills text ARRAY,
-- sector text ARRAY,
-- contacts VARCHAR(100) -- temporary but need to be connected to address for example phone and email from user
-- );
-- CREATE TABLE handyman (
-- handyman_id SERIAL PRIMARY KEY,
-- first_name VARCHAR(50),
-- last_name VARCHAR(50),
-- images VARCHAR(50),
-- address_offer text ARRAY,
-- postcode VARCHAR(50),
-- email VARCHAR(50),
-- phone_number VARCHAR(50),
-- skills text ARRAY,
-- bio VARCHAR(450),
-- visible BOOLEAN DEFAULT FALSE
-- );
-- CREATE TABLE reviews (
-- review_id SERIAL PRIMARY KEY,
-- buyer_id_ref INTEGER REFERENCES users(user_id),
-- offert_id_ref INTEGER REFERENCES offers(offer_id),
-- handyman_id_ref INTEGER REFERENCES users(user_id),
-- review_msg VARCHAR(250),
-- rating numeric CHECK (rating BETWEEN 1 AND 5)
-- );
-- -- CREATE TABLE booked_offers (
-- -- booked_offer_id SERIAL PRIMARY KEY,
-- -- );
-- -- ***********************************************************************
-- -- DATA
-- -- usser after creting we need to add address
-- -- CREATE TABLE booked_offers (
-- -- booked_offer_id SERIAL PRIMARY KEY,
-- -- );
-- -- ***********************************************************************
-- -- DATA
-- -- usser after creting we need to add address
-- -- HANDYMANS
-- INSERT INTO users (user_id, profile_picture, first_name, last_name, email, address_table, created_data, last_update, user_role, user_password)
-- VALUES( 1, 'https://dogtime.com/assets/uploads/2011/03/puppy-development.jpg', 'Handyman_1', 'SURNAME_1', '<EMAIL>', NULL, '2021-03-01', NULL, 'handyman', 'password');
-- INSERT INTO users (user_id, profile_picture, first_name, last_name, email, address_table, created_data, last_update, user_role, user_password)
-- VALUES( 2, 'https://dogtime.com/assets/uploads/2011/03/puppy-development.jpg', 'Handyman_2', 'SURNAME_2', '<EMAIL>', NULL, '2021-04-01', NULL, 'handyman', 'password');
-- INSERT INTO users (user_id, profile_picture, first_name, last_name, email, address_table, created_data, last_update, user_role, user_password)
-- VALUES( 3, 'https://dogtime.com/assets/uploads/2011/03/puppy-development.jpg', 'Handyman_3', 'SURNAME_3', '<EMAIL>', NULL, '2021-05-01', NULL, 'handyman', 'password');
-- INSERT INTO users (user_id, profile_picture, first_name, last_name, email, address_table, created_data, last_update, user_role, user_password)
-- VALUES( 4, 'https://dogtime.com/assets/uploads/2011/03/puppy-development.jpg', 'Handyman_4', 'SURNAME_4', '<EMAIL>', NULL, '2021-06-01', NULL, 'handyman', 'password');
-- -- BUYERS
-- INSERT INTO users (user_id, profile_picture, first_name, last_name, email, address_table, created_data, last_update, user_role, user_password)
-- VALUES( 5, 'https://dogtime.com/assets/uploads/2011/03/puppy-development.jpg', 'Buyer_1', 'SURNAME_4', '<EMAIL>', NULL, '2021-01-01', NULL, 'handyman', 'password');
-- INSERT INTO users (user_id, profile_picture, first_name, last_name, email, address_table, created_data, last_update, user_role, user_password)
-- VALUES( 6, 'https://dogtime.com/assets/uploads/2011/03/puppy-development.jpg', 'Buyer_1', 'SURNAME_4', '<EMAIL>', NULL, '2021-02-01', NULL, 'handyman', '<PASSWORD>');
-- INSERT INTO users (user_id, profile_picture, first_name, last_name, email, address_table, created_data, last_update, user_role, user_password)
-- VALUES( 7, 'https://dogtime.com/assets/uploads/2011/03/puppy-development.jpg', 'Buyer_1', 'SURNAME_4', '<EMAIL>', NULL, '2021-03-01', NULL, 'handyman', 'password');
-- INSERT INTO users (user_id, profile_picture, first_name, last_name, email, address_table, created_data, last_update, user_role, user_password)
-- VALUES( 8, 'https://dogtime.com/assets/uploads/2011/03/puppy-development.jpg', 'Buyer_1', 'SURNAME_4', '<EMAIL>', NULL, '2021-04-01', NULL, 'handyman', '<PASSWORD>');
-- -- HANDYMAN OFFERT
-- INSERT INTO offers (offer_id, handyman_id, adressoffert, images, offert_description, skills, sector, contacts)
-- VALUES (1, 1, 'Birmingham - placeholder', '{"https://dogtime.com/assets/uploads/2011/03/puppy-development.jpg"}',
-- '1 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
-- '{"Electric Installation", "Plastering"}', '{"sector1", "sector2"}', 'Contacts - placeholder');
-- INSERT INTO offers (offer_id, handyman_id, adressoffert, images, offert_description, skills, sector, contacts)
-- VALUES (2, 2, 'Birmingham - placeholder', '{"https://dogtime.com/assets/uploads/2011/03/puppy-development.jpg"}',
-- '2 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
-- '{"Electric Installation", "Plastering"}', '{"sector1", "sector2"}', 'Contacts - placeholder');
-- INSERT INTO offers (offer_id, handyman_id, adressoffert, images, offert_description, skills, sector, contacts)
-- VALUES (3, 3, 'Birmingham - placeholder', '{"https://dogtime.com/assets/uploads/2011/03/puppy-development.jpg"}',
-- '3 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
-- '{"Electric Installation", "Plastering"}', '{"sector1", "sector2"}', 'Contacts - placeholder');
-- INSERT INTO offers (offer_id, handyman_id, adressoffert, images, offert_description, skills, sector, contacts)
-- VALUES (4, 4, 'Birmingham - placeholder', '{"https://dogtime.com/assets/uploads/2011/03/puppy-development.jpg"}',
-- '4 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
-- '{"Electric Installation", "Plastering"}', '{"sector1", "sector2"}', 'Contacts - placeholder');
-- -- reviews
-- INSERT INTO reviews (review_id, buyer_id_ref, offert_id_ref, handyman_id_ref, rating, review_msg )
-- VALUES (1, 5, 1, 1, 5, '1A t dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse');
-- INSERT INTO reviews (review_id, buyer_id_ref, offert_id_ref, handyman_id_ref, rating, review_msg )
-- VALUES (2, 6, 2, 2, 3, '2A t dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse');
-- INSERT INTO reviews (review_id, buyer_id_ref, offert_id_ref, handyman_id_ref, rating, review_msg )
-- VALUES (3, 7, 3, 3, 4, '3A t dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse');
-- INSERT INTO reviews (review_id, buyer_id_ref, offert_id_ref, handyman_id_ref, rating, review_msg )
-- VALUES (4, 8, 4, 4, 1, '4A t dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse');
-- INSERT INTO reviews (review_id, buyer_id_ref, offert_id_ref, handyman_id_ref, rating, review_msg )
-- VALUES (5, 5, 1, 1, 5, '1B t dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse');
-- INSERT INTO reviews (review_id, buyer_id_ref, offert_id_ref, handyman_id_ref, rating, review_msg )
-- VALUES (6, 6, 2, 2, 3, '2B t dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse');
-- INSERT INTO reviews (review_id, buyer_id_ref, offert_id_ref, handyman_id_ref, rating, review_msg )
-- VALUES (7, 7, 3, 3, 4, '3B t dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse');
-- INSERT INTO reviews (review_id, buyer_id_ref, offert_id_ref, handyman_id_ref, rating, review_msg )
-- VALUES (8, 8, 4, 4, 1, '4B t dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse');
-- -- ADDRESSES
-- INSERT INTO addresses(address_id, address1, district1, city1, postal_code1, address2, district2, city2, postal_code2, country, phone, last_update)
-- VALUES(1, 'Street 1 Flat 1', 'West Midlands', 'Birmingham', 'b11-1bb', 'Streed Addres', 'West Midlands district2', 'Birmingham2', 'b11-1bb', 'England', '0711 2552 0291', NULL);
-- INSERT INTO addresses(address_id, address1, district1, city1, postal_code1, address2, district2, city2, postal_code2, country, phone, last_update)
-- VALUES(2, 'Street 2 Flat 2', 'West Midlands', 'Birmingham', 'b20-1bb', 'Streed Addres', 'West Midlands district2', 'Birmingham2', 'b21-1bb', 'England', '0711 2552 0291', NULL);
-- INSERT INTO addresses(address_id, address1, district1, city1, postal_code1, address2, district2, city2, postal_code2, country, phone, last_update)
-- VALUES(3, 'Street 3 Flat 3', 'West Midlands', 'Birmingham', 'b30-1bb', 'Streed Addres', 'West Midlands district2', 'Birmingham2', 'b32-1bb', 'England', '0711 2552 0291', NULL);
-- INSERT INTO addresses(address_id, address1, district1, city1, postal_code1, address2, district2, city2, postal_code2, country, phone, last_update)
-- VALUES(4, 'Street 4 Flat 4', 'West Midlands', 'Birmingham', 'b40-1bb', 'Streed Addres', 'West Midlands district2', 'Birmingham2', 'b42-1bb', 'England', '0711 2552 0291', NULL);
-- INSERT INTO addresses(address_id, address1, district1, city1, postal_code1, address2, district2, city2, postal_code2, country, phone, last_update)
-- VALUES(5, 'Street 5 Flat 5', 'West Midlands', 'Birmingham', 'b50-1bb', 'Streed Addres', 'West Midlands district2', 'Birmingham2','b51-1bb', 'England', '0711 2552 0291', NULL);
-- INSERT INTO addresses(address_id, address1, district1, city1, postal_code1, address2, district2, city2, postal_code2, country, phone, last_update)
-- VALUES(6, 'Street 6 Flat 6', 'West Midlands', 'Birmingham', 'b60-1bb', 'Streed Addres', 'West Midlands district2', 'Birmingham2', 'b61-1bb', 'England', '0711 2552 0291', NULL);
-- INSERT INTO addresses(address_id, address1, district1, city1, postal_code1, address2, district2, city2, postal_code2, country, phone, last_update)
-- VALUES(7, 'Street 7 Flat 7', 'West Midlands', 'Birmingham', 'b70-1bb', 'Streed Addres', 'West Midlands district2', 'Birmingham2', 'b71-1bb', 'England', '0711 2552 0291', NULL);
-- INSERT INTO addresses(address_id, address1, district1, city1, postal_code1, address2, district2, city2, postal_code2, country, phone, last_update)
-- VALUES(8, 'Street 8 Flat 8', 'West Midlands', 'Birmingham', 'b80-1bb', 'Streed Addres', 'West Midlands district2', 'Birmingham2', 'b81-1bb', 'England', '0711 2552 0291', NULL);
-- -- updating user account - adding address reference
-- UPDATE users SET address_table = 1 WHERE user_id = 1;
-- UPDATE users SET address_table = 2 WHERE user_id = 2;
-- UPDATE users SET address_table = 3 WHERE user_id = 3;
-- UPDATE users SET address_table = 4 WHERE user_id = 4;
-- UPDATE users SET address_table = 5 WHERE user_id = 5;
-- UPDATE users SET address_table = 6 WHERE user_id = 6;
-- UPDATE users SET address_table = 7 WHERE user_id = 7;
-- UPDATE users SET address_table = 8 WHERE user_id = 8;<file_sep>import React from "react";
import ListElement from "./listElement/ListElement";
import classes from "./UnorderedList.module.scss";
/**
* @DescriptionFunction Component responsible for rendering the unordered list created for need of the ConfirmationFormPage component
* @param {Array of Object} props.formValues [Config object - data needed to render the <ListElement>s]
*/
const unorderedList = (props) => {
const keyObjectArr = [];
for (let key in props.formValues) {
keyObjectArr.push(key);
}
const elementsOfList = keyObjectArr.map((key, index) => {
return (
<ListElement key={index}>
<p
key={props.formValues[key].name}
className={[classes.listElementsChildrens, classes.bolded].join(" ")}
>
{props.formValues[key].name + ":"}
</p>
<p
key={props.formValues[key].value}
className={classes.listElementsChildrens}
>
{props.formValues[key].value}
</p>
</ListElement>
);
});
return <ul className={classes.NoneStyle}>{elementsOfList}</ul>;
};
export default unorderedList;
<file_sep>import React, { useContext } from "react";
import classes from "./NavigationItems.module.scss";
import NavigationItem from "./NavigationItem/NavigationItem.js";
import AuthContext from "../../../store/authContext";
const navigationItems = (props) => {
const authCtx = useContext(AuthContext);
return (
<ul className={classes.navigationItems}>
{/* <NavigationItem link="/" exact>
Home
</NavigationItem> */}
<NavigationItem link="/users/handyman">Find A Repairer</NavigationItem>
<NavigationItem link="/contact">Contact US</NavigationItem>
{authCtx.isLoggedIn && (
<NavigationItem link="/admin-panel">Admin Panel</NavigationItem>
)}
{/* {!authCtx.isLoggedIn && (
<NavigationItem link="/signin">Sign-In</NavigationItem>
)} */}
{authCtx.isLoggedIn && (
<NavigationItem link="/signinout">Sign-Out</NavigationItem>
)}
</ul>
);
};
export default navigationItems;
<file_sep>import { useEffect, useState } from "react";
const allSkills = [
{ name: "brickLaying", value: "Brick laying" },
{ name: "carpentry", value: "Carpentry" },
{ name: "electricalWork", value: "Electrical Work" },
{
name: "installAndRepair",
value: "Appliance installation and repair",
},
{
name: "propertyMaintenance",
value: "Interior and exterior property maintenance",
},
{ name: "tiling", value: "Tiling" },
{ name: "plastering", value: "Plastering" },
{ name: "plumbing", value: "Plumbing" },
{ name: "painting", value: "Painting" },
{ name: "decorating", value: "Decorating" },
];
const Skills = (props) => {
const unselectedSkillsList = allSkills.map((skill) => ({
name: skill.name,
value: "",
}));
const [updatedSkillsList, setUpdatedSkillsList] =
useState(unselectedSkillsList);
const handleChange = (event) => {
const skill = event.target;
const newList = updatedSkillsList.map((item) => {
if (item.name === skill.name && skill.checked) {
return { ...item, value: skill.value };
}
if (item.name === skill.name && !skill.checked) {
return { ...item, value: "" };
}
return item;
});
setUpdatedSkillsList(newList);
// now send only the selected skills
props.onChangeHandler(
newList.filter((item) => item.value !== "").map((item) => item.value)
);
};
return (
<div className="skills-list">
{allSkills.map((skill, index) => (
<div key={index} className="input-field">
<input
type="checkbox"
id={skill.id}
name={skill.name}
value={skill.value}
onChange={handleChange}
/>{" "}
<label htmlFor="carpentry">{skill.value}</label>
</div>
))}
</div>
);
};
export default Skills;
<file_sep>import { useState } from "react";
import "./HandymanRegistrationForm.css";
import Skills from "./Skills";
import {
sendRegistrationRequest,
validateForm,
} from "../../../common/js/functions";
// default profile picture
const defaultHandymanProfilePicture =
"https://dogtime.com/assets/uploads/2011/03/puppy-development.jpg";
const HandymanRegistrationForm = () => {
// form submission errors
const [errors, setErrors] = useState([]);
// handyman registration form entry values
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [img, setProfilePicture] = useState(
defaultHandymanProfilePicture // WARN: NO IMAGE UPLOAD FUNCTIONALITY ADDED!
);
const [addressLineOne, setAddressLineOne] = useState("");
const [addressLineTwo, setAddressLineTwo] = useState("");
const [city, setCity] = useState("Coventry");
const [postcode, setPostcode] = useState("");
const [email, setEmail] = useState("");
const [emailConfirm, setEmailConfirm] = useState("");
const [phoneNumber, setPhoneNumber] = useState("");
const [selectedSkills, setSelectedSkills] = useState([]);
const [otherSkill, setOtherSkill] = useState("");
const [bio, setBio] = useState("");
// organise fields that need further validation
const fieldsToValidate = [
{ type: "email", value: email },
{ type: "tel", value: phoneNumber },
];
// organise the form data to be sent
const formData = {
firstName,
lastName,
img,
address: { addressLineOne, addressLineTwo, city },
postcode,
email,
phoneNumber,
skills: [...selectedSkills, otherSkill],
bio,
};
// EVENT HANDLERS
const sendFormData = async (event) => {
event.preventDefault();
const form = event.target;
const errors = validateForm(fieldsToValidate);
if (selectedSkills.length === 0)
errors.push("You must select at least one skill.");
if (emailConfirm !== email)
errors.push("The emails you entered do not match.");
if (errors.length > 0) {
alert("Error(s) on the form. Please check and try again.");
return setErrors(errors);
}
setErrors([]);
const requestData = [
"service_l0m5rpd",
"template_ybb8yxc",
formData,
"user_Z6650OqueHooRxmmi5Geo",
];
// check if sending quote request was successful. Navigate to homepage if it was.
const okToGoHome = await sendRegistrationRequest(requestData);
if (okToGoHome) window.location.assign("/");
};
return (
<form
id="form-add-handyman"
name="form-add-handyman"
onSubmit={sendFormData}
>
{errors.map((e, index) => (
<p key={index} className="error">
{e}
</p>
))}
<h1 className="title">Become a Repairer</h1>
<fieldset className="input-field-group details">
<legend className="subtitle">Your Details</legend>
<div className="basic-details">
<h3>Basic Details</h3>
<div className="input-field">
<label htmlFor="first-name">
First Name<span className="required">*</span>
</label>{" "}
<input
type="text"
id="firstName"
name="firstName"
maxLength={50}
required
onChange={(event) => setFirstName(event.target.value)}
placeholder="Enter your first name here"
/>
</div>
<div className="input-field">
<label htmlFor="last-name">
Last Name<span className="required">*</span>
</label>{" "}
<input
type="text"
id="lastName"
name="lastName"
maxLength={50}
required
onChange={(event) => setLastName(event.target.value)}
placeholder="Enter your last name here"
/>
</div>
</div>
<div className="input-field-group address-details">
<h3>Address</h3>
<div className="input-field">
<label htmlFor="address-line-one">
Address Line 1<span className="required">*</span>
</label>{" "}
<input
type="text"
id="addressLineOne"
name="addressLineOne"
maxLength={50}
required
onChange={(event) => setAddressLineOne(event.target.value)}
placeholder="Enter your building or flat number"
/>
</div>
<div className="input-field">
<label htmlFor="address-line-two">
Address Line 2<span className="required">*</span>
</label>{" "}
<input
type="text"
id="addressLineTwo"
name="addressLineTwo"
maxLength={50}
required
onChange={(event) => setAddressLineTwo(event.target.value)}
placeholder="Enter your street name here"
/>
</div>
<div className="input-field">
<label htmlFor="city">
City or District<span className="required">*</span>
</label>{" "}
<input
type="text"
id="city"
name="city"
maxLength={50}
required
onChange={(event) => setCity(event.target.value)}
defaultValue="Coventry"
/>
</div>
<div className="input-field">
<label htmlFor="Postcode">
Postcode<span className="required">*</span>
</label>{" "}
<input
type="text"
id="postcode"
name="postcode"
maxLength={12}
required
onChange={(event) => setPostcode(event.target.value)}
placeholder="Enter your postcode here"
/>
</div>
</div>
<div className="input-field-group contact-details">
<h3>Contact Details</h3>
<div className="input-field">
<label htmlFor="email">
Email<span className="required">*</span>
</label>{" "}
<input
type="email"
id="email"
name="email"
maxLength={50}
required
onChange={(event) => setEmail(event.target.value)}
placeholder="<EMAIL>"
/>
</div>
<div className="input-field">
<label htmlFor="email">
Confirm Your Email<span className="required">*</span>
</label>{" "}
<input
type="email"
id="email"
name="email"
maxLength={50}
required
onChange={(event) => setEmailConfirm(event.target.value)}
placeholder="<EMAIL>"
/>
</div>
<div className="input-field">
<label htmlFor="phone-number">
Phone Number<span className="required">*</span>
</label>{" "}
<input
type="tel"
id="phoneNumber"
name="phoneNumber"
minLength={11}
maxLength={13}
required
onChange={(event) => setPhoneNumber(event.target.value)}
/>
</div>
</div>
</fieldset>
<fieldset className="input-field-group skills">
<legend className="subtitle">
Skills<span className="required">*</span>
</legend>
<em className="required">Please select at least one skill</em>
<Skills onChangeHandler={(list) => setSelectedSkills(list)} />
<div className="input-field">
<label htmlFor="other-skills">Other:</label>{" "}
<input
type="text"
id="other-skills"
name="other-skills"
onChange={(event) => setOtherSkill(event.target.value)}
placeholder={`What other repairer skill do you have?`}
/>
</div>
</fieldset>
<div className="input-field-bio">
<h2 className="subtitle">
Bio<span className="required">*</span>
</h2>
<textarea
type="text-area"
id="bio"
name="bio"
maxLength={500}
required
onChange={(event) => setBio(event.target.value)}
placeholder="Short introduction about you or what you do..."
/>
</div>
<div className="submit-button-div">
<input type="submit" id="btn-submit" name="btn-submit" value="Submit" />
</div>
</form>
);
};
export default HandymanRegistrationForm;
<file_sep>const repository = require("../data/handymanRepository");
/***************** THE FOLLOWING METHODS ARE ACCESSIBLE TO ALL PUBLIC ROUTES *******************/
// GET ALL HANDYMEN
async function getAllHandymen() {
const result = await repository.getAllHandymen();
return result.rows;
}
// SEARCH HANDYMAN FROM LIST BY HANDYMAN ID
async function getHandymanById(hId) {
const result = await repository.getHandymanById(hId);
return result.rows[0];
}
// POST A NEW HANDYMAN
async function addNewHandyman(hData) {
const dataIsValid = validateHandymanData(hData);
if (dataIsValid) {
try {
const handymanIsNew = await handymanDoesntExist(hData.email);
if (handymanIsNew) {
await repository.addNewHandyman(hData);
return {
status: "OK",
message: "Handyman has been added successfully.",
};
}
return {
status: "FAIL",
message:
"Sorry, but we could not send your request. A user with the same email already exists.",
};
} catch (error) {
// if there is database connection issue
console.log(error);
return {
status: "Error",
message: "Internal server error.",
};
}
}
return {
status: "FAIL",
message: "Handyman could not be saved. Missing handyman information.",
};
}
// WARN: THIS FUNCTION IS CURRENTLY NOT BEING USED. IT IS INCLUDED IN LIGHT OF PROBABLE FUTURE NEEDS
async function getReviewsByHandymanId(hId) {
const result = await repository.getReviewsByHandymanId(hId);
return result.rows;
}
// VALIDATE INCOMING HANDYMAN DATA
// Note: this is used only during the initial stage of handyman registration process (accessible to anyone...
// ...who would like to register as handyman on the site)
function validateHandymanData(hData) {
// required handyman data fields
try {
const {
firstName,
lastName,
address,
postcode,
email,
phoneNumber,
skills,
bio,
} = hData;
// destructure address (={addressLineOne, addressLineTwo,city}) and access individual field values
// city has default value of "Coventry", so no need to validate that
const { addressLineOne, addressLineTwo } = address;
const dataToValidate = [
firstName,
lastName,
addressLineOne,
addressLineTwo,
postcode,
email,
phoneNumber,
skills,
bio,
];
return dataToValidate.every((item) => item);
} catch (err) {
console.log(err);
}
}
// CHECK IF A HANDYMAN WITH THE SAME EMAIL (CREDENTIALS) ALREADY EXISTS
// Note: this is used only during the initial stage of handyman registration process (accessible to anyone...
// ...who would like to rgister as handyman on the site)
async function handymanDoesntExist(hEmail) {
try {
const result = await repository.getHandymanByEmail(hEmail);
return result.rowCount === 0;
} catch (error) {
console.log(error);
}
}
async function getThreeRandomHandyman() {
const result = await repository.getThreeRandomHandyman();
return result.rows;
}
/******************************************************************************************************/
/***************** THE FOLLOWING METHODS ARE DEDICATED TO ADMIN-ACCESSIBLE ROUTES *******************/
// WARN: ANY REQUIRED AUTHORISATION LOGIC IS YET TO BE ADDED
// GET ALL HANDYMEN
async function getAllHandymenForAdmin() {
const result = await repository.getAllHandymenForAdmin();
return result.rows;
}
// SEARCH HANDYMAN FROM LIST BY HANDYMAN ID
async function getHandymanByIdForAdmin(hId) {
const result = await repository.getHandymanByIdForAdmin(hId);
return result.rows[0];
}
// UPDATE THE VISIBILITY STATUS (TRUE OR FALSE) OF A HANDYMAN
async function changeHandymanVisibilityByAdmin(hData) {
const dataIsValid = validateUpdateData(hData);
if (!dataIsValid) {
return {
status: "FAIL",
message:
"Handyman visibility could not updated. Missing or invalid information.",
};
}
// if the provided information is valid, continue...
try {
// check if the requested handyman is found in the database
const result = await repository.getHandymanByIdForAdmin(hData.id);
if (result.rowCount === 0) {
return {
status: "FAIL",
message: `Sorry, but the handyman with id "${hData.id}" could not be found.`,
};
}
await repository.changeHandymanVisibilityByAdmin(hData);
return {
status: "OK",
message: "Handyman visibility has been updated successfully.",
};
} catch (error) {
// if there is database connection issue
console.log(error);
return {
status: "Error",
message: "Internal server error.",
};
}
}
// UPDATE HANDYMAN RECORDS BY ID FOR ADMIN
async function editHandymanDetailsByIdAdmin(hData) {
const dataIsValid = validateHandymanData(hData); //
if (dataIsValid) {
try {
const handymanExists = await getHandymanByIdForAdmin(hData.id);
if (handymanExists) {
const result = await repository.editHandymanDetailsByIdAdmin(hData);
if (result.rowCount > 0) {
return {
status: "OK",
message: "Handyman has been updated successfully.",
};
}
}
return {
status: "FAIL",
message: "A user with this id does not exist.",
};
} catch (error) {
// if there is database connection issue
console.log(error);
return {
status: "Error",
message: "Internal server error.",
};
}
}
return {
status: "FAIL",
message: "Handyman could not be saved. Missing handyman information.",
};
}
// DELETE HANDYMAN RECORD BY ID FOR ADMIN
async function deleteHandymanByIdAdmin(hId) {
const result = await repository.deleteHandymanByIdAdmin(hId);
return result.rows[0];
}
function validateUpdateData(hData) {
const { visible, id } = hData;
// make sure both new visible value ('true' or 'false') and handyman id has been supplied
if (visible === undefined || id === undefined) return false;
// if all informaiton has been provided, validate each data
if (typeof visible !== "boolean") return false;
if (isNaN(parseInt(id))) return false;
// upon successful data validation
return true;
}
module.exports = {
getAllHandymen,
getHandymanById,
getAllHandymenForAdmin,
getHandymanByIdForAdmin,
changeHandymanVisibilityByAdmin,
addNewHandyman,
getReviewsByHandymanId,
getThreeRandomHandyman,
editHandymanDetailsByIdAdmin,
deleteHandymanByIdAdmin,
};
<file_sep>const express = require("express");
const router = express.Router();
import { pool } from "./../db";
/*
the main root of this router is: "/api/v1/reviews"
or
if the request upcoming from offersRouter"
/api/v1/booking/:offerId/reviews
but it still will work in the same way, just it is another redirection
try: http://localhost:3000/api/v1/offers/22/reviews
*/
router.route("/").get(async (req, res, next) => {
try {
const bookingsAll = await pool.query("SELECT * FROM reviews");
res.status(200).json({
status: "success",
length: bookingsAll.rowCount,
data: bookingsAll.rows,
});
} catch (error) {
res.status(400).json({
status: "fail",
msg: error.message,
});
}
});
router
.route("/:reviewId")
.get(async (req, res, next) => {
try {
const { reviewId } = req.params;
const bookingsAll = await pool.query(
`SELECT * FROM offers WHERE offer_id = $1`,
[reviewId]
);
res.status(200).json({
status: "success",
status: "success",
length: bookingsAll.rowCount,
data: bookingsAll.rows[0],
});
} catch (error) {
res.status(400).json({
status: "fail",
msg: error.message,
});
}
})
.patch(async (req, res, next) => {
const { reviewId } = req.params;
res.status(200).json({
status: "success",
msg: `patch method reviewRouter "/:reviewId" You sent ${reviewId}`,
});
})
.delete(async (req, res, next) => {
const { reviewId } = req.params;
res.status(200).json({
status: "success",
msg: `delete method bookingRouter "/:reviewId" You sent ${reviewId}`,
});
});
module.exports = router;
<file_sep>export default function InputFields({ search,setSearch,handleChange }) {
return(
<form className="form" >
<div className="form-group">
<div>
<input type="text" className="by-skill" placeholder="filter by a skill" onChange={handleChange} />
</div>
<div>
<input type="text" className="by-keyword" placeholder="filter by a keyword" onChange={handleChange} />
</div>
</div>
</form>
);
}
<file_sep>import { Redirect, useLocation } from "react-router-dom";
import Handyman from "../components/Handyman/Profile/Handyman";
const HandymanProfile = () => {
const { state } = useLocation();
return state ? <Handyman userData={state} /> : <Redirect to="/" />;
};
export default HandymanProfile;<file_sep>import React from "react";
import classes from "./AdminPage.module.css";
import { Route, useRouteMatch, Switch } from "react-router-dom";
import AdminHandyPeopleTable from "./AdminHandyPeopleTable";
import UpdateForm from "./UpdateForm";
export default function Adminpage(props) {
let { path, url } = useRouteMatch();
return (
<div>
<Switch>
<Route
path={`${url}/handyPeople`}
exact
render={(props) => <AdminHandyPeopleTable {...props} />}
/>
<Route
path={`${url}/handyPeople/:id`}
component={(props) => <UpdateForm {...props} />}
/>
<Route
path={`${url}/buyersrequests`}
render={(props) => <p>BUYERS Requests</p>}
/>
<Route path={`${url}/buyers`} component={(props) => <p>BUYERS</p>} />
<Route
path={`${url}/repairrequest`}
render={(props) => <p>Repairs Requests</p>}
/>
</Switch>
</div>
);
}
<file_sep>import React from "react";
import classes from "./mainPage.module.scss";
import PrimarySection from "./primarySection/PrimarySection";
import AboutSection from "./aboutSection/AboutSection";
import CustomersSection from "./customersSection/CustomerSection";
import Explanation from "./explanation/explanation";
/**
* @DescriptionFunction This is component which is use as a mainPage in react app on the route "/" - home route
* It is using four other components as a sub components PrimarySection AboutSection CustomersSection Explanation
*/
const MainPage = (props) => {
return (
<div className={classes.mainPage}>
<PrimarySection />
<AboutSection />
<CustomersSection />
<Explanation />
</div>
);
};
export default MainPage;
<file_sep>import { useEffect, useState } from "react";
import { useRouteMatch, useParams } from "react-router";
const TemporaryEditForm = (props) => {
let { path, url } = useRouteMatch();
const { id } = useParams();
const [user, setUser] = useState({});
useEffect(() => {
// fetch("/api/users/handyman")
fetch(`/api/users/handyman/adminsacceshandymans/${id}`)
.then((res) => {
if (!res.ok) {
throw new Error(res.statusText);
}
return res.json();
})
.then((body) => {
//!TODO: brutal solution of storing data inside the db as a string - fix it
// const newArray = body.data.map((item) => {
// return (item = {
// ...item,
// address_offer: JSON.parse(item.address_offer[0]),
// });
// });
// setUser(newArray);
setUser(body.data);
})
.catch((err) => {
console.error(err);
});
}, []);
const handleChange = (e) => {
console.log(e.target.value);
//TODO: modify it to handle the update of the visibility true / false
setUser((prevState) => {
return {
...prevState,
[`${e.target.name}`]: e.target.value,
};
});
};
// Function to send update
const patchUser = async () => {
try {
} catch (error) {
// TODO: temporary
console.log(error);
}
};
//"form" to input the data to sent if needed
// TODO: disabled='disabled'
console.log(user);
let form = <p>LOADING...</p>;
if (user.first_name) {
form = (
<form>
<p>First name:</p>
<input
type="text"
id="first_name"
name="first_name"
value={user.first_name}
onChange={handleChange}
/>
<p>First name:</p>
<input
type="text"
id="last_name"
name="last_name"
value={user.last_name}
onChange={handleChange}
/>
<p>Visible /Not visible</p>
<input type="checkbox" name="inputOne" onClick={handleChange} />
</form>
);
}
return form;
};
export default TemporaryEditForm;
<file_sep>import React, { useEffect, useState, useContext } from "react";
import { Route, Redirect } from "react-router-dom";
import AuthContext from "../../../store/authContext";
import UserAccount from "./userAccount/UserAccount";
/**
* @DescriptionFunction component which is sub element in relation to AdminPanel component. This component is first component where we can manage users accounts.
*/
const UserManagements = (props) => {
const [allUsers, SetAllUsers] = useState([]);
const authCtx = useContext(AuthContext);
console.log(authCtx.token)
useEffect(async () => {
try {
const allUsersRaw = await fetch("/api/v1/users", {
method: 'GET',
headers: {
Authorization: `Bearer ${authCtx.token}`,
"Content-Type": 'application/json'
}
});
const allUsersFetched = await allUsersRaw.json();
console.log(allUsersFetched);
if(allUsersFetched.data) {
SetAllUsers((prevState) => {
return (prevState = [...allUsersFetched.data]);
});
}
} catch (error) {
console.log(error.message);
}
}, []);
const usersAccounts = allUsers.map((item) => (
<UserAccount key={item.user_id} user={item} {...props} />
));
if (!allUsers) usersAccount = <p>LOADING</p>;
return (
<div>
<h1>I am lovely UserManagements component</h1>
{usersAccounts}
</div>
);
};
export default UserManagements;
<file_sep>import { useLocation, useParams,Redirect } from "react-router-dom";
import { useContext, useEffect, useState } from "react";
import AuthContext from "../../store/authContext";
import classes from "./AdminPage.module.css";
export default function UpdateForm() {
const [isRedirect,setIsRedirect]=useState(false);
const authCtx = useContext(AuthContext);
const { id } = useParams();
// INPUT FIELDS STATES DECLARATION AND INITIALIZING TO EMPTY STRING
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [email, setEmail] = useState("");
const [skills, setSkills] = useState([]);
const [newSkill, setNewSkill] = useState("");
const [city, setCity] = useState("");
const [postcode, setPostcode] = useState("");
const [phoneNumber, setPhoneNumber] = useState("");
const [addressLineOne, setAddressLineOne] = useState("");
const [addressLineTwo, setAddressLineTwo] = useState("");
const [bio, setBio] = useState("");
// FETCH HANDYMAN DATA BY ID
useEffect(() => {
fetch(`/api/v1/handyman/handymanprotected/${id}`, {
headers: { Authorization: `Bearer ${authCtx.token}` },
})
.then((res) => res.json())
.then((data) => {
// INPUT FIELDS UPDATE WITH INCOMING DATA
setFirstName(data.first_name);
setLastName(data.last_name);
setPhoneNumber(data.phone_number);
setEmail(data.email);
setCity(data.address.city);
setPostcode(data.postcode);
setSkills(data.skills);
setAddressLineOne(data.address.addressLineOne);
setAddressLineTwo(data.address.addressLineTwo);
setBio(data.bio);
});
}, [id]);
// SUBMIT FORM DATA FUNCTION
const submitData = async (e) => {
e.preventDefault();
fetch(`/api/v1/handyman/handymanprotected/${id}`, {
method: "PUT",
body: JSON.stringify({
firstName,
lastName,
email,
address: {
addressLineOne,
addressLineTwo,
city,
},
phoneNumber,
postcode,
skills:[...skills, newSkill],
bio,
id,
}),
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${authCtx.token}`,
},
}).then((res) => res.json())
.then((data) => console.log(data))
.catch((error) => console.log(error));
alert(`Repairer's detail has been updated`)
setIsRedirect(true);
};
return (
!isRedirect ? <div>
<form
className={classes.updateForm}
name="form-edit-repairer"
onSubmit={submitData}
>
<fieldset className={classes.input_field_group_details}>
<legend className={classes.subtitle}>Edit repairer details</legend>
<div className={classes.basic_details}>
<h3>Basic Details</h3>
<div className={classes.input_field}>
<label htmlFor="first-name">
First Name<span className="required">*</span>
</label>{" "}
<input
type="text"
id="firstName"
name="firstName"
maxLength={50}
required
value={firstName}
onChange={(e) => setFirstName(e.target.value)} // INPUT FIELD VALUES WILL BE RESET TO TYPED VALUE
/>
</div>
<div className={classes.input_field}>
<label htmlFor="last-name">
Last Name<span className="required">*</span>
</label>{" "}
<input
type="text"
id="lastName"
name="lastName"
maxLength={50}
required
value={lastName}
onChange={(e) => {
console.log(e.target.value);
setLastName(e.target.value);
}}
/>
</div>
</div>
<div className={classes.input_field_group_details}>
<h3>Address</h3>
<div className={classes.input_field}>
<label htmlFor="address-line-one">
Address Line 1<span className="required">*</span>
</label>{" "}
<input
type="text"
id="addressLineOne"
name="addressLineOne"
maxLength={50}
required
value={addressLineOne}
onChange={(e) => setAddressLineOne(e.target.value)}
/>
</div>
<div className={classes.input_field}>
<label htmlFor="address-line-two">
Address Line 2<span className="required">*</span>
</label>{" "}
<input
type="text"
id="addressLineTwo"
name="addressLineTwo"
maxLength={50}
required
value={addressLineTwo}
onChange={(e) => setAddressLineTwo(e.target.value)}
/>
</div>
<div className={classes.input_field}>
<label htmlFor="city">
City or District<span className="required">*</span>
</label>{" "}
<input
type="text"
id="city"
name="city"
maxLength={50}
required
value={city}
onChange={(e) => setCity(e.target.value)}
/>
</div>
<div className={classes.input_field}>
<label htmlFor="Postcode">
Postcode<span className="required">*</span>
</label>{" "}
<input
type="text"
id="postcode"
name="postcode"
maxLength={12}
required
value={postcode}
onChange={(e) => setPostcode(e.target.value)}
/>
</div>
</div>
<div className={classes.contact_details}>
<h3>Contact Details</h3>
<div className={classes.input_field}>
<label htmlFor="email">
Email<span className="required">*</span>
</label>{" "}
<input
type="email"
id="email"
name="email"
maxLength={50}
required
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className={classes.input_field}>
<label htmlFor="phone-number">
Phone Number<span className="required">*</span>
</label>{" "}
<input
type="tel"
id="phoneNumber"
name="phoneNumber"
// minLength={11}
//maxLength={13}
required
value={phoneNumber}
onChange={(e) => setPhoneNumber(e.target.value)}
/>
</div>
</div>
</fieldset>
<fieldset className={classes.input_field_skills}>
<legend className="subtitle">
Skills<span className="required">*</span>
</legend>
{skills.map((skill, index) => (
<p key={index}>{skill}</p>
))}
{/* INPUT FIELD FOR THE ADMIN TO ADD NEW SKILL TO THE HANDYMAN SKILLS */}
<input
value={newSkill}
onChange={(e) => setNewSkill(e.target.value)}
placeholder="add new skill"
></input>
</fieldset>
<div className={classes.edit_button}>
<input type="submit" id="btn-submit" name="btn-submit" value="Update" />
</div>
</form>
</div>
: <Redirect to="/admin-panel/handyPeople" />
);
}
<file_sep>import React, { useState, useCallback, useEffect } from "react";
let logoutTimer;
const AuthContext = React.createContext({
token: "",
isLoggedIn: false,
login: (token) => {},
logout: () => {},
});
//helper functions
/**
* @description function is calculating difference between current time and the expiration time
* @param {milliseconds} expiration is provided from the server with the respond
* @returns remaining time in the form of milliseconds
*/
const calcRemainingTime = (expiration) => {
const currentTime = new Date().getTime();
const expirationOfToken = new Date(expiration).getTime();
const remainingTime = expirationOfToken - currentTime;
return remainingTime;
};
/**
* @description function is retrieving the expiration time of token and the token from local storage
* @returns {object} object contain token and duration in milliseconds
*/
const getStoredItem = () => {
const storedToken = localStorage.getItem("token");
const storedExpirationTime = localStorage.getItem("expTime");
const remainingTime = calcRemainingTime(storedExpirationTime);
if (remainingTime <= 3600) {
localStorage.removeItem("token");
localStorage.removeItem("expTime");
return null;
}
return {
token: storedToken,
duration: remainingTime,
};
};
// exported context
export const AuthContextProvide = (props) => {
//retrieving item from local storage
const tokenData = getStoredItem();
let initialToken;
if (tokenData) {
initialToken = tokenData.token;
}
const [token, setToken] = useState(initialToken);
const userIsLoggedIn = !!token;
// useCallback to stop unnecessary re rendering components
const logoutHandler = useCallback(() => {
setToken(null);
localStorage.removeItem("token");
localStorage.removeItem("expTime");
if (logoutTimer) {
clearTimeout(logoutTimer);
}
}, []);
const loginHandler = (token, expiration) => {
setToken(token);
localStorage.setItem("token", token);
localStorage.setItem("expTime", expiration);
const remainingTime = calcRemainingTime(expiration);
logoutTimer = setTimeout(logoutHandler, remainingTime);
};
// Setting the timer to auto logout
useEffect(() => {
if (tokenData) {
logoutTimer = setTimeout(logoutHandler, tokenData.duration);
}
}, [tokenData, logoutHandler]);
const contextValue = {
token: token,
isLoggedIn: userIsLoggedIn,
login: loginHandler,
logout: logoutHandler,
};
return (
<AuthContext.Provider value={contextValue}>
{props.children}
</AuthContext.Provider>
);
};
export default AuthContext;
<file_sep>import React from "react";
import classes from "./Input.module.scss";
/**
* @DescriptionFunction Simple Input component which has dynamic style to emphasize wrong input
*/
const input = (props) => {
const inputCSSClasses = [classes.inputClass];
/**
* If condition which are going to change the CSS classes
* CSS class Invalid is going to emphasize incorrect input
*/
if (props.invalid && props.shouldValidate && props.touched) {
inputCSSClasses.push(classes.Invalid);
}
if (props.incorrectEmOrPass) {
inputCSSClasses.push(classes.Invalid);
}
const inputItem = (
<input
className={inputCSSClasses.join(" ")}
placeholder={props.placeholder}
onChange={props.formInputHandler}
value={props.value}
{...props.elementConfig}
/>
);
return inputItem;
};
export default input;
<file_sep>import React, { useEffect, useState } from "react";
import classes from "./CustomerSection.module.scss";
import backgroundVideo from "../../../public/ConstructionWorkersDESKTOP.mp4";
import CustomerCommentMain from "./customerCommentMain/CustomerCommentMain";
import HandymanProfileMain from "./handymanProfileMain/handymanProfileMain";
import Spinner from "../../../UI/Spinner/Spinner";
/**
* @DescriptionFunction Sub component used in MainPage component
*/
const CustomerSection = (props) => {
const [handymenProfiles, setHandymanProfiles] = useState([]);
useEffect(async () => {
try {
const dataRAW = await fetch(
"/api/v1/handyman/handymannotprotected/randomthree"
);
const data = await dataRAW.json();
const threeHandyman = data.data;
setHandymanProfiles(threeHandyman);
} catch (error) {
// after functionality TODO: error handling
console.log(error);
}
}, []);
//!TODO: style in nice way spinner or to put it into the container (?)
// but first functionality!
let usersComments = <Spinner />;
if (handymenProfiles && handymenProfiles.length > 0) {
// if handymen profiles could be fetched from database, load profiles (max 3) at random
usersComments = handymenProfiles.map((item) => (
<HandymanProfileMain key={item.id} item={item} />
));
} else {
// otherwise, replace the handymenProfiles area with other content
usersComments = ""; // hopefully this will be replaced by some text related to handymen
}
return (
<div className={classes.customers}>
<div className={classes.customers__bgVideo}>
<video
className={classes.customers__bgVideo__video}
autoPlay
muted
loop
>
<source src={backgroundVideo} type="video/mp4" />
Your browser is not supported!
</video>
</div>
<h2 className={classes.customers__heading}> Our Repairers </h2>
<div className={classes.customers__commentContainer}>{usersComments}</div>
</div>
);
};
export default CustomerSection;
<file_sep>import React from "react";
import { Link } from "react-router-dom";
import classes from "./PrimarySection.module.scss";
/**
* @DescriptionFunction Sub component used in MainPage component
*/
const PrimarySection = (props) => {
return (
<div className={classes.primary}>
<div>
<h1 className={classes.primary__heading}>
<span className={classes.primary__heading__main}>
find a repairer
</span>
<span className={classes.primary__heading__sub}>
from your <span>community</span>
</span>
</h1>
<Link
to="/users/handyman/register"
className={`${classes.primary__button} ${classes.primary__button__publish}`}
>
BECOME A REPAIRER
</Link>
<Link
to="/users/handyman/0/forms/request-for-quote"
className={`${classes.primary__button} ${classes.primary__button__hire}`}
>
ASK FOR A PRICE
</Link>
</div>
</div>
);
};
export default PrimarySection;
<file_sep>import { createHash } from "crypto";
const jwt = require("jsonwebtoken");
const { promisify } = require("util");
import userModel from "../model/userModel";
const sendEmail = require("../utils/email");
const signToken = (id) => {
return jwt.sign({ id }, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRES_IN,
});
};
/**
* @description function is creating and sending token and expiration time. Function is using signToken() helper function
* @param {object} user
* @param {integer} statusCode
* @param {response object} res
*/
const createSendToken = (user, statusCode, res) => {
const token = signToken(user.user_id);
const expirationTime = new Date();
expirationTime.setMinutes(
expirationTime.getMinutes() +
parseInt(process.env.JWT_COOKIE_EXPIRES_IN_MINUTES)
);
const cookieOptions = {
expires: expirationTime,
httpOnly: true,
};
if (process.env.DATABASE_URL) cookieOptions.secure = true;
res.cookie("jwt", token, cookieOptions);
res.status(statusCode).json({
status: "success",
token,
expirationTime,
data: {
user,
},
});
};
/**
* * @Description this is the controller responsible for signing up the user.
* this controller importing signUpUser from userModel.js
* */
exports.signup = async (req, res, next) => {
try {
// Is it logical to pass req.body or just to split data here to?
const newUser = await userModel.signUpUser(req.body);
createSendToken(newUser.rows[0], 201, res);
} catch (error) {
res.status(400).json({
status: "fail",
msg: error.message,
});
}
};
/**
* * @Description this is the controller responsible for login the user.
* this controller importing logInUser from userModel.js
* */
exports.login = async (req, res, next) => {
try {
const { email, password } = req.body;
// to check email and password
if (!email || !password)
throw new Error("Please provide email and password");
// correctness of password and email
const newUser = await userModel.logInUser(req.body);
// all ok - > send token
createSendToken(newUser, 201, res);
} catch (error) {
res.status(401).json({
status: "fail",
msg: error.message,
});
}
};
/**
* @description Middleware used to protection of routes
*/
exports.protect = async (req, res, next) => {
try {
// 1 - getting token and check if it exist
let token;
if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer")
) {
token = req.headers.authorization.split(" ")[1];
}
if (!token) {
//!TODO: next step it would be great to implement GLOBAL error handling!
res.status(401).json({
status: "fail",
msg: "You are not logged in! Please log in to get access.",
});
}
// 2 verification of token <- the most important jwt is going to do it
const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET);
// 3 check if the user still exist
// 4 if user changed password after jwt token was sent to him
const fetchedUser = await userModel.findUserByTokenDecoded(decoded);
//GRANTING ACCESS TO PROTECTED ROUTE
req.user = fetchedUser;
next();
} catch (error) {
res.status(401).json({
status: "fail",
msg: error.message,
});
}
};
/**
*
* @param {Array of strings} roles is the Array of the roles which are passed to the function
* @returns
*/
exports.restrictTo = (...roles) => {
return (req, res, next) => {
//!TODO it should send error 403 -> We need to specify the global error handling or introduce temporary solution
if (!roles.includes(req.user.user_role))
throw new Error("You do not have permission to perform this action");
next();
};
};
exports.forgotPassword = async (req, res, next) => {
try {
// get user based on posted email
const user = await userModel.findOneUser(req.body);
// generate the random reset token and saving it to DB
const passwordResetToken = await userModel.createPasswordResetToken(user);
// send back as a email
const resetURL = `${req.protocol}://${req.get(
"host"
)}/api/v1/users/resetPassword/${passwordResetToken}`;
const message = `Forgot Your password? Submit a Patch request with your new password and password Confirm to:
${resetURL}. \nIf You did not forger your password, please ignore this email!`;
await sendEmail({
email: user.email,
subject: "Your password reset token (valid 10 minutes)",
message,
});
res.status(200).json({
status: "success",
message: "Token sent to your email address",
});
} catch (error) {
// !TODO in this place in case of error we have to undone the changes in DB in users -> password token and expire token - delete it
res.status(404).json({
status: "fail",
msg: error.message,
});
}
};
exports.resetPassword = async (req, res, next) => {
try {
// get user base on the token
const hashedToken = createHash("sha256")
.update(req.params.token)
.digest("hex");
//set new password only if the token is not expired and there is the user - set new password
// ANOTHER APPROACH IS TO BUILD ERROR BASE ON FETCHING OR NOT FETCHING USERS (?)
const user = await userModel.findUserBaseOnResetToken(hashedToken);
// update changedPasswordAt for the current user
// - it looks very repetitive. There must be better way
// - I need to hash the new password as well.
await userModel.updatePasswordAfterRecovery(
user,
req.body.password,
req.body.passwordConfirm
);
//login user in
createSendToken(user, 201, res);
} catch (error) {
res.status(404).json({
status: "fail",
msg: error.message,
});
}
};
/**
* @@description only for logged in user
*/
exports.updatePassword = async (req, res, next) => {
//TODO: logically it would be much better to check if passwordCandidate and passwordCandidateConfirm
// are the same from start because it would save at least 1 request to DB
try {
// get user from DB
const user = await userModel.findUserById(
req.user.user_id,
req.body.passwordCurrent
);
// check if posted password is correct - second level confirmation
//!TODO: temporary implemented in messy way in one function inside userModel
// if correct update password
//!TODO: think over if i need to return something here for security reasons
const updatesUser = await userModel.updateUserPassword(
user.user_id,
req.body.passwordCandidate,
req.body.passwordCandidateConfirm
);
// log user in with new password - jwt token
//login user in
createSendToken(user, 201, res);
} catch (error) {
res.status(404).json({
status: "fail",
msg: error.message,
});
}
};
<file_sep>const repository = require("../data/buyerRepository");
/***
*
* WARN: THIS FILE IS CURRENTLY NOT BEING USED. IT IS PREPARED IN LIGHT OF PROBABLE FUTURE NEED.
*
*/
/***************** THE FOLLOWING METHODS ARE ACCESSIBLE TO ALL PUBLIC ROUTES *******************/
// GET ALL BUYERS
async function getAllBuyers() {
const result = await repository.getAllBuyers();
return result.rows;
}
// SEARCH BUYER FROM LIST BY BUYER ID
async function getBuyerById(bId) {
const result = repository.getBuyerById(bId);
return result.rows[0];
}
// POST A NEW BUYER
async function addNewBuyer(bData) {
// console.log(bData)
const dataIsValid = validateNewBuyerData(bData);
if (dataIsValid) {
try {
const buyerIsNew = await buyerDoesntExist(bData.email);
if (buyerIsNew) {
await repository.addNewBuyer(bData);
return {
status: "OK",
message: "Buyer has been added successfully.",
};
}
return {
status: "FAIL",
message:
"Sorry, but we could not send your request. A user with the same email already exists.",
};
} catch (error) {
// if there is database connection issue
return console.log(error);
}
}
return {
status: "FAIL",
message: "Buyer could not be saved. Missing buyer information.",
};
}
// VALIDATE INCOMING BUYER DATA
// Note: this is used only during the initial stage of quote requesting process (accessible to anyone...
// ...who would like to send quote reqeust to a handyman on the site)
function validateNewBuyerData(bData) {
// required buyer data fields
try {
const {
buyerName,
buyerEmail,
} = bData;
const dataToValidate = [
buyerName,
buyerEmail,
];
return dataToValidate.every((item) => item);
} catch (err) {
console.log(err);
}
}
// CHECK IF A BUYER WITH THE SAME EMAIL (CREDENTIALS) ALREADY EXISTS
// Note: this is used only during the initial stage of quote requesting process (accessible to anyone...
// ...who would like to send quote reqeust to a handyman on the site)
async function buyerDoesntExist(bEmail) {
try {
const result = await repository.getBuyerByEmail(bEmail);
return result.rowCount === 0;
} catch (error) {
console.log(error);
}
}
/******************************************************************************************************/
/***************** THE FOLLOWING METHODS ARE DEDICATED TO ADMIN-ACCESSIBLE ROUTES *******************/
// WARN: ANY REQUIRED AUTHORISATION LOGIC IS YET TO BE ADDED
// GET ALL BUYERS
async function getAllBuyersForAdmin() {
const result = await repository.getAllBuyersForAdmin();
return result.rows;
}
// SEARCH BUYER FROM LIST BY BUYER ID
async function getBuyerByIdForAdmin(bId) {
const result = await repository.getBuyerByIdForAdmin(bId);
return result.rows[0];
}
module.exports = {
getAllBuyers,
getBuyerById,
addNewBuyer,
getAllBuyersForAdmin,
getBuyerByIdForAdmin,
};
<file_sep>import React from "react";
import classes from "./handymanProfileMain.module.scss";
//TODO: add the alt from where I took this svg!
import user from "../../../../public/user.svg";
/**
* @DescriptionFunction sub component used by CustomerSection to create the review of users widget which is going to be displayed on main page.
* @params component is getting object <item> passed though parent component, which contain:
* - review: integer
* - photo: string which point to directory where is stored picture
* - user_name: string with name of the user
* - user_surname: string with surname of the user
* - comment: comment provided by user regarding service
*/
const HandymanProfileMain = (props) => {
return (
<div className={classes.customer}>
<figure className={classes.customer__figure}>
<img className={classes.customer__img} src={props.item.photo ? props.item.photo : user} />
<figcaption className={classes.customer__figcaption}>
{props.item.first_name} {props.item.last_name}.
</figcaption>
</figure>
<p>{props.item.bio}</p>
</div>
);
};
export default HandymanProfileMain;
<file_sep>import React from "react";
export default function TableRows({ oneList, handleChange }) {
return (
<tbody>
<tr>
<th scope="row">{oneList.id}</th>
<td>{oneList.first_name}</td>
<td>{oneList.last_name}</td>
<td>{oneList.email}</td>
<td>{oneList.phone_number}</td>
<td>{oneList.postcode}</td>
<td>{oneList.address.addressLineTwo}</td>
<td>{oneList.visible ? "Visible" : "Hidden"}</td>
<td>
<select
id={oneList.id}
onChange={(e) => {
handleChange(e, oneList);
}}
>
<option>action</option>
<option>Update</option>
<option>Delete</option>
<option>Deactivate</option>
<option>Activate</option>
</select>
</td>
</tr>
</tbody>
);
}
|
2be3d31ed9715edb1bab9c30697befc7a5062215
|
[
"JavaScript",
"SQL"
] | 59 |
JavaScript
|
Pat-On/repairs_for_you
|
34c5070bb4a6c47c17282156c1b077d6aa308519
|
181ba6341567b9ee3191f4eb056475bcf771cdac
|
refs/heads/master
|
<repo_name>VOEURNRADY/Demo<file_sep>/src/main/java/com/example/demo/Student.java
package com.example.demo;
public class Student implements People{
@Override
public void showTitle() {
System.out.println("I'm a student");
}
}
<file_sep>/src/main/java/com/example/demo/People.java
package com.example.demo;
public interface People {
void showTitle();
}
<file_sep>/src/main/java/com/example/demo/DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
//ApplicationContext context= SpringApplication.run(DependencyInjectionDemoApplication.class, args);
ApplicationContext context = SpringApplication.run(DemoApplication.class, args);
Title t= context.getBean("titleShow",Title.class);
t.show();
/*Title t1= context.getBean("titleShow1",Title.class);
t1.show();
*/
}
}
|
dca4bf789431fa897cb4b5d8f292a7a9c0542eb2
|
[
"Java"
] | 3 |
Java
|
VOEURNRADY/Demo
|
b57aa924a6abcc2c14b5a10a69c5d81f7bb1def2
|
09deba8d8020b51cfe1271a3e5871f221bc3290e
|
refs/heads/main
|
<repo_name>wodin/react-pdf-node<file_sep>/scripts/bundle.js
const Bundler = require("parcel-bundler");
const Path = require("path");
const entryFiles = "./index.js";
const options = {
target: "node",
};
(async function () {
const bundler = new Bundler(entryFiles, options);
bundler.on("bundled", (bundle) => {
const { execFile } = require("child_process");
console.log("$ node dist/index.js");
execFile("node", ["dist/index.js"], (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
if (stdout) {
console.log(`stdout: ${stdout}`);
}
});
});
// Run the bundler, this returns the main bundle
// Use the events if you're using watch mode as this promise will only trigger once and not for every rebuild
const bundle = await bundler.bundle();
})();
|
84ba7ba114a2a9f44f230a470713831a40cd9d01
|
[
"JavaScript"
] | 1 |
JavaScript
|
wodin/react-pdf-node
|
e34736e5398acb7b9b90e44e0fb28af8af6e5e10
|
5ac4b8899201065f8192ea014f24dfd311c9eccc
|
refs/heads/master
|
<file_sep>$( document ).ready(function() {
// https://shaack.com/projekte/bootstrap-input-spinner/
$("input[type='number']").inputSpinner();
$("input[type='number']").on("change", function (event) {
if($(this).val()==''){
$(this).val( $(this).attr('min') );
}
});
var curentStep = 1;
$('.btn.next-step').click(function(event){
event.preventDefault();
if(curentStep==1){
continueSurvey = verifyStep1();
}else if(curentStep==2){
continueSurvey = verifyStep2();
}else{
continueSurvey = verifyStep3();
}
if(continueSurvey==true){
$('#step-'+curentStep).addClass("d-none");
curentStep++;
$('#step-'+curentStep).removeClass("d-none");
$('#curentStep').text(curentStep);
}
});
//Dynamicly adding or removing model input in function generateQeustion8()
$('#q7').on("change", function (event) {
var amountOfInputs = $(this).val();
generateQeustion8( amountOfInputs );
});
});
function verifyStep1()
{
var age = $('#q1').val();
if(age<18){
//END SURVEY and save survey answers
alertMessage = 'Thank you for your interest in helping BMW.';
var surveyAnswers = {
Q1: $('#q1').val(),
Q2: $('#q2').val(),
};
saveSurvey(surveyAnswers, alertMessage);
return false;
}else if(age>=18 && age<=25){
//Display question 4
$('#question-4').removeClass("d-none");
return true;
}else{
return true;
}
}
function verifyStep2()
{
var answer3 = $('#q3').val();
if(answer3 =='no'){
var surveyAnswers = {
Q1: $('#q1').val(),
Q2: $('#q2').val(),
Q3: answer3,
};
var alertMessage = 'Thank you for your interest in helping BMW.';
saveSurvey(surveyAnswers,alertMessage);
return false;
}else if( !$('#question-4').hasClass('d-none') ){
var answer4 = $('#q4').val();
if(answer4=='yes'){
var surveyAnswers = {
Q1: $('#q1').val(),
Q2: $('#q2').val(),
Q3: answer3,
Q4: answer4,
};
var alertMessage = 'We are targeting more experienced clients, thank you for your interest.';
saveSurvey(surveyAnswers,alertMessage);
return false;
}else{
return true;
}
}else{
return true;
}
}
function generateQeustion8( expectingElements )
{
//Display question 8 block
if(expectingElements>0){
$('#question-8').removeClass("d-none");
}
var newInputModel = '<input type="text" class="form-control mt-3 new-input animate-box fadeIn animated" autofocus="" placeholder="Model name" />';
var currentInputs = $("#question-8").find( "input" );
if(currentInputs.length<expectingElements){
//We add new inputs
while (currentInputs.length < expectingElements) {
$('#question-8').append( newInputModel );
expectingElements--;
}
}else{
//We remove last inputs
while (currentInputs.length > expectingElements) {
$('#question-8').children('span:last-child').remove();
$('#question-8').children('input:last-child').remove();
expectingElements++;
}
}
//Patterns Verification
/*
// I did pattern validation here to make better interface for user
// He will see that model is incorrect(without submitting form) until he will not enter correct model
*/
var pattern1 = /^M?[0-9]{3}[d|i]?$/i;
var pattern2 = /^[X|Z]{1}[0-9]{1}$/i;
$("#question-8").find( "input" ).on("change paste keyup", function(value) {
$(this).removeClass('new-input');
var model = $(this).val();
if( pattern1.test(model) || pattern2.test(model) ) {
//valid bmw model
$(this).next('span').remove();
}else{
//invalid bmw model - Adding error message for user
if($(this).next('span').length){
$(this).next('span').text( 'Invalid BMW Model' );
}else{
$(this).after( '<span class="text-danger">Invalid BMW Model</span>' );
}
}
});
}
function verifyStep3()
{
//Checking if there is empty model inputs or invalid models
var emptyModelInputs = $("#question-8").find( ".new-input" );
var incorectModels = $("#question-8").find( "span.text-danger" );
if(emptyModelInputs.length>0 || incorectModels.length>0){
//Adding error message for user
emptyModelInputs.each(function() {
if($(this).next('span').length){
$(this).next('span').text( 'Invalid BMW Model' );
}else{
$(this).after( '<span class="text-danger">Invalid BMW Model</span>' );
}
});
}else{
var answer4 = null;
if( !$('#question-4').hasClass('d-none') ){
var answer4 = $('#q4').val();
}
var answer8 = {};
$("#question-8").find( "input" ).each(function(i, e) {
answer8[i] = $( this ).val();
});
var surveyAnswers = {
Q1: $('#q1').val(),
Q2: $('#q2').val(),
Q3: $('#q3').val(),
Q4: answer4,
Q5: $('#q5').val(),
Q6: $('#q6').val(),
Q7: $('#q7').val(),
Q8: answer8,
};
alertMessage = 'Thank you for your interest in helping BMW.';
saveSurvey(surveyAnswers, alertMessage);
}
}
function saveSurvey(surveyAnswers,alertMessage)
{
//Adding 1 extra field with current time when this survey was submitted
surveyAnswers['time']=new Date().getTime();
//SAVE TO LOCAL STORAGE
var surveyAnswersArr = [];
if (localStorage.getItem("surveyAnswers") === null) {
//the first submited survey
surveyAnswersArr.push( surveyAnswers );
}else{
//Getting Old answers and adding new
surveyAnswersArr = JSON.parse(localStorage.getItem('surveyAnswers'));
surveyAnswersArr.push( surveyAnswers );
}
localStorage.setItem('surveyAnswers', JSON.stringify(surveyAnswersArr));
//END OF SURVEY Part for user
$('.end-survey-remove').remove();
$('#end-survey').text(alertMessage);
$('#end-survey').removeClass('d-none');
}
<file_sep><?php
$request = $_SERVER['REQUEST_URI'];
switch ($request)
{
case '/' :
require("app/components/header.html");
require("app/model/survey.php");
break;
case '' :
require("app/components/header.html");
require("app/model/survey.php");
break;
case '/survey-review/' :
require("app/components/header.html");
include_once("app/model/surveyReview.php");
break;
default:
//Usually we would put here 404 page But in this case we can show survey form to users
require("app/components/header.html");
require("app/model/survey.php");
break;
}
?>
<file_sep>$( document ).ready(function() {
var surveyAnswers = JSON.parse(localStorage.getItem('surveyAnswers'));
var countSurveys = surveyAnswers.length;
var adolescents = 0;
var unlicensed = 0;
var firstTimers = 0;
var targetables = 0;
var driftingLover = 0;
var countFWD = 0;
var countOwnedBMW = 0;
var carModels={};
//Looping trough our answers to get amount of each respondent group
$.each(surveyAnswers, function( key, survey ) {
if(survey.Q1<18){
adolescents++;
}else if(survey.Q3=='no'){
unlicensed++;
}else if(survey.Q4=='yes'){
firstTimers++;
}else{
targetables++;
if(survey.Q5=='FWD' || survey.Q5=='I don’t know'){
countFWD++;
}
if(survey.Q6=='yes'){
driftingLover++;
}
countOwnedBMW = countOwnedBMW + parseInt(survey.Q7);
$.each( survey.Q8, function( key, model ) {
if(model in carModels){
var amount = carModels[model];
amount++;
carModels[model]=amount;
}else{
carModels[model]=1;
}
});
}
});
//Calculating percentage of each group
var adolescentsPercentage = getPercentage(adolescents, countSurveys);
var unlicensedPercentage = getPercentage(unlicensed, countSurveys);
var firstTimersPercentage = getPercentage(firstTimers, countSurveys);
var targetablesPercentage = getPercentage(targetables, countSurveys);
var driftingPercentage = 0;
var fwdPercentage = 0;
var averageOwnedBMW =0;
if(targetables>0){
var driftingPercentage = getPercentage(driftingLover, targetables);
var fwdPercentage = getPercentage(countFWD, targetables);
var averageOwnedBMW = Math.round(countOwnedBMW / targetables * 10) / 10; //2.6
}
//Staff requirements Display
var html = '<li>How many under 18s participated? - <b>'+adolescents+ ' ('+adolescentsPercentage+'%)'+'</b></li>';
html = html + '<li>How many unlicensed drivers participated? - <b>'+unlicensed+ ' ('+unlicensedPercentage+'%)'+'</b></li>';
html = html + '<li>How many 18-25s first car owners participated? - <b>'+firstTimers+ ' ('+firstTimersPercentage+'%)'+'</b></li>';
html = html + '<li>How many targetable clients participated? - <b>'+targetables+ ' ('+targetablesPercentage+'%)'+'</b></li>';
html = html + '<li>Percentage of targetables that care about drifting: <b>'+targetablesPercentage+'%'+'</b></li>';
html = html + '<li>Percentage of targetables that picked FWD or “I don’t know” for drivetrain: <b>'+fwdPercentage+'%'+'</b></li>';
html = html + '<li>The average amount of BMWs owned by targetables: <b>'+averageOwnedBMW+'</b></li>';
html = html + '<li>The model distribution of all the BMW models entered: <b>'+JSON.stringify(carModels)+'</b></li>';
$('#staff-requirements').html(html);
//chart for group
var labels = ["Adolescents", "Unlicensed", "First-timers", "Targetables"];
var data = [adolescents, unlicensed, firstTimers, targetables];
var colors = ["#ff6384", "#36a2eb", "#cc65fe", "#ffce56"];
createChart('groupChart', 'Amount of Participants by groups', 'bar', labels, data, colors);
//chart for group %
var labels = ["Adolescents", "Unlicensed", "First-timers", "Targetables"];
var data = [adolescentsPercentage, unlicensedPercentage, firstTimersPercentage, targetablesPercentage];
var colors = ["#ff6384", "#36a2eb", "#cc65fe", "#ffce56"];
createChart('groupPercentageChart', ' A breakdown of each respondent group by percentage ', 'bar', labels, data, colors);
//chart for targetGroup %
var labels = ["Care about drifting", "Picked FWD or “I don’t know” for drivetrain"];
var data = [driftingPercentage, fwdPercentage ];
var colors = ["#ff6384", "#36a2eb"];
createChart('targetGroup', 'Percentage of targetables ', 'bar', labels, data, colors);
//chart for models
createChartModels(carModels);
});
function getPercentage(num, per)
{
var percents = (num/per)*100;
percents = Math.round(percents * 100) / 100;
return percents;
}
function createChart(divID, title, type, labels, data, colors)
{
var ctx = document.getElementById(divID).getContext('2d');
var myChart = new Chart(ctx, {
type: type,
data: {
labels: labels,
datasets: [{
label: title,
data: data,
backgroundColor: colors,
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
function createChartModels(models)
{
var labels = [];
var data = [];
$.each(models, function (key, value) {
labels.push(key);
data.push(value);
});
var colors = [];
var ctx = document.getElementById('models').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'The model distribution of all the BMW models entered',
data: data,
backgroundColor: colors,
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
|
67848d16f2b9ecb4bd7309e17da231ee0a0926b9
|
[
"JavaScript",
"PHP"
] | 3 |
JavaScript
|
admkot/bmw-survey
|
5dc0743cd6fd2625d82c8df7f18a91777a2aa922
|
11ca24ea3f2a3d20e5676a50a3042011a69c9fb3
|
refs/heads/master
|
<file_sep>package XMLTree;
import java.util.Vector;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XMLTreeModel implements TreeModel {
private Document document;
Vector<TreeModelListener> listeners = new Vector<TreeModelListener>();
public Document getDocument() {
return document;
}
public void setDocument(Document document) {
this.document = document;
TreeModelEvent evt = new TreeModelEvent(this, new TreePath(getRoot()));
for (TreeModelListener listener : listeners) {
listener.treeStructureChanged(evt);
}
}
public void addTreeModelListener(TreeModelListener listener) {
if (!listeners.contains(listener)) {
listeners.add(listener);
}
}
public void removeTreeModelListener(TreeModelListener listener) {
listeners.remove(listener);
}
public Object getChild(Object parent, int index) {
if (parent instanceof XMLTreeNode) {
Vector<Element> elements = getChildElements( ((XMLTreeNode)parent).getElement() );
return new XMLTreeNode( elements.get(index) );
}
else {
return null;
}
}
public int getChildCount(Object parent) {
if (parent instanceof XMLTreeNode) {
Vector<Element> elements = getChildElements( ((XMLTreeNode)parent).getElement() );
return elements.size();
}
return 0;
}
public int getIndexOfChild(Object parent, Object child) {
if (parent instanceof XMLTreeNode && child instanceof XMLTreeNode) {
Element pElement = ((XMLTreeNode)parent).getElement();
Element cElement = ((XMLTreeNode)child).getElement();
if (cElement.getParentNode() != pElement) {
return -1;
}
Vector<Element> elements = getChildElements(pElement);
return elements.indexOf(cElement);
}
return -1;
}
public Object getRoot() {
if (document==null) {
return null;
}
Vector<Element> elements = getChildElements(document);
if (elements.size() > 0) {
return new XMLTreeNode( elements.get(0));
}
else {
return null;
}
}
public boolean isLeaf(Object node) {
if (node instanceof XMLTreeNode) {
Element element = ((XMLTreeNode)node).getElement();
Vector<Element> elements = getChildElements(element);
return elements.size()==0;
}
else {
return true;
}
}
public void valueForPathChanged(TreePath path, Object newValue) {
throw new UnsupportedOperationException();
}
private Vector<Element> getChildElements(Node node) {
Vector<Element> elements = new Vector<Element>();
NodeList list = node.getChildNodes();
for (int i=0 ; i<list.getLength() ; i++) {
if (list.item(i).getNodeType() == Node.ELEMENT_NODE) {
elements.add( (Element) list.item(i));
}
}
return elements;
}
}
<file_sep># mycodepad
Documentation available on
https://codepad.appinous.com
Please use below link to download library files
https://codepad.appinous.com/downloads
for runnable jar :
https://codepad.appinous.com/downloads
thank you so much for downloading MyCodePad
<file_sep>package javaComp;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class JavaCompile {
public static StringBuilder printLines(String name, InputStream ins) throws Exception {
String line = null;
StringBuilder compileMsg=new StringBuilder();
BufferedReader in = new BufferedReader(new InputStreamReader(ins));
while ((line = in.readLine()) != null) {
compileMsg.append(name + " " + line+"\n");
}
return compileMsg;
}
public static StringBuilder runProcess(String command) throws Exception {
Process pro = Runtime.getRuntime().exec(command);
StringBuilder compileMsg=new StringBuilder();
//compileMsg.append(printLines(command + " stdout:", pro.getInputStream()));
// compileMsg.append(printLines(command + " stderr:", pro.getErrorStream()));
compileMsg.append(printLines("", pro.getInputStream()));
compileMsg.append(printLines("", pro.getErrorStream()));
pro.waitFor();
// compileMsg.append(command + " exitValue() " + pro.exitValue());
return compileMsg;
}
}<file_sep>package dockWindow;
import javax.swing.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import XMLTree.XMLTreePanel;
import hierarchy.XMLEditorKit;
import java.awt.event.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.awt.*;
public class Test {
Desktop desktop;
public JTextArea textArea;
@SuppressWarnings("deprecation")
public Test() {
JFrame frame=new JFrame("XML Editor");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
desktop=new Desktop();
desktop.setBackground(Color.white);
init(desktop);
frame.getContentPane().add(desktop,BorderLayout.CENTER);
JButton b=new JButton("New XML");
frame.getContentPane().add(b,BorderLayout.SOUTH);
ActionListener lst=new ActionListener() {
public void actionPerformed(ActionEvent e) {
desktop.removeAll();
init(desktop);
desktop.refresh();
}
};
b.addActionListener(lst);
frame.setBounds(50,50,600,400);
frame.show();
}
public void init(Desktop panel) {
DockablePanel dp=new DockablePanel();
try {
dp=new DockablePanel();
dp.title="XML Source";
dp.setLayout(new BorderLayout());
textArea = new JTextArea ();
dp.add(new JScrollPane(textArea),BorderLayout.CENTER);
JButton button=new JButton("Align");
dp.add(button,BorderLayout.SOUTH);
panel.addDesktopComponent(dp,0,2,2,1);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try
{
File file=File.createTempFile("temp", ".xml");
OutputStream out=new FileOutputStream(file);
out.write(textArea.getText().getBytes());
out.close();
DockablePanel dp=new DockablePanel();
dp.title="XML Tree";
dp.setLayout(new BorderLayout());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbFactory.newDocumentBuilder();
Document document = builder.parse(file);
document.normalize();
XMLTreePanel xmlpanel = new XMLTreePanel();
xmlpanel.setDocument(document);
dp.add(xmlpanel,BorderLayout.CENTER);
panel.addDesktopComponent(dp,2,1,1,2);
dp=new DockablePanel();
dp.title="XML Structure";
dp.setLayout(new BorderLayout());
JEditorPane edit = new JEditorPane();
String testXML="";
byte[] data = Files.readAllBytes(file.toPath());
testXML=new String(data);
edit.setEditorKit(new XMLEditorKit());
edit.setText(testXML);
edit.setEditable(false);
dp.add(new JScrollPane(edit),BorderLayout.CENTER);
panel.addDesktopComponent(dp,0,3,3,1);
panel.refresh();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,"XML not in well form","result :",
JOptionPane.INFORMATION_MESSAGE);
}
}
});
} catch (Exception e) {
}
}
}<file_sep>package dockWindow;
import javax.swing.*;
import java.awt.*;
import javax.swing.border.*;
import java.awt.event.*;
public class DockablePanel extends SimpleDockablePanel {
protected String title="Title";
protected Color titleBackgroundColor=new Color(170,170,255);
protected Color titleForegroundColor=Color.white;
public DockablePanel() {
super();
super.setBorder(new EmptyBorder(20,2,2,2));
}
public void setTitle(String title) {
this.title=title;
repaint();
}
public void setTitleBackground(Color color) {
titleBackgroundColor=color;
}
public Color getTitleBackground() {
return titleBackgroundColor;
}
public void setTitleForeground(Color color) {
titleForegroundColor=color;
}
public Color getTitleForeground() {
return titleForegroundColor;
}
public void setBorder(Border border) {
Border margin = new EmptyBorder(20,2,2,2);
super.setBorder(new CompoundBorder(margin, border));
}
public void paint (Graphics g) {
super.paint(g);
int width=getWidth();
int height=getHeight();
Color oldColor=g.getColor();
g.setColor(Color.gray);
g.drawRect(0,0,width-1,height-1);
g.setColor(Color.darkGray);
g.drawRect(1,1,width-2,height-2);
g.setColor(Color.white);
g.drawLine(1,height-2,width-2,height-2);
g.drawLine(width-2,1,width-2,height-2);
//draw caption
width-=4;
height-=4;
g.setColor(titleBackgroundColor);
((Graphics2D)g).setPaint(new GradientPaint(1,2,Color.blue,width-2,height-2,Color.cyan));
g.fillRect(2,2,width,18);
g.setColor(titleForegroundColor);
g.drawString(title,3,15);
//draw close button
g.setColor(Color.lightGray);
g.fillRect(width-17,4,15,14);
g.setColor(Color.white);
g.drawLine(width-17,4,width-2,4);
g.drawLine(width-17,4,width-17,18);
g.setColor(Color.darkGray.darker());
g.drawLine(width-17,18,width-2,18);
g.drawLine(width-2,4,width-2,18);
g.setColor(Color.darkGray);
g.drawLine(width-16,17,width-3,17);
g.drawLine(width-3,5,width-3,17);
g.setColor(Color.black);
g.drawLine(width-13,8,width-7,14);
g.drawLine(width-13,14,width-7,8);
g.setColor(oldColor);
}
public void mousePressed(MouseEvent e) {
if (regim==DESKTOP_REGIM) {
if ((e.getY()>this.getHeight()-2) || (e.getY()<18) || (e.getX()<2) || (e.getX()>this.getWidth()-2))
super.mousePressed(e);
}
else {
if ((e.getY()>1) && (e.getY()<18) && (e.getX()>2) && (e.getX()<this.getWidth()-2))
super.mousePressed(e);
else {
startDragX=-1;
startDragY=-1;
}
}
}
public void mouseDragged(MouseEvent e) {
if (regim==DESKTOP_REGIM) {
super.mouseDragged(e);
}
else {
if ((startDragX>-1) && (startDragY>-1)) {
super.mouseDragged(e);
}
}
}
/**
* Invoked when the mouse button has been clicked (pressed
* and released) on a component.
*/
public void mouseClicked(MouseEvent e) {
Container c=this.getParent();
if (c==null) return;
int width=this.getWidth()-4;
if ((e.getX()>=width-17) && (e.getX()<=width-2) && (e.getY()>=4) && (e.getY()<=14)) {
if (c instanceof Desktop) {
Desktop parentDesktop=(Desktop)c;
parentDesktop.removeComponent(this);
parentDesktop.refresh();
}
dragWindow.hide();
}
else {
super.mouseClicked(e);
}
}
}<file_sep>package application;
//package p1;
import java.io.*;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.metal.DefaultMetalTheme;
import javax.swing.plaf.metal.MetalLookAndFeel;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.fife.ui.autocomplete.AutoCompletion;
import org.fife.ui.autocomplete.BasicCompletion;
import org.fife.ui.autocomplete.CompletionProvider;
import org.fife.ui.autocomplete.DefaultCompletionProvider;
import org.fife.ui.autocomplete.ShorthandCompletion;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
import org.fife.ui.rsyntaxtextarea.spell.SpellingParser;
import org.fife.ui.rtextarea.RTextScrollPane;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import XMLTree.DemoMain;
import dockWindow.Test;
import hierarchy.App;
import javaComp.JavaCompile;
//import p1.FontChooser;
//import p1.FontDialog;
//import p1.FindDialog;
//import p1.LookAndFeelMenu;
//import p1.MyFileFilter;
/************************************/
class Splash extends JFrame {
private JLabel imglabel;
private ImageIcon img;
private static JProgressBar pbar;
Thread t = null;
public Splash() {
super("CodePad");
setSize(404, 310);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
setUndecorated(true);
img = new ImageIcon(getClass().getResource("/application/loader1.gif"));
setBackground(new Color(0, 255, 0, 0));
imglabel = new JLabel(img);
add(imglabel);
setLayout(null);
pbar = new JProgressBar();
pbar.setMinimum(0);
pbar.setMaximum(100);
pbar.setStringPainted(true);
pbar.setForeground(Color.LIGHT_GRAY);
imglabel.setBounds(0, 0, 404, 310);
//add(pbar);
pbar.setPreferredSize(new Dimension(310, 30));
pbar.setBounds(0, 290, 404, 20);
Thread t = new Thread() {
public void run() {
int i = 0;
while (i <= 100) {
pbar.setValue(i);
try {
sleep(90);
} catch (InterruptedException ex) {
Logger.getLogger(Splash.class.getName()).log(Level.SEVERE, null, ex);
}
i++;
}
}
};
t.start();
}
}
class FileOperation
{
Notepad npd;
boolean saved;
boolean newFileFlag;
String fileName;
String applicationTitle="Codepad";
File fileRef;
JFileChooser chooser;
/////////////////////////////
boolean isSave(){return saved;}
void setSave(boolean saved){this.saved=saved;}
String getFileName(){return new String(fileName);}
void setFileName(String fileName){this.fileName=new String(fileName);}
/////////////////////////
FileOperation(Notepad npd)
{
this.npd=npd;
saved=true;
newFileFlag=true;
fileName=new String("Untitled");
fileRef=new File(fileName);
this.npd.f.setTitle(fileName+" - "+applicationTitle);
chooser=new JFileChooser();
chooser.addChoosableFileFilter(new MyFileFilter(".java","Java Source Files(*.java)"));
chooser.addChoosableFileFilter(new MyFileFilter(".txt","Text Files(*.txt)"));
chooser.setCurrentDirectory(new File("."));
}
//////////////////////////////////////
boolean saveFile(File temp)
{
FileWriter fout=null;
try
{
fout=new FileWriter(temp);
fout.write(npd.ta.getText());
}
catch(IOException ioe){updateStatus(temp,false);return false;}
finally
{try{fout.close();}catch(IOException excp){}}
updateStatus(temp,true);
return true;
}
////////////////////////
boolean saveThisFile()
{
if(!newFileFlag)
{return saveFile(fileRef);}
return saveAsFile();
}
////////////////////////////////////
boolean saveAsFile()
{
File temp=null;
chooser.setDialogTitle("Save As...");
chooser.setApproveButtonText("Save Now");
chooser.setApproveButtonMnemonic(KeyEvent.VK_S);
chooser.setApproveButtonToolTipText("Click me to save!");
do
{
if(chooser.showSaveDialog(this.npd.f)!=JFileChooser.APPROVE_OPTION)
return false;
temp=chooser.getSelectedFile();
if(!temp.exists()) break;
if( JOptionPane.showConfirmDialog(
this.npd.f,"<html>"+temp.getPath()+" already exists.<br>Do you want to replace it?<html>",
"Save As",JOptionPane.YES_NO_OPTION
)==JOptionPane.YES_OPTION)
break;
}while(true);
return saveFile(temp);
}
////////////////////////
boolean openFile(File temp)
{
FileInputStream fin=null;
BufferedReader din=null;
try
{
fin=new FileInputStream(temp);
din=new BufferedReader(new InputStreamReader(fin));
String str=" ";
while(str!=null)
{
str=din.readLine();
if(str==null)
break;
this.npd.ta.append(str+"\n");
}
}
catch(IOException ioe){updateStatus(temp,false);return false;}
finally
{try{din.close();fin.close();}catch(IOException excp){}}
updateStatus(temp,true);
this.npd.ta.setCaretPosition(0);
return true;
}
///////////////////////
void openFile()
{
if(!confirmSave()) return;
chooser.setDialogTitle("Open File...");
chooser.setApproveButtonText("Open this");
chooser.setApproveButtonMnemonic(KeyEvent.VK_O);
chooser.setApproveButtonToolTipText("Click me to open the selected file.!");
File temp=null;
do
{
if(chooser.showOpenDialog(this.npd.f)!=JFileChooser.APPROVE_OPTION)
return;
temp=chooser.getSelectedFile();
if(temp.exists()) break;
JOptionPane.showMessageDialog(this.npd.f,
"<html>"+temp.getName()+"<br>file not found.<br>"+
"Please verify the correct file name was given.<html>",
"Open", JOptionPane.INFORMATION_MESSAGE);
} while(true);
this.npd.ta.setText("");
if(!openFile(temp))
{
fileName="Untitled"; saved=true;
this.npd.f.setTitle(fileName+" - "+applicationTitle);
}
if(!temp.canWrite())
newFileFlag=true;
}
////////////////////////
void updateStatus(File temp,boolean saved)
{
if(saved)
{
this.saved=true;
fileName=new String(temp.getName());
if(!temp.canWrite())
{fileName+="(Read only)"; newFileFlag=true;}
fileRef=temp;
npd.f.setTitle(fileName + " - "+applicationTitle);
npd.statusBar.setText("File : "+temp.getPath()+" saved/opened successfully.");
newFileFlag=false;
}
else
{
npd.statusBar.setText("Failed to save/open : "+temp.getPath());
}
}
///////////////////////
boolean confirmSave()
{
String strMsg="<html>The text in the "+fileName+" file has been changed.<br>"+
"Do you want to save the changes?<html>";
if(!saved)
{
int x=JOptionPane.showConfirmDialog(this.npd.f,strMsg,applicationTitle,JOptionPane.YES_NO_CANCEL_OPTION);
if(x==JOptionPane.CANCEL_OPTION) return false;
if(x==JOptionPane.YES_OPTION && !saveAsFile()) return false;
}
return true;
}
///////////////////////////////////////
void newFile()
{
if(!confirmSave()) return;
this.npd.ta.setText("");
fileName=new String("Untitled");
fileRef=new File(fileName);
saved=true;
newFileFlag=true;
this.npd.f.setTitle(fileName+" - "+applicationTitle);
}
//////////////////////////////////////
}// end defination of class FileOperation
/************************************/
public class Notepad extends JFrame implements ActionListener, MenuConstants
{
public static JFrame f;
RSyntaxTextArea ta;
public static JLabel statusBar;
DefaultCompletionProvider provider= new DefaultCompletionProvider();
private String fileName="Untitled";
private boolean saved=true;
String applicationName="Javapad";
String searchString, replaceString;
int lastSearchIndex;
FileOperation fileHandler;
FontChooser fontDialog=null;
FindDialog findReplaceDialog=null;
JColorChooser bcolorChooser=null;
JColorChooser fcolorChooser=null;
JDialog backgroundDialog=null;
JDialog foregroundDialog=null;
JMenuItem cutItem,copyItem, deleteItem, findItem, findNextItem, replaceItem, gotoItem, selectAllItem;
/**
* @throws UnsupportedLookAndFeelException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws ClassNotFoundException **************************/
Notepad() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException
{
f=new JFrame(fileName+" - "+applicationName);
ta=new RSyntaxTextArea(20, 60);
ta.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_NONE);
ta.setAnimateBracketMatching(true);
ta.setCodeFoldingEnabled(true);
DropTarget target=new DropTarget(ta,new DropTargetListener(){
public void dragEnter(DropTargetDragEvent e)
{
}
public void dragExit(DropTargetEvent e)
{
}
public void dragOver(DropTargetDragEvent e)
{
}
public void dropActionChanged(DropTargetDragEvent e)
{
}
public void drop(DropTargetDropEvent e)
{
try
{
// Accept the drop first, important!
e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
// Get the files that are dropped as java.util.List
java.util.List list=(java.util.List) e.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
// Now get the first file from the list,
File file=(File)list.get(0);
f.setTitle(file.getName());
saved=true;
fileName=new String(file.getName());
statusBar.setText("File : "+file.getPath()+" saved/opened successfully.");
ta.setText(new String(Files.readAllBytes(Paths.get(file.getAbsolutePath()))));
}catch(Exception ex){}
}
});
/*ta.addKeyListener(new KeyAdapter() {
@Override public void keyPressed(KeyEvent event)
{
System.out.println(event);
DefaultCompletionProvider provider = new DefaultCompletionProvider();
System.out.println(provider.getParameterListSeparator());
}
}
);*/
statusBar=new JLabel("|| Ln 1, Col 1 ",JLabel.RIGHT);
try
{
//File zip = new File(getClass().getResource("/application/english_dic.zip").toURI());
InputStream in = getClass().getResourceAsStream("/english_dic.zip");
File out=File.createTempFile("Eng", "Dic");
Files.copy(in,out.toPath() , StandardCopyOption.REPLACE_EXISTING);
boolean usEnglish = false; // "false" will use British English
SpellingParser parser;
out.deleteOnExit();
parser = SpellingParser.createEnglishSpellingParser(out, usEnglish);
ta.addParser(parser);
} catch (Exception e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
statusBar.setText(e1.toString());
}
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.add(new RTextScrollPane(ta));
setContentPane(contentPane);
f.add(new JScrollPane(ta),BorderLayout.CENTER);
f.add(statusBar,BorderLayout.SOUTH);
f.add(new JLabel(" "),BorderLayout.EAST);
f.add(new JLabel(" "),BorderLayout.WEST);
createMenuBar(f);
//f.setSize(350,350);
f.pack();
f.setLocation(100,50);
f.setVisible(true);
f.setLocation(150,50);
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
fileHandler=new FileOperation(this);
/////////////////////
ta.addCaretListener(
new CaretListener()
{
public void caretUpdate(CaretEvent e)
{
int lineNumber=0, column=0, pos=0;
try
{
pos=ta.getCaretPosition();
lineNumber=ta.getLineOfOffset(pos);
column=pos-ta.getLineStartOffset(lineNumber);
}catch(Exception excp){}
if(ta.getText().length()==0){lineNumber=0; column=0;}
statusBar.setText("|| Ln "+(lineNumber+1)+", Col "+(column+1));
}
});
//////////////////
DocumentListener myListener = new DocumentListener()
{
public void changedUpdate(DocumentEvent e){fileHandler.saved=false;}
public void removeUpdate(DocumentEvent e){fileHandler.saved=false;}
public void insertUpdate(DocumentEvent e){fileHandler.saved=false;}
};
ta.getDocument().addDocumentListener(myListener);
/////////
WindowListener frameClose=new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
if(fileHandler.confirmSave())System.exit(0);
}
};
f.addWindowListener(frameClose);
//////////////////
/*
ta.append("Hello dear hello hi");
ta.append("\nwho are u dear mister hello");
ta.append("\nhello bye hel");
ta.append("\nHello");
ta.append("\nMiss u mister hello hell");
fileHandler.saved=true;
*/
}
////////////////////////////////////
void goTo()
{
int lineNumber=0;
try
{
lineNumber=ta.getLineOfOffset(ta.getCaretPosition())+1;
String tempStr=JOptionPane.showInputDialog(f,"Enter Line Number:",""+lineNumber);
if(tempStr==null)
{return;}
lineNumber=Integer.parseInt(tempStr);
ta.setCaretPosition(ta.getLineStartOffset(lineNumber-1));
}catch(Exception e){}
}
///////////////////////////////////
//action Performed
////////////////////////////////////
void showBackgroundColorDialog()
{
if(bcolorChooser==null)
bcolorChooser=new JColorChooser();
if(backgroundDialog==null)
backgroundDialog=JColorChooser.createDialog
(Notepad.this.f,
formatBackground,
false,
bcolorChooser,
new ActionListener()
{public void actionPerformed(ActionEvent evvv){
Notepad.this.ta.setBackground(bcolorChooser.getColor());}},
null);
backgroundDialog.setVisible(true);
}
////////////////////////////////////
void showForegroundColorDialog()
{
if(fcolorChooser==null)
fcolorChooser=new JColorChooser();
if(foregroundDialog==null)
foregroundDialog=JColorChooser.createDialog
(Notepad.this.f,
formatForeground,
false,
fcolorChooser,
new ActionListener()
{public void actionPerformed(ActionEvent evvv){
Notepad.this.ta.setForeground(fcolorChooser.getColor());}},
null);
foregroundDialog.setVisible(true);
}
///////////////////////////////////
JMenuItem createMenuItem(String s, int key,JMenu toMenu,ActionListener al)
{
JMenuItem temp=new JMenuItem(s,key);
temp.addActionListener(al);
toMenu.add(temp);
return temp;
}
////////////////////////////////////
JMenuItem createMenuItem(String s, int key,JMenu toMenu,int aclKey,ActionListener al)
{
JMenuItem temp=new JMenuItem(s,key);
temp.addActionListener(al);
temp.setAccelerator(KeyStroke.getKeyStroke(aclKey,ActionEvent.CTRL_MASK));
toMenu.add(temp);
return temp;
}
////////////////////////////////////
JCheckBoxMenuItem createCheckBoxMenuItem(String s, int key,JMenu toMenu,ActionListener al)
{
JCheckBoxMenuItem temp=new JCheckBoxMenuItem(s);
temp.setMnemonic(key);
temp.addActionListener(al);
temp.setSelected(false);
toMenu.add(temp);
return temp;
}
////////////////////////////////////
JMenu createMenu(String s,int key,JMenuBar toMenuBar)
{
JMenu temp=new JMenu(s);
temp.setMnemonic(key);
toMenuBar.add(temp);
return temp;
}
/**
* @throws UnsupportedLookAndFeelException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws ClassNotFoundException *******************************/
void createMenuBar(JFrame f) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException
{
JMenuBar mb=new JMenuBar();
JMenuItem temp;
JMenu fileMenu=createMenu(fileText,KeyEvent.VK_F,mb);
JMenu editMenu=createMenu(editText,KeyEvent.VK_E,mb);
JMenu formatMenu=createMenu(formatText,KeyEvent.VK_O,mb);
JMenu theme=createMenu("Theme",KeyEvent.VK_V,mb);
JMenu viewMenu=createMenu(viewText,KeyEvent.VK_V,mb);
JMenu langMenu=createMenu(langText,KeyEvent.VK_F11,mb);
JMenu XMLView=createMenu(xmlText,KeyEvent.VK_8,mb);
JMenu cmdView=createMenu(cmdText,KeyEvent.VK_F10,mb);
JMenu shareView=createMenu(shareText,KeyEvent.VK_F10,mb);
JMenu helpMenu=createMenu(helpText,KeyEvent.VK_H,mb);
createMenuItem(fileNew,KeyEvent.VK_N,fileMenu,KeyEvent.VK_N,this);
createMenuItem(fileOpen,KeyEvent.VK_O,fileMenu,KeyEvent.VK_O,this);
createMenuItem(fileSave,KeyEvent.VK_S,fileMenu,KeyEvent.VK_S,this);
createMenuItem(fileSaveAs,KeyEvent.VK_A,fileMenu,this);
fileMenu.addSeparator();
temp=createMenuItem(filePageSetup,KeyEvent.VK_U,fileMenu,this);
temp.setEnabled(false);
createMenuItem(filePrint,KeyEvent.VK_P,fileMenu,KeyEvent.VK_P,this);
fileMenu.addSeparator();
createMenuItem(fileExit,KeyEvent.VK_X,fileMenu,this);
temp=createMenuItem(editUndo,KeyEvent.VK_U,editMenu,KeyEvent.VK_Z,this);
temp.setEnabled(false);
editMenu.addSeparator();
cutItem=createMenuItem(editCut,KeyEvent.VK_T,editMenu,KeyEvent.VK_X,this);
copyItem=createMenuItem(editCopy,KeyEvent.VK_C,editMenu,KeyEvent.VK_C,this);
createMenuItem(editPaste,KeyEvent.VK_P,editMenu,KeyEvent.VK_V,this);
deleteItem=createMenuItem(editDelete,KeyEvent.VK_L,editMenu,this);
deleteItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0));
editMenu.addSeparator();
findItem=createMenuItem(editFind,KeyEvent.VK_F,editMenu,KeyEvent.VK_F,this);
findNextItem=createMenuItem(editFindNext,KeyEvent.VK_N,editMenu,this);
findNextItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3,0));
replaceItem=createMenuItem(editReplace,KeyEvent.VK_R,editMenu,KeyEvent.VK_H,this);
gotoItem=createMenuItem(editGoTo,KeyEvent.VK_G,editMenu,KeyEvent.VK_G,this);
editMenu.addSeparator();
selectAllItem=createMenuItem(editSelectAll,KeyEvent.VK_A,editMenu,KeyEvent.VK_A,this);
createMenuItem(editTimeDate,KeyEvent.VK_D,editMenu,this).setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5,0));
createCheckBoxMenuItem(formatWordWrap,KeyEvent.VK_W,formatMenu,this);
createMenuItem(formatFont,KeyEvent.VK_F,formatMenu,this);
formatMenu.addSeparator();
createMenuItem(formatForeground,KeyEvent.VK_T,formatMenu,this);
createMenuItem(formatBackground,KeyEvent.VK_P,formatMenu,this);
createMenuItem("Suggestion",KeyEvent.VK_P,formatMenu,this);
createMenuItem(java,KeyEvent.VK_F3,langMenu,this).setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3,0));;
createMenuItem(XML,KeyEvent.VK_F4,langMenu,this);
createMenuItem(HTML,KeyEvent.VK_F5,langMenu,this);
createMenuItem(JSON,KeyEvent.VK_F6,langMenu,this);
createMenuItem(others,KeyEvent.VK_F7,langMenu,this);
langMenu.addSeparator();
createMenuItem("Sea",KeyEvent.VK_SPACE,theme,this);
createMenuItem("Metal",KeyEvent.VK_SPACE,theme,this);
createMenuItem("Windows",KeyEvent.VK_SPACE,theme,this);
createMenuItem("WindowsClassic",KeyEvent.VK_SPACE,theme,this);
createMenuItem("Nimbus",KeyEvent.VK_SPACE,theme,this);
createMenuItem("Motif",KeyEvent.VK_SPACE,theme,this);
createMenuItem("Dark",KeyEvent.VK_SPACE,theme,this);
createMenuItem("SendMail",KeyEvent.VK_SPACE,shareView,this);
createMenuItem("Whatsapp",KeyEvent.VK_SPACE,shareView,this);
createMenuItem("etc",KeyEvent.VK_Q,shareView,this);
createMenuItem("XML Editor",KeyEvent.VK_SPACE,XMLView,this);
createMenuItem("Align",KeyEvent.VK_SPACE,XMLView,this);
createMenuItem("XML Tree",KeyEvent.VK_Q,XMLView,this);
createMenuItem("XML Structure",KeyEvent.VK_Q,XMLView,this);
createMenuItem("Remove Node",KeyEvent.VK_Q,XMLView,this);
/************CMD***/
createMenuItem("Custom CMD",KeyEvent.VK_SPACE,cmdView,this);
createMenuItem("IP Address(Full)",KeyEvent.VK_SPACE,cmdView,this);
createMenuItem("IP Address(IP only)",KeyEvent.VK_SPACE,cmdView,this);
createMenuItem("SystemInfo",KeyEvent.VK_0,cmdView,this);
createMenuItem("EnviromentInfo",KeyEvent.VK_0,cmdView,this);
createMenuItem("Notepad",KeyEvent.VK_SPACE,cmdView,this);
createMenuItem("Calculator",KeyEvent.VK_SPACE,cmdView,this);
createMenuItem("Ping",KeyEvent.VK_SPACE,cmdView,this);
createMenuItem("Remote Desktop",KeyEvent.VK_SPACE,cmdView,this);
createCheckBoxMenuItem(viewStatusBar,KeyEvent.VK_S,viewMenu,this).setSelected(true);
/************For Look and Feel, May not work properly on different operating environment***/
//LookAndFeelMenu.createLookAndFeelMenuItem(viewMenu,this.f);
temp=createMenuItem(helpHelpTopic,KeyEvent.VK_H,helpMenu,this);
//temp.setEnabled(false);
helpMenu.addSeparator();
createMenuItem(helpAboutNotepad,KeyEvent.VK_A,helpMenu,this);
MenuListener editMenuListener=new MenuListener()
{
public void menuSelected(MenuEvent evvvv)
{
if(Notepad.this.ta.getText().length()==0)
{
findItem.setEnabled(false);
findNextItem.setEnabled(false);
replaceItem.setEnabled(false);
selectAllItem.setEnabled(false);
gotoItem.setEnabled(false);
}
else
{
findItem.setEnabled(true);
findNextItem.setEnabled(true);
replaceItem.setEnabled(true);
selectAllItem.setEnabled(true);
gotoItem.setEnabled(true);
}
if(Notepad.this.ta.getSelectionStart()==ta.getSelectionEnd())
{
cutItem.setEnabled(false);
copyItem.setEnabled(false);
deleteItem.setEnabled(false);
}
else
{
cutItem.setEnabled(true);
copyItem.setEnabled(true);
deleteItem.setEnabled(true);
}
}
public void menuDeselected(MenuEvent evvvv){}
public void menuCanceled(MenuEvent evvvv){}
};
editMenu.addMenuListener(editMenuListener);
f.setJMenuBar(mb);
}
public void actionPerformed(ActionEvent ev)
{
String cmdText=ev.getActionCommand();
////////////////////////////////////
if(cmdText.equals(fileNew))
fileHandler.newFile();
else if(cmdText.equals(fileOpen))
fileHandler.openFile();
////////////////////////////////////
else if(cmdText.equals(fileSave))
fileHandler.saveThisFile();
////////////////////////////////////
else if(cmdText.equals(fileSaveAs))
fileHandler.saveAsFile();
////////////////////////////////////
else if(cmdText.equals(fileExit))
{if(fileHandler.confirmSave())System.exit(0);}
////////////////////////////////////
else if(cmdText.equals(filePrint))
JOptionPane.showMessageDialog(
Notepad.this.f,
"Get ur printer repaired first! It seems u dont have one!",
"Bad Printer",
JOptionPane.INFORMATION_MESSAGE
);
////////////////////////////////////
else if(cmdText.equals(editCut))
ta.cut();
////////////////////////////////////
else if(cmdText.equals(editCopy))
ta.copy();
////////////////////////////////////
else if(cmdText.equals(editPaste))
ta.paste();
////////////////////////////////////
else if(cmdText.equals(editDelete))
ta.replaceSelection("");
////////////////////////////////////
else if(cmdText.equals(editFind))
{
if(Notepad.this.ta.getText().length()==0)
return; // text box have no text
if(findReplaceDialog==null)
findReplaceDialog=new FindDialog(Notepad.this.ta);
findReplaceDialog.showDialog(Notepad.this.f,true);//find
}
////////////////////////////////////
else if(cmdText.equals(editFindNext))
{
if(Notepad.this.ta.getText().length()==0)
return; // text box have no text
if(findReplaceDialog==null)
statusBar.setText("Nothing to search for, use Find option of Edit Menu first !!!!");
else
findReplaceDialog.findNextWithSelection();
}
////////////////////////////////////
else if(cmdText.equals(editReplace))
{
if(Notepad.this.ta.getText().length()==0)
return; // text box have no text
if(findReplaceDialog==null)
findReplaceDialog=new FindDialog(Notepad.this.ta);
findReplaceDialog.showDialog(Notepad.this.f,false);//replace
}
////////////////////////////////////
else if(cmdText.equals(editGoTo))
{
if(Notepad.this.ta.getText().length()==0)
return; // text box have no text
goTo();
}
////////////////////////////////////
else if(cmdText.equals(editSelectAll))
ta.selectAll();
////////////////////////////////////
else if(cmdText.equals(editTimeDate))
ta.insert(new Date().toString(),ta.getSelectionStart());
////////////////////////////////////
else if(cmdText.equals(formatWordWrap))
{
JCheckBoxMenuItem temp=(JCheckBoxMenuItem)ev.getSource();
ta.setLineWrap(temp.isSelected());
}
////////////////////////////////////
else if(cmdText.equals(formatFont))
{
if(fontDialog==null)
fontDialog=new FontChooser(ta.getFont());
if(fontDialog.showDialog(Notepad.this.f,"Choose a font"))
Notepad.this.ta.setFont(fontDialog.createFont());
}
////////////////////////////////////
else if(cmdText.equals(formatForeground))
showForegroundColorDialog();
////////////////////////////////////
else if(cmdText.equals(formatBackground))
showBackgroundColorDialog();
////////////////////////////////////
else if(cmdText.equals(viewStatusBar))
{
JCheckBoxMenuItem temp=(JCheckBoxMenuItem)ev.getSource();
statusBar.setVisible(temp.isSelected());
}
////////////////////////////////////
else if(cmdText.equals(helpAboutNotepad))
{
//InputStream in = getClass().getResourceAsStream("/index.html");
//StringBuilder XMLGenerationString = new StringBuilder(
//new Scanner(in).useDelimiter("\\Z").next());
JOptionPane.showMessageDialog(Notepad.this.f,aboutText,"Dedicated 2 u!",JOptionPane.INFORMATION_MESSAGE);
}
else if(cmdText.equals("IP Address(Full)"))
{
try {
StringBuilder sb=JavaCompile.runProcess("ipconfig /all");
JOptionPane.showMessageDialog(Notepad.this.f,sb,"result :",
JOptionPane.INFORMATION_MESSAGE);
if(sb.length()>0)
{
Notepad.this.ta.setText(Notepad.this.ta.getText()+"\n******************************************************************\n"+sb);
}
}
catch(Exception e){}
}
else if(cmdText.equals("IP Address(IP only)"))
{
try {
StringBuilder sb=JavaCompile.runProcess("ipconfig /all");
String temp[]=sb.toString().split(" IPv4 Address. . . . . . . . . . . :");
JOptionPane.showMessageDialog(Notepad.this.f,temp[1].substring(0, 15),"result :",
JOptionPane.INFORMATION_MESSAGE);
if(sb.length()>0)
{
Notepad.this.ta.setText(Notepad.this.ta.getText()+"\n******************************************************************\nIPV4 :"+temp[1].substring(0, 15));
}
}
catch(Exception e){JOptionPane.showMessageDialog(Notepad.this.f,"Network not connected !!\nPlease try again aftersome times","result :",
JOptionPane.INFORMATION_MESSAGE); }
}
else if(cmdText.equals("Remote Desktop"))
{
try {
JavaCompile.runProcess("mstsc");
}
catch(Exception e){}
}
else if(cmdText.equals("SystemInfo"))
{
try {
JavaCompile.runProcess("systeminfo");
}
catch(Exception e){
System.out.println(e);
}
}
else if(cmdText.equals("EnviromentInfo"))
{
Map<String, String> map=System.getenv();
StringBuilder sb=new StringBuilder();
for (Map.Entry<String, String> entry : map.entrySet())
{
if(entry.getKey().equals("Path"))
{
sb.append(" "+entry.getKey() + "\t\t ==>\n");
String[] paths=(entry.getValue()).split(";");
for (String s: paths) {
sb.append(" \t\t\t ==> " + s+"\n");
}
}
else
{
sb.append(" "+entry.getKey() + " ==> " + entry.getValue()+"\n");
}
}
JOptionPane.showMessageDialog(Notepad.this.f,sb,"System Info :",
JOptionPane.INFORMATION_MESSAGE);
if(sb.length()>0)
{
Notepad.this.ta.setText(Notepad.this.ta.getText()+"\n******************************************************************\n"+sb);
}
}
else if(cmdText.equals("Notepad"))
{
try {
JavaCompile.runProcess("notepad");
}
catch(Exception e){}
}
else if(cmdText.equals("Sea"))
{
try {
UIManager.setLookAndFeel("com.seaglasslookandfeel.SeaGlassLookAndFeel");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SwingUtilities.updateComponentTreeUI(f);
}
else if(cmdText.equals("Metal"))
{
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SwingUtilities.updateComponentTreeUI(f);
}
else if(cmdText.equals("Motif"))
{
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SwingUtilities.updateComponentTreeUI(f);
}
else if(cmdText.equals("Nimbus"))
{
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SwingUtilities.updateComponentTreeUI(f);
}
else if(cmdText.equals("Windows"))
{
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SwingUtilities.updateComponentTreeUI(f);
}
else if(cmdText.equals("WindowsClassic"))
{
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SwingUtilities.updateComponentTreeUI(f);
}
else if(cmdText.equals("Dark"))
{
try {
DefaultMetalTheme darkTheme = new DefaultMetalTheme() {
@Override
public ColorUIResource getPrimary1() {
return new ColorUIResource(new Color(30, 30, 30));
}
@Override
public ColorUIResource getPrimary2() {
return new ColorUIResource(new Color(20, 20, 20));
}
@Override
public ColorUIResource getPrimary3() {
return new ColorUIResource(new Color(30, 30, 30));
}
@Override
public ColorUIResource getBlack(){
return new ColorUIResource(new Color(30, 30, 30));
}
@Override
public ColorUIResource getWhite() {
return new ColorUIResource(new Color(240, 240, 240));
}
@Override
public ColorUIResource getMenuForeground() {
return new ColorUIResource(new Color(200, 200, 200));
}
@Override
public ColorUIResource getMenuBackground() {
return new ColorUIResource(new Color(25, 25, 25));
}
@Override
public ColorUIResource getMenuSelectedBackground(){
return new ColorUIResource(new Color(50, 50, 50));
}
@Override
public ColorUIResource getMenuSelectedForeground() {
return new ColorUIResource(new Color(255, 255, 255));
}
@Override
public ColorUIResource getSeparatorBackground() {
return new ColorUIResource(new Color(15, 15, 15));
}
@Override
public ColorUIResource getUserTextColor() {
return new ColorUIResource(new Color(240, 240, 240));
}
@Override
public ColorUIResource getTextHighlightColor() {
return new ColorUIResource(new Color(80, 40, 80));
}
@Override
public ColorUIResource getAcceleratorForeground(){
return new ColorUIResource(new Color(30, 30,30));
}
@Override
public ColorUIResource getWindowTitleInactiveBackground() {
return new ColorUIResource(new Color(30, 30, 30));
}
@Override
public ColorUIResource getWindowTitleBackground() {
return new ColorUIResource(new Color(30, 30, 30));
}
@Override
public ColorUIResource getWindowTitleForeground() {
return new ColorUIResource(new Color(230, 230, 230));
}
@Override
public ColorUIResource getPrimaryControlHighlight() {
return new ColorUIResource(new Color(40, 40, 40));
}
@Override
public ColorUIResource getPrimaryControlDarkShadow() {
return new ColorUIResource(new Color(40, 40, 40));
}
@Override
public ColorUIResource getPrimaryControl() {
//color for minimize,maxi,and close
return new ColorUIResource(new Color(60, 60, 60));
}
@Override
public ColorUIResource getControlHighlight() {
return new ColorUIResource(new Color(20, 20, 20));
}
@Override
public ColorUIResource getControlDarkShadow() {
return new ColorUIResource(new Color(50, 50, 50));
}
@Override
public ColorUIResource getControl() {
return new ColorUIResource(new Color(25, 25, 25));
}
@Override
public ColorUIResource getControlTextColor() {
return new ColorUIResource(new Color(230, 230, 230));
}
@Override
public ColorUIResource getFocusColor() {
return new ColorUIResource(new Color(0, 100, 0));
}
@Override
public ColorUIResource getHighlightedTextColor() {
return new ColorUIResource(new Color(250, 250, 250));
}
};
MetalLookAndFeel.setCurrentTheme(darkTheme);
try {
UIManager.setLookAndFeel(new MetalLookAndFeel());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SwingUtilities.updateComponentTreeUI(f);
}
catch(Exception e) {
}
}
else if(cmdText.equals("Calculator"))
{
try {
JavaCompile.runProcess("calc");
}
catch(Exception e){}
}
else if(cmdText.equals("SendMail"))
{
try {
String subject="CodePad%20Content";
String body="sent%20from%20CodePad";
Desktop.getDesktop().mail( new URI( "mailto:<EMAIL>?subject="+subject+"&body="+body) );
}
catch ( Exception ex )
{
System.out.println(ex);
}
}
else if(cmdText.equals("Ping"))
{
try {
String message = JOptionPane.showInputDialog(null, "Enter Address :");
StringBuilder sb=JavaCompile.runProcess("ping "+message);
JOptionPane.showMessageDialog(Notepad.this.f,sb,"CompileTime result :",
JOptionPane.INFORMATION_MESSAGE);
if(sb.length()>0)
{
Notepad.this.ta.setText(Notepad.this.ta.getText()+"\n******************************************************************\n"+sb);
}
//System.out.println();
} catch (Exception e) {
Notepad.this.ta.setText(Notepad.this.ta.getText()+"\n******************************************************************\n"
+e.toString().substring(e.toString().indexOf(':')+1));
System.out.println(e.toString());
}
}
else if(cmdText.equals("Custom CMD"))
{
try {
String message = JOptionPane.showInputDialog(null, "Enter command :");
StringBuilder sb=JavaCompile.runProcess(message);
JOptionPane.showMessageDialog(Notepad.this.f,sb,"result :",
JOptionPane.INFORMATION_MESSAGE);
if(sb.length()>0)
{
Notepad.this.ta.setText(Notepad.this.ta.getText()+"\n******************************************************************\n"+sb);
}
//System.out.println();
} catch (Exception e) {
Notepad.this.ta.setText(Notepad.this.ta.getText()+"\n******************************************************************\n"
+e.toString().substring(e.toString().indexOf(':')+1));
System.out.println(e.toString());
}
}
else if(cmdText.equals("Suggestion"))
{
JTextField field1 = new JTextField();
JTextField field2 = new JTextField();
JTextField field3 = new JTextField();
Object[] message = {
"Key : ", field1,
"Value : ", field2,
"Discription:", field3,
};
int option = JOptionPane.showConfirmDialog(this, message, "Enter all your values", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION)
{
String key = field1.getText();
String value = field2.getText();
String description = field3.getText();
provider.addCompletion(new ShorthandCompletion(provider, key,
value, description));
AutoCompletion ac = new AutoCompletion(provider);
ac.install(ta);
}
}
else if(cmdText.equals("Remove Node"))
{
String payload=Notepad.this.ta.getText();
try
{
String message = JOptionPane.showInputDialog(null, "Enter tag name (Case sencitive) :");
File file=File.createTempFile("temp", ".xml");
OutputStream out=new FileOutputStream(file);
out.write(payload.getBytes());
out.close();
ArrayList<Node> policylist=new ArrayList<Node>();
ArrayList<Node> parentlist=new ArrayList<Node>();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new FileInputStream(file));
NodeList entries = doc.getElementsByTagName("*");
int count=0;
for (int i=0; i<entries.getLength(); i++) {
Node node = (Element) entries.item(i);
if (message.equals(node.getNodeName()))
{
parentlist.add(node.getParentNode());
policylist.add(node);
System.out.println("Removed element " + node.getNodeName());
statusBar.setText("Removing Node :"+count);
count++;
}
}
for(int i=0;i<policylist.size();i++)
{
parentlist.get(i).removeChild(policylist.get(i));
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(file);
transformer.transform(source, result);
byte[] data = Files.readAllBytes(file.toPath());
Notepad.this.ta.setText(new String(data));
statusBar.setText(" Node "+message+" "+count+" found and successfully removed");
file.deleteOnExit();
}
catch(Exception e){System.out.println(e);}
}
else if(cmdText.equals("XML Structure"))
{
System.out.println("hdchk");
try {
File file = File.createTempFile("temp", ".xml");
String payload=Notepad.this.ta.getText();
OutputStream out=new FileOutputStream(file);
out.write(payload.getBytes());
out.close();
App.setFile(file.getAbsolutePath());
new App();
file.deleteOnExit();
} catch (IOException e) {
statusBar.setText("Wrong XML DATA");
e.printStackTrace();
}
}
else if(cmdText.equals("Help Topic"))
{
try {
Desktop.getDesktop().browse( new URI( "https://appinous.blogspot.in/2018/02/codepad.html") );
}
catch ( Exception ex )
{
System.out.println(ex);
}
}
else if(cmdText.equals("XML Editor"))
{
try {
File file=File.createTempFile("temp", ".xml");
String payload=Notepad.this.ta.getText();
OutputStream out=new FileOutputStream(file);
out.write(payload.getBytes());
out.close();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new FileInputStream(file));
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
tf.setOutputProperty(OutputKeys.INDENT, "yes");
Writer out1 = new StringWriter();
tf.transform(new DOMSource(doc), new StreamResult(out1));
Notepad.this.ta.setText(out1.toString());
Test t=new Test();
t.textArea.setText(Notepad.this.ta.getText());
file.deleteOnExit();
} catch (Exception e) {
statusBar.setText("Wrong XML DATA");
int reply= JOptionPane.showConfirmDialog(f,"XML not in well form or untitled file ?\nDo you want to continue ?","Error",JOptionPane.YES_NO_OPTION,0);
if(reply==JOptionPane.YES_OPTION)
{
Test t=new Test();
}
}
}
else if(cmdText.equals("XML Tree"))
{
try {
File file=File.createTempFile("temp", ".xml");
String payload=Notepad.this.ta.getText();
OutputStream out=new FileOutputStream(file);
out.write(payload.getBytes());
out.close();
DemoMain.setFileLocation(file.getAbsolutePath());
DemoMain d=new DemoMain();
d.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
file.deleteOnExit();
} catch (IOException e) {
statusBar.setText("Wrong XML DATA");
e.printStackTrace();
}
}
else if(cmdText.equals(java))
{
ta.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
ta.setCodeFoldingEnabled(true);
JOptionPane messagePane = new JOptionPane(
"Loading suggestion list...\nDon't close this window... Please wait...",
JOptionPane.DEFAULT_OPTION);
final JDialog dialog = messagePane.createDialog(this, "Loading");
new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
CompletionProvider provider = createCompletionProvider("java");
AutoCompletion ac = new AutoCompletion(provider);
ac.install(ta);
Thread.sleep(3000);
return null;
}
protected void done() {
dialog.dispose();
};
}.execute();
dialog.setVisible(true);
JOptionPane.showMessageDialog(this, "All done..",
"Done", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.getRootFrame().dispose();
}
else if(cmdText.equals(HTML))
{
ta.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_XML);
ta.setCodeFoldingEnabled(true);
ta.setAutoIndentEnabled(true);
JOptionPane messagePane = new JOptionPane(
"Loading suggestion list...\nDon't press close or OK button...\nPlease wait...",
JOptionPane.PLAIN_MESSAGE);
final JDialog dialog = messagePane.createDialog(this, "Loading");
dialog.setVisible(false);
new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
CompletionProvider provider = createCompletionProvider("html");
AutoCompletion ac = new AutoCompletion(provider);
ac.install(ta);
//Thread.sleep(3000);
return null;
}
protected void done() {
dialog.dispose();
};
}.execute();
dialog.setVisible(true);
JOptionPane.showMessageDialog(this, "All done..",
"Done", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.getRootFrame().dispose();
}
else if(cmdText.equals(JSON))
{
ta.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JSON);
ta.setCodeFoldingEnabled(true);
}
else if(cmdText.equals(XML))
{
try {
/*File file=File.createTempFile("temp", ".xml");
String payload=Notepad.this.ta.getText();
OutputStream out=new FileOutputStream(file);
out.write(payload.getBytes());
out.close();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new FileInputStream(file));
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
tf.setOutputProperty(OutputKeys.INDENT, "yes");
Writer out1 = new StringWriter();
tf.transform(new DOMSource(doc), new StreamResult(out1));
Notepad.this.ta.setText(out1.toString());
file.deleteOnExit();*/
ta.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_XML);
ta.setCodeFoldingEnabled(true);
} catch (Exception e) {
JOptionPane.showMessageDialog(Notepad.this.f,"Not a Proper XML","Java",JOptionPane.ERROR_MESSAGE);
}
}
else if(cmdText.equals(others))
{
String input = (String) JOptionPane.showInputDialog(null, "Select Language...",
"The Choice of Languages", JOptionPane.QUESTION_MESSAGE, null, // Use
// default
// icon
langList, // Array of choices
langList[0]); // Initial choice
System.out.println(input.split("/")[1]);
ta.setSyntaxEditingStyle(input);
ta.setCodeFoldingEnabled(true);
//JOptionPane.showOptionDialog(null, "Hello","Empty?", JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE, null, new Object[]{}, null);
//JOptionPane.showMessageDialog(f, "Loading......");
JOptionPane messagePane = new JOptionPane(
"Loading suggestion list...\nDon't press close or OK button...\nPlease wait...",
JOptionPane.PLAIN_MESSAGE);
final JDialog dialog = messagePane.createDialog(this, "Loading");
dialog.setVisible(false);
new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
System.out.println(input.split("/")[1]);
CompletionProvider provider = createCompletionProvider(input.split("/")[1]);
AutoCompletion ac = new AutoCompletion(provider);
ac.install(ta);
//Thread.sleep(3000);
return null;
}
protected void done() {
dialog.dispose();
};
}.execute();
dialog.setVisible(true);
JOptionPane.showMessageDialog(this, "All done..",
"Done", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.getRootFrame().dispose();
}
else
statusBar.setText("This "+cmdText+" command is yet to be implemented");
}
/*************Constructor
* @throws UnsupportedLookAndFeelException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws ClassNotFoundException **************/
////////////////////////////////////
@SuppressWarnings("static-access")
public static void main(String[] s) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException
{
//UIManager.setLookAndFeel("com.seaglasslookandfeel.SeaGlassLookAndFeel");
try
{
Splash s1=new Splash();
s1.setVisible(true);
Thread t=Thread.currentThread();
t.sleep(10000);
SwingUtilities.invokeLater(new Runnable(){
public void run()
{
//opening the main application
// new Splash().setVisible(true);
}
});
s1.dispose();
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
Notepad tb = new Notepad();
//LookAndFeelAction.setWindowsLookAndFeel();
}
catch(Exception e)
{
System.out.println(e);
}
}
private CompletionProvider createCompletionProvider(String language) {
// A DefaultCompletionProvider is the simplest concrete implementation
// of CompletionProvider. This provider has no understanding of
// language semantics. It simply checks the text entered up to the
// caret position for a match against known completions. This is all
// that is needed in the majority of cases.
// Add completions for all Java keywords. A BasicCompletion is just
// a straightforward word completion.
if(language.equals("java"))
{
provider.clear();
for(int i=0;i<keyWord.length;i++)
{
provider.addCompletion(new BasicCompletion(provider, keyWord[i]));
}
// Add a couple of "shorthand" completions. These completions don't
// require the input text to be the same thing as the replacement text.
provider.addCompletion(new ShorthandCompletion(provider, "sysout",
"System.out.println(", "System.out.println("));
provider.addCompletion(new ShorthandCompletion(provider, "syserr",
"System.err.println(", "System.err.println("));
long startTime = System.nanoTime();
try {
/*public static void main(String[] args) {
long startTime = System.nanoTime();
try (Scanner sc = new Scanner(new FileInputStream(getClass().getResource("/java.txt").getFile()), "UTF-8")) {
long freeMemoryBefore = Runtime.getRuntime().freeMemory();
while (sc.hasNextLine()) {
String line = sc.nextLine();
provider.addCompletion(new ShorthandCompletion(provider, line.split("-")[0],
line.split("-")[0], line.split("-")[1]));
// parse line
//System.out.println(line);
}
// note that Scanner suppresses exceptions
if (sc.ioException() != null) {
sc.ioException().printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
long endTime = System.nanoTime();
long elapsedTimeInMillis = TimeUnit.MILLISECONDS.convert((endTime - startTime), TimeUnit.NANOSECONDS);
System.out.println("Total elapsed time: " + elapsedTimeInMillis + " ms" );
}*/
InputStream in = getClass().getResourceAsStream("/java.txt");
//Reader rdr = Channels.newReader(fis.getChannel(), "UTF-8");
BufferedReader bufferReaderInputPayload = null;
String line = null;
bufferReaderInputPayload = new BufferedReader(new InputStreamReader(in));
while ((line = bufferReaderInputPayload.readLine()) != null) {
provider.addCompletion(new ShorthandCompletion(provider, line.split("-")[0],
line.split("-")[0], line.split("-")[1]));
}
JOptionPane.getRootFrame().dispose();
} catch (Exception e) {
// TODO Auto-generated catch block
statusBar.setText(e.toString());
}
finally {
long endTime = System.nanoTime();
long elapsedTimeInMillis = TimeUnit.MILLISECONDS.convert((endTime - startTime), TimeUnit.NANOSECONDS);
statusBar.setText("Total elapsed time: " + elapsedTimeInMillis + " ms to import suggestion" );
System.out.println("Total elapsed time: " + elapsedTimeInMillis + " ms" );
//input.close();
}
/*ZipInputStream zip;
try {
String binPath=System.getenv("Path");
String path[]=binPath.split(";");
for(String a:path)
{
if(a.endsWith("/bin") &&a.contains("Java"))
{
binPath=a;
}
}
File zipFile=new File("C:\\Program Files\\Java\\jdk-9.0.1\\lib\\src.zip");
zip = new ZipInputStream(new FileInputStream(zipFile));
FileOutputStream fos=new FileOutputStream(new File("D:\\javaClassNameList.txt"));
StringBuilder sb=new StringBuilder();
for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
if (!entry.isDirectory() && entry.getName().endsWith(".java")) {
// This ZipEntry represents a class. Now, what class does it represent?
String className = entry.getName().replace('/', '.').replace(".java", ""); // including ".class"
String name=className;
name=name.substring(name.lastIndexOf('.')+1);
sb.append("\n"+name+" - "+className);
provider.addCompletion(new ShorthandCompletion(provider, name,
name, className));
}
}
fos.write(sb.toString().getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
else if(language.equals("html"))
{
provider.clear();
try {
InputStream in = getClass().getResourceAsStream("/html.txt");
BufferedReader bufferReaderInputPayload = null;
String line = null;
bufferReaderInputPayload = new BufferedReader(new InputStreamReader(in));
while ((line = bufferReaderInputPayload.readLine()) != null) {
provider.addCompletion(new ShorthandCompletion(provider, line.substring(0, line.indexOf(',')),
line.substring(0, line.indexOf(',')), line.substring( line.indexOf(','))));
}
JOptionPane.getRootFrame().dispose();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*provider.addCompletion(new ShorthandCompletion(provider, "siva",
"sivabharathi", "sivabharathi"));*/
}
else if(language.equals("plain"))
{
provider.clear();
try {
InputStream in = getClass().getResourceAsStream("/english.txt");
BufferedReader bufferReaderInputPayload = null;
String line = null;
bufferReaderInputPayload = new BufferedReader(new InputStreamReader(in));
while ((line = bufferReaderInputPayload.readLine()) != null) {
provider.addCompletion(new ShorthandCompletion(provider, line,
line, line));
}
JOptionPane.getRootFrame().dispose();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*provider.addCompletion(new ShorthandCompletion(provider, "siva",
"sivabharathi", "sivabharathi"));*/
}
else
{
//provider.clear();
}
return provider;
}
}
/**************************************/
//public
interface MenuConstants
{
final String fileText="File";
final String editText="Edit";
final String formatText="Format";
final String viewText="View";
final String langText="Language";
final String xmlText="XML";
final String cmdText="Command";
final String shareText="Share";
final String helpText="Help";
final String fileNew="New";
final String fileOpen="Open...";
final String fileSave="Save";
final String fileSaveAs="Save As...";
final String filePageSetup="Page Setup...";
final String filePrint="Print";
final String fileExit="Exit";
final String editUndo="Undo";
final String editCut="Cut";
final String editCopy="Copy";
final String editPaste="Paste";
final String editDelete="Delete";
final String editFind="Find...";
final String editFindNext="Find Next";
final String editReplace="Replace";
final String editGoTo="Go To...";
final String editSelectAll="Select All";
final String editTimeDate="Time/Date";
final String formatWordWrap="Word Wrap";
final String formatFont="Font...";
final String formatForeground="Set Text color...";
final String formatBackground="Set Pad color...";
final String viewStatusBar="Status Bar";
final String helpHelpTopic="Help Topic";
final String helpAboutNotepad="About Javapad";
final String java="Java";
final String XML="XML";
final String HTML="HTML";
final String JSON="JSON";
final String others="Others";
final String[] langList={"text/plain","text/actionscript","text/asm","text/bbcode","text/c","text/clojure","text/cpp","text/cs","text/css","text/d","text/dockerfile","text/dart","text/delphi","text/dtd","text/fortran","text/groovy","text/hosts","text/htaccess","text/html","text/ini","text/java","text/javascript","text/json","text/jshintrc","text/jsp","text/latex","text/less","text/lisp","text/lua","text/makefile","text/mxml","text/nsis","text/perl","text/php","text/properties","text/python","text/ruby","text/sas","text/scala","text/sql","text/tcl","text/typescript","text/unix","text/vb","text/bat","text/xml","text/yaml"};
final String[] keyWord={"abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","double","do","else","enum","extends","false","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","true","try","void","volatile","while"};
final String aboutText=
"<html><big>Your Javapad</big><hr><hr>"
+"<p align=right>Prepared by a Siva!"
+"<hr><p align=left>I Used jdk1.8 to compile the source code.<br><br>"
+"<strong>Thanx 4 using Javapad</strong><br>"
+"Ur Comments as well as bug reports r very welcome at<p align=center>"
+"<hr><em><big><EMAIL></big></em><hr><html>";
}
<file_sep>package dockWindow;
import javax.swing.*;
import java.awt.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
public class SimpleDockablePanel extends JPanel implements MouseListener, MouseMotionListener {
protected int moveDirection=-1;
protected JWindow dragWindow=null;
protected Desktop ownerDesktop;
protected Point desktopWindowLocation=new Point(0,0);
protected static final int DIRECTION_NONE=-1;
protected static final int DIRECTION_TOP=0;
protected static final int DIRECTION_LEFT=1;
protected static final int DIRECTION_RIGHT=2;
protected static final int DIRECTION_BOTTOM=3;
protected int startDragX=0;
protected int startDragY=0;
public static int DESKTOP_REGIM=0;
public static int WINDOW_REGIM=1;
protected int regim=DESKTOP_REGIM;
public SimpleDockablePanel() {
super();
// dragWindow.getContentPane().setLayout(new BorderLayout());
setPreferredSize(null);
addMouseListener(this);
addMouseMotionListener(this);
}
/**
* Invoked when the mouse button has been clicked (pressed
* and released) on a component.
*/
public void mouseClicked(MouseEvent e) {
}
/**
* Invoked when a mouse button has been pressed on a component.
*/
public void mousePressed(MouseEvent e) {
Container c=this.getParent();
if (c==null) return;
this.startDragX=e.getX();
this.startDragY=e.getY();
if (regim==DESKTOP_REGIM) {
BufferedImage img=new BufferedImage(this.getWidth(),this.getHeight(),BufferedImage.TYPE_INT_RGB);
this.paint(img.getGraphics());
if (dragWindow==null) {
Container parent=c;
Window owner=null;
while (parent!=null) {
if (parent instanceof Window) {
owner=(Window)parent;
}
parent=parent.getParent();
}
dragWindow=new JWindow(owner);
dragWindow.getContentPane().setLayout(new BorderLayout());
}
dragWindow.getContentPane().removeAll();
dragWindow.getContentPane().add(new JLabel(new ImageIcon(img)));
dragWindow.setSize(this.getWidth(),this.getHeight());
}
else {
}
if (!(c instanceof Desktop)) return;
Desktop parentDesktop=(Desktop)c;
this.ownerDesktop=parentDesktop;
parentDesktop.startDragX=startDragX+this.getX();
parentDesktop.startDragY=startDragY+this.getY();
if (startDragY<2) {
parentDesktop.splitDragY=startDragY+this.getY();
parentDesktop.repaint(0,parentDesktop.splitDragY,parentDesktop.getWidth(),1);
moveDirection=DIRECTION_TOP;
}
else if (startDragY>getHeight()-2) {
parentDesktop.splitDragY=startDragY+this.getY();
parentDesktop.repaint(0,parentDesktop.splitDragY,parentDesktop.getWidth(),1);
moveDirection=DIRECTION_BOTTOM;
}
else if (startDragX<2) {
parentDesktop.splitDragX=startDragX+this.getX();
parentDesktop.repaint(parentDesktop.splitDragX,0,1,parentDesktop.getHeight());
moveDirection=DIRECTION_LEFT;
}
else if (startDragX>getWidth()-2) {
parentDesktop.splitDragX=startDragX+this.getX();
parentDesktop.repaint(parentDesktop.splitDragX,0,1,parentDesktop.getHeight());
moveDirection=DIRECTION_RIGHT;
}
else {
parentDesktop.drag=true;
parentDesktop.dragSourceComponent=this;
}
}
/**
* Invoked when a mouse button has been released on a component.
*/
public void mouseReleased(MouseEvent e) {
Container c=this.getParent();
if (c==null) return;
if (c instanceof Desktop) {
Desktop parentDesktop=(Desktop)c;
parentDesktop.endDragX=e.getX()+this.getX();
parentDesktop.endDragY=e.getY()+this.getY();
if (parentDesktop.drag) {
if ((parentDesktop.endDragX<0) ||
(parentDesktop.endDragX>parentDesktop.getWidth()) ||
(parentDesktop.endDragY<0) ||
(parentDesktop.endDragY>parentDesktop.getHeight()) ) {
//drop outside the desktop
parentDesktop.removeComponent(this);
parentDesktop.refresh();
dragWindow.getContentPane().removeAll();
dragWindow.getContentPane().add(this);
dragWindow.setVisible(true);
desktopWindowLocation=dragWindow.getOwner().getLocation();
dragWindow.getOwner().addComponentListener(new ComponentAdapter() {
public void componentHidden(ComponentEvent e) {
}
public void componentMoved(ComponentEvent e) {
Point oldLocation=dragWindow.getLocation();
oldLocation.x+=dragWindow.getOwner().getX()-desktopWindowLocation.x;
oldLocation.y+=dragWindow.getOwner().getY()-desktopWindowLocation.y;
dragWindow.setLocation(oldLocation);
desktopWindowLocation=dragWindow.getOwner().getLocation();
}
public void componentResized(ComponentEvent e) {
}
public void componentShown(ComponentEvent e) {
}
});
regim=WINDOW_REGIM;
}
else {
parentDesktop.drop();
dragWindow.dispose();
}
}
parentDesktop.drag=false;
int oldDragX=parentDesktop.splitDragX;
parentDesktop.splitDragX=-1;
parentDesktop.repaint(oldDragX,0,1,parentDesktop.getHeight());
if (oldDragX!=-1) {
GridBagConstraints thisGBC=parentDesktop.contaiterLayout.getConstraints(this);
int gridX=0;
int gridY=thisGBC.gridy;
int x=parentDesktop.endDragX-parentDesktop.startDragX;
if (moveDirection==DIRECTION_LEFT) {
gridX=thisGBC.gridx;
} else if (moveDirection==DIRECTION_RIGHT) {
gridX=thisGBC.gridx+thisGBC.gridwidth;
}
parentDesktop.moveSplitterHorizontal(gridX,gridY,x);
}
int oldDragY=parentDesktop.splitDragY;
parentDesktop.splitDragY=-1;
parentDesktop.repaint(0,oldDragY,parentDesktop.getWidth(),1);
if (oldDragY!=-1) {
GridBagConstraints thisGBC=parentDesktop.contaiterLayout.getConstraints(this);
int gridX=thisGBC.gridx;
int gridY=0;
int y=parentDesktop.endDragY-parentDesktop.startDragY;
if (moveDirection==DIRECTION_TOP) {
gridY=thisGBC.gridy;
} else if (moveDirection==DIRECTION_BOTTOM) {
gridY=thisGBC.gridy+thisGBC.gridheight;
}
parentDesktop.moveSplitterVertical(gridX,gridY,y);
}
moveDirection=DIRECTION_NONE;
}
else { //window
Point p=e.getPoint();
SwingUtilities.convertPointToScreen(p,this);
if (ownerDesktop!=null) {
SwingUtilities.convertPointFromScreen(p,ownerDesktop);
ownerDesktop.startDragX=-1;
ownerDesktop.startDragY=-1;
ownerDesktop.dragSourceComponent=this;
ownerDesktop.endDragX=p.x;
ownerDesktop.endDragY=p.y;
if ((ownerDesktop.endDragX>0) &&
(ownerDesktop.endDragX<ownerDesktop.getWidth()) &&
(ownerDesktop.endDragY>0) &&
(ownerDesktop.endDragY<ownerDesktop.getHeight()) ) {
dragWindow.getContentPane().removeAll();
dragWindow.hide();
ownerDesktop.drop();
}
/* if (parentDesktop.drag) {
if ((parentDesktop.endDragX<0) ||
(parentDesktop.endDragX>parentDesktop.getWidth()) ||
(parentDesktop.endDragY<0) ||
(parentDesktop.endDragY>parentDesktop.getHeight()) ) {
//drop outside the desktop
parentDesktop.removeComponent(this);
parentDesktop.refresh();
dragWindow.getContentPane().removeAll();
dragWindow.getContentPane().add(this);
dragWindow.setVisible(true);
regim=WINDOW_REGIM;
}
else {*/
// }
// }
}
}
}
/**
* Invoked when the mouse enters a component.
*/
public void mouseEntered(MouseEvent e) {
}
/**
* Invoked when the mouse exits a component.
*/
public void mouseExited(MouseEvent e) {
}
/**
* Invoked when a mouse button is pressed on a component and then
* dragged. <code>MOUSE_DRAGGED</code> events will continue to be
* delivered to the component where the drag originated until the
* mouse button is released (regardless of whether the mouse position
* is within the bounds of the component).
* <p>
* Due to platform-dependent Drag&Drop implementations,
* <code>MOUSE_DRAGGED</code> events may not be delivered during a native
* Drag&Drop operation.
*/
public void mouseDragged(MouseEvent e) {
Container c=this.getParent();
if (c==null) return;
if (c instanceof Desktop) {
Desktop parentDesktop=(Desktop)c;
if (parentDesktop.splitDragX>0) {
int oldSplitX=parentDesktop.splitDragX;
parentDesktop.splitDragX=-1;
parentDesktop.repaint(oldSplitX,0,1,parentDesktop.getHeight());
parentDesktop.splitDragX=e.getX()+this.getX();
parentDesktop.repaint(parentDesktop.splitDragX,0,1,parentDesktop.getHeight());
}
if (parentDesktop.splitDragY>0) {
int oldSplitY=parentDesktop.splitDragY;
parentDesktop.splitDragY=-1;
parentDesktop.repaint(0,oldSplitY,parentDesktop.getWidth(),1);
parentDesktop.splitDragY=e.getY()+this.getY();
parentDesktop.repaint(0,parentDesktop.splitDragY,parentDesktop.getWidth(),1);
}
if (parentDesktop.drag) {
Point p=e.getPoint();
SwingUtilities.convertPointToScreen(p,this);
p.x-=startDragX;
p.y-=startDragY;
dragWindow.setLocation(p);
dragWindow.setSize(this.getWidth(),getHeight());
dragWindow.show();
}
}
else {
if ((startDragX>-1) && (startDragY>-1)) {
Point p=e.getPoint();
SwingUtilities.convertPointToScreen(p,this);
p.x-=startDragX;
p.y-=startDragY;
dragWindow.setLocation(p);
}
}
}
/**
* Invoked when the mouse cursor has been moved onto a component
* but no buttons have been pushed.
*/
public void mouseMoved(MouseEvent e) {
int x=e.getX();
int y=e.getY();
if (regim!=DESKTOP_REGIM)
return;
if (y<2) {
this.setCursor(new Cursor(Cursor.N_RESIZE_CURSOR));
}
else if (y>getHeight()-2) {
this.setCursor(new Cursor(Cursor.S_RESIZE_CURSOR));
}
else if (x<2) {
this.setCursor(new Cursor(Cursor.W_RESIZE_CURSOR));
}
else if (x>getWidth()-2) {
this.setCursor(new Cursor(Cursor.E_RESIZE_CURSOR));
}
else {
this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
}
}
|
858ae1f0a18caf8a71689d9c78d3da244c608215
|
[
"Markdown",
"Java"
] | 7 |
Java
|
sivabharathik/mycodepad
|
94018e273b9e6d1d9f19c526cb644f07f2eb5585
|
25557de34cf75267bbc0667a21d1f57502e02d67
|
refs/heads/master
|
<file_sep>#include <stdio.h>
void x()
{
x();
}
int main()
{
x();
}
<file_sep>#include "common.h"
int getline2(char *s, int lim, FILE *fp) {
int c, i = -1;
for (i = 0; i < lim-1 && (c=fgetc(fp))!=EOF && c!='\n'; ++i)
s[i] = c;
if (c == '\n')
s[i++] = c;
s[i] = '\0';
return i;
}
int main(int argc, char const *argv[])
{
FILE *in, *out, *tmp;
char line_in[80], line_out[80], line_tmp[80];
size_t len_in = 0, len_out = 0, len_tmp = 0;
in = fopen(argv[1], "r");
out = fopen(argv[2], "r");
tmp = fopen(argv[3], "r");
if (!in || !out || !tmp)
exit(EXIT_FAILURE);
while (-1 != getline2(line_tmp, 80, tmp)
&& -1 != getline2(line_out, 80, out)) {
if (-1 != getline2(line_in, 80, in) && 0 != strcmp(line_out, line_tmp)) {
fprintf(stderr, "Input:%sOutput:%sExpected:%s",
line_in, line_tmp, line_out);
break;
}
}
if (fclose(in) || fclose(out) || fclose(tmp))
EXIT_MSG("fclose() Failed", EXIT_FAILURE);
return 0;
}
<file_sep>#include <stdio.h>
#include <string.h>
int stack[1024*1024*4];
int main() {
memset(stack, 0xf, sizeof stack);
// int stackx[1024*4];
// int *p = malloc(1024*1024*10); memset(p, 0xf, 1000);
int a, b;
while (2 == scanf("%d%d", &a, &b))
printf("%d\n", a+b);
}
<file_sep>#!/bin/bash
code=`ls ../test/*.c`
for c in $code; do
time ./OJ.sh $c ../test/data
done
#time ./OJ.sh ../test/CompileErr.c ../test/data
#time ./OJ.sh ../test/Accept.c ../test/data
#time ./OJ.sh ../test/TimeOut.c ../test/data
#time ./OJ.sh ../test/MemoryOut.c ../test/data
#time ./OJ.sh ../test/RuntimeErr.c ../test/data
#time ./OJ.sh ../test/WrongAnswer.c ../test/data
#time ./OJ.sh ../test/PreErr.c ../test/data
<file_sep>/*
Given the input and output file, respectively,
decide whether a specified source is satiesfied.
*/
#include "common.h"
/*
Check whether the value in REG_SYS_CALL(x)
is amongst the allowed system call list
*/
static int isAllowedCall(int syscall)
{
int i;
for (i = 0; -1 != strace[i]; ++i)
if (syscall == strace[i])
return 1;
return 0;
}
/*
Check whether the value in REG_ARG_1(x)
is amongst the legal library mapping list
*/
static int isValidAccess(const char *file)
{
int i;
for (i = 0; ltrace[i]; ++i)
if (0 == strcmp(file, ltrace[i]))
return 1;
return 0;
}
static void setRlimit()
{
struct rlimit limit;
limit.rlim_cur = MAX_TIME / 1000;
limit.rlim_max = MAX_TIME / 1000 + 1; // second(s)
if (setrlimit(RLIMIT_CPU, &limit))
EXIT_MSG("Set Time Limit Failed", SYSTEM_ERROR);
limit.rlim_cur = MAX_MEMORY;
limit.rlim_max = MAX_MEMORY; // byte(s)
if (setrlimit(RLIMIT_DATA, &limit))
EXIT_MSG("Set Memory Limit Failed", SYSTEM_ERROR);
}
int main(int argc, char *argv[])
{
int result = ACCEPTED;
int i;
int fd[2];
int status;
long file_tmp[10];
pid_t child;
struct rusage usage;
struct user_regs_struct regs;
if (4 != argc)
EXIT_MSG("Usage: run executable in_file temp_file", EXIT_FAILURE);
const char *bin = argv[1];
const char *in = argv[2];
const char *out = argv[3];
child = vfork();
if (child < 0)
EXIT_MSG("vfork() Failed", SYSTEM_ERROR);
/* fork a child to monitor(ptrace) its status */
if (0 == child) {
setRlimit();
if ((fd[0] = open(in, O_RDONLY, 0644)) < 0 || dup2(fd[0], STDIN_FILENO) < 0)
EXIT_MSG("open & dup2(STDIN) Failed", SYSTEM_ERROR);
if ((fd[1] = creat(out, 0644)) < 0 || dup2(fd[1], STDOUT_FILENO) < 0)
EXIT_MSG("open & dup2(STDOUT) Failed", SYSTEM_ERROR);
if (ptrace(PTRACE_TRACEME, 0, NULL, NULL))
EXIT_MSG("ptrace(PTRACE_TRACEME) Failed", SYSTEM_ERROR);
if (-1 == execl(bin, "", NULL))
EXIT_MSG("execl() Failed", SYSTEM_ERROR);
}
for (;;) {
if (-1 == wait4(child, &status, WSTOPPED, &usage))
EXIT_MSG("wait4() Failed", SYSTEM_ERROR);
if (WIFEXITED(status)) {
if (SYSTEM_ERROR == WEXITSTATUS(status))
_exit(SYSTEM_ERROR);
break;
} else if (SIGTRAP != WSTOPSIG(status)) {
ptrace(PTRACE_KILL, child, NULL, NULL);
switch (WSTOPSIG(status)) {
case SIGSEGV:
if (usage.ru_maxrss * (sysconf(_SC_PAGESIZE)) / MAX_MEMORY < 2)
result = MEMORY_LIMIT_EXCEEDED;
else
result = RUNTIME_ERROR;
break;
case SIGALRM:
case SIGXCPU:
result = TIME_LIMIT_EXCEEDED;
break;
}
}
if (-1 == ptrace(PTRACE_GETREGS, child, NULL, ®s))
goto END;
if (!isAllowedCall(REG_SYS_CALL(®s))) {
ptrace(PTRACE_KILL, child, NULL, NULL);
result = RUNTIME_ERROR;
goto END;
} else if (SYS_open == REG_SYS_CALL(®s)) {
/* peek what the program is opening */
for (i = 0; i < 10; i++) {
file_tmp[i] = ptrace(PTRACE_PEEKDATA, child,
REG_ARG_1(®s) + i*sizeof(long), NULL);
if (file_tmp[i] == 0)
break;
}
if (!isValidAccess((const char*)file_tmp)) {
ptrace(PTRACE_KILL, child, NULL, NULL);
fprintf(stderr, "RUNTIME_ERROR %s\n", (const char*)file_tmp);
result = RUNTIME_ERROR;
goto END;
}
}
if (-1 == ptrace(PTRACE_SYSCALL, child, NULL, NULL))
EXIT_MSG("PTRACE_SYSCALL Failed", SYSTEM_ERROR);
}
END:
return result;
}
<file_sep>#include "common.h"
/*
user-defined getline()
*/
static int getline2(char *s, int lim, FILE *stream)
{
int c, i = 0;
while (i < lim-1 && EOF != (c = fgetc(stream)) && '\n' != c)
s[i++] = c;
if ('\n' == c)
s[i++] = '\0';
s[lim - 1] = '\0';
return i;
}
int main(int argc, char const *argv[])
{
FILE *fp_in, *fp_out, *fp_tmp;
char line_in[MAX_LINE_LEN], line_out[MAX_LINE_LEN], line_tmp[MAX_LINE_LEN];
if (4 != argc) {
fprintf(stderr, "Usage: %s in_file out_file temp_file\n", argv[0]);
return EXIT_FAILURE;
}
fp_in = fopen(argv[1], "r");
fp_out = fopen(argv[2], "r");
fp_tmp = fopen(argv[3], "r");
if (!fp_in || !fp_out || !fp_tmp)
MSG_ERR_RET("fopen() Failed", SYSTEM_ERROR);
while (getline2(line_tmp, MAX_LINE_LEN, fp_tmp) && getline2(line_out, MAX_LINE_LEN, fp_out)) {
if (getline2(line_in, MAX_LINE_LEN, fp_in) && 0 != strcmp(line_out, line_tmp)) {
fprintf(stderr, "Input:^%s$\n"
"Output:^%s$\n"
"Expected:^%s$\n",
line_in, line_tmp, line_out);
break;
}
}
if (fclose(fp_in) || fclose(fp_out) || fclose(fp_tmp))
MSG_ERR_RET("fclose() Failed", SYSTEM_ERROR);
return EXIT_SUCCESS;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
int a, b;
while (2 == scanf("%d%d", &a, &b))
printf("%d\n", a+b);
getpid();
}
<file_sep>/*
Given the input file and output file, respectively,
decide whether a specified source is satiesfied.
*/
#include "common.h"
/*
check whether the value in REG_SYS_CALL(x)
is amongst the allowed system call list
*/
static int isAllowedCall(int syscall) {
int i;
for (i = 0; -1 != strace[i]; ++i)
if (syscall == strace[i])
return 1;
return 0;
}
/*
check whether the value in REG_ARG_1(x)
is amongst allowed library mapping list
*/
static int isValidAccess(const char *file) {
int i;
for (i = 0; ltrace[i]; ++i)
if (0 == strcmp(file, ltrace[i]))
return 1;
return 0;
}
static void setRlimit() {
struct rlimit limit;
limit.rlim_cur = MAX_TIME / 1000;
limit.rlim_max = MAX_TIME / 1000 + 1; // second(s)
if (setrlimit(RLIMIT_CPU, &limit))
EXIT_MSG("Set Time Limit Failed", SYSTEM_ERROR);
limit.rlim_cur = MAX_MEMORY;
limit.rlim_max = MAX_MEMORY; // byte(s)
if (setrlimit(RLIMIT_DATA, &limit))
EXIT_MSG("Set Memory Limit Failed", SYSTEM_ERROR);
}
int main(int argc, char *argv[])
{
int i, result = EXIT_SUCCESS;
int status;
int fd[2];
pid_t child;
struct rusage usage;
struct user_regs_struct regs;
long file_tmp[100];
if (4 != argc)
EXIT_MSG("Usage: exec executable in temp", EXIT_FAILURE);
child = vfork();
if (child < 0)
EXIT_MSG("vfork() Failed", SYSTEM_ERROR);
/* fork a child to monitor(ptrace) its status */
if (0 == child) {
setRlimit();
if ((fd[0] = open(argv[2], O_RDONLY, 0644)) < 0 || dup2(fd[0], STDIN_FILENO) < 0)
EXIT_MSG("dup2(STDIN) Failed", SYSTEM_ERROR);
if ((fd[1] = creat(argv[3], 0644)) < 0 || dup2(fd[1], STDOUT_FILENO) < 0)
EXIT_MSG("dup2(STDOUT) Failed", SYSTEM_ERROR);
if (ptrace(PTRACE_TRACEME, 0, NULL, NULL))
EXIT_MSG("PTRACE_TRACEME Failed", SYSTEM_ERROR);
if (-1 == execl(argv[1], "", NULL))
EXIT_MSG("execl() Failed", SYSTEM_ERROR);
}
for ( ; ; ) {
if (-1 == wait4(child, &status, WSTOPPED, &usage))
EXIT_MSG("wait4() Failed", SYSTEM_ERROR);
if (WIFEXITED(status)) {
if (SYSTEM_ERROR == WEXITSTATUS(status))
_exit(SYSTEM_ERROR);
break;
} else if (SIGTRAP != WSTOPSIG(status)) {
ptrace(PTRACE_KILL, child, NULL, NULL);
switch (WSTOPSIG(status)) {
case SIGSEGV:
if (usage.ru_maxrss * (sysconf(_SC_PAGESIZE)) / MAX_MEMORY < 2)
result = MEMORY_LIMIT_EXCEEDED;
else
result = RUNTIME_ERROR;
break;
case SIGALRM:
case SIGXCPU:
result = TIME_LIMIT_EXCEEDED;
break;
}
}
if (-1 == ptrace(PTRACE_GETREGS, child, NULL, ®s))
goto END;
if (0 == isAllowedCall(REG_SYS_CALL(®s))) {
ptrace(PTRACE_KILL, child, NULL, NULL);
result = RUNTIME_ERROR;
goto END;
} else if (SYS_open == REG_SYS_CALL(®s)) {
for (i = 0; i < 100; i++) {
file_tmp[i] = ptrace(PTRACE_PEEKDATA, child,
REG_ARG_1(®s) + i * sizeof(long), NULL);
if (file_tmp[i] == 0)
break;
}
if (0 == isValidAccess((const char*)file_tmp)) {
ptrace(PTRACE_KILL, child, NULL, NULL);
printf("RUNTIME_ERROR %s\n", (const char*)file_tmp);
result = RUNTIME_ERROR;
goto END;
}
}
if (-1 == ptrace(PTRACE_SYSCALL, child, NULL, NULL))
EXIT_MSG("PTRACE_SYSCALL Failed", SYSTEM_ERROR);
}
END:
return result;
}
<file_sep>#define _GNU_SOURCE
#include <sys/resource.h>
#include <sys/syscall.h>
#include <sys/ptrace.h>
#include <sys/mman.h>
#include <sys/user.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/reg.h>
#include <libgen.h>
#include <dirent.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <error.h>
#include <ctype.h>
#include <fcntl.h>
#include <stdio.h>
#include <time.h>
/* check target platform */
#if __WORDSIZE == 64
#define REG_SYS_CALL(x) ((x)->orig_rax)
#define REG_ARG_1(x) ((x)->rdi)
#else
#define REG_SYS_CALL(x) ((x)->orig_eax)
#define REG_ARG_1(x) ((x)->ebi)
#endif
/* total size of memory that one program can possess */
#define MAX_MEMORY (1 << 24)
/* total length of time that one program can possess */
#define MAX_TIME (1500)
/* restrict maximum lines of printed output */
#define MAX_OUTPUT (1 << 22)
#define MAX_LINE_LEN 80
/* in case of error occurence */
#define MSG_ERR_EXIT(msg, ret) \
do { fprintf(stderr, "%s\n", msg); _exit(ret); } while (0)
#define MSG_ERR_RET(msg, ret) \
do { fprintf(stderr, "%s\n", msg); return(ret); } while (0)
/* all kinds of judged results */
enum {
ACCEPTED = 1,
COMPILE_ERROR,
MEMORY_LIMIT_EXCEEDED,
OUTPUT_LIMIT_EXCEEDED,
RUNTIME_ERROR,
SYSTEM_ERROR,
TIME_LIMIT_EXCEEDED,
PRESENTATION_ERROR,
WRONG_ANWSER,
};
/* allowed system call list */
const int strace[] = {
SYS_open,
SYS_read,
SYS_write,
SYS_lseek,
SYS_close,
SYS_access,
SYS_mprotect,
SYS_brk,
SYS_uname,
SYS_fstat,
SYS_execve,
SYS_readlink,
SYS_arch_prctl,
SYS_mmap,
SYS_munmap,
SYS_exit_group,
-1, /* the end flag */
};
/* allowed library mapping list */
const char *ltrace[] = {
"/etc/ld.so.cache",
/* for C */
"/lib/x86_64-linux-gnu/libc.so.6", /* in this case it's on x86-64 */
"/lib/x86_64-linux-gnu/libm.so.6",
/* for C++ */
"/lib/x86_64-linux-gnu/libgcc_s.so.1",
"/usr/lib/x86_64-linux-gnu/libstdc++.so.6",
NULL, /* the end flag */
};
<file_sep>#include "common.h"
/* user-defined getline() */
ssize_t usr_getline(char *string, int lim, FILE *stream)
{
ssize_t pos = -1;
int ch;
if ( !string || !lim || !stream ) {
errno = EINVAL;
return -1;
}
for (pos = 0; pos < lim-1 && (ch=fgetc(stream)) != EOF && ch != '\n'; ++pos)
string[pos] = ch;
if (ch == '\n')
string[pos++] = ch;
string[pos] = '\0';
return pos;
}
int main(int argc, char const *argv[])
{
FILE *fp_in, *fp_out, *fp_tmp;
char line_in[80], line_out[80], line_tmp[80];
size_t len_in = 0, len_out = 0, len_tmp = 0;
fp_in = fopen(argv[1], "r");
fp_out = fopen(argv[2], "r");
fp_tmp = fopen(argv[3], "r");
if (!fp_in || !fp_out || !fp_tmp)
return EXIT_FAILURE;
while (-1 != usr_getline(line_tmp, sizeof(line_tmp), fp_tmp)
&& -1 != usr_getline(line_out, sizeof(line_out), fp_out)) {
if (-1 != usr_getline(line_in, sizeof(line_in), fp_in)
&& 0 != strcmp(line_out, line_tmp)) {
fprintf(stderr, "Input:%sOutput:%sExpected:%s",
line_in, line_tmp, line_out);
break;
}
}
if (fclose(fp_in) || fclose(fp_out) || fclose(fp_tmp))
EXIT_MSG("fclose() Failed", EXIT_FAILURE);
return 0;
}
<file_sep>all:
gcc -o SANDBOX sandbox.c -Wall
gcc -o COMPARE compare.c -Wall
gcc -o HINT hint.c -Wall
clean:
rm SANDBOX COMPARE HINT
<file_sep>#!/bin/bash
time toy/main src/source.c testdata
time toyO/main src/source.c testdata
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char const *argv[])
{
int n = atoi(argv[1]);
srandom(time(0));
while (n--)
printf("%ld %ld\n", random(), random());
return 0;
}
<file_sep>#include <sys/resource.h>
#include <sys/syscall.h>
#include <sys/ptrace.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <sys/reg.h>
#include <unistd.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
/*
check target platform
*/
#if __WORDSIZE == 64
#define REG_SYS_CALL(x) ((x)->orig_rax)
#define REG_ARG_1(x) ((x)->rdi)
#define REG_ARG_2(x) ((x)->rsi)
#else
#define REG_SYS_CALL(x) ((x)->orig_eax)
#define REG_ARG_1(x) ((x)->ebi)
#define REG_ARG_2(x) ((x)->eci)
#endif
/* total size of memory that one program can possess */
#define MAX_MEMORY (1024*1024*32)
/* restrict maximum lines of printed output */
#define MAX_OUTPUT (1<<25)
/* in case of error occurence */
#define EXIT_MSG(msg, res) \
do { fprintf(stderr, "%s\n", msg); _exit(res); } while (0)
/* all kinds of judged results */
enum {
SYSTEM_ERROR = 1,
COMPILE_ERROR,
RUNTIME_ERROR,
TIME_LIMIT_EXCEEDED,
MEMORY_LIMIT_EXCEEDED,
OUTPUT_LIMIT_EXCEEDED,
PRESENTATION_ERROR,
WRONG_ANWSER,
ACCEPTED,
};
/* allowed system call list */
const int strace[] = {
SYS_execve,
SYS_brk,
SYS_access,
SYS_mmap,
SYS_open,
SYS_fstat,
SYS_close,
SYS_read,
SYS_write,
SYS_mprotect,
SYS_arch_prctl,
SYS_munmap,
SYS_exit_group,
-1, /* the end flag */
};
/* allowed library mapping list */
const char *ltrace[] = {
"/etc/ld.so.cache",
"/lib/x86_64-linux-gnu/libc.so.6", /* in this case it's on x86-64 */
NULL, /* the end flag */
};
<file_sep>/*
Let's say hello and good-bye to the world!
To be careful, make sure every system API
in this file has checked its return value.
*/
/*
This main.c only does one job fairly well:
given an executable candidate, check whether it satisfies the following rule -
i.e. For each target input, the candidate is capable of delivering
the output as expect. If not, report the reason.
*/
#include "common.h"
#define MSG_ERR_RET(msg, res) \
do { fprintf(stderr, "%s\n", msg); return(res); } while (0)
#define MSG_JUDGE_QUIT(msg) \
do { printf("%s\n", msg); goto FINAL; } while (0)
long Time, Memory;
/*
check whether the value in REG_SYS_CALL(x)
is amongst the allowed system call list
*/
int isAllowedCall(int syscall) {
int i;
for (i = 0; -1 != strace[i]; ++i)
if (syscall == strace[i])
return 1;
return 0;
}
/*
check whether the value in REG_ARG_1(x)
is amongst allowed library mapping list
*/
int isValidAccess(const char *file) {
int i;
for (i = 0; ltrace[i]; ++i)
if (0 == strcmp(file, ltrace[i]))
return 1;
return 0;
}
/*
a wrap-up function for setting up resource limit
*/
void setRlimit() {
struct rlimit usr_limit;
usr_limit.rlim_cur = MAX_TIME / 1000;
usr_limit.rlim_max = MAX_TIME / 1000 + 1; // second(s)
if (setrlimit(RLIMIT_CPU, &usr_limit))
EXIT_MSG("Set Time Limit Failed", SYSTEM_ERROR);
usr_limit.rlim_cur = MAX_MEMORY;
usr_limit.rlim_max = MAX_MEMORY; // byte(s)
if (setrlimit(RLIMIT_AS, &usr_limit))
EXIT_MSG("Set Memory Limit Failed", SYSTEM_ERROR);
}
#define kill_it(pid) ptrace(PTRACE_KILL, pid, NULL, NULL);
int invalidAccess(pid_t pid, struct user_regs_struct *registers) {
int i;
long access_file[10];
/* peek which file the process is about to open */
for (i = 0; i < 10; i++) {
access_file[i] = ptrace(PTRACE_PEEKDATA,
pid, REG_ARG_1(registers) + i * sizeof(long), NULL);
if (0 == access_file[i])
break;
}
if (!isValidAccess((const char*)access_file)) {
kill_it(pid);
fprintf(stderr, "%s\t", (const char*)access_file);
return 1;
}
return 0;
}
/*
Given the input file and output file, respectively,
decide whether a specified source is satiesfied.
*/
int run(const char *bin, const char *in, const char *out) {
int result = EXIT_SUCCESS;
int status;
struct rusage usage;
struct user_regs_struct regs;
pid_t child = vfork();
/* assure that parent gets executed after child exits */
if (child < 0) {
MSG_ERR_RET("vfork() Failed", SYSTEM_ERROR);
}
/* fork a child to monitor(ptrace) its status */
if (0 == child) {
int fd[2];
setRlimit();
/* dup2 guarantees the atomic operation */
if ((fd[0] = open(in, O_RDONLY, 0644)) < 0 || dup2(fd[0], STDIN_FILENO) < 0)
EXIT_MSG("dup2(STDIN_FILENO) Failed", SYSTEM_ERROR);
if ((fd[1] = creat(out, 0644)) < 0 || dup2(fd[1], STDOUT_FILENO) < 0)
EXIT_MSG("dup2(STDOUT_FILENO) Failed", SYSTEM_ERROR);
if (ptrace(PTRACE_TRACEME, 0, NULL, NULL))
EXIT_MSG("PTRACE_TRACEME Failed", SYSTEM_ERROR);
if (-1 == execl(bin, "", NULL))
EXIT_MSG("execl() Failed", SYSTEM_ERROR);
}
for ( ; ; ) {
if (-1 == wait4(child, &status, WSTOPPED, &usage))
MSG_ERR_RET("wait4() Failed", SYSTEM_ERROR);
/* child has already exited */
if (WIFEXITED(status)) {
if (SYSTEM_ERROR == WEXITSTATUS(status))
return SYSTEM_ERROR;
} else if (SIGTRAP != WSTOPSIG(status)) {
kill_it(child);
switch (WSTOPSIG(status)) {
case SIGSEGV:
if (usage.ru_maxrss * (sysconf(_SC_PAGESIZE)) / MAX_MEMORY < 2)
result = MEMORY_LIMIT_EXCEEDED;
else
result = RUNTIME_ERROR;
break;
case SIGALRM: case SIGXCPU: case SIGKILL:
result = TIME_LIMIT_EXCEEDED;
break;
}
}
/* unable to peek register info */
if (-1 == ptrace(PTRACE_GETREGS, child, NULL, ®s))
goto END;
if (!isAllowedCall(REG_SYS_CALL(®s))) {
kill_it(child);
fprintf(stderr, "%llu\t", REG_SYS_CALL(®s));
MSG_ERR_RET("Invalid Syscall", RUNTIME_ERROR);
}
/* watch what the child is going to open */
if (SYS_open == REG_SYS_CALL(®s)) {
if (invalidAccess(child, ®s))
MSG_ERR_RET("Invalid Access", RUNTIME_ERROR);
}
/* trace next system call */
if (-1 == ptrace(PTRACE_SYSCALL, child, NULL, NULL))
MSG_ERR_RET("PTRACE_SYSCALL Failed", SYSTEM_ERROR);
}
END:
Time = usage.ru_utime.tv_sec * 1000 + usage.ru_utime.tv_usec / 1000
+ usage.ru_stime.tv_sec * 1000 + usage.ru_stime.tv_usec / 1000;
Memory = usage.ru_maxrss * (sysconf(_SC_PAGESIZE) / 1024);
return result;
}
int diff(const char *s1, const char *s2) {
/* test if the same */
while (*s1 && *s1 == *s2) {
++s1;
++s2;
}
/* both encounter NUL */
if (!(*s1 || *s2))
return ACCEPTED;
for ( ; ; ) {
/* skip invisible characters */
while (isspace(*s1))
s1++;
while (isspace(*s2))
s2++;
/* either is NUL, no need to compare more */
if (!(*s1 && *s2))
break;
/* neither is NUL */
if (*s1 != *s2)
return WRONG_ANWSER;
/* keep running */
++s1;
++s2;
}
return (*s1 || *s2) ? WRONG_ANWSER : PRESENTATION_ERROR;
}
/*
when the tested source file has been compiled and
successfully produced the output file, this function
will perform the answer checking exercise.
*/
int check(const char *out, const char *tmp) {
int fd[2];
int result = ACCEPTED;
char *out_mem, *tmp_mem;
off_t out_len, tmp_len;
if ((fd[0] = open(out, O_RDONLY, 0644)) < 0)
MSG_ERR_RET("open(out) Failed.", SYSTEM_ERROR);
if ((fd[1] = open(tmp, O_RDONLY, 0644)) < 0)
MSG_ERR_RET("open(tmp) Failed.", SYSTEM_ERROR);
/* collect length infomation */
out_len = lseek(fd[0], 0, SEEK_END);
tmp_len = lseek(fd[1], 0, SEEK_END);
if (-1 == out_len || -1 == tmp_len)
MSG_ERR_RET("lseek() Failed", SYSTEM_ERROR);
if (MAX_OUTPUT <= tmp_len)
return OUTPUT_LIMIT_EXCEEDED;
/* compare them according to their size */
/* both are empty */
if (0 == (out_len || tmp_len))
return ACCEPTED;
/* either is empty */
if (0 == (out_len && tmp_len))
return WRONG_ANWSER;
/* rewind */
lseek(fd[0], 0, SEEK_SET);
lseek(fd[1], 0, SEEK_SET);
if (-1 == out_len || -1 == tmp_len)
MSG_ERR_RET("lseek() or rewind Failed", SYSTEM_ERROR);
/* map files to memory for efficiency */
if ((out_mem = mmap(NULL, out_len, PROT_READ, MAP_PRIVATE, fd[0], 0)) == MAP_FAILED)
MSG_ERR_RET("mmap(out_mem) Failed", SYSTEM_ERROR);
if ((tmp_mem = mmap(NULL, tmp_len, PROT_READ, MAP_PRIVATE, fd[1], 0)) == MAP_FAILED)
MSG_ERR_RET("mmap(tmp_mem) Failed", SYSTEM_ERROR);
result = diff(out_mem, tmp_mem);
/* clean */
if (-1 == munmap(out_mem, out_len) || -1 == munmap(tmp_mem, tmp_len))
MSG_ERR_RET("munmap() Failed", SYSTEM_ERROR);
/* in case of running out of available file descriptors */
if (-1 == close(fd[0]) || -1 == close(fd[1]))
MSG_ERR_RET("close() Failed", SYSTEM_ERROR);
return result;
}
/*
test if haystack ends with the needle
*/
int endWith(const char *haystack, const char *needle) {
size_t haystackLen = strlen(haystack);
size_t needleLen = strlen(needle);
if (haystackLen < needleLen)
return 0;
char *end = (char *)haystack + (haystackLen - needleLen);
return 0 == strcmp(end, needle);
}
/*
generate a temporary file name
*/
void randomString(char str[], const size_t len) {
int i;
srand(time(NULL));
for (i = 0; i < len-1; ++i) {
str[i] = rand()%26 + 'a';
}
str[len - 1] = '\0';
}
/*
count how many .in files there are in the folder
*/
int countFiles(const char *directory, const char *suffix) {
int n, cnt = 0;
struct dirent **filename;
n = scandir(directory, &filename, NULL, alphasort);
if (n < 0)
EXIT_MSG("scandir() Failed", EXIT_FAILURE);
else
while (n--) {
if (endWith(filename[n]->d_name, suffix))
++cnt;
free(filename[n]);
}
free(filename);
return cnt;
}
#define countTestdata(dir) countFiles(dir, ".in")
void compare(const char *test_in, const char *test_out, const char *test_tmp) {
FILE *in, *out, *tmp;
char *line_in, *line_out, *line_tmp;
size_t len_in = 0, len_out = 0, len_tmp = 0;
in = fopen(test_in, "r");
out = fopen(test_out, "r");
tmp = fopen(test_tmp, "r");
if (!in || !out || !tmp)
exit(EXIT_FAILURE);
while (-1 != getline(&line_tmp, &len_tmp, tmp)
&& -1 != getline(&line_out, &len_out, out)) {
if (-1 != getline(&line_in, &len_in, in) && 0 != strcmp(line_out, line_tmp)) {
fprintf(stderr, "Input:%sOutput:%sExpected:%s",
line_in, line_out, line_tmp);
break;
}
}
free(line_in);
free(line_out);
free(line_tmp);
if (fclose(in) || fclose(out) || fclose(tmp))
EXIT_MSG("fclose() Failed", EXIT_FAILURE);
}
int main(int argc, char *argv[], char *env[]) {
int result = ACCEPTED;
int num, total;
char test_temp[9];
typedef char char32[32];
char32 test_in, test_out;
if (3 != argc)
EXIT_MSG("Usage: judge exec_file problem_folder", EXIT_FAILURE);
randomString(test_temp, sizeof test_temp);
total = countTestdata(argv[2]);
for (num = 0; num < total; ++num) {
snprintf(test_in ,sizeof test_in, "%s/%d.in", argv[2], num);
switch (run(argv[1], test_in, test_temp)) {
case SYSTEM_ERROR:
MSG_JUDGE_QUIT("System Error");
case RUNTIME_ERROR:
MSG_JUDGE_QUIT("Runtime Error");
case TIME_LIMIT_EXCEEDED:
MSG_JUDGE_QUIT("Time Limit Exceeded");
case MEMORY_LIMIT_EXCEEDED:
MSG_JUDGE_QUIT("Memory Limit Exceeded");
}
snprintf(test_out, sizeof test_out, "%s/%d.out", argv[2], num);
switch (check(test_out, test_temp)) {
case OUTPUT_LIMIT_EXCEEDED:
MSG_JUDGE_QUIT("Output Limit Exceeded");
case PRESENTATION_ERROR:
MSG_JUDGE_QUIT("Presentation Error");
case WRONG_ANWSER:
compare(test_in, test_out, test_temp);
MSG_JUDGE_QUIT("Wrong Anwser");
case SYSTEM_ERROR:
MSG_JUDGE_QUIT("System Error");
case ACCEPTED: ;
}
}
if (ACCEPTED == result)
printf("Accepted TIME: %ldMS MEM: %ldKB\n", Time, Memory);
FINAL:
if (-1 == unlink(test_temp))
MSG_ERR_RET("unlink Failed", SYSTEM_ERROR);
return EXIT_SUCCESS;
}
<file_sep>time ./OJ.sh ../test/CompileErr.c ../test/data
time ./OJ.sh ../test/Accept.c ../test/data
time ./OJ.sh ../test/TimeOut.c ../test/data
time ./OJ.sh ../test/MemoryOut.c ../test/data
time ./OJ.sh ../test/RuntimeErr.c ../test/data
time ./OJ.sh ../test/WrongAnswer.c ../test/data
time ./OJ.sh ../test/PreErr.c ../test/data
<file_sep>/*
Given the input file and output file, respectively,
decide whether a specified source is satiesfied.
*/
#include "toy.h"
/*
check whether the value in REG_SYS_CALL(x)
is amongst the allowed system call list
*/
static int isAllowedCall(int syscall) {
int i;
size_t n = sizeof(strace) / sizeof(strace[0]);
for (i = 0; -1 != strace[i]; ++i)
if (syscall == strace[i])
return 1;
return 0;
}
/*
check whether the value in REG_ARG_1(x)
is amongst allowed library mapping list
*/
static int isValidAccess(const char *file) {
int i;
size_t n = sizeof(ltrace) / sizeof(ltrace[0]);
for (i = 0; ltrace[i]; ++i)
if (0 == strcmp(file, ltrace[i]))
return 1;
return 0;
}
static void setRlimit() {
struct rlimit limit;
limit.rlim_cur = 1;
limit.rlim_max = 2; // second(s)
if (setrlimit(RLIMIT_CPU, &limit))
EXIT_MSG("Set Time Limit Failed", SYSTEM_ERROR);
limit.rlim_cur = limit.rlim_max = MAX_MEMORY; // bit
if (setrlimit(RLIMIT_DATA, &limit))
EXIT_MSG("Set Memory Limit Failed", SYSTEM_ERROR);
}
int main(int argc, char *argv[])
{
int i, result = EXIT_SUCCESS;
int status;
int fd[2];
pid_t child;
struct rusage usage;
struct user_regs_struct regs;
long file_tmp[100];
if (4 != argc)
EXIT_MSG("Usage: run exec in temp", EXIT_FAILURE);
child = vfork();
if (child < 0)
EXIT_MSG("vfork() Failed", SYSTEM_ERROR);
if (0 == child) {
setRlimit();
if ((fd[0] = open(argv[2], O_RDONLY, 0644)) < 0 || dup2(fd[0], STDIN_FILENO) < 0)
EXIT_MSG("dup2(STDIN_FILENO) Failed", SYSTEM_ERROR);
if ((fd[1] = creat(argv[3], 0644)) < 0 || dup2(fd[1], STDOUT_FILENO) < 0)
EXIT_MSG("dup2(STDOUT_FILENO) Failed", SYSTEM_ERROR);
if (ptrace(PTRACE_TRACEME, 0, NULL, NULL))
EXIT_MSG("PTRACE_TRACEME Failed", SYSTEM_ERROR);
if (-1 == execl(argv[1], "", NULL))
EXIT_MSG("execl() Failed", SYSTEM_ERROR);
}
for ( ; ; ) {
if (-1 == wait4(child, &status, WSTOPPED, &usage))
EXIT_MSG("wait4() Failed", SYSTEM_ERROR);
if (WIFEXITED(status)) {
if (SYSTEM_ERROR == WEXITSTATUS(status))
_exit(SYSTEM_ERROR);
break;
} else if (SIGTRAP != WSTOPSIG(status)) {
ptrace(PTRACE_KILL, child, NULL, NULL);
switch (WSTOPSIG(status)) {
case SIGSEGV:
if (usage.ru_maxrss * (sysconf(_SC_PAGESIZE)) / MAX_MEMORY < 2)
result = MEMORY_LIMIT_EXCEEDED;
else
result = RUNTIME_ERROR;
break;
case SIGALRM: case SIGXCPU:
result = TIME_LIMIT_EXCEEDED;
break;
}
}
if (-1 == ptrace(PTRACE_GETREGS, child, NULL, ®s))
goto END;
//printf("%llu is in(%d)?\n", REG_SYS_CALL(®s), isAllowedCall(REG_SYS_CALL(®s)));
if (0 == isAllowedCall(REG_SYS_CALL(®s))) {
ptrace(PTRACE_KILL, child, NULL, NULL);
result = RUNTIME_ERROR;
goto END;
} else if (SYS_open == REG_SYS_CALL(®s)) {
for (i = 0; i < 100; i++) {
file_tmp[i] = ptrace(PTRACE_PEEKDATA, child, REG_ARG_1(®s) + i * sizeof(long), NULL);
if (file_tmp[i] == 0)
break;
}
if (0 == isValidAccess((const char*)file_tmp)) {
ptrace(PTRACE_KILL, child, NULL, NULL);
printf("RUNTIME_ERROR %s\n", (const char*)file_tmp);
result = RUNTIME_ERROR;
goto END;
}
//printf("%s:%lld\n", (const char*)file_tmp, REG_ARG_2(®s));
}
if (-1 == ptrace(PTRACE_SYSCALL, child, NULL, NULL))
EXIT_MSG("PTRACE_SYSCALL Failed", SYSTEM_ERROR);
}
END:
// printf("%lf\n", (double)usage.ru_maxrss * (sysconf(_SC_PAGESIZE)) / MAX_MEMORY);
printf("Time %ldMS Memory %ldKB\n",
usage.ru_utime.tv_sec * 1000 + usage.ru_utime.tv_usec / 1000
+ usage.ru_stime.tv_sec * 1000 + usage.ru_stime.tv_usec / 1000,
usage.ru_maxrss * (sysconf(_SC_PAGESIZE) / 1024));
return result;
}
<file_sep>all:
gcc -o exec exec.c -Wall
gcc -o judge main.c -Wall
<file_sep>#!/bin/bash
if [ $# -ne 4 ]; then
echo "Usage: $0 fileNO lineNO testGenTool.c src.c"
exit 0
fi
cnt=$1
line=$2
gen=$3
src=$4
# compile input generate source code
gcc $gen -o Gen_Unit -Wall
# compile programe source code
gcc $src -o Src_Code -Wall
for ((i=0; i<$cnt; ++i)); do
rm $i.in 2>>/dev/null
./Gen_Unit $line >> $i.in
# for ((j=0; j<$line; ++j)); do $gen >> $i.in done
./Src_Code < $i.in > $i.out
done
exit 0
<file_sep>all:
cc -o JUDGE *.c -Wall
clean:
rm *.o JUDGE
<file_sep>void x()
{
int arr[1024];
x();
}
int main()
{
x();
}
<file_sep>/*
2016/6/8
Original Author: <NAME>
<<EMAIL>>
Let's say hello and good-bye to the world!
In this universe of beauty and grace, set
blank barrier to your forward path.
To be careful, make sure every system API
in this file has checked its return value.
*/
#include "common.h"
long Time;
long Memory;
/*
Check whether the value in REG_SYS_CALL(x)
is amongst the allowed system call list
*/
static int isAllowedCall(int syscall)
{
int i;
for (i = 0; -1 != strace[i]; ++i)
if (syscall == strace[i])
return 1;
return 0;
}
/*
Check whether the value in REG_ARG_1(x)
is amongst the legal library mapping list
*/
static int isValidAccess(const char *file)
{
int i;
for (i = 0; ltrace[i]; ++i)
if (0 == strcmp(file, ltrace[i]))
return 1;
return 0;
}
/*
a wrap-up function for setting up resource limit
*/
static void setResourceLimit()
{
struct rlimit limit;
limit.rlim_cur = MAX_TIME / 1000;
limit.rlim_max = MAX_TIME / 1000 + 1; // second(s)
if (setrlimit(RLIMIT_CPU, &limit))
MSG_ERR_EXIT("Set Time Limit Failed", SYSTEM_ERROR);
limit.rlim_cur = MAX_MEMORY;
limit.rlim_max = MAX_MEMORY; // byte(s)
if (setrlimit(RLIMIT_AS, &limit))
MSG_ERR_EXIT("Set Memory Limit Failed", SYSTEM_ERROR);
}
static void forkChild(const char *bin, const char *in, const char *out)
{
int fd[2];
setResourceLimit();
/* dup2 guarantees the atomic operation */
if ((fd[0] = open(in, O_RDONLY, 0644)) < 0 || dup2(fd[0], STDIN_FILENO) < 0)
MSG_ERR_EXIT("dup2(STDIN_FILENO) Failed", SYSTEM_ERROR);
if ((fd[1] = creat(out, 0644)) < 0 || dup2(fd[1], STDOUT_FILENO) < 0)
MSG_ERR_EXIT("dup2(STDOUT_FILENO) Failed", SYSTEM_ERROR);
if (ptrace(PTRACE_TRACEME, 0, NULL, NULL))
MSG_ERR_EXIT("PTRACE_TRACEME Failed", SYSTEM_ERROR);
if (-1 == execl(bin, "", NULL))
MSG_ERR_EXIT("execl() Failed", SYSTEM_ERROR);
}
#define kill_it(pid) ptrace(PTRACE_KILL, pid, NULL, NULL);
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
static int invalidAccess(pid_t pid, struct user_regs_struct *registers)
{
int i;
long access_file[16];
/* peek which file the process is about to open */
for (i = 0; i < ARRAY_SIZE(access_file); i++) {
access_file[i] = ptrace(PTRACE_PEEKDATA,
pid, REG_ARG_1(registers) + i * sizeof(long), NULL);
if (0 == access_file[i])
break;
}
if (!isValidAccess((const char*)access_file)) {
kill_it(pid);
fprintf(stderr, "Invalid access: %s\n", (const char*)access_file);
return 1;
}
return 0;
}
int main(int argc, char *argv[])
{
int result = ACCEPTED;
int status;
struct rusage usage;
struct user_regs_struct regs;
if (4 != argc) {
fprintf(stderr, "Usage: %s executable in_file temp_file\n", argv[0]);
return EXIT_FAILURE;
}
const char *bin = argv[1];
const char *in = argv[2];
const char *out = argv[3];
pid_t child = vfork();
/* assure that parent gets executed after child exits */
if (child < 0) {
MSG_ERR_RET("vfork() Failed", SYSTEM_ERROR);
}
/* fork a child to monitor(ptrace) its status */
if (0 == child) {
forkChild(bin, in, out);
}
for (;;) {
if (-1 == wait4(child, &status, WSTOPPED, &usage))
MSG_ERR_RET("wait4() Failed", SYSTEM_ERROR);
/* child has already exited */
if (WIFEXITED(status)) {
if (SYSTEM_ERROR == WEXITSTATUS(status))
return SYSTEM_ERROR;
}
if (SIGTRAP != WSTOPSIG(status)) {
kill_it(child);
switch (WSTOPSIG(status)) {
case SIGSEGV:
if (usage.ru_maxrss * (sysconf(_SC_PAGESIZE)) / MAX_MEMORY < 2)
result = MEMORY_LIMIT_EXCEEDED;
else
result = RUNTIME_ERROR;
break;
case SIGALRM:
case SIGKILL:
case SIGXCPU:
result = TIME_LIMIT_EXCEEDED;
break;
}
}
/* unable to peek register info */
if (-1 == ptrace(PTRACE_GETREGS, child, NULL, ®s))
goto END;
if (!isAllowedCall(REG_SYS_CALL(®s))) {
kill_it(child);
fprintf(stderr, "%llu\n", REG_SYS_CALL(®s));
MSG_ERR_RET("Invalid Syscall", RUNTIME_ERROR);
}
/* watch what the child is going to open */
if (SYS_open == REG_SYS_CALL(®s)) {
if (invalidAccess(child, ®s))
MSG_ERR_RET("Invalid Access", RUNTIME_ERROR);
}
/* trace next system call */
if (-1 == ptrace(PTRACE_SYSCALL, child, NULL, NULL))
MSG_ERR_RET("PTRACE_SYSCALL Failed", SYSTEM_ERROR);
}
END:
Time = usage.ru_utime.tv_sec * 1000 + usage.ru_utime.tv_usec / 1000
+ usage.ru_stime.tv_sec * 1000 + usage.ru_stime.tv_usec / 1000;
Memory = usage.ru_maxrss * (sysconf(_SC_PAGESIZE) / 1024);
if (ACCEPTED == result)
printf("TIME: %ldMS MEM: %ldKB\n", Time, Memory);
return result;
}
<file_sep>#include "common.h"
static int compare(const char *s1, const char *s2)
{
/* test if the same */
while (*s1 && *s1 == *s2) {
++s1;
++s2;
}
/* both encounter NUL */
if (!(*s1 || *s2))
return ACCEPTED;
for (;;) {
/* skip invisible characters */
while (isspace(*s1))
s1++;
while (isspace(*s2))
s2++;
/* either is NUL, no need to compare more */
if (!(*s1 && *s2))
break;
/* neither is NUL */
if (*s1 != *s2)
return WRONG_ANWSER;
/* keep running */
++s1;
++s2;
}
return (*s1 || *s2) ? WRONG_ANWSER : PRESENTATION_ERROR;
}
/*
When the tested source file has been compiled and
successfully produced the output file, this function
will perform the answer checking exercise.
*/
int main(int argc, char *argv[], char *env[])
{
int result = ACCEPTED;
int fd[2];
char *out_mem, *tmp_mem;
off_t out_len, tmp_len;
const char *out = argv[1];
const char *tmp = argv[2];
if (3 != argc) {
fprintf(stderr, "Usage: %s out_file temp_file\n", argv[0]);
return EXIT_FAILURE;
}
if ((fd[0] = open(out, O_RDONLY, 0644)) < 0)
MSG_ERR_RET("open(out) Failed", SYSTEM_ERROR);
if ((fd[1] = open(tmp, O_RDONLY, 0644)) < 0)
MSG_ERR_RET("open(tmp) Failed", SYSTEM_ERROR);
/* collect length infomation */
out_len = lseek(fd[0], 0, SEEK_END);
tmp_len = lseek(fd[1], 0, SEEK_END);
if (-1 == out_len || -1 == tmp_len)
MSG_ERR_RET("lseek() Failed", SYSTEM_ERROR);
if (MAX_OUTPUT <= tmp_len)
return OUTPUT_LIMIT_EXCEEDED;
/* compare them according to their size */
/* both are empty */
if (0 == (out_len || tmp_len))
return ACCEPTED;
/* either is empty */
if (0 == (out_len && tmp_len))
return WRONG_ANWSER;
/* rewind */
lseek(fd[0], 0, SEEK_SET);
lseek(fd[1], 0, SEEK_SET);
if (-1 == out_len || -1 == tmp_len)
MSG_ERR_RET("lseek() or rewind Failed", SYSTEM_ERROR);
/* map files to memory for efficiency */
if ((out_mem = mmap(NULL, out_len, PROT_READ, MAP_PRIVATE, fd[0], 0)) == MAP_FAILED)
MSG_ERR_RET("mmap(out_mem) Failed", SYSTEM_ERROR);
if ((tmp_mem = mmap(NULL, tmp_len, PROT_READ, MAP_PRIVATE, fd[1], 0)) == MAP_FAILED)
MSG_ERR_RET("mmap(tmp_mem) Failed", SYSTEM_ERROR);
result = compare(out_mem, tmp_mem);
/* clean */
if (-1 == munmap(out_mem, out_len) || -1 == munmap(tmp_mem, tmp_len))
MSG_ERR_RET("munmap() Failed", SYSTEM_ERROR);
/* in case of running out of available file descriptors */
if (-1 == close(fd[0]) || -1 == close(fd[1]))
MSG_ERR_RET("close() Failed", SYSTEM_ERROR);
return result;
}
<file_sep>#define _GNU_SOURCE
#include <sys/resource.h>
#include <sys/syscall.h>
#include <sys/ptrace.h>
#include <sys/mman.h>
#include <sys/user.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/reg.h>
#include <libgen.h>
#include <dirent.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <error.h>
#include <ctype.h>
#include <fcntl.h>
#include <stdio.h>
#include <time.h>
#if __WORDSIZE == 64
#define REG_SYS_CALL(x) ((x)->orig_rax)
#define REG_ARG_1(x) ((x)->rdi)
#define REG_ARG_2(x) ((x)->rsi)
#else
#define REG_SYS_CALL(x) ((x)->orig_eax)
#define REG_ARG_1(x) ((x)->ebi)
#define REG_ARG_2(x) ((x)->eci)
#endif
#define MAX_MEMORY (1024*1024*16)
#define MAX_OUTPUT (1<<25)
#define EXIT_MSG(msg, res) \
do { fprintf(stderr, "%s\n", msg); _exit(res); } while (0)
#define RET_MSG(msg, res) \
do { fprintf(stderr, "%s\n", msg); return(res); } while (0)
#define RAISE_MSG(msg) \
do { printf("%s , %s\n", \
baseName(argv[1]), msg); goto CLEAN; } while (0)
long Time, Memory;
enum {
SYSTEM_ERROR = 1,
COMPILE_ERROR,
RUNTIME_ERROR,
TIME_LIMIT_EXCEEDED,
MEMORY_LIMIT_EXCEEDED,
OUTPUT_LIMIT_EXCEEDED,
PRESENTATION_ERROR,
WRONG_ANWSER,
ACCEPTED,
};
const int strace[] = {
SYS_mmap,
SYS_open,
SYS_read,
SYS_write,
SYS_close,
SYS_access,
SYS_mprotect,
SYS_brk,
SYS_fstat,
SYS_execve,
SYS_arch_prctl,
SYS_munmap,
SYS_exit_group,
-1,
};
const char *ltrace[] = {
"/etc/ld.so.cache",
"/lib/x86_64-linux-gnu/libc.so.6",
"/lib/x86_64-linux-gnu/libm.so.6",
NULL,
};
int isAllowedCall(int syscall) {
int i;
for (i = 0; -1 != strace[i]; ++i)
if (syscall == strace[i])
return 1;
return 0;
}
int isValidAccess(const char *file) {
int i;
for (i = 0; ltrace[i]; ++i)
if (0 == strcmp(file, ltrace[i]))
return 1;
return 0;
}
void setRlimit() {
struct rlimit limit;
limit.rlim_cur = 1;
limit.rlim_max = 2; // second(s)
if (setrlimit(RLIMIT_CPU, &limit))
EXIT_MSG("Set Time Limit Failed", SYSTEM_ERROR);
limit.rlim_cur = MAX_MEMORY;
limit.rlim_max = MAX_MEMORY; // byte(s)
if (setrlimit(RLIMIT_AS, &limit))
EXIT_MSG("Set Memory Limit Failed", SYSTEM_ERROR);
}
void forkChild(const char *exec, const char *in, const char *temp) {
int fd[2];
setRlimit();
if ((fd[0] = open(in, O_RDONLY, 0644)) < 0 || dup2(fd[0], STDIN_FILENO) < 0)
EXIT_MSG("dup2(STDIN_FILENO) Failed", SYSTEM_ERROR);
if ((fd[1] = creat(temp, 0644)) < 0 || dup2(fd[1], STDOUT_FILENO) < 0)
EXIT_MSG("dup2(STDOUT_FILENO) Failed", SYSTEM_ERROR);
if (ptrace(PTRACE_TRACEME, 0, NULL, NULL))
EXIT_MSG("PTRACE_TRACEME Failed", SYSTEM_ERROR);
if (-1 == execl(exec, "", NULL))
EXIT_MSG("execl() Failed", SYSTEM_ERROR);
}
int run(const char *exec, const char *in, const char *temp) {
int i;
int status;
int result = EXIT_SUCCESS;
long file_test_tmp[100];
struct rusage usage;
struct user_regs_struct regs;
pid_t child;
child = vfork();
if (child < 0) {
RET_MSG("vfork() Failed", SYSTEM_ERROR);
}
if (0 == child) {
forkChild(exec, in, temp);
}
for ( ; ; ) {
if (-1 == wait4(child, &status, WSTOPPED, &usage))
RET_MSG("wait4() Failed", SYSTEM_ERROR);
if (WIFEXITED(status)) {
if (SYSTEM_ERROR == WEXITSTATUS(status))
return(SYSTEM_ERROR);
break;
} else if (SIGTRAP != WSTOPSIG(status)) {
ptrace(PTRACE_KILL, child, NULL, NULL);
switch (WSTOPSIG(status)) {
case SIGSEGV:
if (usage.ru_maxrss * (sysconf(_SC_PAGESIZE)) / MAX_MEMORY < 2)
result = MEMORY_LIMIT_EXCEEDED;
else
result = RUNTIME_ERROR;
break;
case SIGALRM: case SIGXCPU:
result = TIME_LIMIT_EXCEEDED;
break;
}
}
if (-1 == ptrace(PTRACE_GETREGS, child, NULL, ®s))
goto END;
if (!isAllowedCall(REG_SYS_CALL(®s))) {
ptrace(PTRACE_KILL, child, NULL, NULL);
RET_MSG("Invalid Syscall", RUNTIME_ERROR);
} else if (SYS_open == REG_SYS_CALL(®s)) {
for (i = 0; i < 100; i++) {
file_test_tmp[i] = ptrace(PTRACE_PEEKDATA, child, REG_ARG_1(®s) + i * sizeof(long), NULL);
if (0 == file_test_tmp[i])
break;
}
if (!isValidAccess((const char*)file_test_tmp)) {
ptrace(PTRACE_KILL, child, NULL, NULL);
RET_MSG("Invalid Access", RUNTIME_ERROR);
}
// printf("%s:%lld\n", (const char*)file_test_tmp, REG_ARG_2(®s));
}
if (-1 == ptrace(PTRACE_SYSCALL, child, NULL, NULL))
RET_MSG("PTRACE_SYSCALL Failed", SYSTEM_ERROR);
}
END:
Time = usage.ru_utime.tv_sec * 1000 + usage.ru_utime.tv_usec / 1000
+ usage.ru_stime.tv_sec * 1000 + usage.ru_stime.tv_usec / 1000;
Memory = usage.ru_maxrss * (sysconf(_SC_PAGESIZE) / 1024);
return result;
}
int diff(const char *s1, const char *s2) {
while (*s1 && *s1 == *s2) {
++s1;
++s2;
}
if (!(*s1 || *s2))
return ACCEPTED;
for ( ; ; ) {
while (isspace(*s1))
s1++;
while (isspace(*s2))
s2++;
if (!(*s1 && *s2))
break;
if (*s1 != *s2)
return WRONG_ANWSER;
++s1;
++s2;
}
return (*s1 || *s2) ? WRONG_ANWSER : PRESENTATION_ERROR;
}
int check(const char *rightOutput, const char *userOutput) {
int fd[2];
int result;
char *rightOut, *userOut;
off_t rightLen, userLen;
if ((fd[0] = open(rightOutput, O_RDONLY, 0644)) < 0)
RET_MSG("open(out) Failed.", SYSTEM_ERROR);
if ((fd[1] = open(userOutput, O_RDONLY, 0644)) < 0)
RET_MSG("open(test_tmp) Failed.", SYSTEM_ERROR);
rightLen = lseek(fd[0], 0, SEEK_END);
userLen = lseek(fd[1], 0, SEEK_END);
if (-1 == rightLen || -1 == userLen)
RET_MSG("lseek() Failed", SYSTEM_ERROR);
if (MAX_OUTPUT <= userLen)
return OUTPUT_LIMIT_EXCEEDED;
if (0 == (rightLen || userLen))
return ACCEPTED;
else if (0 == (rightLen && userLen))
return WRONG_ANWSER;
lseek(fd[0], 0, SEEK_SET);
lseek(fd[1], 0, SEEK_SET);
if ((rightOut = mmap(NULL, rightLen, PROT_READ, MAP_PRIVATE, fd[0], 0)) == MAP_FAILED)
RET_MSG("mmap(rightOut) Failed", SYSTEM_ERROR);
if ((userOut = mmap(NULL, userLen, PROT_READ, MAP_PRIVATE, fd[1], 0)) == MAP_FAILED)
RET_MSG("mmap(userOut) Failed", SYSTEM_ERROR);
result = diff(rightOut, userOut);
munmap(rightOut, rightLen);
munmap(userOut, userLen);
close(fd[0]);
close(fd[1]);
return result;
}
int endWith(const char *haystack, const char *needle) {
size_t haystackLen = strlen(haystack);
size_t needleLen = strlen(needle);
if (haystackLen < needleLen)
return 0;
char *end = (char *)haystack + (haystackLen - needleLen);
return 0 == strcmp(end, needle);
}
void randomString(char str[], size_t len) {
int i;
srand(time(NULL));
for (i = 0; i < len-1; ++i) {
str[i] = rand()%26 + 'a';
}
str[len - 1] = '\0';
}
int countTestdata(const char *filename_dir) {
int n, cnt = 0;
struct dirent **filename;
n = scandir(filename_dir, &filename, NULL, alphasort);
if (n < 0)
EXIT_MSG("scandir() Failed", EXIT_FAILURE);
else
while (n--) {
if (endWith(filename[n]->d_name, ".in"))
++cnt;
free(filename[n]);
}
free(filename);
return cnt;
}
char *baseName(char *name) {
char *p = basename(name);
size_t len = strlen(p);
p[len - 2] = 0;
return p;
}
int main(int argc, char *argv[], char *env[]) {
int result = ACCEPTED;
int num, total;
char temp[9], cmd[200];
char test_in[100], test_out[100], test_tmp[100];
if (3 != argc)
EXIT_MSG("Usage: main src.c filename_dir", EXIT_FAILURE);
randomString(temp, sizeof temp);
total = countTestdata(argv[2]);
snprintf(cmd, sizeof(cmd), "clang -o %s -Wall -lm %s", temp, argv[1]);
if (WEXITSTATUS(system(cmd)))
EXIT_MSG("Compile Error", EXIT_FAILURE);
for (num = 0; num < total; ++num) {
snprintf(test_in ,sizeof test_in, "%s/%d.in", argv[2], num);
snprintf(test_tmp, sizeof test_tmp, "%s.temp", temp);
switch (run(temp, test_in, test_tmp)) {
case SYSTEM_ERROR:
RAISE_MSG("System Error");
case RUNTIME_ERROR:
RAISE_MSG("Runtime Error");
case TIME_LIMIT_EXCEEDED:
RAISE_MSG("Time Limit Exceeded");
case MEMORY_LIMIT_EXCEEDED:
RAISE_MSG("Memory Limit Exceeded");
}
snprintf(test_out, sizeof test_out, "%s/%d.out", argv[2], num);
snprintf(test_tmp, sizeof test_tmp, "%s.temp", temp);
switch (check(test_out, test_tmp)) {
case OUTPUT_LIMIT_EXCEEDED:
RAISE_MSG("Output Limit Exceeded");
case PRESENTATION_ERROR:
RAISE_MSG("Presentation Error");
case WRONG_ANWSER:
RAISE_MSG("Wrong Anwser");
case SYSTEM_ERROR:
RAISE_MSG("System Error");
case ACCEPTED: ;
}
}
if (ACCEPTED == result)
printf("%s , %s Time: %ldMS Memory: %ldKB\n",
baseName(argv[1]), "Accepted", Time, Memory);
CLEAN:
snprintf(cmd, sizeof(cmd), "rm %s %s.temp", temp, temp);
if (WEXITSTATUS(system(cmd)))
EXIT_MSG("rm Failed", SYSTEM_ERROR);
return EXIT_SUCCESS;
}
<file_sep>#include "toy.h"
/*
when the tested source file has been compiled and
successfully produced the output file, this function
will perform the answer checking exercise.
*/
static int diff(const char *s1, const char *s2) {
while (*s1 && *s1 == *s2) {
++s1;
++s2;
}
if (!(*s1 || *s2))
return ACCEPTED;
for ( ; ; ) {
while (isspace(*s1))
s1++;
while (isspace(*s2))
s2++;
if (!(*s1 && *s2))
break;
if (*s1 != *s2)
return WRONG_ANWSER;
++s1;
++s2;
}
return (*s1 || *s2) ? WRONG_ANWSER : PRESENTATION_ERROR;
}
int main(int argc, char const *argv[])
{
int result;
char *right_out, *user_out;
off_t right_len, user_len;
int right_fd, user_fd;
if (3 != argc)
EXIT_MSG("Usage: diff out tmp", EXIT_FAILURE);
if ((right_fd = open(argv[1], O_RDONLY, 0644)) < 0)
EXIT_MSG("open(out) Failed.", SYSTEM_ERROR);
if ((user_fd = open(argv[2], O_RDONLY, 0644)) < 0)
EXIT_MSG("open(tmp) Failed.", SYSTEM_ERROR);
right_len = lseek(right_fd, 0, SEEK_END);
user_len = lseek(user_fd, 0, SEEK_END);
if (-1 == right_len || -1 == user_len)
EXIT_MSG("lseek() Failed", SYSTEM_ERROR);
if (MAX_OUTPUT <= user_len)
return OUTPUT_LIMIT_EXCEEDED;
if (0 == (right_len || user_len))
return ACCEPTED;
else if (0 == (right_len && user_len))
return WRONG_ANWSER;
lseek(right_fd, 0, SEEK_SET);
lseek(user_fd, 0, SEEK_SET);
if ((right_out = mmap(NULL, right_len, PROT_READ, MAP_PRIVATE, right_fd, 0)) == MAP_FAILED)
EXIT_MSG("mmap(right_out) Failed", SYSTEM_ERROR);
if ((user_out = mmap(NULL, user_len, PROT_READ, MAP_PRIVATE, user_fd, 0)) == MAP_FAILED)
EXIT_MSG("mmap(user_out) Failed", SYSTEM_ERROR);
result = diff(right_out, user_out);
munmap(right_out, right_len);
munmap(user_out, user_len);
close(right_fd);
close(user_fd);
return result;
}
<file_sep>#include "toy.h"
#include <time.h>
#include <dirent.h>
#include <libgen.h>
#define RAISE_MSG(msg) \
{ fprintf(stderr, "%s\n", msg); goto CLEAN; }
static int endWith(const char *haystack, const char *needle) {
size_t haystackLen = strlen(haystack);
size_t needleLen = strlen(needle);
if (haystackLen < needleLen)
return 0;
char *end = (char *)haystack + (haystackLen - needleLen);
return 0 == strcmp(end, needle);
}
static void randomString(char str[], size_t len) {
int i;
srand(time(NULL));
for (i = 0; i < len-1; ++i) {
str[i] = rand() %26 + 'a' ;
}
str[len - 1] = '\0';
}
static int countTestdata(const char *filename_dir) {
int n, cnt = 0;
struct dirent **filename;
n = scandir(filename_dir, &filename, NULL, alphasort);
if (n < 0)
EXIT_MSG("scandir() Failed", EXIT_FAILURE);
while (n--) {
if (endWith(filename[n]->d_name, ".in"))
++cnt;
free(filename[n]);
}
free(filename);
return cnt;
}
int main(int argc, char *argv[])
{
int num, total, iRetVal;
char temp[9], cmd[200];
char *relative_path;
if (3 != argc)
EXIT_MSG("Usage: main src.c filename_dir", EXIT_FAILURE);
randomString(temp, sizeof temp);
relative_path = dirname(argv[0]);
total = countTestdata(argv[2]);
snprintf(cmd, sizeof(cmd), "gcc -o %s -Wall -lm %s", temp, argv[1]);
iRetVal = system(cmd);
if (WEXITSTATUS(iRetVal))
EXIT_MSG("COMPILE_ERROR", EXIT_FAILURE);
for (num = 0; num < total; ++num) {
snprintf(cmd, sizeof(cmd), "%s/run %s %s/%d.in %s.temp",
relative_path, temp, argv[2], num, temp);
iRetVal = system(cmd);
if (WEXITSTATUS(iRetVal)) {
switch (WEXITSTATUS(iRetVal)) {
case SYSTEM_ERROR: RAISE_MSG("SYSTEM_ERROR");
case RUNTIME_ERROR: RAISE_MSG("RUNTIME_ERROR");
case TIME_LIMIT_EXCEEDED: RAISE_MSG("TIME_LIMIT_EXCEEDED");
case MEMORY_LIMIT_EXCEEDED: RAISE_MSG("MEMORY_LIMIT_EXCEEDED");
}
}
snprintf(cmd, sizeof(cmd), "%s/diff %s/%d.out %s.temp",
relative_path, argv[2], num, temp);
iRetVal = system(cmd);
if (WEXITSTATUS(iRetVal)) {
switch (WEXITSTATUS(iRetVal)) {
case OUTPUT_LIMIT_EXCEEDED: RAISE_MSG("OUTPUT_LIMIT_EXCEEDED");
case PRESENTATION_ERROR: RAISE_MSG("PRESENTATION_ERROR");
case WRONG_ANWSER: RAISE_MSG("WRONG_ANWSER");
case SYSTEM_ERROR: RAISE_MSG("SYSTEM_ERROR");
case ACCEPTED: printf("ACCEPTED\n");
}
}
}
CLEAN:
/*
snprintf(cmd, sizeof(cmd), "rm %s %s.temp", temp, temp);
iRetVal = system(cmd);
if (WEXITSTATUS(iRetVal))
EXIT_MSG("rm Failed", SYSTEM_ERROR);
*/
return EXIT_SUCCESS;
}
<file_sep># Lab-Online-Judge
BUPT C Lab Online Judge
<file_sep>#!/bin/bash
# only aided for Lab Online Judge
# core/judge.sh user_source.c problem_dir
if [ $# -ne 2 ]; then
echo "core/judge.sh source_file problem_dir"
exit 0
fi
# compose variable names
folder=`pwd`
folder=`dirname ${folder}/$0`
source=$1
problem=$2
# obtain base name with extension
name=`basename $source`
# strip suffix
name=${name%%.*}
# determine which compiler to exercise
suffix=${source##*.}
# try compiling the source file
case $suffix in
c) clang -o $name -Wall -lm -std=c11 $source
if [ 0 -ne $? ]; then
status="Compile Error"
echo $name , $status
exit 0
fi
;;
cpp) clang++ -o $name -Wall -std=c++11 $source
if [ 0 -ne $? ]; then
status="Compile Error"
echo $name , $status
exit 0
fi
;;
esac
#echo $folder/judge $name $problem
# compiled successfully, execute it and compare the output
status=`$folder/judge $name $problem`
# remove the binary executeable file
rm $name
# print the result and append it to destination
echo $name , $status | tee -a $problem/result
<file_sep>#include <stdio.h>
int main() {
int a, b;
while (2 == scanf("%d%d", &a, &b))
printf("%d\n", a+b);
int len = 0x4;
int s[len];
int *p = s;
for (int i = 0; i <= len+4; ++i)
*p++ = 0;
}
<file_sep>toy:
cc -o run run.c -O2
cc -o diff diff.c -O2
cc -o main main.c -O2
clean:
rm diff run main
<file_sep>/*
2016/6/8
Original Author: <NAME>
<<EMAIL>>
Let's say hello and good-bye to the world!
In this universe of beauty and grace, set
blank barrier to your forward path.
To be careful, make sure every system API
in this file has checked its return value.
*/
#include "common.h"
long Time;
long Memory;
/*
Check whether the value in REG_SYS_CALL(x)
is amongst the allowed system call list
*/
static int isAllowedCall(int syscall)
{
int i;
for (i = 0; -1 != strace[i]; ++i)
if (syscall == strace[i])
return 1;
return 0;
}
/*
Check whether the value in REG_ARG_1(x)
is amongst the legal library mapping list
*/
static int isValidAccess(const char *file)
{
int i;
for (i = 0; ltrace[i]; ++i)
if (0 == strcmp(file, ltrace[i]))
return 1;
return 0;
}
/*
a wrap-up function for setting up resource limit
*/
static void setResourceLimit()
{
struct rlimit limit;
limit.rlim_cur = MAX_TIME / 1000;
limit.rlim_max = MAX_TIME / 1000 + 1; // second(s)
if (setrlimit(RLIMIT_CPU, &limit))
MSG_ERR_EXIT(SYSTEM_ERROR, "Set Time Limit Failed");
limit.rlim_cur = MAX_STACK_SIZE;
limit.rlim_max = MAX_STACK_SIZE; // byte(s)
if (setrlimit(RLIMIT_STACK, &limit))
MSG_ERR_EXIT(SYSTEM_ERROR, "Set Memory Limit Failed");
#if 0
limit.rlim_cur = MAX_MEMORY * (1 << 20);
limit.rlim_max = MAX_MEMORY * (1 << 20); // byte(s)
/* The maximum size of the process's virtual memory (address space) in bytes */
if (setrlimit(RLIMIT_AS, &limit))
MSG_ERR_EXIT(SYSTEM_ERROR, "Set Memory Limit Failed");
#endif
}
#define kill_it(pid) ptrace(PTRACE_KILL, pid, NULL, NULL)
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
static int invalidAccess(pid_t pid, struct user_regs_struct *registers)
{
int i;
long access_file[16];
/* peek which file the process is about to open */
for (i = 0; i < ARRAY_SIZE(access_file); i++) {
access_file[i] = ptrace(PTRACE_PEEKDATA,
pid, REG_ARG_1(registers) + i * sizeof(long), NULL);
if (0 == access_file[i])
break;
}
if (!isValidAccess((const char*)access_file)) {
kill_it(pid);
MSG_ERR_RET(1, "Accessing File: \"%s\"\n", (const char*)access_file);
}
return 0;
}
int main(int argc, char *argv[])
{
int result = ACCEPTED;
int status;
struct rusage usage;
struct user_regs_struct regs;
if (2 != argc)
MSG_ERR_RET(EXIT_FAILURE, "Usage: %s executable\n", argv[0]);
const char *binary = argv[1];
pid_t child = fork();
/* fork a child to monitor(ptrace) its status */
if (0 == child) {
setResourceLimit();
if (ptrace(PTRACE_TRACEME, 0, NULL, NULL))
MSG_ERR_EXIT(SYSTEM_ERROR, "PTRACE_TRACEME Failed");
if (-1 == execl(binary, "", NULL))
MSG_ERR_EXIT(SYSTEM_ERROR, "execl() Failed");
}
/* assure that parent gets executed after child exits */
if (-1 == child) {
MSG_ERR_RET(SYSTEM_ERROR, "vfork() Failed");
}
for (;;) {
if (-1 == wait4(child, &status, WSTOPPED, &usage))
MSG_ERR_RET(SYSTEM_ERROR, "wait4() Failed");
/* child has already exited */
if (WIFEXITED(status)) {
if (SYSTEM_ERROR == WEXITSTATUS(status))
return SYSTEM_ERROR;
}
if (SIGTRAP != WSTOPSIG(status)) {
kill_it(child);
switch (WSTOPSIG(status)) {
case SIGSEGV:
result = RUNTIME_ERROR;
//MSG_ERR_RET(RUNTIME_ERROR, "SIGSEGV");
break;
case SIGALRM:
case SIGKILL:
case SIGXCPU:
result = TIME_LIMIT_EXCEEDED;
break;
}
}
/* unable to peek register info */
if (-1 == ptrace(PTRACE_GETREGS, child, NULL, ®s))
goto END;
if (!isAllowedCall(REG_SYS_CALL(®s))) {
kill_it(child);
char cmd[1024];
snprintf(cmd, sizeof(cmd), "grep -E "
"'*SYS.*.[[:space:]]%llu$'"
" /usr/include/x86_64-linux-musl/bits/syscall.h"
" | gawk -F' ' '{print $2}' 1>&2", REG_SYS_CALL(®s));
system(cmd);
MSG_ERR_RET(RUNTIME_ERROR, "Invalid Syscall");
}
/* watch what the child is going to open */
if (SYS_open == REG_SYS_CALL(®s)) {
if (invalidAccess(child, ®s))
MSG_ERR_RET(RUNTIME_ERROR, "Invalid Access");
}
/* allocate too much from data section */
if (SYS_writev == REG_SYS_CALL(®s))
MSG_ERR_RET(MEMORY_LIMIT_EXCEEDED, "ENOMEM on BSS/DATA");
/* trace next system call */
if (-1 == ptrace(PTRACE_SYSCALL, child, NULL, NULL))
MSG_ERR_RET(SYSTEM_ERROR, "PTRACE_SYSCALL Failed");
}
END:
Time = usage.ru_utime.tv_sec * 1000 + usage.ru_utime.tv_usec / 1000
+ usage.ru_stime.tv_sec * 1000 + usage.ru_stime.tv_usec / 1000;
Memory = usage.ru_maxrss * (sysconf(_SC_PAGESIZE) / 1024) / 1024;
if (MAX_MEMORY <= Memory)
result = MEMORY_LIMIT_EXCEEDED;
if (ACCEPTED == result)
fprintf(stderr, "TIME: %ldMS MEM: %ldMB\n", Time, Memory);
return result;
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <fcntl.h>
int main()
{
int a;
int b;
while (2 == scanf("%d%d", &a, &b))
printf("%d\n", a + b);
}
<file_sep>#!/bin/bash
# only aided for Lab Online Judge
result=(
"UN-USED"
"Accepted"
"Compile Error"
"Memory Limit Exceeded"
"Output Limit Exceeded"
"Runtime Error"
"System Error"
"Time Limit Exceeded"
"Presentation Error"
"Wrong Anwser"
)
# OJ user_source.c testdata_directory
if [ $# -ne 2 ]; then
echo "$0 source_file testdata_directory"
exit 0
fi
# compose variable names
folder=`pwd`
folder=`dirname ${folder}/$0`
source=$1
problem=$2
# obtain base name with extension
name=`basename $source`
# strip suffix
name=${name%%.*}
# determine which compiler to exercise
suffix=${source##*.}
# try compiling the source file
case $suffix in
c) clang -o $name -Wall -lm -std=c11 $source
;;
cpp) clang++ -o $name -Wall -std=c++11 $source
;;
*) echo "Unsupported language type."
;;
esac
if [ 0 -ne $? ]; then
status="Compile Error"
fi
if [ -z "$status" ]; then
# compiled successfully, execute it and compare the output
in=`ls $problem/*.in`
tmpfile=`openssl rand -hex 5`
for infile in $in; do
outfile=${infile%.*}.out
$folder/SANDBOX $name < $infile > $tmpfile
status=${result[$?]}
# successfully pass the execute path
if [ "$status" != ${result[1]} ]; then
break
else
$folder/COMPARE $outfile $tmpfile
status=${result[$?]}
# drop hints for what's wrong
if [ "$status" != ${result[1]} ]; then
$folder/HINT $infile $outfile $tmpfile
break
fi
fi
done
# remove the binary executeable file
rm $name $tmpfile
fi
# print the result and append it to destination
echo -e "\n$name , $status" | tee -a $problem/result
<file_sep>#include <stdio.h>
int main() {
int a, b;
int num = 0xffff;
while (2 == scanf("%d%d", &a, &b))
printf("%d\n", a+b);
while (num--)
printf("%d\n", a+b);
}
<file_sep>toy:
cc -o main main.c -Wall -O2
clean:
rm main
|
2f73b728b45293c774d5343751c5d01a6764eba9
|
[
"Markdown",
"C",
"Makefile",
"Shell"
] | 35 |
C
|
Maxul/Lab-Online-Judge
|
ca535e56740755312ed681095c83c144fabaccbe
|
85830ed139a8575c59210b9aea7955bf5b078e60
|
refs/heads/main
|
<file_sep>filename = input("Input the Filename: ")
f_extns = filename.split(".")
my_dict = {"c":"C","cpp":"C++","py":"Python","java":"Java"}
print ("The extension of the file is : " + my_dict[f_extns[-1]])
|
d8d08dae558499464f945ed4f4128b71e447be10
|
[
"Python"
] | 1 |
Python
|
SoumiliSahu/Extension-of-the-file
|
9bad1d02f1c9d890ac8d60fcbbfefc09fe1e9323
|
e856ba0912d1cf9376b7f2ba5d99c5ccf1577e1e
|
refs/heads/master
|
<file_sep># Spring boot with Rest & Soap at the same time
Generate Sources from wsdl file with `mvn generate-sources`
### Endpoints
* Rest: http://localhost:8080/home
* Soap: http://localhost:8080/soap-api/helloworld.wsdl<file_sep>package com.guilherme.miguel.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
* @author <NAME>
*/
@RestController
public class HomeController {
@GetMapping("home")
public Map<String, Object> home() {
Map<String, Object> data = new HashMap<>();
data.put("id", 1);
data.put("name", "<NAME>");
return data;
}
}
|
472bd1b162e8b0133a4714d56fb8150809cf0142
|
[
"Markdown",
"Java"
] | 2 |
Markdown
|
mguilherme/rest-soap
|
a306e306149e5172d5ce0b3b7c8f5e2c2660450f
|
7eaa36ff5cb4695132fb55c2ef25f6500c7ffff4
|
refs/heads/master
|
<file_sep>package main
import (
"bufio"
"bytes"
"crypto/tls"
"encoding/csv"
"fmt"
"html/template"
"io"
"io/ioutil"
"math/rand"
"net/mail"
"net/url"
"os"
"reflect"
"strconv"
"strings"
"time"
"github.com/dajohi/goemail"
)
type Participant struct {
ID int64
Name string
Gender string
SpouseID int64
MatchID *int64
EmailAddress string
Wishlist string
}
type EmailTemplateData struct {
Name string
Pronoun string
Wishlist []string
}
type smtp struct {
client *goemail.SMTP // SMTP client
mailName string // Email address name
mailAddress string // Email address
}
var (
participants map[int64]*Participant
orderedParticipantsIDs []int64
smtpClient *smtp
cfg map[string]string
emailTemplate *template.Template
)
func main() {
rand.Seed(time.Now().Unix())
readConfigFromFile("config.txt")
readParticipantsFromFile("participants.csv")
for {
fmt.Println("Attempting matchmaking...")
if attemptMatchMaking(participants, orderedParticipantsIDs) {
fmt.Println("Matchmaking successful!")
break
}
}
if _, ok := cfg["mailhost"]; ok {
fmt.Println("Sending emails...")
sendEmails()
} else {
fmt.Printf("No email config found, printing results:\n\n")
for _, p := range participants {
fmt.Printf("%s -> %s\n", p.Name, participants[*p.MatchID].Name)
}
}
}
func readParticipantsFromFile(filePath string) {
f, err := os.Open(filePath)
defer f.Close()
check(err)
reader := csv.NewReader(f)
reader.Comment = '#'
lines, err := reader.ReadAll()
check(err)
participants = make(map[int64]*Participant, len(lines))
orderedParticipantsIDs = make([]int64, 0, len(lines))
for _, line := range lines {
id, err := strconv.ParseInt(line[0], 10, 64)
check(err)
spouseID, err := strconv.ParseInt(line[3], 10, 64)
check(err)
participants[id] = &Participant{
ID: id,
Name: line[1],
Gender: line[2],
SpouseID: spouseID,
EmailAddress: line[4],
Wishlist: line[5],
}
orderedParticipantsIDs = append(orderedParticipantsIDs, id)
}
}
func attemptMatchMaking(participants map[int64]*Participant,
orderedParticipantsIDs []int64) bool {
unmatchedParticipantsIDs := map[int]int64{}
for idx, id := range orderedParticipantsIDs {
unmatchedParticipantsIDs[idx] = id
}
for _, id := range orderedParticipantsIDs {
//fmt.Printf("Matching %s... ", participants[id].Name)
for {
// Grab a random index into the array of unmatched participants.
unmatchedParticipantsIndices := reflect.ValueOf(
unmatchedParticipantsIDs).MapKeys()
keyIdx := rand.Intn(len(unmatchedParticipantsIndices))
matchIdx := unmatchedParticipantsIndices[keyIdx].Interface().(int)
matchID := unmatchedParticipantsIDs[matchIdx]
if matchID != id && matchID != participants[id].SpouseID {
participants[id].MatchID = &matchID
delete(unmatchedParticipantsIDs, matchIdx)
//fmt.Printf("matched with %s\n", participants[matchID].Name)
break
}
if len(unmatchedParticipantsIDs) <= 2 {
fmt.Printf("\nRan out of participants to match with, starting over\n")
// We ended up with
return false
}
}
}
return true
}
func sendEmails() {
initEmailClient()
initEmailTemplate()
for _, participant := range participants {
match := participants[*participant.MatchID]
templateData := EmailTemplateData{
Name: match.Name,
}
if len(match.Wishlist) == 0 {
templateData.Wishlist = []string{
"(not provided)",
}
} else {
templateData.Wishlist = strings.Split(match.Wishlist, ",")
}
if strings.Compare(match.Gender, "Male") == 0 {
templateData.Pronoun = "his"
} else {
templateData.Pronoun = "her"
}
var buf bytes.Buffer
err := emailTemplate.Execute(&buf, templateData)
check(err)
sendEmail(participant.EmailAddress, "Secret Santa 2019", buf.String())
}
}
func initEmailClient() {
// Parse mail host
h := fmt.Sprintf("smtps://%v:%v@%v", cfg["mailuser"], cfg["mailpass"],
cfg["mailhost"])
u, err := url.Parse(h)
check(err)
// Parse email address
a, err := mail.ParseAddress(cfg["mailaddr"])
check(err)
// Config tlsConfig based on config settings
tlsConfig := &tls.Config{
InsecureSkipVerify: true,
}
// Initialize SMTP client
client, err := goemail.NewSMTP(u.String(), tlsConfig)
check(err)
smtpClient = &smtp{
client: client,
mailName: a.Name,
mailAddress: a.Address,
}
}
func initEmailTemplate() {
buf, err := ioutil.ReadFile("email.htmlt")
check(err)
emailTemplate, err = template.New("email").Parse(string(buf))
check(err)
}
func sendEmail(toAddress, subject, body string) {
msg := goemail.NewHTMLMessage(cfg["mailaddr"], subject, body)
msg.AddTo(toAddress)
msg.SetName(smtpClient.mailName)
err := smtpClient.client.Send(msg)
check(err)
}
func readConfigFromFile(filePath string) map[string]string {
f, err := os.Open(filePath)
defer f.Close()
check(err)
r := bufio.NewReader(f)
cfg = make(map[string]string)
for {
t, _, err := r.ReadLine()
if err == io.EOF {
break
}
check(err)
if len(t) == 0 {
break
}
s := strings.Split(string(t), "=")
cfg[s[0]] = s[1]
}
return cfg
}
func check(e error) {
if e != nil {
panic(e)
}
}
|
d4db60be395af7d409ed51bf9bf63d6c07a1148f
|
[
"Go"
] | 1 |
Go
|
sndurkin/secret-santa
|
7545237e45781f312cd42ab5f790b53eaf69f6e2
|
ca54505094f078acd18ebe80d16f447c5ecdfa81
|
refs/heads/master
|
<file_sep>#include "parse_functions.h"
char * lastIndexOf(char * phrase, char key) {
char * location = NULL;
//We don't know the length, so we walk through the string from beginning to end
do {
if(*phrase == key){
location = phrase;
}
}while(*(++phrase));
return location;
}
int stringToArray(char * theString, int max_len, char* delim, char ** theArray) {
int arrayIndex = 0;
//Tokenize first element, store in array
theArray[arrayIndex++] = strtok(theString, delim);
//Tokenize the rest of the elements
while(arrayIndex < max_len && (theArray[arrayIndex++] = strtok(NULL, delim)) != NULL)
;
// for(int i=1; theArray[i-1] != NULL && i < max_len; i++)
// theArray[i] = strtok(NULL, delim);
return arrayIndex-1;
}<file_sep>#include <stdio.h>
#include <string.h>
int stringToArray(char *, int, char*, char **);
char *lastIndexOf(char *, char);<file_sep>IDIR=.
CC=gcc
CFLAGS=-std=c99
SDIR=src
ODIR=obj
LIBS=-Wall -Werror
_DEPS = minishell.h parse_functions.h
DEPS = $(patsubst %,$(IDIR)/$(SDIR)/%,$(_DEPS))
_OBJ = minishell.o parse_functions.o
OBJ = $(patsubst %,$(ODIR)/%,$(_OBJ))
$(ODIR)/%.o : $(SDIR)/%.c $(DEPS)
$(CC) -c -o $@ $< $(CFLAGS)
minishell: $(OBJ)
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
run: minishell
./minishell
.PHONY: clean
clean:
rm -f $(ODIR)/*.o *~ core $(IDIR)/*~
<file_sep>A lightweight shell for executing commands.
More functionality to come.
<file_sep>This directory are where the object files saved to.
If you are moving your already compiled minishell program to another device, you will need to recompile the object files.
To do so: please enter "make clean ; make run" in the main directory to run the program for the first time on the new device.
<file_sep>#include "parse_functions.h"
#include "minishell.h"
int main(int argc, char *argv[], char *envp[])
{
startShell(envp);
return 0;
}
int startShell(char *envp[]) {
char commandLine[LINE_LEN];
char *pathv[MAX_PATHS];
int child_pid;
int stat;
//pid_t thisChPID;
prompt_s prompt;
command_s command;
initShell(&prompt, &command); // Shell initialization
// get all directories from PATH env var
parsePath(pathv);
// Main loop
while(TRUE) {
// Print the prompt
printPrompt(&prompt);
// Read the command line
readCommand(commandLine);
// Quit the shell ?
if( (strcmp(commandLine, "exit") == 0) ||
(strcmp(commandLine, "quit") == 0) )
break;
// Parse the command line
if(!prepareCommandForExecution(commandLine, &command, pathv)) {
continue; //Non lethal error occured
}
// child process pid
// used by parent wait
// create child process to execute the command
// (be careful with the pipes, you need to re-direct the
// output from the child to stdout to display the results)
// wait for the child to terminate
//--- Fork, Exec, Wait process ---
createRunProc(&command, envp);
}
deallocShellVars(&command);
printf("Terminating Mini Shell\n");
// Shell termination
return 0;
}
void initShell(prompt_s * prompt, command_s * command) {
//Prompt initialization
prompt->shell = shellName;
prompt->cwd = (lastIndexOf(getenv("PWD"), '/'))+1;
prompt->user = getenv("USER");
//Command initialization
command->name = (char *) malloc(MAX_ARG_LEN);
// for(int i=0; i < MAX_ARGS; i++) {
// command->argv[i] = (char *) malloc(MAX_ARG_LEN);
// }
}
void parsePath(char ** pathv) {
//Pointer to PATH environment variable
char * thePath;
//Point to the path
thePath = getenv("PATH");
// Initialize all locations in path to null before store
for(int i=0; i< MAX_PATHS; i++)
pathv[i] = NULL;
//Tokenize the path and store each token in pathv
stringToArray(thePath,MAX_PATHS, ":", pathv);
if(DEBUG){
//Print the contents of pathv after store
printf("PATH variable:\n");
for(int i=0; pathv[i] != NULL && i < MAX_PATHS; i++)
printf("%s\n", pathv[i]);
}
}
void printPrompt(prompt_s *prompt) {
printf("%s %s:%s$ ", prompt->shell, prompt->user, prompt->cwd);
}
void readCommand(char * inputString) {
if((scanf(" %[^\n]", inputString)) <= 0) {
perror("Invalid string was read\n");
inputString = NULL;
}
}
int prepareCommandForExecution(char * commandLine, command_s * command, char ** pathv) {
//Tokenize commandline into the command_S argument array
command->argc = stringToArray(commandLine, MAX_ARGS, WHITESPACE, command->argv);
// Get the full path name
if(lookupPath(command->name, command->argv[0], pathv) == NULL) {
printf("Invalid command\n"); //Cannot find command
return NON_LETHAL_ERROR;
}
// Display each parsed token
if(DEBUG) {
printf("ParseCommand: ");
for(int j=0; j<command->argc; j++)
printf(" %s, ",command->argv[j]);
printf("\n");
}
//If file found is not executable
if(access(command->name, X_OK) != 0)
{
printf("The command \"%s\" is not executable\n", command->name);
return NON_LETHAL_ERROR;
}
return TRUE;
}
char *lookupPath(char * name, char * argv, char ** dirs) {
char * result = (char *)malloc(MAX_ARG_LEN); //To store command location
int fileExists; //Set if file exists
// if absolute path (/) or relative path (. , ..)
if((argv[0] == '/' || argv[0] == '.') && (fileExists = access(argv, F_OK))) {
return strcpy(name, argv);
}
//Search the path for the file.
//Attach paths to command until file is found
//or not found.
int dirIndex = 0;
do
{ //Copy and concat onto the result string the
//absolute paths and command.
strcpy(result, dirs[dirIndex]);
strcat(result, "/");
strcat(result, argv);
fileExists = access(result, F_OK); //Exists?
dirIndex++;
}while(dirs[dirIndex] != NULL && fileExists != 0);
strcpy(name, result);
free(result);
//If the file exists, return the string
if(fileExists == 0) {
return strcpy(name, result);
} else {
return name = NULL;
}
}
void createRunProc(command_s * command, char * envp[])
{
int child_pid; // Child process PID
int stat; // used by parent wait
pid_t thisChPID; // This process's PID
short runBackground = FALSE; //CHANGE THIS: Implement in command structuer itself
thisChPID = fork();
if(command->argc > 1 && strcmp(command->argv[command->argc-1],"&")==0 ) {
//printf("& passed as back\n");
command->argv[command->argc-1] = NULL;
runBackground = TRUE;
}
if(thisChPID < 0) { // Failed fork
perror("Error, failed to fork command\n");
}
else if(thisChPID == 0) { // This is the child prcess. Execute command.
if(execve(command->name, command->argv, envp) == -1) {
perror("Error, failed to execute command\n");
}
} else { //Must be parent, wait for child
if(runBackground == FALSE) {
child_pid = wait(&stat);
} else {
printf("BG [%i]\n", thisChPID);
}
}
}
void deallocShellVars(command_s * command) {
printf("name\n");
free(command->name);
}
<file_sep>#define DEBUG 1
#define FALSE 0
#define TRUE 1
#define LINE_LEN 80
#define MAX_ARGS 64
#define MAX_ARG_LEN 64
#define MAX_PATHS 64
#define MAX_PATH_LEN 96
#define MAX_COMMANDS 16
#define WHITESPACE " \t"
#define COMMAND_SEP ";"
#define STD_INPUT 0
#define STD_OUTPUT 1
#define NON_LETHAL_ERROR 0
#ifndef NULL
#define NULL 0
#endif
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <unistd.h>
//Structure for shell command
typedef struct _command_s {
char *name;
int argc;
char *argv[MAX_ARGS];
}command_s;
//Structure for shell prompt
typedef struct _prompt_s {
char *shell;
char *cwd;
char *user;
}prompt_s;
//Main shell functions
int startShell(char **);
int prepareCommandForExecution(char *, command_s *, char **);
char *lookupPath(char *, char *, char **);
void parsePath(char **);
void printPrompt(prompt_s *);
void readCommand(char *);
void initShell(prompt_s *, command_s *);
// int stringToArray(char *, int, char*, char **);
void createRunProc(command_s *, char **);
// char *lastIndexOf(char *, char);
void deallocShellVars(command_s *);
//Prompt strings
char *shellName = "minsh";
char *cwd = "";
char *user = "";
|
bff26743c6366bca016ec79d9e2b317e97597ea5
|
[
"Markdown",
"C",
"Text",
"Makefile"
] | 7 |
C
|
gargirou/minishell
|
a930e807dcdb17e00830f01381a6ee475b411284
|
7c26e5e4674d26aac35c3c0920f090f6ea9b321e
|
refs/heads/master
|
<file_sep>#include "node.h"
using namespace std;
node::node()
{
id = 0;
arrival_time = 0;
age = 0;
tickets = 0;
priority= 0;
quota = ((10 - priority) * 10) / 5;
processed_tickets = 0;
runs = 0;
ready = 0;
end = 0;
running_time = 0;
last_running_time = 0;
waiting_time = 0;
}
node::node(int id, int at, int p, int a, int t)
{
this->id = id;
arrival_time = at;
age = a;
tickets = t;
priority= p;
quota = ((10 - priority) * 10) / 5;
processed_tickets = 0;
runs = 0;
ready = 0;
end = 0;
running_time = 0;
last_running_time = 0;
waiting_time = 0;
}<file_sep>#include "node.h"
#include <string>
class linked{
node *head;
node *tracker;
node *tail;
public:
linked();
void process(linked *finished);
void add(node *n);
bool isEmpty();
void print();
void to_finished();
void to_linked_two();
void to_linked_one();
};<file_sep>#include <iostream>
#include "node.h"
using namespace std;
int main(){
node *n1 = new node();
node *n2 = n1;
n1 = NULL;
cout << n2->id << endl;
cout << n1->id << endl;
}<file_sep>#include "linked.h"
#include <iostream>
using namespace std;
linked::linked()
{
head = NULL;
tracker = NULL;
tail = NULL;
}
void linked::add(node *n)
{
if (head == NULL)
{
head = n;
tail = n;
}
else
{
tail->next = n;
tail = tail->next;
tail->next = NULL;
cout << "added when finished" << endl;
}
}
bool linked::isEmpty()
{
if (head == NULL)
{
return true;
}
else
{
return false;
}
}
void linked::process(linked *finished)
{
if (head->processed_tickets < head->quota && head->tickets > 0)
{
head->processed_tickets++;
head->tickets--;
head->running_time += 5;
cout << head->id << " " << head->processed_tickets << " " << head->tickets << " " << head->running_time << endl;
}
else
{
head->runs++;
if (head->tickets == 0)
{
//to finished
//new head of queue 1 is the next node
if (head->next != NULL)
{
head = head->next;
//add to finished queue
if (finished->head == NULL)
{
finished->head = head;
finished->tail = head;
finished->tail->next = NULL;
cout << "To finished not null -- finished null" << endl;
}
else
{
finished->tail->next = head;
finished->tail = head;
finished->tail->next = NULL;
cout << "To finished not null -- finished not null" << endl;
}
}
//new head of queue 1 is null
else
{
if (finished->head == NULL)
{
finished->head = head;
finished->tail = head;
cout << "To finished null -- finished null" << endl;
}
else
{
finished->tail->next = head;
finished->tail = head;
finished->tail->next = NULL;
cout << "To finished null -- finished not null" << endl;
}
head = NULL;
}
}
else if (head->runs % 2 == 0)
{
//to queue 2
}
else
{
//to subqueue
if (head->next != NULL)
{
head->processed_tickets = 0;
tail->next = head;
tail = head;
head = head->next;
cout << "is to subqueue with non null head next" << endl;
}
}
}
}
void linked::print()
{
tracker = head;
while (tracker != NULL)
{
cout << tracker->id << " " << tracker->arrival_time << " " << tracker->tickets << " " << tracker->running_time << " " << tracker->priority << " " << tracker->runs << endl;
tracker = tracker->next;
}
}<file_sep>/*
created by:<NAME>, student2
ID:a1709743, student2_Id(for undergraduate)
time:06.08.2020
Contact Email:
Include int main(int argc,char *argv[])
input: argv[1]
output: Screen
input sample:
ID arrival_time priority age total_tickets_required
for example: s1 3 1 0 50
output sample:
ID, arrival and termination times, ready time and durations of running and waiting
*/
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <fstream>
#include <numeric>
#include <iomanip>
#include <bitset>
#include <list>
#include <stdexcept>
#include <functional>
#include <utility>
#include <ctime>
#include "linked.h"
using namespace std;
void output()
{
string result;
int i;
cout << "name arrival end ready running waiting" << endl;
for (i = 0; i < result.size(); i++) // every result
{
}
cout << endl;
}
int main(int argc, char *argv[])
{
int i, j, k;
freopen(argv[1], "r", stdin);
node *n1 = new node(0, 0, 1, 0, 46);
node *n2 = new node(1, 0, 1, 0, 20);
node *n3 = new node(2, 0, 1, 0, 38);
linked *q1 = new linked();
q1->add(n1);
q1->add(n2);
q1->add(n3);
linked *f = new linked();
q1->print();
for (int i = 0; i < 2000; i = i + 5)
{
if (q1->isEmpty() == false)
{
cout << i << " ";
q1->process(f);
//cout << "is false" << i << endl;
}
else
{
// cout << "is true" << i << endl;
break;
}
}
f->print();
// initial(); // initial data
// input(); // input data
// works(); // process data
// output(); // output result
return 0;
}
<file_sep>#include <string>
class node
{
public:
//input
int id;
int arrival_time;
int priority;
int age;
int tickets;
//process
int quota;
int processed_tickets;
int runs;
//output
int ready;
int end;
int running_time;
int waiting_time;
node *next;
node();
node(int id, int at, int a, int t, int);
void decrease_priority();
void process();
void wait();
};
|
b2cbca1e21596a31fbe9996b64d64a39a20ecd73
|
[
"C++"
] | 6 |
C++
|
carlos2354/OS-assignment1
|
e754585a9175d06175ad9347fd21ce1957f5e948
|
d61d64fef65022dc82eeecf23854c02568116493
|
refs/heads/master
|
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Modul extends Model
{
protected $table = 'm_modul';
public $timestamps = false;
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use App\User;
use App\HakAkses;
use App\Modul;
use App\PCLPNU;
use App\Kategori;
use App\LevelPengusaha;
use App\Jabatan;
use DB;
class MasterController extends Controller
{
public function getDataMaster(){
$master['hak-akses']=HakAkses::get();
$master['modul']=Modul::get();
$master['pc-lpnu']=PCLPNU::get();
$master['kategori']=Kategori::get();
$master['level-pengusaha']=LevelPengusaha::get();
$master['jabatan']=Jabatan::get();
return $master;
}
public function getModulSidebar($parent){
$modul=Modul::where('parent','=',$parent)->orderBy('urutan')->get();
foreach ($modul as $key => $value) {
$modul[$key]->submodul=$this->getModulSidebar($value->id);
}
return $modul;
}
public function dashboard(){
$modul=$this->getModulSidebar(0);
return view('admin-page.dashboard')
->with('modul',$modul);
}
//---------------------------------------------------------------------------------------------------//
//---------------------------------------------MASTER USER-------------------------------------------//
//---------------------------------------------------------------------------------------------------//
//Ambil Data User per Page
public function getUser($search,$page){
//DB::statement("set sql_mode=''");
//DB::statement("set global sql_mode=''");
$perpage = 10;
$query=User::select('m_user.*','m_hak_akses.hak_akses','pc_lpnu.nama_cabang')
->leftJoin('pc_lpnu','pc_lpnu.id','m_user.fid_pc_lpnu')
->join('m_hak_akses','m_hak_akses.id','=','m_user.fid_hak_akses');
if($search != 'all'){
$search = explode('=',$search);
$query = $query->whereRaw("(m_user.nama_lengkap LIKE '%".$search[1]."%' or m_hak_akses.hak_akses LIKE '%".$search[1]."%' )");
}
$data['datatotal'] = $query->count();
$data['pagetotal'] = ceil($query->count() / $perpage);
$data['perpage'] = $perpage;
$data['pageposition'] = $page;
$result = $query->skip(($page-1)*$perpage)->take($perpage)->get();
$data['data'] = $result;
return $data;
}
//Cari Data User
public function searchUser(Request $request){
if($request->input('search') != ''){
$restrict = array('/');
$keyword = str_replace($restrict,"",$request->input('search'));
$search = 'search='.$keyword;
return redirect('admin/master/user/'.$search);
}
else{
return redirect('admin/master/user');
}
}
//Return View User
public function user($search='all',$page=1){
$master=$this->getDataMaster();
$data=$this->getUser($search,$page);
$modul=$this->getModulSidebar(0);
return view('admin-page.data-master.user')
->with('search',$search)
->with('master',$master)
->with('modul',$modul)
->with('data',$data);
}
//Proses Data User
public function prosesUser(Request $request, $action='save'){
if($action=='save'){
if($request->id==0){
$kolom=new User;
}
else{
$kolom=User::find($request->id);
}
$kolom->username=$request->username;
$kolom->nama_lengkap=$request->nama_lengkap;
if(!empty($request->password)){
$kolom->password=encrypt($request->password);
}
$kolom->fid_hak_akses=$request->hak_akses;
$kolom->fid_pc_lpnu=$request->pc_lpnu;
$kolom->email=$request->email;
$kolom->no_hp=$request->hp;
$kolom->save();
return redirect('admin/master/user')
->with('message','Master User berhasil disimpan')
->with('message_type','success');
}
else{
$pisah=explode('=',$action);
$kolom=User::find($pisah[1]);
$kolom->delete();
return redirect('admin/master/user')
->with('message','Master User berhasil dihapus')
->with('message_type','success');
}
}
//----------------------------------------------------------------------------------------------------//
//---------------------------------------------MASTER MODUL-------------------------------------------//
//----------------------------------------------------------------------------------------------------//
//Ambil Modul per Parent
public function getModul(){
$data=Modul::get();
foreach ($data as $key => $value) {
$parent_modul=Modul::find($value->parent);
if(!empty($parent_modul)){
$data[$key]->parent_modul=$parent_modul->nama_modul;
}
else{
$data[$key]->parent_modul='Tidak Mempunyai Sub Modul';
}
}
return $data;
}
//Return View Modul
public function modul(){
$data=$this->getModul();
$master=$this->getDataMaster();
$modul=$this->getModulSidebar(0);
return view('admin-page.data-master.modul')
->with('master',$master)
->with('modul',$modul)
->with('data',$data);
}
public function prosesModul(Request $request, $action='save'){
if($action=='save'){
if($request->id==0){
$kolom=new Modul;
}
else{
$kolom=Modul::find($request->id);
}
$kolom->nama_modul=$request->nama_modul;
$kolom->jenis_data=$request->jenis_data;
$kolom->parent=$request->parent;
$kolom->icon=$request->icon;
$kolom->save();
return redirect('admin/master/modul')
->with('message','Master Modul berhasil disimpan')
->with('message_type','success');
}
else{
$pisah=explode('=',$action);
$kolom=Modul::find($pisah[1]);
$kolom->delete();
return redirect('admin/master/modul')
->with('message','Master Modul berhasil dihapus')
->with('message_type','success');
}
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use App\MultiplePost;
use App\Modul;
use App\PCLPNU;
use App\KategoriPosting;
use App\Quote;
use DB;
class DashboardController extends Controller
{
//Get Data Posting
public function getPost($modul,$kategori,$headline,$limit,$offset){
$data=MultiplePost::select('multiple_post.*','m_modul.nama_modul')
->join('m_user','m_user.id','multiple_post.fid_user')
->join('m_modul','m_modul.id','multiple_post.fid_modul')
->leftJoin('pc_lpnu','pc_lpnu.id','multiple_post.fid_pc_lpnu');
if($modul!='all'){
$data=$data->where('multiple_post.fid_modul','=',$modul);
}
if($kategori!='all'){
$data=$data->join('kategori_post','kategori_post.fid_posting','multiple_post.id')
->where('kategori_post.fid_kategori','=',$kategori);
}
if($headline=='1'){
$data=$data->where('multiple_post.headline','=','1');
}
$data=$data->limit($limit)->get();
return $data;
}
public function index(){
$data['headline-post']=$this->getPost('all','all',1,5,0);
$data['berita-post-single']=$this->getPost(1,'all','all',1,0);
$data['berita-post']=$this->getPost(1,'all','all',4,0);
$data['agenda-post-single']=$this->getPost(2,'all','all',1,0);
$data['agenda-post']=$this->getPost(2,'all','all',4,0);
$data['pesantren-post']=$this->getPost('all',1,'all',5,0);
$data['koperasi-post']=$this->getPost('all',2,'all',5,0);
$data['quote']=Quote::where('tampil','=','1')->limit('5')->get();
return view('website.dashboard')->with('data',$data);
}
}
<file_sep><?php
Route::get('storage/{folder}/{filename}', function ($folder,$filename){
$path = storage_path('app/' . $folder . '/' . $filename);
if (!File::exists($path)) {
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
});
//-------------------------------------------------------------------------------//
//-------------------------------WEBSITE-PAGE------------------------------------//
//-------------------------------------------------------------------------------//
// Route::get('/', function () {
// return view('website.dashboard');
// });
Route::get('/','DashboardController@index');
Route::get('about/{submenu}/{id?}','AboutController@index');
Route::get('post/{modul}/list/{kategori?}/{pc_lpnu?}/{search?}/{page?}','PostController@index');
Route::get('post-detil/{modul}/{id?}','PostController@detil');
Route::get('pc-lpnu','PCLPNUController@index');
Route::get('pc-lpnu/{id}/{tab?}/{kategori?}/{search?}/{page?}','PCLPNUController@detil');
Route::get('pengusaha/list/{pc_lpnu?}/{level?}/{search?}/{page?}','PengusahaController@index');
Route::get('pengusaha/detil/{id}','PengusahaController@detilWebsite');
//-------------------------------------------------------------------------------//
//---------------------------------ADMIN-PAGE------------------------------------//
//-------------------------------------------------------------------------------//
Route::get('admin/login','AuthController@index');
Route::post('admin/login/proses','AuthController@login');
Route::group(['middleware' => ['ceklogin']],function(){
Route::get('admin/logout','AuthController@logout');
Route::get('admin','MasterController@dashboard');
Route::post('admin/master/user/search','MasterController@searchUser');
Route::post('admin/master/user/proses/{action?}','MasterController@prosesUser');
Route::get('admin/master/user/{search?}/{page?}','MasterController@user');
Route::post('admin/pc-lpnu/search','PCLPNUController@search');
Route::post('admin/pc-lpnu/proses/{action}/{id}','PCLPNUController@proses');
Route::get('admin/pc-lpnu/list/{search?}/{page?}','PCLPNUController@admin');
Route::get('admin/pc-lpnu/form/{action?}/{id?}','PCLPNUController@form');
Route::get('admin/master/modul','MasterController@modul');
Route::post('admin/master/modul/proses/{action?}','MasterController@prosesModul');
Route::get('admin/post/{modul}/list/{kategori?}/{pc_lpnu?}/{search?}/{page?}','PostController@admin');
Route::get('admin/post/{modul}/form/{parameter?}','PostController@form');
Route::post('admin/post/{modul}/proses/{parameter}','PostController@proses');
Route::post('admin/post/{modul}/search','PostController@search');
Route::post('admin/post/{modul}/filter','PostController@filter');
Route::get('admin/about/{modul}/{id?}/{search?}/{page?}','AboutController@admin');
Route::post('admin/about/proses/{modul}/{parameter}','AboutController@proses');
Route::post('admin/pengurus/proses/{action?}','AboutController@prosesPengurus');
Route::post('admin/gallery/{id}/proses/{action?}','AboutController@prosesGallery');
Route::get('admin/kontak','KontakController@admin');
Route::post('admin/kontak/proses','KontakController@proses');
Route::post('admin/pengusaha/search','PengusahaController@searchPengusaha');
Route::post('admin/pengusaha/proses/{action?}/{id?}','PengusahaController@prosesPengusaha');
Route::post('admin/pengusaha/detil/{id}/proses/{action?}','PengusahaController@prosesUnitUsaha');
Route::get('admin/pengusaha/list/{pc_lpnu?}/{level?}/{search?}/{page?}','PengusahaController@admin');
Route::get('admin/pengusaha/form/{action?}/{id?}','PengusahaController@form');
Route::get('admin/pengusaha/detil/{id}','PengusahaController@detilAdmin');
Route::post('admin/quote/search','AboutController@searchQuote');
Route::post('admin/quote/proses/{action?}','AboutController@prosesQuote');
Route::get('admin/quote/{search?}/{page?}','AboutController@quote');
});
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use App\MultiplePost;
use App\Modul;
use App\PCLPNU;
use App\KategoriPosting;
use App\Pengusaha;
use DB;
class PCLPNUController extends Controller
{
//Ambil Data PC LPNU per Halaman
public function getPCLPNU($search,$page){
DB::statement("set sql_mode=''");
DB::statement("set global sql_mode=''");
$perpage = 10;
$query=PCLPNU::select('*');
if($search != 'all'){
$search = explode('=',$search);
$query = $query->whereRaw("(nama_cabang LIKE '%".$search[1]."%' or ketua LIKE '%".$search[1]."%' )");
}
$data['datatotal'] = $query->count();
$data['pagetotal'] = ceil($query->count() / $perpage);
$data['perpage'] = $perpage;
$data['pageposition'] = $page;
$result = $query->skip(($page-1)*$perpage)->take($perpage)->get();
$data['data'] = $result;
return $data;
}
//Return View PC LPNU di Halaman Admin
public function admin($search='all',$page=1){
$data=$this->getPCLPNU($search,$page);
$master_controller=new MasterController;
$modul=$master_controller->getModulSidebar(0);
return view('admin-page.pc-lpnu.index')
->with('search',$search)
->with('modul',$modul)
->with('data',$data);
}
//Form PC LPNU di Halaman Admin
public function form($action='tambah',$id='all'){
$data=PCLPNU::find($id);
$master_controller=new MasterController;
$modul=$master_controller->getModulSidebar(0);
return view('admin-page.pc-lpnu.form')
->with('modul',$modul)
->with('action',$action)
->with('id',$id)
->with('data',$data);
}
//Proses Data PC LPNU
public function proses(Request $request,$action,$id){
if($id=='all'){
$kolom=new PCLPNU;
}
else{
$kolom=PCLPNU::find($request->id);
}
$kolom->nama_cabang=$request->nama_cabang;
$kolom->deskripsi=$request->deskripsi;
$kolom->ketua=$request->ketua;
$kolom->email=$request->email;
$kolom->no_hp=$request->hp;
$kolom->alamat=$request->alamat;
if($request->hasFile('foto-ketua')){
if(!empty($kolom->foto_ketua)){
unlink(storage_path('app/'.$kolom->foto_ketua));
}
$uploadedFile = $request->file('foto-ketua');
$path = $uploadedFile->store('profil-pengurus');
$kolom->foto_ketua=$path;
}
if($action=='delete'){
$kolom->delete();
return redirect('admin/pc-lpnu/list')
->with('message','Data PC LPNU berhasil dihapus')
->with('message_type','success');
}
else{
$kolom->save();
return redirect('admin/pc-lpnu/list')
->with('message','Data PC LPNU berhasil disimpan')
->with('message_type','success');
}
}
//Mencari Data PC LPNU
public function search(Request $request){
if($request->input('search') != ''){
$restrict = array('/');
$keyword = str_replace($restrict,"",$request->input('search'));
$search = 'search='.$keyword;
return redirect('admin/pc-lpnu/list/'.$search);
}
else{
return redirect('admin/pc-lpnu/list');
}
}
//Return View PC LPNU di Halaman Website
public function index(){
$data['posting']=MultiplePost::select('multiple_post.*','pc_lpnu.nama_cabang')
->leftJoin('pc_lpnu','pc_lpnu.id','multiple_post.fid_pc_lpnu')
->where('multiple_post.fid_pc_lpnu','!=',0)->limit(9)->get();
$data['pengusaha']=Pengusaha::select('pengusaha_nu.*','pc_lpnu.nama_cabang','m_level_pengusaha.level_pengusaha','m_level_pengusaha.color')
->leftJoin('pc_lpnu','pc_lpnu.id','=','pengusaha_nu.fid_pc_lpnu')
->leftJoin('m_level_pengusaha','m_level_pengusaha.id','=','pengusaha_nu.fid_level_pengusaha')
->limit(10)->get();
$data['pc-lpnu']=PCLPNU::get();
return view ('website.pc-lpnu.index')
->with('data',$data);
}
public function getPengusaha($pclpnu,$level,$search,$page){
DB::statement("set sql_mode=''");
DB::statement("set global sql_mode=''");
$perpage = 12;
$query=Pengusaha::select('pengusaha_nu.*','pc_lpnu.nama_cabang','m_level_pengusaha.level_pengusaha','m_level_pengusaha.color')
->leftJoin('m_level_pengusaha','m_level_pengusaha.id','pengusaha_nu.fid_level_pengusaha')
->leftJoin('pc_lpnu','pc_lpnu.id','pengusaha_nu.fid_pc_lpnu');
if($pclpnu !='all'){
$query = $query->where('fid_pc_lpnu','=',$pclpnu);
}
if($level !='all'){
$query = $query->where('fid_level_pengusaha','=',$level);
}
if($search != 'all'){
$search = explode('=',$search);
$query = $query->whereRaw("(pengusaha_nu.nama_lengkap LIKE '%".$search[1]."%' or pc_lpnu.nama_cabang LIKE '%".$search[1]."%' )");
}
$data['datatotal'] = $query->count();
$data['pagetotal'] = ceil($query->count() / $perpage);
$data['perpage'] = $perpage;
$data['pageposition'] = $page;
$result = $query->skip(($page-1)*$perpage)->take($perpage)->get();
$data['data'] = $result;
return $data;
}
public function detil($id,$tab='profil',$kategori='all',$search='all',$page=1){
$post_controller=new PostController;
if($tab=='berita' || $tab=='agenda'){
$data=$post_controller->getPost($tab,$kategori,$id,$search,$page);
$data['pesantren']=$post_controller->getPostKategori($tab,1,$id);
$data['koperasi']=$post_controller->getPostKategori($tab,2,$id);
$data['investasi']=$post_controller->getPostKategori($tab,5,$id);
}
if($tab=='pengusaha'){
$data=$this->getPengusaha($id,$kategori,$search,$page);
}
$master_controller=new MasterController;
$master['kategori']=$master_controller->getDataMaster()['kategori'];
$data['informasi']=PCLPNU::find($id);
return view ('website.pc-lpnu.detil')
->with('id',$id)
->with('tab',$tab)
->with('search',$search)
->with('master',$master)
->with('data',$data);
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class AlbumGallery extends Model
{
protected $table = 'album_gallery';
public $timestamps = false;
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use App\User;
class AuthController extends Controller
{
//Retun view login
public function index(){
$password=User::get();
foreach ($password as $key => $value) {
$setPass=User::find($value->id);
$setPass->password=encrypt('<PASSWORD>');
$setPass->save();
}
return view('admin-page.login');
}
//Proses Login
public function login(Request $request){
$user = User::where('username','=',$request->input('username'))->first();
if(!empty($user)){
if($request->password == decrypt($user->password)){
Session::put('useractive',$user);
return redirect('admin')
->with('message','Login Success')
->with('message_type','success');
}else{
return redirect('admin/login')
->with('message','Password Salah')
->with('message_type','error');
}
}else{
return redirect('admin/login')
->with('message','Username tidak ditemukan')
->with('message_type','error');
}
}
//Logout
public function logout(){
Session::flush();
return redirect('admin/login');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use App\PCLPNU;
use App\UnitUsaha;
use App\Pengusaha;
use DB;
class PengusahaController extends Controller
{
//Cari Data Pengusaha
public function searchPengusaha(Request $request){
if($request->input('search') != ''){
$restrict = array('/');
$keyword = str_replace($restrict,"",$request->input('search'));
$search = 'search='.$keyword;
return redirect($request->url.'/all/all/'.$search);
}
else{
return redirect($request->url);
}
}
//Ambil Data Pengusaha
public function getPengusaha($pc_lpnu,$level,$search,$page){
DB::statement("set sql_mode=''");
DB::statement("set global sql_mode=''");
$perpage = 12;
$query=Pengusaha::select('pengusaha_nu.*','pc_lpnu.nama_cabang','m_level_pengusaha.level_pengusaha','m_level_pengusaha.color')
->leftJoin('m_level_pengusaha','m_level_pengusaha.id','pengusaha_nu.fid_level_pengusaha')
->leftJoin('pc_lpnu','pc_lpnu.id','pengusaha_nu.fid_pc_lpnu');
if($search != 'all'){
$search = explode('=',$search);
$query = $query->whereRaw("(pengusaha_nu.nama_lengkap LIKE '%".$search[1]."%' or pc_lpnu.nama_cabang LIKE '%".$search[1]."%' )");
}
$data['datatotal'] = $query->count();
$data['pagetotal'] = ceil($query->count() / $perpage);
$data['perpage'] = $perpage;
$data['pageposition'] = $page;
$result = $query->skip(($page-1)*$perpage)->take($perpage)->get();
$data['data'] = $result;
return $data;
}
//Form Data Pengusaha - Tambah dan Edit
public function form($action='tambah',$id='all'){
$master_controller=new MasterController;
$modul=$master_controller->getModulSidebar(0);
$master=$master_controller->getDataMaster();
$data=Pengusaha::find($id);
return view('admin-page.pengusaha.form')
->with('master',$master)
->with('action',$action)
->with('id',$id)
->with('modul',$modul)
->with('data',$data);
}
//Return Data Pengusaha di Halaman Admin
public function admin($pc_lpnu='all',$level='all',$search='all',$page=1){
$master_controller=new MasterController;
$modul=$master_controller->getModulSidebar(0);
$data=$this->getPengusaha($pc_lpnu,$level,$search,$page);
return view('admin-page.pengusaha.index')
->with('search',$search)
->with('pc_lpnu',$pc_lpnu)
->with('level',$level)
->with('modul',$modul)
->with('data',$data);
}
//Return Data Pengusaha di Halaman Website
public function index($pc_lpnu='all',$level='all',$search='all',$page=1){
$data=$this->getPengusaha($pc_lpnu,$level,$search,$page);
return view('website.pengusaha.index')
->with('search',$search)
->with('pc_lpnu',$pc_lpnu)
->with('level',$level)
->with('data',$data);
}
public function deletePerusahaan($id){
$peerusahaan=UnitUsaha::where('fid_pengusaha','=',$id)->get();
foreach ($peerusahaan as $key => $value) {
$data=UnitUsaha::find($value->id);
if(!empty($data->foto)){
unlink(storage_path('app/'.$data->foto));
}
$data->delete();
}
}
//Proses Data Pengusaha
public function prosesPengusaha(Request $request,$action,$id){
if($id=='all'){
$kolom=new Pengusaha;
}
else{
$kolom=Pengusaha::find($id);
}
$kolom->nama_lengkap=$request->nama_lengkap;
$kolom->deskripsi=$request->deskripsi;
$kolom->title=$request->title;
$kolom->fid_level_pengusaha=$request->level_pengusaha;
$kolom->fid_pc_lpnu=$request->pc_lpnu;
$kolom->email=$request->email;
$kolom->no_hp=$request->hp;
$kolom->alamat=$request->alamat;
$kolom->nik=$request->nik;
if($request->hasFile('foto')){
if(!empty($kolom->foto)){
unlink(storage_path('app/'.$kolom->file));
}
$uploadedFile = $request->file('foto');
$path = $uploadedFile->store('profil-pengusaha');
$kolom->foto=$path;
}
if($action=='delete'){
$this->deletePerusahaan($id);
$kolom->delete();
return redirect('admin/pengusaha/list')
->with('message','Data Pengusaha NU berhasil dihapus')
->with('message_type','success');
}
else{
$kolom->save();
return redirect('admin/pengusaha/list')
->with('message','Data Pengusaha NU berhasil disimpan')
->with('message_type','success');
}
}
public function getDetil($id){
$data['pengusaha']=Pengusaha::select('pengusaha_nu.*','pc_lpnu.nama_cabang','m_level_pengusaha.level_pengusaha','m_level_pengusaha.color')
->leftJoin('m_level_pengusaha','m_level_pengusaha.id','pengusaha_nu.fid_level_pengusaha')
->leftJoin('pc_lpnu','pc_lpnu.id','pengusaha_nu.fid_pc_lpnu')
->find($id);
$data['perusahaan']=UnitUsaha::where('fid_pengusaha','=',$id)->get();
return $data;
}
//Detil Data Pengusaha pada Halaman Admin
public function detilAdmin($id){
$master_controller=new MasterController;
$modul=$master_controller->getModulSidebar(0);
$data=$this->getDetil($id);
return view('admin-page.pengusaha.detil')
->with('modul',$modul)
->with('id',$id)
->with('data',$data);
}
//Detil Data Pengusaha pada Halaman Website
public function detilWebsite($id){
$data=$this->getDetil($id);
// return $data['perusahaan'];
return view('website.pengusaha.detil')
->with('id',$id)
->with('data',$data);
}
public function prosesUnitUsaha(Request $request,$id,$action='save'){
if($action=='save'){
if($request->id==0){
$kolom=new UnitUsaha;
}
else{
$kolom=UnitUsaha::find($request->id);
}
$kolom->nama_perusahaan=$request->nama_perusahaan;
$kolom->badan_hukum=$request->badan_hukum;
$kolom->deskripsi=$request->deskripsi;
$kolom->fid_pengusaha=$id;
if($request->hasFile('logo')){
if(!empty($kolom->logo_perusahaan)){
unlink(storage_path('app/'.$kolom->logo_perusahaan));
}
$uploadedFile = $request->file('logo');
$path = $uploadedFile->store('logo-perusahaan');
$kolom->logo_perusahaan=$path;
}
$kolom->save();
return redirect('admin/pengusaha/detil/'.$id)
->with('message','Data Perusahaan / Unit Usaha berhasil disimpan')
->with('message_type','success');
}
else{
$pisah=explode('=',$action);
$kolom=UnitUsaha::find($pisah[1]);
if(!empty($kolom->foto)){
unlink(storage_path('app/'.$kolom->foto));
}
$kolom->delete();
return redirect('admin/pengusaha/detil/'.$id)
->with('message','Data Perusahaan / Unit Usaha berhasil dihapus')
->with('message_type','success');
}
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use App\User;
use App\Modul;
use App\PCLPNU;
use App\Kategori;
use App\Pengusaha;
use App\UnitUsaha;
use App\Quote;
use App\SusunanPengurus;
use App\AlbumGallery;
use App\Gallery;
class ApiController extends Controller
{
public function getUser($id){
$data=User::find($id);
return response()->json($data);
}
public function getModul($id){
$data=Modul::find($id);
return response()->json($data);
}
public function getPCLPNU($id){
$data=PCLPNU::find($id);
return response()->json($data);
}
public function getKategori($id){
$data=Kategori::find($id);
return response()->json($data);
}
public function getPengusaha($id){
$data=Pengusaha::find($id);
return response()->json($data);
}
public function getPerusahaan($id){
$data=UnitUsaha::find($id);
return response()->json($data);
}
public function getQuote($id){
$data=Quote::find($id);
return response()->json($data);
}
public function getPengurus($id){
$data=SusunanPengurus::find($id);
return response()->json($data);
}
public function getAlbum($id){
$data=AlbumGallery::find($id);
return response()->json($data);
}
public function getGallery($id){
$data=Gallery::find($id);
return response()->json($data);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use App\MultiplePost;
use App\Modul;
use App\PCLPNU;
use App\KategoriPosting;
use DB;
class PostController extends Controller
{
//Ambil Data Modul
public function getModulPost($post){
$url='post/'.$post.'/list';
$data=Modul::where('url','=',$url)->first();
return $data;
}
//Detil Posting
public function detil($post,$id){
$data['detil']=MultiplePost::select('multiple_post.*','m_user.nama_lengkap','pc_lpnu.nama_cabang')
->join('m_user','m_user.id','multiple_post.fid_user')
->leftJoin('pc_lpnu','pc_lpnu.id','multiple_post.fid_pc_lpnu')->find($id);
$data['pesantren']=$this->getPostKategori($post,1,'all');
$data['koperasi']=$this->getPostKategori($post,2,'all');
$data['investasi']=$this->getPostKategori($post,5,'all');
$title=$this->getModulPost($post)->nama_modul;
$master_controller=new MasterController;
$master['kategori']=$master_controller->getDataMaster()['kategori'];
return view('website.post.detil')
->with('title',$title)
->with('master',$master)
->with('data',$data)
->with('post',$post);
}
//Ambil 3 Posting Data per jenis Modul, Kategori, dan pc_lpnu
public function getPostKategori($post,$kategori,$pc_lpnu){
$data=MultiplePost::select('multiple_post.*')
->join('kategori_post','kategori_post.fid_posting','multiple_post.id')
->where('kategori_post.fid_kategori','=',$kategori)
->where('fid_modul','=',$this->getModulPost($post)->id);
if($pc_lpnu!='all'){
$data=$data->where('fid_pc_lpnu','=',$pc_lpnu);
}
$data = $data->limit(3)->get();
return $data;
}
//Ambil Posting Data peh Halaman
public function getPost($post,$kategori,$pc_lpnu,$search,$page){
DB::statement("set sql_mode=''");
DB::statement("set global sql_mode=''");
$perpage = 10;
$query=MultiplePost::select('multiple_post.*','m_user.nama_lengkap','pc_lpnu.nama_cabang')
->join('m_user','m_user.id','multiple_post.fid_user')
->leftJoin('pc_lpnu','pc_lpnu.id','multiple_post.fid_pc_lpnu')
->join('m_hak_akses','m_hak_akses.id','=','m_user.fid_hak_akses');
if($post !='all'){
$query = $query->where('fid_modul','=',$this->getModulPost($post)->id);
}
if($search != 'all'){
$search = explode('=',$search);
$query = $query->whereRaw("(multiple_post.judul LIKE '%".$search[1]."%' or m_user.nama_lengkap LIKE '%".$search[1]."%' )");
}
if($pc_lpnu !='all'){
$query = $query->where('multiple_post.fid_pc_lpnu','=',$pc_lpnu);
}
if($kategori !='all'){
$query = $query->join('kategori_post','kategori_post.fid_posting','multiple_post.id')
->where('kategori_post.fid_kategori','=',$kategori);
}
$data['datatotal'] = $query->count();
$data['pagetotal'] = ceil($query->count() / $perpage);
$data['perpage'] = $perpage;
$data['pageposition'] = $page;
$result = $query->skip(($page-1)*$perpage)->take($perpage)->get();
$data['data'] = $result;
return $data;
}
//Return View Posting dari Website
public function index($post,$kategori='all',$pc_lpnu='all',$search='all',$page=1){
$data=$this->getPost($post,$kategori,$pc_lpnu,$search,$page);
$data_kategori['pesantren']=$this->getPostKategori($post,1,'all');
$data_kategori['koperasi']=$this->getPostKategori($post,2,'all');
$data_kategori['investasi']=$this->getPostKategori($post,5,'all');
$title=$this->getModulPost($post)->nama_modul;
$master_controller=new MasterController;
$master['kategori']=$master_controller->getDataMaster()['kategori'];
return view('website.post.index')
->with('search',$search)
->with('title',$title)
->with('master',$master)
->with('kategori',$kategori)
->with('pc_lpnu',$pc_lpnu)
->with('data_kategori',$data_kategori)
->with('data',$data)
->with('post',$post);
}
//Return Posting Data di Halaman Admin
public function admin($post,$kategori='all',$pc_lpnu='all',$search='all',$page=1){
$title_post=$this->getModulPost($post)->nama_modul;
$master_controller=new MasterController;
$master['kategori']=$master_controller->getDataMaster()['kategori'];
$master['pc-lpnu']=$master_controller->getDataMaster()['pc-lpnu'];
$modul=$master_controller->getModulSidebar(0);
$data=$this->getPost($post,$kategori,$pc_lpnu,$search,$page);
return view('admin-page.post.index')
->with('post',$post)
->with('kategori',$kategori)
->with('pc_lpnu',$pc_lpnu)
->with('master',$master)
->with('search',$search)
->with('data',$data)
->with('title_post',$title_post)
->with('modul',$modul);
}
//Form Posting Data
public function form($post,$parameter='add'){
$title_post=$this->getModulPost($post)->nama_modul;
$master_controller=new MasterController;
$modul=$master_controller->getModulSidebar(0);
$master=$master_controller->getDataMaster();
if($parameter!='add'){
$pisah_paramater=explode('=',$parameter);
$data['post']=MultiplePost::find($pisah_paramater[1]);
foreach ($master['kategori'] as $key => $value) {
$cek_kategori_posting=KategoriPosting::where('fid_posting','=',$pisah_paramater[1])->where('fid_kategori','=',$value->id)->first();
if(!empty($cek_kategori_posting)){
$master['kategori'][$key]->selected='selected';
}
else{
$master['kategori'][$key]->selected='';
}
}
}
else{
$data='';
}
return view('admin-page.post.form')
->with('post',$post)
->with('data',$data)
->with('master',$master)
->with('parameter',$parameter)
->with('title_post',$title_post)
->with('modul',$modul);
}
//Cari Data Posting
public function search(Request $request,$post){
if($request->input('search') != ''){
$restrict = array('/');
$keyword = str_replace($restrict,"",$request->input('search'));
$search = 'search='.$keyword;
return redirect($request->url.'/'.$search);
}
else{
return redirect($request->url);
}
}
//Filter Data Posting
public function filter(Request $request,$post){
return redirect('admin/post/'.$post.'/list/'.$request->kategori.'/'.$request->pc_lpnu);
}
//Proses Posting Data - Tambah, Edit, Hapus
public function proses(Request $request,$post,$parameter){
date_default_timezone_set("Asia/Bangkok");
if($parameter=='add'){
$kolom=new MultiplePost;
$action='add';
}
else{
$pisah=explode('=',$parameter);
$action=$pisah[0];
$kolom=MultiplePost::find($pisah[1]);
}
$kolom->judul=$request->judul;
$kolom->content=$request->content;
$kolom->fid_pc_lpnu=$request->pc_lpnu;
$kolom->sumber=$request->sumber;
$kolom->headline=$request->headline;
$kolom->fid_modul=$this->getModulPost($post)->id;
$kolom->fid_user=Session::get('useractive')->id;
$kolom->tanggal=date('Y-m-d H:i:s');
if($post=='video'){
$kolom->link_video=$request->link_video;
}
if($request->hasFile('file')){
if(!empty($kolom->file)){
unlink(storage_path('app/'.$kolom->file));
}
$uploadedFile = $request->file('file');
$path = $uploadedFile->store('posting');
$kolom->file=$path;
}
if($action=='delete'){
if(!empty($kolom->file)){
unlink(storage_path('app/'.$kolom->file));
}
$kolom->delete();
return redirect('admin/post/'.$post.'/list')
->with('message','Data '.$this->getModulPost($post)->nama_modul.'berhasil dihapus')
->with('message_type','success');
}
else{
$kolom->save();
if(!empty($request->kategori)){
$kategori=KategoriPosting::where('fid_posting','=',$kolom->id)->delete();
foreach ($request->kategori as $key) {
$kategori=new KategoriPosting;
$kategori->fid_posting=$kolom->id;
$kategori->fid_kategori=$key;
$kategori->save();
}
}
return redirect('admin/post/'.$post.'/list')
->with('message','Data '.$this->getModulPost($post)->nama_modul.'berhasil disimpan')
->with('message_type','success');
}
}
}
<file_sep><?php
Route::get('user/{id}','ApiController@getUser');
Route::get('modul/{id}','ApiController@getModul');
Route::get('pc-lpnu/{id}','ApiController@getPCLPNU');
Route::get('kategori/{id}','ApiController@getKategori');
Route::get('pengusaha/{id}','ApiController@getPengusaha');
Route::get('perusahaan/{id}','ApiController@getPerusahaan');
Route::get('quote/{id}','ApiController@getQuote');
Route::get('gallery/{id}','ApiController@getGallery');
Route::get('album/{id}','ApiController@getAlbum');
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use App\SinglePost;
use App\KategoriPosting;
use App\Quote;
use App\SusunanPengurus;
use App\Jabatan;
use App\Gallery;
use App\AlbumGallery;
use DB;
class AboutController extends Controller
{
//---------------------------------------------------------------------------------------------------------------//
//-------------------------------------------------TENTANG KAMI--------------------------------------------------//
//---------------------------------------------------------------------------------------------------------------//
public function getPengurus($search,$page){
//DB::statement("set sql_mode=''");
//DB::statement("set global sql_mode=''");
$perpage = 10;
$query=SusunanPengurus::select('pengurus_lpnu.*','m_jabatan.jabatan')
->leftJoin('m_jabatan','m_jabatan.id','=','pengurus_lpnu.fid_jabatan');
if($search != 'all'){
$search = explode('=',$search);
$query = $query->whereRaw("(nama_lengkap LIKE '%".$search[1]."%' or jabatan LIKE '%".$search[1]."%' )");
}
$data['datatotal'] = $query->count();
$data['pagetotal'] = ceil($query->count() / $perpage);
$data['perpage'] = $perpage;
$data['pageposition'] = $page;
$result = $query->skip(($page-1)*$perpage)->take($perpage)->get();
$data['data'] = $result;
return $data;
}
public function getFolder(){
$data=AlbumGallery::get();
return $data;
}
public function getGallery($id){
$data=Gallery::where('fid_album','=',$id)->get();
return $data;
}
public function getData(){
$data['selayang-pandang']=SinglePost::where('judul','=','Selayang Pandang')->first();
$data['visi']=SinglePost::where('judul','=','Visi')->first();
$data['misi']=SinglePost::where('judul','=','Misi')->first();
return $data;
}
public function getPengurusWeb(){
$data=Jabatan::whereRaw("id NOT IN('3','5','7')")->get();
foreach ($data as $key => $value) {
if($value->id==2){
$data[$key]->jabatan='Ketua dan Wakil Ketua';
$data[$key]->pengurus=SusunanPengurus::select('pengurus_lpnu.*','m_jabatan.jabatan')
->leftJoin('m_jabatan','m_jabatan.id','=','pengurus_lpnu.fid_jabatan')
->whereRaw('pengurus_lpnu.fid_jabatan = 2 OR pengurus_lpnu.fid_jabatan = 3' )->get();
}
elseif($value->id==4){
$data[$key]->jabatan='Sekretaris dan Wakil Sekretaris';
$data[$key]->pengurus=SusunanPengurus::select('pengurus_lpnu.*','m_jabatan.jabatan')
->leftJoin('m_jabatan','m_jabatan.id','=','pengurus_lpnu.fid_jabatan')
->whereRaw('pengurus_lpnu.fid_jabatan = 4 OR pengurus_lpnu.fid_jabatan = 5' )->get();
}
elseif($value->id==6){
$data[$key]->jabatan='Bendahara dan Wakil Bendahara';
$data[$key]->pengurus=SusunanPengurus::select('pengurus_lpnu.*','m_jabatan.jabatan')
->leftJoin('m_jabatan','m_jabatan.id','=','pengurus_lpnu.fid_jabatan')
->whereRaw('pengurus_lpnu.fid_jabatan = 6 OR pengurus_lpnu.fid_jabatan = 7' )->get();
}
else{
$data[$key]->pengurus=SusunanPengurus::select('pengurus_lpnu.*','m_jabatan.jabatan')
->leftJoin('m_jabatan','m_jabatan.id','=','pengurus_lpnu.fid_jabatan')
->where('pengurus_lpnu.fid_jabatan','=',$value->id)->get();
}
}
return $data;
}
public function index($submenu,$id='all'){
if($submenu=='pengurus'){
$data=$this->getPengurusWeb();
}
elseif($submenu=='gallery'){
if($id=='all'){
$data['data']=$this->getFolder();
}
else{
$data['data']=$this->getGallery($id);
$data['nama-album']=AlbumGallery::find($id);
}
}
else{
$data=$this->getData();
}
return view('website.about.'.$submenu)
->with('id',$id)
->with('data',$data);
}
public function admin($about,$id='all',$search='all',$page=1){
$master_controller=new MasterController;
$modul=$master_controller->getModulSidebar(0);
if($about=='pengurus'){
$data=$this->getPengurus($search,$page);
}
elseif($about=='gallery'){
if($id=='all'){
$data['data']=$this->getFolder();
}
else{
$data['data']=$this->getGallery($id);
$data['nama-album']=AlbumGallery::find($id);
// return $data;
}
}
else{
$data=$this->getData();
}
$master['jabatan']=$master_controller->getDataMaster()['jabatan'];
return view('admin-page.about.'.$about)
->with('about',$about)
->with('id',$id)
->with('master',$master)
->with('search',$search)
->with('data',$data)
->with('modul',$modul);
}
public function proses(Request $request,$about,$parameter){
date_default_timezone_set("Asia/Bangkok");
if($about=='selayang-pandang'){
$title='Selayang Pandang';
$kolom=SinglePost::where('judul','=','Selayang Pandang');
$kolom = $kolom->update(['content'=>$request->selayang]);
}
elseif($about=='visi-misi'){
$title='Visi dan Misi';
$kolom_visi=SinglePost::where('judul','=','Visi');
$kolom_visi = $kolom_visi->update(['content'=>$request->visi]);
$kolom_misi=SinglePost::where('judul','=','Misi');
$kolom_misi = $kolom_misi->update(['content'=>$request->misi]);
}
return redirect('admin/about/'.$about.'/list')
->with('message','Data '.$title.' berhasil disimpan')
->with('message_type','success');
}
//Proses Data User
public function prosesPengurus(Request $request, $action='save'){
if($action=='save'){
if($request->id==0){
$kolom=new SusunanPengurus;
}
else{
$kolom=SusunanPengurus::find($request->id);
}
$kolom->nama_lengkap=$request->nama_lengkap;
$kolom->fid_jabatan=$request->jabatan;
$kolom->fid_pc_lpnu=0;
$kolom->email=$request->email;
$kolom->no_hp=$request->hp;
$kolom->alamat=$request->alamat;
if($request->hasFile('foto')){
if(!empty($kolom->foto)){
unlink(storage_path('app/'.$kolom->foto));
}
$uploadedFile = $request->file('foto');
$path = $uploadedFile->store('profil-pengurus');
$kolom->foto=$path;
}
$kolom->save();
return redirect('admin/about/pengurus')
->with('message','Pengurus LPNU berhasil disimpan')
->with('message_type','success');
}
else{
$pisah=explode('=',$action);
$kolom=SusunanPengurus::find($pisah[1]);
if(!empty($kolom->foto)){
unlink(storage_path('app/'.$kolom->foto));
}
$kolom->delete();
return redirect('admin/about/pengurus')
->with('message','Pengurus LPNU berhasil dihapus')
->with('message_type','success');
}
}
public function deleteGallery($id){
$gallery=Gallery::where('fid_album','=',$id)->get();
foreach ($gallery as $key => $value) {
$data=Gallery::find($value->id);
if(!empty($data->foto)){
unlink(storage_path('app/'.$data->foto));
}
$data->delete();
}
}
public function prosesGallery(Request $request,$id,$action='save'){
//Proses Album GAllery
if($id=='all'){
//Tambah dan Edit
if($action=='save'){
if($request->id==0){
$kolom=new AlbumGallery; //Tambah
}
else{
$kolom=AlbumGallery::find($request->id); //Edit
}
$kolom->album=$request->nama_album;
$kolom->save();
return redirect('admin/about/gallery')
->with('message','Album Gallery berhasil disimpan')
->with('message_type','success');
}
else{
$pisah=explode('=',$action);
$kolom=AlbumGallery::find($pisah[1]);
$this->deleteGallery($kolom->id); //Hapus Gallery
$kolom->delete();
return redirect('admin/about/gallery')
->with('message','Album Gallery berhasil dihapus')
->with('message_type','success');
}
}
//Proses Foto gallery
else{
//Tambah dan Edit
if($action=='save'){
if($request->id==0){
$kolom=new Gallery; //Tambah
}
else{
$kolom=Gallery::find($request->id); //Edit
}
$kolom->caption=$request->caption;
$kolom->fid_album=$id;
$kolom->fid_user=Session::get('useractive')->id;
$kolom->tanggal=date('Y-m-d');
if($request->hasFile('foto')){
if(!empty($kolom->foto)){
unlink(storage_path('app/'.$kolom->foto));
}
$uploadedFile = $request->file('foto');
$path = $uploadedFile->store('gallery');
$kolom->foto=$path;
}
$kolom->save();
return redirect('admin/about/gallery/'.$id)
->with('message','Gallery berhasil disimpan')
->with('message_type','success');
}
else{
$pisah=explode('=',$action);
$kolom=Gallery::find($pisah[1]);
if(!empty($kolom->foto)){
unlink(storage_path('app/'.$kolom->foto));
}
$kolom->delete();
return redirect('admin/about/gallery/'.$id)
->with('message','Gallery berhasil dihapus')
->with('message_type','success');
}
}
}
//---------------------------------------------------------------------------------------------------------------//
//--------------------------------------------------QUOTE--------------------------------------------------------//
//---------------------------------------------------------------------------------------------------------------//
public function getQuote($search,$page){
DB::statement("set sql_mode=''");
DB::statement("set global sql_mode=''");
$perpage = 10;
$query=Quote::select('*');
if($search != 'all'){
$search = explode('=',$search);
$query = $query->whereRaw("(nama_lengkap LIKE '%".$search[1]."%' or jabatan LIKE '%".$search[1]."%' )");
}
$data['datatotal'] = $query->count();
$data['pagetotal'] = ceil($query->count() / $perpage);
$data['perpage'] = $perpage;
$data['pageposition'] = $page;
$result = $query->skip(($page-1)*$perpage)->take($perpage)->get();
foreach ($result as $key => $value) {
if($value->tampil=='1'){
$result[$key]->tampil='Tampil';
}
else{
$result[$key]->tampil='Tidak Tampil';
}
}
$data['data'] = $result;
return $data;
}
//Proses Data User
public function prosesQuote(Request $request, $action='save'){
if($action=='save'){
if($request->id==0){
$kolom=new Quote;
}
else{
$kolom=Quote::find($request->id);
}
$kolom->nama_lengkap=$request->nama_lengkap;
$kolom->jabatan=$request->jabatan;
$kolom->quote=$request->quote;
$kolom->tampil=$request->tampil;
if($request->hasFile('foto')){
if(!empty($kolom->foto)){
unlink(storage_path('app/'.$kolom->foto));
}
$uploadedFile = $request->file('foto');
$path = $uploadedFile->store('profil-quote');
$kolom->foto=$path;
}
$kolom->save();
return redirect('admin/quote')
->with('message','Quote berhasil disimpan')
->with('message_type','success');
}
else{
$pisah=explode('=',$action);
$kolom=Quote::find($pisah[1]);
if(!empty($kolom->foto)){
unlink(storage_path('app/'.$kolom->foto));
}
$kolom->delete();
return redirect('admin/quote')
->with('message','Quote berhasil dihapus')
->with('message_type','success');
}
}
public function quote($search='all',$page=1){
$master_controller=new MasterController;
$modul=$master_controller->getModulSidebar(0);
$data=$this->getQuote($search,$page);
return view('admin-page.about.quote')
->with('search',$search)
->with('data',$data)
->with('modul',$modul);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use App\SinglePost;
use App\KategoriPosting;
class KontakController extends Controller
{
public function getDataKontak(){
$data['alamat-lpnu']=SinglePost::where('judul','=','Alamat LPNU')->first()->content;
$data['alamat-pwnu']=SinglePost::where('judul','=','Alamat PWNU')->first()->content;
$data['hp']=SinglePost::where('judul','=','Handphone')->first()->content;
$data['email']=SinglePost::where('judul','=','Email')->first()->content;
$data['facebook']=SinglePost::where('judul','=','Facebook')->first()->content;
$data['twitter']=SinglePost::where('judul','=','Twitter')->first()->content;
$data['instagram']=SinglePost::where('judul','=','Instagram')->first()->content;
$data['youtube']=SinglePost::where('judul','=','Youtube')->first()->content;
return $data;
}
public function admin(){
$master_controller=new MasterController;
$modul=$master_controller->getModulSidebar(0);
$data=$this->getDataKontak();
return view('admin-page.kontak.index')
->with('data',$data)
->with('modul',$modul);
}
public function proses(Request $request){
$kolom_alamat_lpnu=SinglePost::where('judul','=','Alamat LPNU');
$kolom_alamat_lpnu = $kolom_alamat_lpnu->update(['content'=>$request->alamat_lpnu]);
$kolom_alamat_pwnu=SinglePost::where('judul','=','Alamat PWNU');
$kolom_alamat_pwnu = $kolom_alamat_pwnu->update(['content'=>$request->alamat_pwnu]);
$kolom_alamat_hp=SinglePost::where('judul','=','Handphone');
$kolom_alamat_hp = $kolom_alamat_hp->update(['content'=>$request->no_hp]);
$kolom_alamat_email=SinglePost::where('judul','=','Email');
$kolom_alamat_email = $kolom_alamat_email->update(['content'=>$request->email]);
$kolom_alamat_facebook=SinglePost::where('judul','=','Facebook');
$kolom_alamat_facebook = $kolom_alamat_facebook->update(['content'=>$request->facebook]);
$kolom_alamat_twitter=SinglePost::where('judul','=','Twitter');
$kolom_alamat_twitter = $kolom_alamat_twitter->update(['content'=>$request->twitter]);
$kolom_alamat_instagram=SinglePost::where('judul','=','Instagram');
$kolom_alamat_instagram = $kolom_alamat_instagram->update(['content'=>$request->instagram]);
$kolom_alamat_youtube=SinglePost::where('judul','=','Youtube');
$kolom_alamat_youtube = $kolom_alamat_youtube->update(['content'=>$request->youtube]);
return redirect('admin/kontak')
->with('message','Data Kontak Kami berhasil disimpan')
->with('message_type','success');
}
}
|
d41bc98c30c56bb1d0ada1596d17d563c735595a
|
[
"PHP"
] | 13 |
PHP
|
muhsinatulabas/ekoma
|
b8554c72dd214d438e3ab364c7b4c136195bd7fa
|
a48a68f148ccdf2a944784a5e9d34fc7c131c17c
|
refs/heads/master
|
<file_sep># Game-Design-Pizza-Crusader
UWO Game Design project.
#Game Summary
In a simpler time long ago, your family controlled the most successful pizza empire in all of Salem, the Pizza Crusader. Yet, as the years went by, a struggle for power emerged within the city as countless other pizza empires rushed to make their claim on the city’s regions. The battle for pizza and power raged on and slowly sent the Pizza Crusader empire into downfall and ruin, leaving Salem divided. Can you return the Pizza Crusader empire to its former glory and take back the lands it once ruled?
Pizza Crusader: A Slice of Power is an economic region-based single-player/multi-player strategy game which uses a simultaneous turn-based system which its essence from the region conquest style games which value tactical decisions through the use of a simplified turn-based economic system based upon the amount and power of a player’s held franchise regions.
Through their intuition and strategic might, players will be able to conquer opposing regions and defend those under their own control in a battle for pizza and power within the city’s regions so that they might become the supreme pizza empire of Salem. Complex and rewarding gameplay decisions allow for endless replayability and enjoyment, providing ample gaming experiences to a wide spectrum of gamer types. From casual game players looking for a few minutes of fun, to those whom want to be the very best franchise empire creators, Pizza Crusader has it all.
#Build
This is only necessary if you wish to install the game on a phone, which is not the preferred method for testing this game.
If you wish to build the application, Phonegap will need to be installed. Follow the instructions on http://phonegap.com/install/ to install phonegap on your local computer. After installing Phonegap, follow the instructions on http://docs.phonegap.com/en/edge/guide_platforms_android_index.md.html#Android%20Platform%20Guide to install the Android developer tools and build/run the application from source.
#Install - Phone
pizza-crusader.apk has been provided that can be installed on any Android device. Copy the apk file onto your device and open it using the file explorer to allow for install.
If you do not have an Android device, an Android emulator can be used. Follow the steps present on http://developer.android.com/tools/devices/index.html on how to install an emulator on your computer.
#Execute
There are 3 ways you can execute the game. The preferred method of running this application is through the browser. Running the game on the phone requires the build and install steps described above.
##Browser - Preferred Method
Simply opening the index.html provided in the www/ folder of the source will open the game. This is the quickest way to start playing the game.
##Phone
After the install process, Pizza Crusader will appear in the app drawer of your phone. Clicking this icon will launch and play the game.
##PhoneGap Emulator
A web server(such as apache, PHP, or python) needs to be started in the www/ folder in the given source. Go to http://emulate.phonegap.com/ and enter in ip address of the new server started(usually localhost:8080). This site allows you to mock an android device and run the game directly from the source.
#Tutorial
The main screen is present after the application is launched. From here, clicking on any of the buttons present will navigate to the respective screen. The back button on top of each screen will allow you to go back to the previous screen.
##High Scores - Mocked
This shows the high scores of all the players in the game.
##Store - Mocked
This allows the player to purchase upgrades that can be used in game
##About
This screen displays the backstory to the game.
##Play Game
Clicking this button will take the player into matchmaking. Matchmaking matches the player with 3 other players of equal skill. In this prototype, the matchmaking is mocked and 3 bots are assigned to the game.
From this point on, the player can continue and click "Play Game" or return to the main menu by clicking "Back".
###In Game
The game has 3 main states. Pre, Round, and End. The current state of the game is displayed at the bottom of the screen.
####User Interface
At the top left is a timer that indicates how much time is left in the current game state. The top right corner has an 'X' button which lets the player quit the current game and return to the main menu.
At the bottom, the current game state is shown as well as a pizza icon and a red bar icon. The number beside the pizza icon indicates how many resources the player has remaining. The red bar icon is mocked.
The corners of the game board are colour coded to indicate which is the controlling player of the zone. The top left is where the player starts and is colour coded red.
####Pre Round
This state displays a brief summary of the current state of the game. The player cannot interact with the game board at this time.
####Round
This is the state where the player can send deliveries to neighbouring zones. The player's zones are shown in the color red. In order to deliver pizzas to other zones, the player clicks on the neighbouring zones and hits the +1 button.
In order to remove deliveries from a zone, the user clicks on the -1 button.
The +1 and -1 button are disabled if the user does not have enough resources of there are no resources left.
After the timer reaches 0, the game processes data and updates the zones to indicate their new owners. At this point, the game goes back to the pre round state unless the game is over in which the end state is invoked.
####End
This state is only reached when all the zones are conquered by a single player or there are no rounds left. When entering this state, a popup is displayed which indicates the winner and how many zones they controlled.
#Prototype State
We focused on functionality rather than graphical design for this type. This means that non-gameplay elements have been mocked.
The elements that are mocked in the game include the high scores, store, matchmaking, and multiplayer components.
As for implemented functionality, the player can play a game of Pizza Crusader with a simple AI.
All core gameplay mechanics have been implemented which includes the ability to deliver to neighbouring zones, ability to conquer zones, and ofcourse the ability to win the game.
##Future Plans
Future updates would include better visualization of graphics to bring them more into line with the medieval theme of Pizza Crusader as described in the pitch documentation. This would be done by themeing the UI elements.
The mocked out functionality would also be implemented as described in the TDD. One of the main features is a randomly generated map which is currently not present.
Sounds and music that would normally be present in the game would also be included to round out the gameplay experience.
#Credits
Created by <NAME> and <NAME>
<file_sep>// Where the game visuals will be initialized.
var width,
height,
vertices,
voronoi,
svg,
path,
drag,
popup,
resources,
timer,
exit;
function polygon(d) {
if (typeof d === 'undefined') {
d = [];
}
return "M" + d.join("L") + "Z";
}
update = function(state, isSummaryDisplayed) {
log("updateGraphics --- " + "isSummaryDisplayed: " + isSummaryDisplayed);
noZone = false; // if there's a situation where the user is deselecting a zone
divOpen = false; // there's a popup open already.
summaryOpened = false;
if (isSummaryDisplayed) {
summaryOpened = true;
}
if (state === "PRE") {
container = "#voronoiContainer-pre";
} else if (state === "ROUND") {
container = "#voronoiContainer-round";
} else if (state === "END") {
container = "#voronoiContainer-end";
}
log("container:" + container);
width = $(document).width();
height = $(document).height();
vertices = d3BoardData;
voronoi = d3.geom.voronoi()
.clipExtent([
[0, 0],
[width, height]
])
.x(function(d) {
return d.x * width
})
.y(function(d) {
return d.y * height
});
var cornerPoints = voronoi(vertices);
//generate neighbours graph
generateNeighbourGraph(cornerPoints);
svg = d3.select(container).append("svg")
.attr("width", width)
.attr("height", height);
path = svg.append("g").selectAll("path");
popup = d3.select(container).append("div")
.classed("tooltip", true)
.classed(state, true)
.style("opacity", 0);
resources = d3.select(container).append("div")
.classed("resources", true)
.classed(state, true)
.style("opacity", 0.8);
if(state !== "END") {
timer = d3.select(container).append("div")
.classed("timer", true)
.classed(state, true)
.style("opacity", 0.8);
}
exit = d3.select(container).append("button")
.classed("exit", true)
.classed(state, true)
.style("opacity", 0.8);
path = path.data(voronoi(vertices), polygon);
path.exit().remove();
path.enter().append("path")
.attr("id", function(d) {
return "path" + d.point.id;
})
.attr("d", polygon)
.attr("opacity", function() {
return 1;
})
.data(d3BoardData)
.on("click", function(d) {
// every zone is unfaded
if (!divOpen && !isSummaryDisplayed) { // if there's a pop up open,
//you can't click a zone
if (d3.selectAll(".unfaded")[0].length > 1) {
d3.selectAll('.unfaded').classed("faded", true);
d3.selectAll('.unfaded').classed("unfaded", false);
d3.select(this).classed("unfaded", true);
d3.select(this).classed("faded", false);
} else { // single zone is selected
// clicking already unfaded zone
if (d3.select(this).attr("class").indexOf("unfaded") != -1) {
d3.selectAll('.faded').classed("unfaded", true);
d3.selectAll('.faded').classed("faded", false);
noZone = !noZone;
} else { // clicking faded zone
d3.selectAll('.unfaded').classed("faded", true);
d3.selectAll('.unfaded').classed("unfaded", false);
d3.select(this).classed("unfaded", true);
d3.select(this).classed("faded", false);
}
}
} else { // close popup instead of clicking new zone.
if (summaryOpened) {
summaryOpened = false;
}
popup.transition().duration(200)
.style("pointer-events", "none")
.style("opacity", 0);
}
if (!noZone && !divOpen) {
divOpen = true;
popup.selectAll("*").remove();
popup.transition().duration(200)
.style("pointer-events", "all")
.style("opacity", .9);
popup.style("left", width * 0.1 + "px")
.style("top", height * 0.2 + "px")
.style("width", width * 0.75 + "px")
.style("height", height * 0.6 + "px");
popup.append("div")
.attr("class", "summary-header")
.text("FRANCHISE REGION " + d.id + 1);
popup.append("div")
.attr("class", "summary-contents")
.html(function(g) {
var owner = gameBoard.getOwner(d.id);
if ( owner == null){
owner = "Independant Franchise";
}else{
owner = "<font color='"+owner.color+"'>"+owner.name+"</font>";
}
var ownerText = "<p><b>Franchise Owner:</b> "+owner + "</p>";
var numDeliveriesText = "<p><b>Pizzas Delivered This Turn:</b> <span id='deliveries'>"+gameBoard.getNumberOfDeliveries(d.id)+"</span></p>";
var productionText = "<p><b>Franchise Pizza Production:</b> "+gameBoard.regions[d.id].generator + "</p>";
return [ownerText,numDeliveriesText,productionText].join("<br />");
});
if ( state == "ROUND" && gameBoard.canDeliver(currentPlayer.id,d.id)){
var zoneButtons = popup.append("div")
.attr("class", "zone-buttons");
zoneButtons.append("button")
.attr("class", "zone-button-deliver")
.on("click", function(e) {
currentPlayer.assignDelivery(d.id);
tempNum = gameBoard.getNumberOfDeliveries(d.id);
if (tempNum > 0) {
d3.select("#path" + d.id).attr("fill", function() {
return "yellow";
});
} else {
playerId = gameBoard.regions[d.id].playerId;
if (playerId === null){
d3.select("#path" + d.id).attr("fill", function() {
return "grey";
});
}else{
d3.select("#path" + d.id).attr("fill", function() {
return gameBoard.players[playerId].color;
});
}
}
$("#deliveries").text(gameBoard.getNumberOfDeliveries(d.id));
$("#resource-bar-text").text(currentPlayer.numResources);
$(".zone-button-undeliver").prop("disabled",false);
if(currentPlayer.numResources <= 0){
$(this).prop("disabled",true);
}
})
.text("+1");
zoneButtons.append("button")
.attr("class", "zone-button-undeliver")
.on("click", function(e) {
currentPlayer.removeDelivery(d.id);
tempNum = gameBoard.getNumberOfDeliveries(d.id);
if (tempNum > 0) {
d3.select("#path" + d.id).attr("fill", function() {
return "yellow";
});
log(d3.select("#path" + d.id));
} else {
playerId = gameBoard.regions[d.id].playerId;
if (playerId === null){
d3.select("#path" + d.id).attr("fill", function() {
return "grey";
});
}else{
d3.select("#path" + d.id).attr("fill", function() {
return gameBoard.players[playerId].color;
});
}
}
var numDeliveries = gameBoard.getNumberOfDeliveries(d.id);
$("#deliveries").text(numDeliveries);
$("#resource-bar-text").text(currentPlayer.numResources);
$(".zone-button-deliver").prop("disabled",false);
if(numDeliveries <= 0){
$(this).prop("disabled",true);
}
})
.text("-1");
//disable +1 if not enough resources
if(currentPlayer.numResources <= 0 ){
$(".zone-button-deliver").prop("disabled",true);
}
if( gameBoard.getNumberOfDeliveries(d.id) <= 0){
$(".zone-button-undeliver").prop("disabled",true);
}
}
popup.append("button")
.attr("class", "ui-btn ui-shadow ui-corner-all summary-button")
.on("click", function(d) {
popup.transition().duration(200)
.style("pointer-events", "none")
.style("opacity", 0);
divOpen = false;
summaryOpened = false;
})
.text("CLOSE");
} else {
divOpen = false;
noZone = false;
}
})
.attr("fill", function(d,i){
playerId = gameBoard.regions[i].playerId;
if (playerId === null){
return "grey";
}else{
return gameBoard.players[playerId].color;
}
})
.classed("unfaded", true);
path.order();
if(state !== "END") {
timer.style("left", width * 0.01 + "px")
.style("top", height * 0.01 + "px")
.style("width", 40 + "px")
.style("height", 40 + "px");
}
exit.style("right", width * 0.01 + "px")
.style("top", height * 0.01 + "px")
.style("width", 40 + "px")
.style("height", 40 + "px")
.on("click", function(d) {
game.endTimer();
$.mobile.changePage("#page-main-menu");
})
.text("X");
resources.style("left", width * 0.25 + "px")
.style("top", height * 0.85 + "px")
.style("width", width * 0.5 + "px")
.style("height", 40 + "px");
resources.append("text")
.text(function(d) {
if(state === "PRE") {
return "PHASE: " + "PRE-ROUND ";
}
return "PHASE: " + state + " ";
})
.attr("class","resource-text")
.attr("margin", 20+"px")
.attr("height", 30 + "px")
.attr("width", 30 + "px");
resources.append("img")
.attr("src", "img/splash-pizza-2.PNG")
.attr("height", 30 + "px")
.attr("width", 30 + "px");
resources.append("text")
.text(function(d) {
return currentPlayer.numResources;
})
.attr("id","resource-bar-text")
.attr("margin", 20+"px")
.attr("height", 30 + "px")
.attr("width", 30 + "px");
resources.append("img")
.attr("src", "img/store-red.png")
.attr("height", 30 + "px")
.attr("width", 30 + "px");
resources.append("text")
.text(function(d) {
return gameBoard.getOwnedRegions(currentPlayer.id).length
})
.attr("height", 30 + "px")
.attr("width", 30 + "px");
if (isSummaryDisplayed && summaryOpened) { // load right off in summary states
divOpen = true;
popup.transition().duration(200)
.style("pointer-events", "all")
.style("opacity", .9);
popup.style("left", width * 0.1 + "px")
.style("top", height * 0.15 + "px")
.style("width", width * 0.75 + "px")
.style("height", height * 0.65 + "px");
popup.append("div")
.attr("class", "summary-header")
.text(function(d) {
if(state === "PRE") {
return "PRE-ROUND SUMMARY";
}
return state + " SUMMARY";
});
if(state === "PRE") {
popup.append("div")
.attr("class", "summary-contents")
.html(function(d) {
return "<p><b>Current Expansion Round:</b> " + gameBoard.currentRound +"</p>"
+ "<p><b>Number of Expansion Rounds Left:</b> "+ (gameBoard.numberOfRounds - gameBoard.currentRound) +"</p>"
+ "<p><b>Number of Franchises:</b> "+ gameBoard.numFranchies() +"</p>";
});
} else if (state === "END") {
popup.append("div")
.attr("class", "summary-contents")
.html(function(d) {
log(gameBoard.getWinner());
return "<p>Conquering Franchise: " + gameBoard.getWinner().name +"</p>"
+ "<p>Number of Franchise Regions: " + gameBoard.getWinner().numResources +"</p>";
});
}
if(state === "END") {
popup.append("button")
.attr("class", "ui-btn ui-shadow ui-corner-all summary-button")
.on("click", function(d) {
popup.transition().duration(200)
.style("pointer-events", "none")
.style("opacity", 0);
divOpen = false;
summaryOpened = false;
cleanup(state);
$.mobile.changePage("#page-main-menu");
})
.text("RETURN TO MAIN MENU");
} else {
popup.append("button")
.attr("class", "ui-btn ui-shadow ui-corner-all summary-button")
.on("click", function(d) {
popup.transition().duration(200)
.style("pointer-events", "none")
.style("opacity", 0);
divOpen = false;
summaryOpened = false;
})
.text("CLOSE");
}
}
}
updateTimer = function(state, timerValue) {
d3.selectAll(".timer").filter("." + state).text(timerValue);
}
cleanup = function(state) {
if (state === "PRE") {
container = "#voronoiContainer-pre";
} else if (state === "ROUND") {
container = "#voronoiContainer-round";
} else if (state === "END") {
container = "#voronoiContainer-end";
}
d3.select(container).selectAll("*").remove();
}<file_sep>var d3BoardData = [
{id: 0, x: 0.15, y: 0.14},
{id: 1, x: 0.23, y: 0.10},
{id: 2, x: 0.37, y: 0.08},
{id: 3, x: 0.74, y: 0.09},
{id: 4, x: 0.80, y: 0.10},
{id: 5, x: 0.15, y: 0.18},
{id: 6, x: 0.23, y: 0.33},
{id: 7, x: 0.37, y: 0.31},
{id: 8, x: 0.70, y: 0.23},
{id: 9, x: 0.85, y: 0.18},
{id: 10, x: 0.01, y: 0.49},
{id: 11, x: 0.23, y: 0.47},
{id: 12, x: 0.37, y: 0.37},
{id: 13, x: 0.74, y: 0.42},
{id: 14, x: 0.85, y: 0.44},
{id: 15, x: 0.01, y: 0.63},
{id: 16, x: 0.23, y: 0.57},
{id: 17, x: 0.37, y: 0.52},
{id: 18, x: 0.74, y: 0.51},
{id: 19, x: 0.85, y: 0.65},
{id: 20, x: 0.01, y: 0.67},
{id: 21, x: 0.23, y: 0.81},
{id: 22, x: 0.37, y: 0.73},
{id: 23, x: 0.74, y: 0.69},
{id: 24, x: 0.85, y: 0.72},
{id: 25, x: 0.01, y: 0.99},
{id: 26, x: 0.23, y: 0.86},
{id: 27, x: 0.37, y: 0.89},
{id: 28, x: 0.74, y: 0.94},
{id: 29, x: 0.85, y: 0.99}
]
var neighboursGenerated = false;
function generateNeighbourGraph(allCornerPoints){
if ( neighboursGenerated ){
return;
}
allCornerPoints.forEach(function(zoneCornerPoints,idx){
var neighbours = [];
//loop through the zone's corner points
zoneCornerPoints.forEach(function(cornerPoint){
//loop through other zones and find zones that have same corner point
allCornerPoints.forEach(function(zcPoints2,idx2){
if ( idx2 == idx){
return;
}
zcPoints2.forEach(function(cp2){
if ( cp2[0] == cornerPoint[0] && cp2[1] == cornerPoint[1]){
neighbours.push(idx2);
found = true;
return;
}
})
})
})
var uniqueNeighbours = []
$.each(neighbours, function(i, el){
if($.inArray(el, uniqueNeighbours) === -1) uniqueNeighbours.push(el);
});
d3BoardData[idx].neighbours = uniqueNeighbours;
})
neighboursGenerated = true;
}<file_sep>var Player = function(color,name){
this.color = color;
this.name = name;
this.numResources = 1;
}
Player.prototype.assignDelivery = function(regionId){
if ( this.numResources > 0){
gameBoard.assignDeliveries(this.id,regionId,1);
this.numResources--;
}
}
Player.prototype.removeDelivery = function(regionId){
this.numResources += gameBoard.removeDeliveries(this.id,regionId);
}
var botPlayer = new Player('blue','Bot 1');
var botPlayer2 = new Player('green','Bot 2');
var botPlayer3 = new Player('cyan','Bot 3');
var currentPlayer = new Player('red','You');
var bots = [botPlayer,botPlayer2,botPlayer3];
function initializePlayers(){
bots.forEach(function(bot){
bot.id = gameBoard.players.length;
gameBoard.players.push(bot);
})
currentPlayer.id = gameBoard.players.length;
gameBoard.players.push(currentPlayer);
gameBoard.regions[4].playerId = currentPlayer.id;
gameBoard.regions[25].playerId = botPlayer.id;
gameBoard.regions[0].playerId = botPlayer2.id
gameBoard.regions[29].playerId = botPlayer3.id
}<file_sep>var game = {};
game.page = {
'LOAD': '#page-play-game',
'PRE': '#page-game-pre-round',
'ROUND': '#page-game-round',
'END': '#page-game-end'
}
game.isInitialized = false;
game.currentRound = 0;
timerDurations = {
'LOAD': 1,
'PRE': 10,
'ROUND': 20,
}
var botNames = ['Chenbot', 'Marsha', 'Zingbot'];
game.newGame = function(){
gameBoard = new GameBoard();
initializePlayers();
game.currentState = 'PRE';
update("PRE", true);
updateTimer("PRE", timerDurations['PRE']);
$.mobile.changePage(game.page['PRE']);
};
/* debug variable */
game.paused = false;
game.initialize = function(){
if ( game.isInitialized ){
return;
}
game.isInitialized = true;
function pageLoadHandler(id,callback){
$(document).on("pageshow",id,callback);
}
var interval = null;
function countDown(startTime,callback,endCallback){
var timeRemaining = startTime;
interval = setInterval(function(){
callback(timeRemaining);
if( !game.paused ){
timeRemaining--;
if ( timeRemaining < 0){
clearInterval(interval);
endCallback();
}
}
},1000)
}
game.endTimer = function(){
clearInterval(interval)
}
$("#play-game").click(function(){
game.newGame();
})
pageLoadHandler(game.page['LOAD'],function(event){
game.currentState = 'LOAD';
$("#play-game").prop("disabled",true)
$("#matchmaking-loading").removeClass("hidden")
$("#matchmaking-div").addClass("hidden");
countDown(timerDurations['LOAD'],
function(time){
},
function(){
$("#matchmaking-list").html("");
//get bot names
var tmpBotNames = botNames;
bots.forEach(function(bot){
var index = Math.floor(Math.random()*tmpBotNames.length)
var botName = tmpBotNames[index];
bot.name = botName;
tmpBotNames.splice(index, 1);
$("#matchmaking-list").append("<li class='ui-li ui-li-static ui-btn-up-c ui-corner-top'>"+botName+"</li>");
});
$("#matchmaking-loading").addClass("hidden")
$("#matchmaking-div").removeClass("hidden");
$("#play-game").prop("disabled",false)
}
)
})
/* round start function */
pageLoadHandler(game.page['PRE'],function(event){
game.currentState = 'PRE'
countDown(timerDurations['PRE'],
function(time){
updateTimer("PRE", time);
},
function(){
cleanup("PRE");
update("ROUND", false);
updateTimer("ROUND", timerDurations['ROUND']);
$.mobile.changePage(game.page['ROUND']);
}
)
})
$("#btn-deliver").click(function(){
currentPlayer.assignDelivery($("#in-deliver-region").val())
})
function botActions(){
bots.forEach(function(bot){
var botRegions = gameBoard.getOwnedRegions(bot.id);
var numResources = bot.numResources;
for(i =0;i<numResources;i++){
var regionId = botRegions[Math.floor(Math.random()*botRegions.length)];
var neighbours = d3BoardData[regionId].neighbours;
var deliveryRegion = neighbours[Math.floor(Math.random()*neighbours.length)];
bot.assignDelivery(deliveryRegion);
}
})
}
/* ongoing round function */
pageLoadHandler(game.page['ROUND'],function(event){
game.currentState = 'ROUND'
countDown(timerDurations['ROUND'],
function(time){
updateTimer("ROUND", time);
},
function(){
cleanup("ROUND");
botActions();
gameBoard.endRound();
if ( gameBoard.isGameOver() ){
update("END", true);
game.currentState = 'END'
$.mobile.changePage(game.page['END']);
}else{
update("PRE", true);
updateTimer("PRE", timerDurations['PRE']);
$.mobile.changePage(game.page['PRE']);
}
}
)
})
/**
* Returns a random integer between min (inclusive) and max (inclusive)
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
};
|
d0bd3eed2d76a86c83e92fe11dcfa7d2fb9dfef7
|
[
"Markdown",
"JavaScript"
] | 5 |
Markdown
|
Demelode/Game-Design-Pizza-Crusader
|
4c96ff4dabe19523446401f8c1e5bb2aa3527ba9
|
08ac1cb5eccc16fd1220c01c7e7679ae629546b0
|
refs/heads/master
|
<file_sep>import cipher from './cipher.js';
/*console.log(cipher);*/
const btnCodificar = document.getElementById("codificar");
btnCodificar.addEventListener("click", codificar);
function codificar(eventoDeClique){
eventoDeClique.preventDefault();
let msgParaCod = String(document.getElementById("msgCod").value);
let offsetCod = Number(document.getElementById("offsetCod").value);
const resultMsgCod=cipher.encode (offsetCod, msgParaCod);
document.getElementById("resultCod").innerHTML=resultMsgCod;
}
const btnDecodificar = document.getElementById("decodificar");
btnDecodificar.addEventListener("click", decodificar);
function decodificar(eventoDeClique){
eventoDeClique.preventDefault()
let msgParaDecod = String(document.getElementById("msgDecod").value);
let offsetCod = Number(document.getElementById("offsetDecod").value);
const resultMsgDecod=cipher.decode(offsetCod,msgParaDecod);
document.getElementById("resultDecod").innerHTML=resultMsgDecod;
}<file_sep># Cifra de César (<NAME>)
## Índice
* [1. Protótipo](#1-protótipo)
* [2. Resumo do projeto](#2-resumo-do-projeto)
* [3. Usuários e suas relações com o produto](#3-usuários-e-suas-relações-com-o-produto)
* [4. Como o produto soluciona os problemas/necessidades dos usuários](#4-como-o-produto-soluciona-os-problemas-/-necessidades-dos-usuários)
* [5. Considerações Finais](#5-considerações-finais)
* [6. Checklist](#6-checklist)
***
## 1. Protótipo
A seguir, está o protótipo inicial do site. Um fluxograma da criação das funcionalidades do site e um fluxo dos processos para criação do projeto.



## 2. Resumo do projeto
O site "<NAME> Cryptography"é uma ferramenta para criptografar e descriptografar mensagens, usando a Cif<NAME> como método de criptografia. O tema foi baseado no filme "<NAME>", já que nele é usado mensagens codificadas entre a protagonista e sua mãe.
## 3. Usuários e suas relações com o produto
O produto foi criado com foco em usuários que desejam ter uma experiência de comunicação criptografada igual a protagonista do filme. Assim podem tanto enviar mensagens criptografadas, como descriptografas mensagens recebidas.
## 4. Como o produto soluciona os problemas/necessidades dos usuários
O usuário pode tanto enviar mensagens criptografadas, como descriptografar mensagens recebidas. Assim solucionando seus problemas e sanando suas necessidades de uma comunicação que não quer que seja decifrada.
## 5. Considerações Finais
O projeto foi muito intenso e serviu para mostrar como será o método de ensino da Laboratória, não foi fácil, mas acho que a adaptação virá com o tempo.
## 6. Checklist
* [X] `README.md` adicionar informação sobre o processo e decisões do desenho.
* [X] `README.md` explicar claramente quem são os usuários e as suas relações
com o produto.
* [X] `README.md` explicar claramente como o produto soluciona os
problemas/necessidades dos usuários.
* [X] Usar VanillaJS.
* [X] **Não** usar `this`.
* [X] Implementar `cipher.encode`.
* [X] Implementar `cipher.decode`.
* [X] Passar o linter com a configuração definida.
* [X] Passar as provas unitárias.
* [X] Testes unitários cubrindo 70% dos _statements_, _functions_ e _lines_, e
no mínimo 50% das _branches_.
* [X] Interface que permita escolher o `offset` (chave de deslocamento) usava
para cifrar/decifrar.
* [X] Interface que permita escrever um texto para ser cifrado.
* [X] Interface que mostre o resultado da cifra corretamente.
* [X] Interface que permita escrever um texto para ser decifrado.
* [X] Interface que mostre o resultado decifrado corretamente.
### Parte Opcional: "Hacker edition"
* [X] Cifrar/decifrar minúsculas.
* [X] Cifrar/decifrar _outros_ caractéres (espações, pontuação, `ç`, `á`, ...).
* [X] Permitir usar `offset` negativo.
<file_sep>const tamAlfabeto=26;
const cipher = {
encode (offsetCod,msgParaCod){
let resultMsgCod="";
if (typeof offsetCod == "number" && typeof msgParaCod == "string"){
for (let i = 0; i < msgParaCod.length; i++) {
const codASC = msgParaCod.charCodeAt(i);
let MsgCod = "";
if (codASC >=65 && codASC <= 90){
let cod1letra=65;
const desloc = ((codASC-cod1letra+Math.abs(offsetCod))%tamAlfabeto)+cod1letra;
MsgCod=String.fromCharCode(desloc);
resultMsgCod += MsgCod;
}else if (codASC >=97 && codASC <= 122){
let cod1letra=97;
const desloc = ((codASC-cod1letra+Math.abs(offsetCod))%tamAlfabeto)+cod1letra;
MsgCod=String.fromCharCode(desloc);
resultMsgCod += MsgCod;
}else{
MsgCod=String.fromCharCode(codASC);
resultMsgCod += MsgCod;
}
}
}else {
throw new TypeError();
}
return resultMsgCod;
},
decode (offsetDecod,msgParaDecod){
let resultMsgDecod="";
if (typeof offsetDecod == "number" && typeof msgParaDecod == "string"){
for (let i = 0; i < msgParaDecod.length; i++) {
const codASC = msgParaDecod.charCodeAt(i);
let MsgDecod = "";
if (codASC >=65 && codASC <= 90){
let codUltimaLetra=90;
const desloc =((codASC-codUltimaLetra-Math.abs(offsetDecod))%tamAlfabeto)+codUltimaLetra;
MsgDecod=String.fromCharCode(desloc);
resultMsgDecod += MsgDecod;
}else if (codASC >=97 && codASC <= 122){
let codUltimaLetra=122;
const desloc = ((codASC-codUltimaLetra-Math.abs(offsetDecod))%tamAlfabeto)+codUltimaLetra;
MsgDecod=String.fromCharCode(desloc);
resultMsgDecod += MsgDecod;
} else {
MsgDecod=String.fromCharCode(codASC);
resultMsgDecod += MsgDecod;
}
}
}else {
throw new TypeError();
}
return resultMsgDecod;
}
}
export default cipher;
|
06f4b3cf96c1740a2d625cfe2d1e333449de0e4c
|
[
"JavaScript",
"Markdown"
] | 3 |
JavaScript
|
LauraDeperon/EnolaHolmes-Laboratoria
|
4a2341de9ef9bef7a8f19e9f8ca9ec4e9bab9a66
|
d2f657694ad6a9baf37191a80e5ac93d1155bc06
|
refs/heads/master
|
<repo_name>goniti/pixelArtInvader<file_sep>/js/script.js
const app = {
size: 8,
pixel: 20,
color: 'cell--white',
slate: document.getElementById('board'),
container: document.getElementById('app'),
form: document.getElementsByClassName('settings')[0],
makeGrid: () => {
// create a grid of 64 cells 8 rows x 8 columns
for (let indexRow = 0; indexRow < app.size; indexRow++) {
const row = document.createElement('div');
row.classList.add('row');
for (let indexColumn = 0; indexColumn < app.size; indexColumn++) {
const cell = document.createElement('div');
cell.classList.add('cell', 'cell--white');
row.appendChild(cell);
}
app.slate.appendChild(row);
}
// Set a default pixel size of 20
const cells = document.getElementsByClassName('cell');
for (let index = 0; index < cells.length; index++) {
cells[index].style.height = app.pixel + 'px';
cells[index].style.width = app.pixel + 'px';
cells[index].addEventListener('click', (event) => {
event.target.setAttribute('class', `box ${app.color}`);
});
}
},
eraseGrid: () => {
app.slate.innerHTML = '';
},
makePalette: () => {
// Create DOM element
const colorPalette = document.createElement('div');
const colorWhite = document.createElement('div');
const colorBlack = document.createElement('div');
const colorYellow = document.createElement('div');
const colorGreen = document.createElement('div');
// Add class for all palette elements
colorPalette.classList.add('panel');
colorWhite.classList.add(
'panel__button',
'cell--white',
'panel__button--is-active',
);
colorBlack.classList.add('panel__button', 'cell--black');
colorYellow.classList.add('panel__button', 'cell--yellow');
colorGreen.classList.add('panel__button', 'cell--green');
// append elements on DOM
colorPalette.appendChild(colorWhite);
colorPalette.appendChild(colorBlack);
colorPalette.appendChild(colorYellow);
colorPalette.appendChild(colorGreen);
app.container.appendChild(colorPalette);
},
colorPicker: () => {
const buttons = document.getElementsByClassName('panel__button');
for (let indexButtons = 0; indexButtons < buttons.length; indexButtons++) {
buttons[indexButtons].addEventListener('click', function (event) {
const buttonActive = document.getElementsByClassName(
'panel__button--is-active',
)[0];
buttonActive.classList.remove('panel__button--is-active');
event.target.classList.add('panel__button--is-active');
app.color = event.target.className.split(' ')[1];
});
}
},
makeForm: () => {
const inputGrid = document.createElement('input');
inputGrid.classList.add('entries', 'entries--grid');
inputGrid.setAttribute('type', 'text');
inputGrid.setAttribute('name', 'grid');
inputGrid.setAttribute('placeholder', 'Taille de la grille');
const inputSize = document.createElement('input');
inputSize.classList.add('entries', 'entries--pixels');
inputSize.setAttribute('type', 'text');
inputSize.setAttribute('name', 'size');
inputSize.setAttribute('placeholder', 'Taille des pixels');
const submit = document.createElement('input');
submit.classList.add('entries', 'entries--submit');
submit.setAttribute('type', 'submit');
submit.setAttribute('value', 'Valider');
app.form.appendChild(inputGrid);
app.form.appendChild(inputSize);
app.form.appendChild(submit);
},
handleSubmit: (event) => {
event.preventDefault();
const grid = event.target.grid.value;
const size = event.target.size.value;
if (grid < 1 || grid > 16 || isNaN(grid)) {
alert('La taille de la grille doit etre un nombre compris entre 1 et 16');
} else if (size < 15 || size > 40 || isNaN(size)) {
alert(
"La taille d'un case en pixels doit etre un nombre compris entre 15 et 40",
);
} else {
app.pixel = size;
app.size = grid;
app.eraseGrid();
app.makeGrid();
}
},
init: () => {
app.makeGrid();
app.makePalette();
app.colorPicker();
app.makeForm();
app.form.addEventListener('submit', app.handleSubmit);
},
};
app.init();
<file_sep>/README.md
# Pixel Art Invader
## Introduction
In addition to using HTML and CSS, we will learn how to use JavaScript to add interactivity.
> Create a pixel art editor.
>
> 
---
## Summary of the application
### Elements
- A grid with pixels
- colour palette.
### How it works
__step 1 - set up the drawing space.__
- Define a grid size between 1 and 16
- Set a pixel size between 15 and 40
__step 2 - drawing.__
- Choose a colour by clicking on the colour palette ,
- Draw by clicking on the pixels of the grid to change their colour.
[start the demo](https://goniti.github.io/pixelArtInvader/)
|
a202668a0a57702eedda733d9af80d3845ea437b
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
goniti/pixelArtInvader
|
a7cbbb28e16a34ce12fdc58541483e170093fe49
|
e373bab3f551c2c71e89b2342a979fb5307e832e
|
refs/heads/master
|
<file_sep>import React from 'react';
import './About.css';
function About(props) {
return (
<div className='about__container'>
<span>“ To do a great right do a little wrong. "</span>
<span>− <NAME>, 2020</span>
</div>
);
}
export default About;
<file_sep># Movie Info
Info About Movies
|
681a9dea07d38b06f8accc19df21385d752dc3ca
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
tun-eer/movie_info
|
bf56811af4d6d1be6cbd1e55e222bdec47246e34
|
313da9c62a080bf3f7d074b1f2b41559a99cd6f8
|
refs/heads/master
|
<repo_name>mattpetters/battlestuff<file_sep>/README.md
# battlestuff
Unity game
<file_sep>/Assets/Scripts/Network.cs
using UnityEngine;
using System.Collections;
using SocketIO;
public class Network : MonoBehaviour {
static SocketIOComponent socket;
// Use this for initialization
void Start () {
socket = GetComponent<SocketIOComponent> ();
socket.On ("open", OnConnected);
}
// Update is called once per frame
void OnConnected(SocketIOEvent e){
Debug.Log ("connected");
socket.Emit("move");
}
}
|
1339d6e6bd92bb76dea492efe795aadd1cfcc9b7
|
[
"Markdown",
"C#"
] | 2 |
Markdown
|
mattpetters/battlestuff
|
41f71c818f1715883df938ab10d9a321ba0b67b2
|
52a757bd725e05b8808c7d6e82a65cd84d49ad16
|
refs/heads/master
|
<file_sep>rm *.class;
javac _Demo.java;
java _Demo $1 $2;
<file_sep>class _Demo {
public static void main(String[] args){
if (args.length < 2){
System.out.println("Please specify two strings to test");
System.exit(0);
}
IsPermutation is_perm = new IsPermutation(args);
boolean result = is_perm.res;
System.out.println("The result of " + args[0] + " and " + args[1] + " is: " + result);
}
}
<file_sep>class IsPermutation{
public boolean res = false;
public IsPermutation(String[] args){
String word_1 = args[0];
String word_2 = args[1];
if(word_1.length() != word_2.length()){
return;
}
int[] char_array = new int[500];
boolean is_perm = true;
for(int i = 0; i < word_1.length(); i++){
char this_char = word_1.charAt(i);
int char_num = Character.getNumericValue(this_char);
char_array[char_num]++;
}
for(int i = 0; i < word_2.length(); i++){
char this_char = word_2.charAt(i);
int char_num = Character.getNumericValue(this_char);
char_array[char_num]--;
if(char_array[char_num] < 0){
is_perm = false;
}
}
if(is_perm){
res = true;
}
}
}
<file_sep># Is Permutation
Determines if two string are permutations of one another
## Usage
See contents of `run.sh` or use:
>
sh run.sh the_first_string the_second_string
|
8f5bfd140194938c158736e659b51854b1167012
|
[
"Markdown",
"Java",
"Shell"
] | 4 |
Shell
|
wallyfaye/is-permutation
|
37875e64059933c245e83ede8dca343b521fc6e6
|
30c22076c81c4732344aaefb85596bb1477d5716
|
refs/heads/master
|
<repo_name>feawesome/spa-bus<file_sep>/src/index.js
class SPAEventBus {
constructor() {
this.events = {};
this.addEventListener = this.addEventListener.bind(this);
this.emit = this.emit.bind(this);
this.removeEventListener = this.removeEventListener.bind(this);
}
addEventListener(type, callBack) {
if (typeof type !== 'string') {
console.error('event type must be string');
}
if (typeof callBack !== 'function') {
console.error('callBack type must be function');
}
if (!(type in this.events)) {
this.events[type] = [callBack];
} else {
this.events[type].push(callBack);
}
}
removeEventListener(type, callBack) {
if (typeof type !== 'string') {
console.error('event type must be string');
}
if (Array.isArray(this.events[type])) {
this.events[type] = this.events[type].filter(item => item !== callBack);
if (this.events[type].length === 0) {
delete this.events[type];
}
} else {
console.error('This event is not being listened');
}
}
emit(type, params, context = this) {
if (!(type in this.events)) {
console.error('unknown event type');
return
}
if (Array.isArray(this.events[type])) {
this.events[type].forEach(item => {
if (typeof item === 'function') {
item.call(context, params)
} else {
console.error('unknown event type')
}
})
}
}
}
export default new SPAEventBus();
<file_sep>/example/src/app.js
import React from 'react'
import { render } from 'react-dom'
import Parent from './Parent'
import EventEmitter from '../../src'
class App extends React.Component{
constructor(props) {
super(props)
EventEmitter.addEventListener('testEvent', this.testFunction1)
EventEmitter.addEventListener('testEvent', this.testFunction2)
}
testFunction1() {
console.log('testFunction1', this)
}
testFunction2(args) {
console.log('testFunction2', args)
}
componentDidMount() {
document.onclick = () => {
EventEmitter.removeEventListener('testEvent', this.testFunction2)
}
}
render() {
return (
<div>
<h1>父组件</h1>
<Parent/>
</div>
)
}
}
render(<App />, document.getElementById('root'))
<file_sep>/README.md
[](https://github.com/feawesome/spa-bus/stargazers)
[](https://github.com/feawesome/spa-bus/issues)
[](https://github.com/feawesome/spa-bus/network)
[](https://github.com/feawesome/spa-bus)
[](https://github.com/feawesome/spa-bus)
[](https://twitter.com/intent/tweet?url=https://github.com/feawesome/spa-bus)
[](https://nodei.co/npm/spa-bus/)
[](https://nodei.co/npm/spa-bus/)
## spa-bus
By this tool, you can pass values across multilevel components, you don't need to pass them step by step.
### Example
* [Demo Page](https://feawesome.github.io/spa-bus)
* Demo Code
```jsx
import React from 'react'
import { render } from 'react-dom'
import eventEmitter from 'spa-bus'
function Child() {
eventEmitter.emit('testEvent', '传值给父组件')
return <div>我是子组件</div>
}
class App extends React.Component{
constructor(props) {
super(props)
eventEmitter.addEventListener('testEvent', e => console.log(e))
}
render() {
return (
<div>
<h1>我是父组件</h1>
<Child/>
</div>
)
}
}
render(<App />, document.getElementById('root'))
```
### Install
#### NPM
``` bash
npm install spa-bus --save
```
### API
- addEventListener:
* `type` : `[ String ]` : event type for listening
* `callBack` : `[ String ]` : callback for the event emited
- emit:
* `type` : `[ String ]` : event type to emit
* `params` : `[ any ]` : parameters to accross
- removeEventListener:
* `type` : `[ String ]` : event type for removal
### Author
**<NAME>**
**<EMAIL>**
<file_sep>/example/src/Child.js
import React from 'react'
import EventEmitter from '../../src'
export default class Child extends React.Component {
componentDidMount() {
EventEmitter.emit('testEvent', '传值给爷爷组件', this)
}
render() {
return <div>孙子组件</div>
}
}
|
4a72d30ac5aecb7285757380a9fa952e973acd87
|
[
"JavaScript",
"Markdown"
] | 4 |
JavaScript
|
feawesome/spa-bus
|
948563660e0d1cbe258751fbbc9589f44744d6b3
|
df02a31356d7efee2649570efc2f004e4d6fac74
|
refs/heads/master
|
<file_sep>import csv
# CSV format settings
csvlt = '\n'
csvdel = ','
csvquo = '"'
# open the input and output files
with open('out/tables/destination.csv', mode='wt', encoding='utf-8') as out_file:
# write output file header
writer = csv.DictWriter(out_file, fieldnames=['number', 'someText'], lineterminator=csvlt, delimiter=csvdel, quotechar=csvquo)
writer.writeheader()
# do something and write row
writer.writerow({'number': 10, 'someText': 'apples'})
writer.writerow({'number': 20, 'someText': 'oranges'})
writer.writerow({'number': 15, 'someText': 'melons'})
writer.writerow({'number': 6, 'someText': 'bananas'})
<file_sep># cs-python-test
|
fb31ba5aaff042bb0416ceb5ef516734d6a2a5a2
|
[
"Markdown",
"Python"
] | 2 |
Python
|
odinuv/cs-python-test
|
89974508f7047b3791f736e384244e56bfe9c874
|
d6ad329f9d3f3c4a84886f06842353d74743e174
|
refs/heads/master
|
<file_sep>package global
import "github.com/opentracing/opentracing-go"
var(
Tracer opentracing.Tracer
)
<file_sep>package api
import (
"github.com/gin-gonic/gin"
"github.com/wolf88804/blog-service/global"
"github.com/wolf88804/blog-service/internal/service"
"github.com/wolf88804/blog-service/pkg/app"
"github.com/wolf88804/blog-service/pkg/errcode"
)
// @Summary 获取token
// @Produce json
// @Param app_key query string true "Key"
// @Param app_secret query string true "Secret"
// @Success 200 {object} gin.Context "成功"
// @Failure 400 {object} errcode.Error "请求错误"
// @Failure 500 {object} errcode.Error "内部错误"
// @Router /auth [get]
func GetAuth(c *gin.Context) {
param := service.AuthRequest{}
response := app.NewResponse(c)
vaild, errs := app.BindAndValid(c, ¶m)
if vaild {
global.Logger.Errorf(c,"app.BindAndValid errs: %v", errs)
response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
return
}
svc := service.New(c.Request.Context())
err := svc.CheckAuth(¶m)
if err != nil {
global.Logger.Errorf(c,"svc.CheckAuth err: %v", err)
response.ToErrorResponse(errcode.UnauthorizedAuthNotExist)
return
}
token, err := app.GenerateToken(param.AppKey, param.AppSecret)
if err != nil {
global.Logger.Errorf(c,"svc.GenerateToken err: %v", err)
response.ToErrorResponse(errcode.UnauthorizedTokenGenerate)
return
}
response.ToResponse(gin.H{"token": token})
}
<file_sep>package errcode
var (
ErrorGetTagFail = NewError(20010000, "获取标签失败")
ErrorGetTagListFail = NewError(20010001, "获取标签列表失败")
ErrorCreateTagFail = NewError(20010002, "创建标签失败")
ErrorUpdateTagFail = NewError(20010003, "更新标签失败")
ErrorDeleteTagFail = NewError(20010004, "删除标签失败")
ErrorCountTagFail = NewError(20010005, "统计标签失败")
ErrorGetArticleFail = NewError(20020000, "获取文章失败")
ErrorGetArticleListFail = NewError(20020001, "获取文章列表失败")
ErrorCreateArticleFail = NewError(20020002, "创建文章失败")
ErrorUpdateArticleFail = NewError(20020003, "更新文章失败")
ErrorDeleteArticleFail = NewError(20020004, "删除文章失败")
ErrorCountArticleFail = NewError(20020005, "统计文章失败")
ErrorUploadFileFail = NewError(20030000, "上传文件失败")
)
|
a62532ada85f04ecf4f67bb2180060fea405f410
|
[
"Go"
] | 3 |
Go
|
wolf88844/blog-service
|
dc0a2b133f1c7a6877b9b6d25c5041b8f3c822d3
|
1d8f52424c589ef5823fd57253a724cb73f48260
|
refs/heads/master
|
<file_sep>import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
red: string = '#FF0000';
orange: string = '#FFA500';
yellow: string = '#FFFF00';
green: string = '#008000';
blue: string = '#0000FF';
indigo: string = '#4B0082';
violet: string = '#EE82EE';
hideTable:string = '';
eventStyleChanger(e): void {
console.log(e);
this.hideTable = 'collapse';
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-comp1',
templateUrl: './comp1.component.html',
styleUrls: ['./comp1.component.css']
})
export class Comp1Component implements OnInit {
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
interpolationValue: number = 1.1234567;
interpolationPipeValue: string = 'привет мир!';
interpolationPipeDateValue: Date = new Date();
dataBindingValue: string = '';
paramValue: string = '';
constructor() { }
ngOnInit(): void {
}
eventBindingHandler(e): void {
console.log(e);
}
}
|
41277d2b8d269b69ee0f2c076f6f8236a023beb4
|
[
"TypeScript"
] | 2 |
TypeScript
|
garlife/hw-lesson2
|
a5632cf6e113a31b65e457565786e5c017cc29ed
|
48814a9bbd3906fe5cc51d17951232d7831b7dc1
|
refs/heads/master
|
<file_sep>
# monkey
跑Monkey后把日志中的error项转换为Excel表格指导说明:
1、解压xlwt-1.0.0,然后把解压后的文件夹放到python安装文件夹的根目录下面
2、在xlwt-1.0.0文件夹中的setup.py文件路径下,在命令行中输入 python setup.py install
3、把analynsis.py、write_excel.py和导出的monkeyResult文件夹放在同一路径下
4、运行analynsis.py脚本,本地就会生成logresult.xls文件<file_sep>#-*-coding:utf8-*-
import threading,shutil,re
import os,sys,time,tarfile
from optparse import OptionParser
__author__ = 'Virtue'
def runMonkeyAll(SN):
time.sleep(1)
os.system("adb -s %s root" % SN)
os.system("adb -s %s remount" % SN)
time.sleep(1)
os.system("adb -s %s shell rm -rf /sdcard/monkeytest/" % SN)
os.system("adb -s %s shell mkdir /sdcard/monkeytest/" % SN)
os.system('adb -s %s shell am broadcast -a android.intent.action.MEDIA_MOUNTED -d "file:///mnt/sdcard" ' % SN)
os.system("adb -s %s push monkeyAll.sh /data/local/tmp/ " % SN)
os.system("adb -s %s push whitelist.txt /sdcard/ " % SN)
os.system("adb -s %s shell chmod 777 /data/local/tmp/monkeyAll.sh " % SN)
os.system("adb -s %s shell input swipe 500 1000 500 50 100" % SN)
os.system("adb -s %s shell input swipe 500 1000 500 50 100" % SN)
os.system("adb -s %s shell input swipe 500 1000 500 50 100" % SN)
os.system("adb -s %s shell sh /data/local/tmp/monkeyAll.sh" % SN)
return True
def search_sn():
command = 'adb devices'
os.system(command)
output = os.popen(command).read()
if 'List of devices attached' in output:
deviceslist = [device.split('\t')[0] for device in output.split('\n')[1:] if device != '']
if len(deviceslist)>0:
print deviceslist
return deviceslist
else:
print 'no devices found, script exit'
return False
sys.exit()
else:
print ('adb status error, script exit')
return False
sys.exit(1)
def batch_flash():
workers = []
sn_list = search_sn()
for sn in sn_list:
workers.append(threading.Thread(target=runMonkeyAll, args=(sn,)))
for worker in workers:
worker.start()
for worker in workers:
worker.join()
if __name__ == '__main__':
print ('==================================================================')
print (' START monkey ')
print ('============START monkey==============START monkey=============================')
batch_flash()
<file_sep>操作步骤:
1 配置好环境变量;
2 Whitelist.txt 里面放入需要测试的应用apk包名;
3 双击monkey.py 可进行monkey测试;
4 测试完成,手机连上电脑adb,运行PullLog.py 导出monkey日志及报错信息;
5 运行analynsis.py ,生成 excel 的结果文档
备注:设置monkey测试时长通过设置monkey的点击时间,monkeyAll.sh里面的 -v -v -v 后面的数字,时长对应的次数如下:
0.5h=25000 2h=100000 6h= 300000
12h=600000 24h=1200000 72h=3600000
跑Monkey后把日志中的error项转换为Excel表格指导说明:
1、解压xlwt-1.0.0,然后把解压后的文件夹放到python安装文件夹的根目录下面
2、在xlwt-1.0.0文件夹中的setup.py文件路径下,在命令行中输入 python setup.py install
3、把analynsis.py、write_excel.py和导出的monkeyResult文件夹放在同一路径下
4、运行analynsis.py脚本,本地就会生成logresult.xls文件
<file_sep>#coding=utf8
import threading
import sys
__author__ = 'Virtue'
import time,os
def pulllog(SN):
if os.path.exists("monkeyResult"):
pass
else:
os.makedirs("monkeyResult")
print "start pull log"
os.system("adb -s %s pull /sdcard/monkeytest monkeyResult\\%s\\" % (SN,SN))
print "end pull log"
time.sleep(10)
def search_sn():
command = 'adb devices'
os.system(command)
output = os.popen(command).read()
if 'List of devices attached' in output:
deviceslist = [device.split('\t')[0] for device in output.split('\n')[1:] if device != '']
if len(deviceslist)>0:
print deviceslist
return deviceslist
else:
print 'no devices found, script exit'
return False
sys.exit()
else:
print ('adb status error, script exit')
return False
sys.exit(1)
def batch_flash():
workers = []
sn_list = search_sn()
for sn in sn_list:
workers.append(threading.Thread(target=pulllog, args=(sn,)))
for worker in workers:
worker.start()
for worker in workers:
worker.join()
if __name__ == '__main__':
print '=================================================================='
print ' START BATCH FLASH '
print '=================================================================='
batch_flash()
<file_sep>#coding=utf-8
import threading
import sys
import time,os
import re, csv
from write_excel import write_excel as wrex
def analysis():
contents = []
filelist=os.listdir("./monkeyResult")
for erraddress in filelist:
listfile1=os.listdir("./monkeyResult/"+erraddress+"/")
for lili in listfile1:
fl2 = []
matchObi = re.match( r'error.*', lili)
if matchObi:
fl2.append(matchObi.group())
for mon in fl2:
arr_err1 = []
milk = open("./monkeyResult/"+erraddress+"/"+mon,"r")
meat = milk.readlines()
for infoo in meat:
matchObk = re.match( r'\/\/\s(CRASH\:\s\S*)', infoo) #crash
if matchObk:
arr_err1.append(matchObk.group(1))
matchObm = re.match( r'\/\/\sShort\sMsg\:\s(Native\scrash)', infoo) #Native crash
if matchObm:
print (matchObm.group(1))
arr_err1[-1] = arr_err1[-1].replace('CRASH','Native crash')
for infoo in meat:
matchObl = re.match( r'ANR\sin\s\S*', infoo) #ANR
if matchObl:
arr_err1.append(matchObl.group())
arr_err1[-1] = arr_err1[-1].replace(' in',':')
mysets = sorted(set(arr_err1))
for item in mysets:
tt=arr_err1.count(item)
tem='%d' %tt
cont = [erraddress,item,tem]
contents.append(cont)
milk.close()
wrex(contents)
#send_email(contents,"path")
def main():
os.system("pause")
analysis()
if __name__ == '__main__':
print ('==================================================================')
print (' analysis ')
print ('==================================================================')
main()
<file_sep>#!usr/bin/env python
#-*-coding:utf-8-*-
import xlwt
def write_excel(contents):
workbook = xlwt.Workbook(encoding="utf-8")
sheet = workbook.add_sheet("logresult", cell_overwrite_ok=True)
style = xlwt.easyxf(
"align: wrap off,vert centre, horiz centre;"
"font: bold on;" #字体
"borders: left medium,right medium,top medium,bottom medium;"
"pattern: pattern solid, fore_colour gray40;"
)
style1 = xlwt.easyxf(
"align: wrap off, vert centre, horiz left;"
"borders: left medium,right medium,top medium,bottom medium;"
)
style2 = xlwt.easyxf(
"align: wrap off, vert centre, horiz centre;"
"borders: left medium,right medium,top medium,bottom medium;"
)
title_rows = ["SN(pakeage)","issues","counts"]
for i,t in enumerate(title_rows):
sheet.write(0, i, t, style)
for ix,x in enumerate(contents,start=1):
for i,t in enumerate(x):
new_style = style2
if i == 1:
new_style = style1
sheet.write(ix, i, t, new_style)
first_col=sheet.col(0)
sec_col=sheet.col(1)
thri_col=sheet.col(2)
first_col.width=256*15
sec_col.width=256*50
thri_col.width=256*10
workbook.save("logresult.xls")
if __name__ == '__main__':
write_excel()
<file_sep>#!/usr/bin/env bash
echo "start monkey"
echo "get log"
logcat -d -v threadtime > /sdcard/monkeytest/logcat.txt &
monkey --pkg-whitelist-file /sdcard/whitelist.txt -s $RANDOM --throttle 300 --ignore-crashes --ignore-timeouts --ignore-native-crashes -v -v -v 100000 2>/sdcard/monkeytest/error.txt 1>/sdcard/monkeytest/info.txt
echo "end monkey"
logcat -d -b radio -v threadtime > /sdcard/monkeytest/radio.txt
logcat -d -b events -v threadtime > /sdcard/monkeytest/events.txt
logcat -d -b system -v threadtime > /sdcard/monkeytest/system.txt
getprop > /sdcard/monkeytest/props.txt
env > /sdcard/monkeytest/env.txt
dmesg > /sdcard/monkeytest/dmesg.txt
cat /proc/last_kmsg > /sdcard/monkeytest/last_kmsg.txt
cat /sys/fs/pstore/console-ramoops > /sdcard/monkeytest/console-ramoops
ps > /sdcard/monkeytest/ps.txt
ps -t > /sdcard/monkeytest/ps_t.txt
top -n 1 -t > /sdcard/monkeytest/top_t.txt
tinymix > /sdcard/monkeytest/tinymix.txt
cat /proc/cmdline > /sdcard/monkeytest/cmdline.txt
ls -lR /data > /sdcard/monkeytest/userdata_check.txt
echo 1 > /proc/sys/kernel/sysrq
echo w > /proc/sysrq-trigger
dmesg > /sdcard/monkeytest/dmesg_sysrq_blocked_tasks.txt
dumpsys power> /sdcard/monkeytest/power.txt
dmesg > /sdcard/monkeytest/dmesg_sysrq.txt
echo "getting screenshot ..."
screencap -p /sdcard/monkeytest/screenshot.png
echo "getting bugreport ... "
bugreport > /sdcard/monkeytest/bugreport.txt
echo "getting dropbox,anr,tombstones,logd...."
cp -fr /data/system/dropbox /sdcard/monkeytest/dropbox
cp -fr /data/anr /sdcard/monkeytest/anr
cp -fr /data/tombstones /sdcard/monkeytest/tombstones
cp -fr /data/misc/logd /sdcard/monkeytest/logd
cp -fr /data/zslogs /sdcard/monkeytest/zslogs
cp -fr /data/cplc_info /sdcard/monkeytest/cplc
cp -fr /sdcard/logs /sdcard/monkeytest/offlinelogs
cp -fr /sdcard/tcpdump /sdcard/monkeytest/tcpdump
echo "doooooooooone\n"
exit
|
d8e08e0351c80050c3b43fa50aa12c25997369c5
|
[
"Markdown",
"Python",
"Text",
"Shell"
] | 7 |
Markdown
|
virtueqwl/monkey
|
ac74f7b46742bc207d104c14b30b2834e68b411f
|
453bb1c219e488a9c8889bb087cd5d8a1883892e
|
refs/heads/main
|
<repo_name>GajananSOS/sapsol-test<file_sep>/app/Traits/VerifiesEmail.php
<?php
namespace App\Traits;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\Events\Verified;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
trait VerifiesEmail
{
// use RedirectsUsers;
public function verify(Request $request)
{
$user = Session::get('user');
if (!hash_equals((string) $request->route('id'), (string) $user->getKey())) {
throw new AuthorizationException;
}
if (!hash_equals((string) $request->route('hash'), sha1($user->getEmailForVerification()))) {
throw new AuthorizationException;
}
if ($user->hasVerifiedEmail()) {
return $request->wantsJson()
? new JsonResponse([], 204)
: redirect('/home');
}
if ($user->markEmailAsVerified()) {
event(new Verified($user));
}
return $request->wantsJson()
? new JsonResponse([], 204)
: redirect('/home');
}
public function resend(Request $request)
{
if ($request->session()->get('user')->email_verified_at) {
return $request->wantsJson()
? new JsonResponse([], 204)
: redirect('/home');
}
$user = Session::get('user');
$user->sendEmailVerificationNotification();
return $request->wantsJson()
? new JsonResponse([], 202)
: back()->with('resent', true);
}
}
<file_sep>/app/Http/Controllers/AuthController.php
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
public function showRegistrationForm()
{
return view('auth.register');
}
public function register(Request $request)
{
$this->validate($request, [
'name' => ['required'],
'email' => ['required', 'email'],
'password' => ['required', 'confirmed']
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => <PASSWORD>($request->password)
]);
event(new Registered($user));
return redirect()->route('login');
}
public function showLoginForm()
{
return view('auth.login');
}
public function login(Request $request)
{
$request->validate([
'email' => 'required|string',
'password' => '<PASSWORD>',
]);
$user = User::where('email', $request->email)->first();
if (!$user) {
return back()->with('message', "User Desen't Exist");
}
$pass = <PASSWORD>($request->password, $user->password);
// dd($pass);
if ($pass) {
$request->session()->put('user', $user);
$request->session()->regenerate();
}
return redirect('/home');
}
public function logout(Request $request)
{
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}
<file_sep>/routes/web.php
<?php
use App\Http\Controllers\AuthController;
use App\Http\Controllers\VerificationController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/register', [AuthController::class, 'showRegistrationForm'])->name('register');
Route::post('/register', [AuthController::class, 'register'])->name('register');
Route::get('/login', [AuthController::class, 'showLoginForm'])->name('login');
Route::post('/login', [AuthController::class, 'login'])->name('login');
Route::post('/logout', [AuthController::class, 'logout'])->name('logout');
Route::get('/email/verify', [VerificationController::class, 'show'])->name('verification.notice');
Route::get('/email/verify/{id}/{hash}', [VerificationController::class, 'verify'])->name('verification.verify')->middleware(['signed']);
Route::post('/email/resend', [VerificationController::class, 'resend'])->name('verification.resend');
Route::middleware(['authCheck', 'emailVerified'])->group(function () {
Route::get('/home', function () {
return view('home');
})->name('home');
});
<file_sep>/app/Http/Controllers/VerificationController.php
<?php
namespace App\Http\Controllers;
use App\Traits\VerifiesEmail;
use Illuminate\Http\Request;
class VerificationController extends Controller
{
use VerifiesEmail;
protected $redirectTo = '/';
public function __construct()
{
// $this->middleware('auth');
// $this->middleware('signed')->only('verify');
$this->middleware('throttle:6,1')->only('verify', 'resend');
}
public function show(Request $request)
{
// dd('sdf');
return $request->session()->get('user')->email_verified_at
? redirect('/home')
: view('auth.verify', [
'pageTitle' => __('Account Verification')
]);
}
}
<file_sep>/app/Http/Middleware/EmailVerified.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\URL;
class EmailVerified
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next, $redirectToRoute = null)
{
$user = Session::get('user');
if (!$user || ($user instanceof MustVerifyEmail && !$user->email_verified_at)) {
if ($user->email_verified_at == null) {
return Redirect::route('verification.notice');
}
}
// dd($user);
return $next($request);
}
}
|
589a4dbc5c438c170e4606fe5e20be4a16053ce7
|
[
"PHP"
] | 5 |
PHP
|
GajananSOS/sapsol-test
|
ad1854e01b6f360c38712065439f986b7f4d66d0
|
4931cb2a4d7707a79d5f5d8d2697d8c116578dfd
|
refs/heads/main
|
<repo_name>shivam464/World-population-with-next.js<file_sep>/component/Layout.js
import Head from "next/head"
const Layout = ({ children, title = "World Population Rank" }) => {
return (
<div>
<Head>
<title>{title}</title>
<meta name="description" content="World Population" />
<link rel="icon" href="../images/logo.png" />
</Head>
<main>{children}</main>
</div>
)
}
export default Layout
<file_sep>/pages/country/[id].js
import style from '../../styles/country.module.css'
import Button from '@material-ui/core/Button';
import Head from "next/head"
import img from '../../public/favicon.ico'
const Country = ({ data }) => {
return (
<div className={style.main_container}>
<Head>
<title>{data.name}:Details</title>
<meta name="description" content={`${data.name} Population`} />
<link rel="icon" href="../../public/favicon.ico" />
</Head>
<div className={style.container}>
<div className={style.image_div}>
<img src={data.flag} alt="country image" />
</div>
<div className={style.details}>
<div><span>Name :- </span><p>{data.name}</p></div>
<div><span>NativeName :- </span> <p>{data.nativeName}</p> </div>
<div><span>Total Population :- </span> <p>{data.population}</p> </div>
<div><span>Capital :- </span> <p>{data.capital}</p> </div>
<div><span>Currencies :- </span> <p>{data.currencies[0].name}<span>{data.currencies[0].symbol}</span></p> </div>
<div><span>Languages :- </span>
{data.languages.map(language => <p>{language.name}</p>)}
</div>
<div><span>Region :- </span> <p>{data.region}</p> </div>
</div>
</div>
<Button variant="contained" href="/" >Go Back</Button>
</div>
)
}
export default Country;
export const getServerSideProps = async ({ params }) => {
const res = await fetch(`https://restcountries.eu/rest/v2/alpha/${params.id}`);
const data = await res.json();
return {
props: { data },
}
}<file_sep>/component/Population_table.js
import React from 'react'
import { withStyles, makeStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import Button from '@material-ui/core/Button';
import style from '../styles/Population_table.module.css'
import Link from 'next/link';
// import Image from 'next/image'
const StyledTableCell = withStyles((theme) => ({
head: {
backgroundColor: theme.palette.common.black,
color: theme.palette.common.white,
},
body: {
fontSize: 14,
},
}))(TableCell);
const StyledTableRow = withStyles((theme) => ({
root: {
'&:nth-of-type(odd)': {
backgroundColor: theme.palette.action.hover,
},
},
}))(TableRow);
const useStyles = makeStyles({
table: {
minWidth: 300,
},
});
const sortpopulation = (api_data, direction) => {
if (direction === "asc") {
return [...api_data].sort((a, b) => a.population > b.population ? 1 : -1);
}
if (direction === "desc") {
return [...api_data].sort((a, b) => a.population > b.population ? -1 : 1);
}
return api_data;
}
const Population_table = ({ api_data }) => {
const [direction, setdirection] = React.useState("");
const sorted_data = sortpopulation(api_data, direction);
// console.log(sorted_data);
const classes = useStyles();
return (
<div className={style.table_div}>
<div className={style.btn}>
<Button variant="contained" onClick={() => setdirection("asc")}>Less Population</Button>
<Button variant="contained" onClick={() => setdirection("desc")}>High Population</Button>
</div>
<TableContainer component={Paper} className={style.main_table}>
<Table className={classes.table} aria-label="customized table">
<TableHead className={style.heading}>
<TableRow className={style.table_row}>
<StyledTableCell >Country Name</StyledTableCell>
<StyledTableCell align="center">Total Population</StyledTableCell>
</TableRow>
</TableHead>
<TableBody>
{sorted_data.map((row) => (
<Link href={`/country/${row.alpha3Code}`}>
<StyledTableRow className={style.tables}>
<StyledTableCell component="th" scope="row" key={row.name}>{row.name}</StyledTableCell>
<StyledTableCell align="center" key={row.population}>{row.population}</StyledTableCell>
</StyledTableRow>
</Link>
))}
</TableBody>
</Table>
</TableContainer>
</div>
)
}
export default Population_table
<file_sep>/component/Search.js
import SearchIcon from '@material-ui/icons/Search';
import Image from 'next/image'
import profilePic from '../public/logo-1.png'
import style from '../styles/Search.module.css'
const Search = ({ onclickhandler }) => {
return (
<div className={style.Search_div}>
<div className={style.image_div}>
<Image src={profilePic} alt="Picture of the author" width={50} height={50} />
</div>
<div className={style.input_div}>
<SearchIcon />
<input type="text" placeholder="Search The Country" onChange={onclickhandler} />
</div>
</div>
)
}
export default Search;
|
5a188ace0e80c5215909f73e08ddc9fc73464cf9
|
[
"JavaScript"
] | 4 |
JavaScript
|
shivam464/World-population-with-next.js
|
1c565a2ad4a52f4a3b1f7bfc6582e768680c45ce
|
5d8b12f6dac8dea2fb18d2e711b6c16b29f322f1
|
refs/heads/develop
|
<repo_name>Tubitv/rpclib<file_sep>/benchmarks/src/main/protobuf/README.md
These proto files are taken directly from [grpc-java](https://github.com/grpc/grpc-java/tree/master/benchmarks/src/main/proto/grpc/testing)
<file_sep>/README.md
# RPCLib
This is a library that enables gRPC services and clients written in
Scala to seamlessly use gRPC methods as though they were Akka Stream
flows. Given a Protocol Buffer such as the following:
```proto
service ExampleService {
rpc Unary ( Request) returns ( Response);
rpc ServerStreaming ( Request) returns (stream Response);
rpc ClientStreaming (stream Request) returns ( Response);
rpc BidiStreaming (stream Request) returns (stream Response);
}
```
This library enables Scala services and clients to use the following
uniform API:
```scala
trait ExampleService {
def unary : Flow[Request, Response, NotUsed]
def serverStreaming : Flow[Request, Response, NotUsed]
def clientStreaming : Flow[Request, Response, NotUsed]
def bidiStreaming : Flow[Request, Response, NotUsed]
}
```
## Quick start
To start using RPCLib in your project:
1. Add the RPCLib plugin to SBT by adding the following to
`project/plugins.sbt`:
addSbtPlugin("com.tubitv.rpclib" % "rpclib-compiler" % "0.3.0")
addSbtPlugin("com.thesamet" % "sbt-protoc" % "0.99.18")
2. Tell RPCLib where your Protocol Buffer files are located by adding
the following lines to your project definition (e.g., in
`build.sbt`), substituting `"<path to protobuf directory>"` with a
directory path as a string (e.g., `"src/main/protos"`):
import com.tubitv.rpclib.compiler.RpcLibCodeGenerator
PB.protoSources in Compile := Seq(
baseDirectory.value / "<path to protobuf directory>"
),
PB.targets in Compile := Seq(
scalapb.gen() -> (sourceManaged in Compile).value,
RpcLibCodeGenerator -> (sourceManaged in Compile).value
)
If your project isn't already using ScalaPB, you'll also need to add two
files, `scalapb/scalapb.proto` and `google/protobuf/descriptor.proto`,
to your Protocol Buffer directory. See the example projects in the
`/examples/minimal-server/` and `/examples/minimal-client/` directories
for these files.
## Quick start for RPCLib developers
Contributions to RPCLib are very welcome! Please open pull requests.
This repository is organized into three directories:
* `/rpclib/`: sources for RPCLib;
* `/rpclib-test/`: tests for RPCLib; and
* `/examples/`: example projects demonstrating usage of RPCLib.
### Source files (`/rpclib/`)
The SBT project for RPCLib consists of two subprojects:
* `rpclib-compiler`: an SBT plugin that generates code at compile
time from Protocol Buffers; and,
* `rpclib-runtime`, a Scala runtime library used by the generated
code.
To publish the library locally, execute the following in the `/rpclib/`
directory:
$ sbt +publishLocal
This will compile both subprojects and publish the resulting artifacts
to your local machine.
### Tests (`/rpclib-test/`)
To run the library tests, execute the following in the `/rpclib-test/`
directory:
$ sbt test
## Acknowledgements
The core of this library is based heavily on the [gRPC Akka Stream
library][1].
[1]: https://github.com/btlines/grpcakkastream
<file_sep>/rpclib/src/runtime/src/main/java/com/tubitv/rpclib/runtime/interceptors/util/SimpleForwardingClientCallListenerJavaInteropBridge.java
package com.tubitv.rpclib.runtime.interceptors.util;
import io.grpc.ClientCall;
import io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
import io.grpc.Metadata;
/**
* This class exists solely as a workaround for Scala compiler bug SI-7936.
*
* The Scala compiler has a Java interoperability bug in which a child class written in Scala cannot
* call the methods of a grandparent class written in Java.
*
* The workaround below defines an intermediate parent class in Java, from which the Scala class
* will directly inherit, that calls the grandparent method.
*
* @see <a href="https://issues.scala-lang.org/browse/SI-7936">SI-7936</a>
*/
abstract class SimpleForwardingClientCallListenerJavaInteropBridge<RespT>
extends SimpleForwardingClientCallListener<RespT> {
protected SimpleForwardingClientCallListenerJavaInteropBridge(ClientCall.Listener<RespT> delegate) {
super(delegate);
}
@Override
public void onHeaders(Metadata headers) {
super.onHeaders(headers);
}
}
|
806fa6654b64abe58f8361ce5c60564c20912d25
|
[
"Markdown",
"Java"
] | 3 |
Markdown
|
Tubitv/rpclib
|
9b4a53c33595ddb9c3e13730d3b90bc5cf42f15c
|
9c5210f8faf39b46bcbf9a50f95fb6497426975d
|
refs/heads/master
|
<repo_name>mattboldt/react-rails-primer<file_sep>/README.md
# React-Rails Primer
The fun stuff is in `app/assets/javascripts/components`. To get started, fork this repo, and...
```
bundle
rake db:migrate
rails s
```
Then visit `localhost:3000` in your browser
<file_sep>/app/assets/javascripts/components/_post_form.jsx
class PostForm extends React.Component {
constructor(props) {
super(props);
this.state = {
title: props.post.title,
content: props.post.content
};
this.handleTitleChange = this.handleTitleChange.bind(this);
this.handleContentChange = this.handleContentChange.bind(this);
}
handleTitleChange(e) {
this.setState({ title: e.target.value });
}
handleContentChange(e) {
this.setState({ content: e.target.value });
}
render() {
return (
<div>
<label>Title</label>
<input
type="text"
name="post[title]"
value={this.state.title}
onChange={this.handleTitleChange}
/>
<label>Content</label>
<input
type="text"
name="post[content]"
value={this.state.content}
onChange={this.handleContentChange}
/>
<input type="submit" value="Update Post" />
</div>
);
}
}
|
f3de00cbf2d2d1202747ea6379270d7bd3f202c1
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
mattboldt/react-rails-primer
|
ec52205b3f9b9d947ac7b793deb0881833cab285
|
e44127de15ca8de247b55d800a87371d069259d1
|
refs/heads/master
|
<repo_name>chekalin/Udacity-CS253<file_sep>/registration.py
import hashlib
import hmac
import os
import random
import re
import string
from google.appengine.ext import webapp, db
import jinja2
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape=True)
SECRET = "mega-secret-keyword"
class BaseHandler(webapp.RequestHandler):
def render(self, template, **kwargs):
self.response.out.write(jinja_env.get_template(template).render(**kwargs))
def set_cookie_and_redirect(self, user):
hashed_id_token = create_hashed_token(str(user.key().id()))
self.response.headers.add_header('Set-Cookie', 'user_id=%s; Path=/' % hashed_id_token)
return self.redirect("/blog/welcome")
class RegistrationHandler(BaseHandler):
def get(self):
self.render("signup.html")
def post(self):
username = self.request.get("username")
password = self.request.get("password")
verify = self.request.get("verify")
email = self.request.get("email")
params = {"username" : username, "password" : <PASSWORD>, "verify" : verify, "email" : email}
errors = validate(params)
if errors:
params_errors = dict(params.items() + errors.items())
self.render("signup.html", **params_errors)
else:
hashed = make_pw_hash(username, password)
user = User(username=username, password=hashed, email=email)
user.put()
return self.set_cookie_and_redirect(user)
def validate(params):
errors = {}
if not username_valid(params["username"]):
errors["er_username"] = "That's not a valid username."
if not password_valid(params["password"]):
errors["er_password"] = "That wasn't a valid password."
if not verify_valid(params["password"], params["verify"]):
errors["er_verify"] = "Your passwords didn't match."
if params["email"] and not email_valid(params["email"]):
errors["er_email"] = "That's not a valid email."
return errors
def username_valid(username):
USER_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$")
return USER_RE.match(username)
def password_valid(password):
PASSWORD_RE = re.compile(r"^.{3,20}$")
return PASSWORD_RE.match(password)
def verify_valid(password, verify):
return password == verify
def email_valid(email):
EMAIL_RE = re.compile(r"^[\S]+@[\S]+\.[\S]+$")
return not email or EMAIL_RE.match(email)
class User(db.Model):
username = db.StringProperty(required=True)
password = db.StringProperty(required=True)
email = db.StringProperty()
created = db.DateTimeProperty(auto_now_add=True)
def make_salt():
return ''.join(random.choice(string.letters) for x in xrange(5))
def make_pw_hash(name, pw, salt=None):
if not salt:
salt = make_salt()
h = hashlib.sha256(name + pw + salt).hexdigest()
return '%s,%s' % (h, salt)
def valid_pw(name, pw, h):
salt = h.split(",")[1]
return h == make_pw_hash(name, pw, salt)
def get_hash(user_id):
return hmac.new(SECRET, user_id).hexdigest()
def create_hashed_token(user_id):
user_id = str(user_id)
return str(user_id + "|" + get_hash(user_id))
def valid_username(hashed_id_token):
user_id = extract_id(hashed_id_token)
hashed = hashed_id_token.split("|")[1]
return hashed == get_hash(user_id)
def extract_id(user_id_token):
return user_id_token.split("|")[0]
class WelcomeHandler2(BaseHandler):
def get(self):
user_id_token = str(self.request.cookies.get('user_id'))
if user_id_token and valid_username(user_id_token):
user_id = extract_id(user_id_token)
user = User.get_by_id(int(user_id))
return self.render("welcome.html", username=user.username)
else:
return self.redirect("/blog/signup")
class LoginHandler(BaseHandler):
def get(self):
self.render("login.html")
def post(self):
username = self.request.get("username")
password = self.request.get("password")
users = db.GqlQuery("SELECT * FROM User WHERE username='" + username + "'")
if users.count() > 0:
user = users[0]
if valid_pw(username, password, user.password):
return self.set_cookie_and_redirect(user)
return self.render("login.html", er_login="Invalid login")
class LogoutHandler(BaseHandler):
def get(self):
self.response.headers.add_header('Set-Cookie', 'user_id=; Path=/')
return self.redirect("/blog/signup")
<file_sep>/main.py
import os
from google.appengine.ext import webapp
import jinja2
from blog import NewPostHandler, PostPermalinkHandler, BlogHandler, JsonPermalinkHandler, JsonBlogHandler, FlushCachesHandler
from rot13 import Rot13Handler
from signup import SignupHandler, WelcomeHandler
from registration import RegistrationHandler, WelcomeHandler2, LoginHandler, LogoutHandler
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape=True)
class ContentsHandler(webapp.RequestHandler):
def get(self):
template = jinja_env.get_template("contents.html")
return self.response.out.write(template.render())
app = webapp.WSGIApplication([
('/', ContentsHandler),
('/unit2/rot13', Rot13Handler),
('/unit2/signup', SignupHandler),
('/unit2/welcome', WelcomeHandler),
('/blog/welcome', WelcomeHandler2),
('/blog/login', LoginHandler),
('/blog/logout', LogoutHandler),
('/blog/?', BlogHandler),
('/blog/signup/?', RegistrationHandler),
('/blog/newpost/?', NewPostHandler),
('/blog/(\d+)', PostPermalinkHandler),
('/blog/(\d+).json', JsonPermalinkHandler),
('/blog/?.json', JsonBlogHandler),
('/blog/flush', FlushCachesHandler),
('/flush', FlushCachesHandler)
], debug=True)
<file_sep>/signup.py
import re
from google.appengine.ext import webapp
form = """
<html>
<head>
<title>Sign Up</title>
<style type="text/css">
.label {text-align: right}
.error {color: red}
</style>
</head>
<body>
<h2>Signup</h2>
<form method="post">
<table>
<tr>
<td class="label">
Username
</td>
<td>
<input type="text" name="username" value="%(username)s">
</td>
<td class="error">%(er_username)s</td>
</tr>
<tr>
<td class="label">
Password
</td>
<td>
<input type="password" name="password" value="%(<PASSWORD>">
</td>
<td class="error">
%(er_password)s
</td>
</tr>
<tr>
<td class="label">
Verify Password
</td>
<td>
<input type="password" name="verify" value="%(verify)s">
</td>
<td class="error">
%(er_verify)s
</td>
</tr>
<tr>
<td class="label">
Email (optional)
</td>
<td>
<input type="text" name="email" value="%(email)s">
</td>
<td class="error">
%(er_email)s
</td>
</tr>
</table>
<input type="submit">
</form>
</body>
</html>
"""
def username_valid(username):
USER_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$")
return USER_RE.match(username)
def password_valid(password):
PASSWORD_RE = re.compile(r"^.{3,20}$")
return PASSWORD_RE.match(password)
def verify_valid(password, verify):
return password == verify
def email_valid(email):
EMAIL_RE = re.compile(r"^[\S]+@[\S]+\.[\S]+$")
return EMAIL_RE.match(email)
def get_errors(params):
errors = {"er_username" : "", "er_password" : "", "er_verify" : "", "er_email" : ""}
failed = False
if not username_valid(params["username"]):
errors["er_username"] = "That's not a valid username."
failed = True
if not password_valid(params["password"]):
errors["er_password"] = "That wasn't a valid password."
failed = True
if not verify_valid(params["password"], params["verify"]):
errors["er_verify"] = "Your passwords didn't match."
failed = True
if not email_valid(params["email"]):
errors["er_email"] = "That's not a valid email."
failed = True
return failed, errors
class SignupHandler(webapp.RequestHandler):
def get(self):
self.print_form()
def print_form(self, errors=None, params=None):
if not errors: errors = {"er_username" : "", "er_password" : "", "er_verify" : "", "er_email" : ""}
if not params: params = {"username" : "", "password" : "", "verify" : "", "email" : ""}
self.response.out.write(form % dict(errors.items() + params.items()))
def post(self):
username = self.request.get("username")
password = self.request.get("password")
verify = self.request.get("verify")
email = self.request.get("email")
params = {"username" : username, "password" : <PASSWORD>, "verify" : verify, "email" : email}
failed, errors = get_errors(params)
if not failed:
self.redirect("/unit2/welcome?username=" + username)
else:
self.print_form(errors, params)
class WelcomeHandler(webapp.RequestHandler):
def get(self):
self.response.out.write("Welcome, " + self.request.get("username")+ "!")
<file_sep>/rot13.py
import cgi
import os
import string
from google.appengine.ext import webapp
import jinja2
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape=True)
def encode_char(letter):
uppercase = string.uppercase
lowercase = string.lowercase
if letter in uppercase:
return uppercase[(uppercase.index(letter) + 13) % len(uppercase)]
elif letter in lowercase:
return lowercase[(lowercase.index(letter) + 13) % len(lowercase)]
else:
return letter
def encode_rot13(text):
return "".join(map(encode_char, text))
class Rot13Handler(webapp.RequestHandler):
def print_form(self, text=""):
text = cgi.escape(text)
text = encode_rot13(text)
self.response.out.write(jinja_env.get_template("rot13.html").render(text=text))
def post(self):
text = self.request.get("text")
self.print_form(text)
def get(self):
self.print_form()<file_sep>/blog.py
import os
from google.appengine.api import memcache
from google.appengine.ext import webapp, db
import jinja2
import json
import time
ERROR_MESSAGE = "subject and content, please!"
KEY = 'TOP10'
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape=True)
def update_cache():
posts = db.GqlQuery("SELECT * FROM BlogPost ORDER BY created DESC LIMIT 10")
cache = (posts, time.time())
memcache.set(KEY, cache)
return cache
class NewPostHandler(webapp.RequestHandler):
def new_post_form(self, error_message="", subject="", content=""):
template = jinja_env.get_template("blog-newpost.html")
return self.response.out.write(template.render(error_message=error_message, subject=subject, blog=content))
def get(self):
return self.new_post_form()
def post(self):
subject = self.request.get("subject")
content = self.request.get("content")
if not subject or not content:
return self.new_post_form(subject=subject, content=content, error_message=ERROR_MESSAGE)
else:
post = BlogPost(subject=subject, content=content)
post.put()
update_cache()
self.redirect("/blog/" + str(post.key().id()))
class BlogPost(db.Model):
subject = db.StringProperty(required=True)
content = db.TextProperty(required=True)
created = db.DateTimeProperty(auto_now_add=True)
class GenericBlogHandler(webapp.RequestHandler):
def blog_form(self, posts, updated=0):
template = jinja_env.get_template("blog.html")
return self.response.out.write(template.render(posts=posts, updated=updated))
def get_posts(self):
cache = memcache.get(KEY)
if cache is None:
cache = update_cache()
return cache
class BlogHandler(GenericBlogHandler):
def get(self):
cache = self.get_posts()
updated = int(time.time() - cache[1])
return self.blog_form(cache[0], updated)
class PostPermalinkHandler(GenericBlogHandler):
def get(self, post_id):
cache = memcache.get(post_id)
if cache is None:
post = BlogPost.get_by_id(int(post_id))
if post:
cache = (post, time.time())
memcache.set(post_id, cache)
else:
self.redirect("/blog")
updated = int(time.time() - cache[1])
return self.blog_form([cache[0]], updated)
class GenericJsonHandler(GenericBlogHandler):
def generateJsonForPosts(self, posts):
content = [{'subject': post.subject,
'content': post.content,
'created': str(post.created.strftime('%a %b %d %H:%M:%S %Y'))
} for post in posts]
return json.dumps(content)
class JsonPermalinkHandler(GenericJsonHandler):
def get(self, post_id):
post = BlogPost.get_by_id(int(post_id))
if post:
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write(self.generateJsonForPosts([post]))
else:
self.redirect("/blog")
class JsonBlogHandler(GenericJsonHandler):
def get(self):
cache = self.get_posts()
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write(self.generateJsonForPosts(cache[0]))
class FlushCachesHandler(webapp.RequestHandler):
def get(self):
memcache.flush_all()
self.redirect("/blog")<file_sep>/templates/blog.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>CS 253 Blog</title>
<link rel="stylesheet" type="text/css" href="/stylesheets/blog.css" />
</head>
<body>
<h1>CS 253 Blog</h1>
{% for post in posts %}
<div class="post-header">
<div class="post-subject">{{post.subject}}</div>
<div class="post-created">{{post.created.strftime("%B %d, %Y")}}</div>
</div>
<div class="post-blog">{{post.content}}</div>
<br />
{% endfor %}
<p align="right" class="post-blog">Queried {{updated}} seconds ago.</p>
</body>
</html>
|
6a2b8ea415a44dfaafb0a97bdce86e1919b50687
|
[
"Python",
"HTML"
] | 6 |
Python
|
chekalin/Udacity-CS253
|
be73b4db45f4fad77961f1f312f40902c4015821
|
0f7b9e00b163e13276c4d8162810fbf70c4c5dd2
|
refs/heads/master
|
<file_sep>package cn.huas.xueshe.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import cn.huas.xueshe.R;
public class comment extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_common_comment);
}
}
<file_sep>package cn.huas.xueshe.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import static cn.huas.xueshe.config.APIAddress.LOGIN_URL;
import static cn.huas.xueshe.config.APIAddress.REGISTER_URL;
import static cn.huas.xueshe.service.Http.doPostForm;
/**
* Created by 74071 on 2017/3/14.
*/
public class HttpUtilsImplTest {
//psvm
// public static void main(String[] args) {
//// RequestBody body = new FormBody.Builder().add("")
//
//
// }
@Test
public void login() throws Exception {
RequestBody body = new FormBody.Builder().add("userName", "admin123").add("userPassword", "<PASSWORD>").build();
;
JSONObject jsonObject = JSON.parseObject(doPostForm(LOGIN_URL, body));
System.out.println("Log: " + jsonObject.get("result"));
}
@Test
public void reg() throws Exception {
RequestBody body = new FormBody.Builder().add("userName", "admin123456").add("userPassword", "<PASSWORD>").build();
JSONObject jsonObject = JSON.parseObject(doPostForm(REGISTER_URL, body));
System.out.println("Reg: " + jsonObject.get("result"));
}
}<file_sep>package cn.huas.xueshe.activity.activity;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;
import java.sql.Date;
import java.text.SimpleDateFormat;
import cn.huas.xueshe.config.APIAddress;
import cn.huas.xueshe.service.Http;
import cn.huas.xueshe.util.L;
import cn.huas.xueshe.util.ServiceUtils;
import okhttp3.FormBody;
import okhttp3.RequestBody;
/**
* Created by 74071 on 2017/4/23.
*/
public class creatActivityTest {
@Test
public void submit() {
System.out.println("3333333333333333333333333333333");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss ");
Date curDate = new Date(System.currentTimeMillis());//获取当前时间
String date = formatter.format(curDate);
Context appContext = InstrumentationRegistry.getTargetContext();
String m标题edtTxt = "标题" + date;
String m内容edtTxt = "内容" + date;
String m期望人数edtTxt = "2";
String m已有人数edtTxt = "1";
String m联系QQedtTxt = "15151";
String m地点edtTxt = "地点" + date;
RequestBody body = new FormBody.Builder().
add("activityTitle", m标题edtTxt).
add("activityDescribtion", m内容edtTxt).
add("activityExpectJoiner", m期望人数edtTxt).
add("activityJoiner", m已有人数edtTxt).
add("activityQq", m联系QQedtTxt).
add("activityAddress", m地点edtTxt).
build();
JSONObject jsonObject = null;
String str = "666666666666666666666";
L.e(str);
try {
str = ServiceUtils.analysis(appContext, Http.doPostForm(APIAddress.ADD_ACITIVITY_URL, body));
} catch (Exception e) {
L.e(e.toString());
e.printStackTrace();
return;
}
System.out.println(str);
L.e(str.toString());
}
}<file_sep>package cn.huas.xueshe.util;
import android.util.Log;
/**
* Created by 74071 on 2017/2/8.
*/
public class L {
private L() {
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}
private static final String TAG = "tagWay";
private static boolean debug = true;
private static boolean warring = true;
public static String lastString = "";
public static void e(String msg) {
if (debug)
Log.e(TAG, msg);
System.out.println(msg);
}
public static void e(String msg, String tag) {
if (debug)
Log.e(tag, msg);
}
public static void w(String msg) {
if (warring)
lastString = msg;
Log.e(TAG, msg);
System.out.println(msg);
}
}
<file_sep>package cn.huas.xueshe.util;
import org.junit.Before;
import org.junit.Test;
import cn.huas.xueshe.bean.User;
/**
* Created by 74071 on 2017/3/26.
*/
public class JsonUtilsTest {
User[] user = new User[5];
@Before
public void setUp() throws Exception {
int i = 10;
for (User us : user) {
us = new User();
us.setUserHead("www.3366.cn " + i);
us.setUserEmail("<EMAIL> " + i);
us.setUserId(+i * 10000);
us.setUserName("fuck " + i);
us.setUserNum(i * 100);
us.setUserPassword("<PASSWORD> " + i);
us.setUserQq("qq" + i);
us.setUserTel("Tel" + i);
us.setUserSex("男");
i += 10;
}
}
@Test
public void getObjectJsonString() throws Exception {
}
@Test
public void getObjectArrayJson() throws Exception {
}
@Test
public void jsonToJsonObject() throws Exception {
// JsonUtils.jsonToJsonObject(seas,"data");
}
@Test
public void getObjectToJsonObject() throws Exception {
}
@Test
public void getMapJson() throws Exception {
}
@Test
public void getStringArrayJson() throws Exception {
}
}<file_sep>package cn.huas.xueshe.activity;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import cn.huas.xueshe.service.Http;
import cn.huas.xueshe.util.L;
import static cn.huas.xueshe.config.APIAddress.REGISTER_URL;
/**
* Created by 74071 on 2017/4/22.
*/
public class RegisterActivityTest {
@Test
public void registerUp() throws Exception {
String input_name = "Test121";
String input_email = "<EMAIL>";
String input_password = "<PASSWORD>";
JSONObject send = new JSONObject()
.put("userName", input_name)
.put("userPassword", <PASSWORD>)
.put("userEmail", input_email.toString());
System.out.println(send.toString());
org.json.JSONObject jsonObject = null;
try {
jsonObject = Http.doPostJsom(REGISTER_URL, send, null);
} catch (Exception e) {
L.e(e.toString());
System.out.println("服务器异常");
e.printStackTrace();
}
System.out.println(jsonObject.toString());
if ("success".equals(jsonObject.getString("message"))) {
Assert.assertTrue(true);
}
if ("fail".equals(jsonObject.getString("message"))) {
Assert.assertTrue("成功通向数据库", true);
}
}
}<file_sep>package cn.huas.xueshe.util;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
* Created by 74071 on 2017/2/14.
*/
public class ImageUtils {
public static Bitmap getHttpBitmap(String url) {
URL myFileURL;
Bitmap bitmap = null;
try {
myFileURL = new URL(url);
//获得连接
HttpURLConnection conn = (HttpURLConnection) myFileURL.openConnection();
//设置超时时间为6000毫秒,conn.setConnectionTiem(0);表示没有时间限制
conn.setConnectTimeout(6000);
//连接设置获得数据流
conn.setDoInput(true);
//不使用缓存
conn.setUseCaches(false);
//这句可有可无,没有影响
//conn.connect();
//得到数据流
InputStream is = conn.getInputStream();
//解析得到图片
bitmap = BitmapFactory.decodeStream(is);
//关闭数据流
is.close();
} catch (Exception e) {
e.printStackTrace();
L.e(e.toString());
}
return bitmap;
}
public Bitmap getPicture(String path) {
Bitmap bm = null;
try {
URL url = new URL(path);
URLConnection connection = url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
bm = BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bm;
}
private Bitmap getImageFromNet(String url) {
HttpURLConnection conn = null;
try {
URL mURL = new URL(url);
conn = (HttpURLConnection) mURL.openConnection();
conn.setRequestMethod("GET"); //设置请求方法
conn.setConnectTimeout(10000); //设置连接服务器超时时间
conn.setReadTimeout(5000); //设置读取数据超时时间
conn.connect(); //开始连接
int responseCode = conn.getResponseCode(); //得到服务器的响应码
if (responseCode == 200) {
//访问成功
InputStream is = conn.getInputStream(); //获得服务器返回的流数据
Bitmap bitmap = BitmapFactory.decodeStream(is); //根据流数据 创建一个bitmap对象
return bitmap;
} else {
//访问失败
L.e("访问失败===responseCode:" + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect(); //断开连接
}
}
return null;
}
}
<file_sep>package cn.huas.xueshe.bean;
public class StorePic {
private String storeName;
private String storePicture;
public String getStoreName() {
return storeName;
}
public void setStoreName(String storeName) {
this.storeName = storeName;
}
public String getStorePicture() {
return storePicture;
}
public void setStorePicture(String storePicture) {
this.storePicture = storePicture;
}
}
<file_sep>package cn.huas.xueshe.service;
import android.content.Context;
import org.json.JSONObject;
import java.util.Map;
import okhttp3.RequestBody;
/**
* Created by 74071 on 2017/2/11.
*/
public interface HttpUtils {
String doPostForm(String URL, RequestBody Body) throws Exception;
JSONObject doPostJsom(String URL, JSONObject jsonObject, Context context) throws Exception;
String getInfo(String URL, Context context) throws Exception;
String getInfoByParameter(String URL, Map<String, Integer> m, Context context) throws Exception;
}
<file_sep>package cn.huas.xueshe;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import cn.huas.xueshe.service.Http;
import cn.huas.xueshe.util.L;
import static cn.huas.xueshe.config.APIAddress.REGISTER_URL;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("cn.huas.xueshe", appContext.getPackageName());
System.out.println();
}
@Test
public void registerUp() throws Exception {
Context appContext = InstrumentationRegistry.getTargetContext();
String input_name = "Test121";
String input_email = "<EMAIL>";
String input_password = "<PASSWORD>";
JSONObject send = new JSONObject()
.put("userName", input_name)
.put("userPassword", input_password)
.put("userEmail", input_email.toString());
System.out.println(send.toString());
org.json.JSONObject jsonObject = null;
try {
jsonObject = Http.doPostJsom(REGISTER_URL, send, appContext);
} catch (Exception e) {
L.e(e.toString());
System.out.println("服务器异常");
e.printStackTrace();
return;
}
System.out.println(jsonObject.toString());
if ("success".equals(jsonObject.getString("message"))) {
Assert.assertTrue(true);
}
if ("fail".equals(jsonObject.getString("message"))) {
Assert.assertTrue("成功通向数据库", true);
}
}
}
<file_sep>apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion '25.0.0'
defaultConfig {
applicationId "cn.huas.xueshe"
minSdkVersion 22
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
// testOptions{
// unitTests{
// return true;
// }
// }
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile group: 'com.alibaba', name: 'fastjson', version: '1.1.15'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'me.zhouzhuo.zzbeelayout:zz-bee-layout:1.0.0'
compile 'com.android.support:design:25.3.1'
compile 'com.getbase:floatingactionbutton:1.10.1'
compile 'com.squareup.okhttp3:okhttp:3.6.0'
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.google.android.gms:play-services-appindexing:9.8.0'
compile 'de.hdodenhof:circleimageview:2.1.0'
compile 'com.yolanda.nohttp:nohttp:1.1.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.android.support:support-v4:25.3.1'
testCompile 'junit:junit:4.12'
testCompile 'org.json:json:20140107'
}
<file_sep>package cn.huas.xueshe.service;
import android.content.Context;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Map;
import cn.huas.xueshe.service.impl.HttpUtilsImpl;
import okhttp3.RequestBody;
/**
* Created by 74071 on 2017/2/11.
*/
public class Http {
static public JSONObject doPostJsom(String URL, JSONObject jsonObject, Context context) throws Exception {
HttpUtilsImpl http = new HttpUtilsImpl();
return http.doPostJsom(URL, jsonObject, context);
}
static public String doPostForm(String URL, RequestBody Body) throws Exception {
HttpUtilsImpl http = new HttpUtilsImpl();
return http.doPostForm(URL, Body);
}
static public String getInfo(String URL, Context context) throws IOException {
HttpUtilsImpl http = new HttpUtilsImpl();
return http.getInfo(URL, context);
}
static public String getInfoByParameter(String URL, Map<String, Integer> m, Context context) throws Exception {
HttpUtilsImpl http = new HttpUtilsImpl();
return http.getInfoByParameter(URL, m, context);
}
}
<file_sep>package cn.huas.xueshe.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.getbase.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.huas.xueshe.R;
import cn.huas.xueshe.activity.activity.activityList;
import cn.huas.xueshe.config.configXML;
import cn.huas.xueshe.notUse.MyListView4;
import cn.huas.xueshe.util.L;
import me.zhouzhuo.zzbeelayout.ZzBeeLayout;
import me.zhouzhuo.zzbeelayout.widget.com.meg7.widget.SvgImageView;
public class MainActivity extends AppCompatActivity {
Intent intent;
ListView listView;
FloatingActionButton mFab_1;
FloatingActionButton mFab_2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initZzBee();
mFab_1 = (FloatingActionButton) findViewById(R.id.mainFab_1);
mFab_2 = (FloatingActionButton) findViewById(R.id.mainFab_2);
checklogin();
listView = (ListView) findViewById(R.id.main_ListView);
/*
listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,getData()));
setContentView(listView);
*/
SimpleAdapter adapter = new SimpleAdapter(this, getData(), R.layout.vlist,
new String[]{"title", "info", "img"},
new int[]{R.id.title, R.id.info, R.id.img});
listView.setAdapter(adapter);
}
private void checklogin() {
if (loginOn()) floatBtnChange(true);
else floatBtnChange(false);
}
private void floatBtnChange(boolean isLoginOn) {
if (isLoginOn == true) {
mFab_1.setTitle("个人信息");
mFab_2.setTitle("退出登录");
mFab_1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
intent = new Intent(MainActivity.this, UserInfo.class);
intent.putExtra("userId", configXML.getUserId());
startActivity(intent);
}
});
mFab_2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
configXML.clean();
finish();
}
});
} else {
mFab_1.setTitle("登录");
mFab_2.setTitle("注册");
mFab_1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
});
mFab_2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
intent = new Intent(MainActivity.this, RegisterActivity.class);
startActivity(intent);
}
});
}
}
private boolean loginOn() {
L.e("userID:" + configXML.getUserId() + " takon:" + configXML.getUserId());
if (configXML.getUserId() == "") return false;
else return true;
}
private List<Map<String, Object>> getData() {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> map = new HashMap<String, Object>();
map.put("title", "G1");
map.put("info", "google 1");
map.put("img", R.drawable.one);
list.add(map);
map = new HashMap<String, Object>();
map.put("title", "G2");
map.put("info", "google 2");
map.put("img", R.drawable.two);
list.add(map);
map = new HashMap<String, Object>();
map.put("title", "G3");
map.put("info", "google 3");
map.put("img", R.drawable.three);
list.add(map);
return list;
}
public void initZzBee() {
//首页蜂窝设计
ZzBeeLayout zzBeeLayout = (ZzBeeLayout) findViewById(R.id.bee);
zzBeeLayout.setImageRes(new int[]{
R.drawable.one,
R.drawable.icon_shops,
R.drawable.icon_deal,
R.drawable.icon_skill,
R.drawable.icon_act,
R.drawable.one,
R.drawable.icon_main
});
zzBeeLayout.setOnImageClickListener(new ZzBeeLayout.OnImageClickListener() {
public void onImageClick(SvgImageView iv, int position) {
switch (position) {
case 0:
Toast.makeText(MainActivity.this, "暂无板块", Toast.LENGTH_SHORT).show();
intent = new Intent(MainActivity.this, Test.class);
startActivity(intent);
break;
case 1:
Toast.makeText(MainActivity.this, "周边商店", Toast.LENGTH_SHORT).show();
intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
break;
case 2:
Toast.makeText(MainActivity.this, "二手物品交易", Toast.LENGTH_SHORT).show();
intent = new Intent(MainActivity.this, RegisterActivity.class);
startActivity(intent);
Toast.makeText(MainActivity.this, "技能交换", Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(MainActivity.this, "校园论坛", Toast.LENGTH_SHORT).show();
intent = new Intent(MainActivity.this, MyListView4.class);
startActivity(intent);
break;
case 4:
Toast.makeText(MainActivity.this, "线下活动", Toast.LENGTH_SHORT).show();
intent = new Intent(MainActivity.this, activityList.class);
startActivity(intent);
break;
case 5:
Toast.makeText(MainActivity.this, "暂无板块", Toast.LENGTH_SHORT).show();
break;
case 6:
Toast.makeText(MainActivity.this, "湖南文理学院", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(MainActivity.this, "正在开发" + position, Toast.LENGTH_SHORT).show();
}
}
});
}
}
<file_sep>package cn.huas.xueshe.activity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import cn.huas.xueshe.R;
import cn.huas.xueshe.config.APIAddress;
import cn.huas.xueshe.service.Http;
import cn.huas.xueshe.util.L;
;
public class RegisterActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_user_register);
}
@SuppressLint("NewApi")
public void registerUp(View view) throws JSONException {
EditText input_email = (EditText) findViewById(R.id.input_email);
EditText input_name = (EditText) findViewById(R.id.input_name);
EditText input_password = (EditText) findViewById(R.id.input_password);
JSONObject send = new JSONObject()
.put("userName", input_name.getText().toString())
.put("userPassword", input_password.getText().toString())
.put("userEmail", input_email.getText().toString());
L.e(this.getClass().toString() + " " + send.toString());
JSONObject result = null;
try {
result = Http.doPostJsom(APIAddress.REGISTER_URL, send, this);
} catch (Exception e) {
L.e(e.toString());
e.printStackTrace();
Toast.makeText(RegisterActivity.this, "服务器异常", Toast.LENGTH_SHORT).show();
return;
}
if ("success".equals(result.getString("message"))) {
Toast.makeText(RegisterActivity.this, "注册功", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(intent);
this.finish();
return;
}
L.e(this.getClass().toString() + " " + result.toString());
Toast.makeText(RegisterActivity.this, "注册失败" + "\n" + result.getString("message"), Toast.LENGTH_SHORT).show();
return;
}
public void toLoginaActivity(View view) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(intent);
this.finish();
}
}
<file_sep>package cn.huas.xueshe.config;
public class APIAddress {
public static final String BASIC_API_URL = "http://xueshe.96xm.cn:8080";
//登陆
public static final String LOGIN_URL = BASIC_API_URL + "/user/login";
//注册
public static final String REGISTER_URL = BASIC_API_URL + "/user/register";
//退出
public static final String LOGOUT = BASIC_API_URL + "/user/logout";
//查询用户
public static final String userInfo(String userId) {
return BASIC_API_URL + "/user/getUserInfo/userId=" + userId;
}
//活动新建
public static final String ADD_ACITIVITY_URL = BASIC_API_URL + "/activity/addActivity";
//活动查询帖子
public static final String GETACTIVITY(String activityId) {
return BASIC_API_URL + "/activity/getActivity/activityId=" + activityId;
}
//活动列表查询
public static final String GETACTIVITYLIST = BASIC_API_URL + "/activity/getActivityList";
//活动添加评论
public static final String ADDACTIVITYCOMMENT = BASIC_API_URL + "activityComment/addActivityComment";
}
<file_sep>package cn.huas.xueshe.activity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.junit.Before;
import cn.huas.xueshe.util.L;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import static cn.huas.xueshe.config.APIAddress.LOGIN_URL;
import static cn.huas.xueshe.service.Http.doPostForm;
/**
* Created by 74071 on 2017/3/26.
*/
public class LoginActivityTest {
@Before
public void setUp() throws Exception {
}
@org.junit.Test
public void loginSuccess() throws Exception {
String username = "breeze66xm";
String password = "<PASSWORD>";
RequestBody body = new FormBody.Builder().
add("userName", username.toString()).
add("userPassword", password.toString()).
build();
;
JSONObject jsonObject = null;
try {
jsonObject = JSON.parseObject(doPostForm(LOGIN_URL, body));
} catch (Exception e) {
L.e(e.toString());
System.out.println("connection fall");
e.printStackTrace();
}
if ("success".equals(jsonObject.get("message"))) {
System.out.println(jsonObject.toString());
JSONObject jsonData = (JSONObject) jsonObject.get("data");
// String jsonData = JsonUtils.jsonToJsonObject(jsonObject.toString(),data");
System.out.println(jsonData);
System.out.println(jsonData.get("access_token"));
System.out.println("success");
} else {
System.out.println("fales");
}
}
@org.junit.Test
public void loginFales() throws Exception {
String username = "breeze66xm";
String password = "<PASSWORD>";
RequestBody body = new FormBody.Builder().
add("userName", username.toString()).
add("userPassword", password.toString()).
build();
;
JSONObject jsonObject = null;
try {
jsonObject = JSON.parseObject(doPostForm(LOGIN_URL, body));
} catch (Exception e) {
L.e(e.toString());
System.out.println("connection fall");
e.printStackTrace();
}
if ("success".equals(jsonObject.get("message"))) {
System.out.println("success");
} else {
System.out.println("LoginFales");
}
}
}<file_sep>package cn.huas.xueshe.service.impl;
import android.content.Context;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Map;
import cn.huas.xueshe.config.configXML;
import cn.huas.xueshe.service.HttpUtils;
import cn.huas.xueshe.util.L;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Created by 74071 on 2017/2/11.
*/
public class HttpUtilsImpl implements HttpUtils {
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private final OkHttpClient client = new OkHttpClient();
public String getInfo(String URL, Context context) throws IOException {
Request request = new Request.Builder().
addHeader("Authorization", configXML.getToken()).
url(URL).get().build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
@Override
public String getInfoByParameter(String URL, Map<String, Integer> m, Context context) throws Exception {
String realURL = URL + "?";
for (Map.Entry<String, Integer> entry : m.entrySet()) {
realURL += entry.getKey() + "=" + entry.getValue() + "&";
}
realURL = realURL.substring(0, realURL.length() - 1);
L.e(realURL);
System.out.println(realURL);
Request request = new Request.Builder().
addHeader("Authorization", configXML.getToken()).
url(realURL).get().build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
public String doPostForm(String URL, RequestBody Body) throws Exception {
Request request = new Request.Builder()
.url(URL)
.post(Body)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
return response.body().string();
}
public JSONObject doPostJsom(String URL, JSONObject jsonObject, Context context) throws Exception {
RequestBody body = RequestBody.create(JSON, jsonObject.toString());
Request request = new Request.Builder()
.addHeader("Authorization", configXML.getToken())
.url(URL)
.post(body)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
return new JSONObject(response.body().string());
}
}
|
8b49e5eb557d4f13419371a3d2c50e9316612c76
|
[
"Java",
"Gradle"
] | 17 |
Java
|
AngusWG/xueshe
|
b29fb7c75b906b72ababfa5486618126e4f3705e
|
d88ce5624595f38f80b066c690ba414e05bab493
|
refs/heads/main
|
<repo_name>jstallings2/farmlink-pipeline<file_sep>/function-source/requirements.txt
# Function dependencies, for example:
# package>=version
pymongo==3.11.3
dnspython==2.1.0
google-cloud-datastore==2.1.0
firebase-admin==4.5.1
pandas==1.2.3
numpy==1.20.1
lxml
google-cloud-storage
gcsfs
<file_sep>/raw_data/CARROTS_SOUTHWEST+U.S._2016.html
<html><body><table border=1>
<tr><th>Date</th><th>Region</th><th>Class</th><th>Commodity</th><th>Variety</th><th>Organic</th><th>Environment</th><th>Unit</th><th>Number of Stores</th><th>Weighted Avg Price</th><th>Low Price</th><th>High Price</th><th>% Marked Local</th></tr><tr><td>01/08/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>35</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>01/08/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>51</td><td>.89</td><td>.79</td><td>.99</td><td></td></tr><tr><td>01/08/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>45</td><td>.38</td><td>.33</td><td>.50</td><td></td></tr><tr><td>01/08/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>96</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>01/08/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>147</td><td>1.00</td><td>.98</td><td>1.29</td><td></td></tr><tr><td>01/08/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>243</td><td>1.99</td><td>1.99</td><td>2.00</td><td></td></tr><tr><td>01/08/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>1,036</td><td>1.78</td><td>1.50</td><td>2.00</td><td></td></tr><tr><td>01/15/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>29</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>01/15/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>27</td><td>1.49</td><td>1.49</td><td>1.49</td><td></td></tr><tr><td>01/15/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>34</td><td>.36</td><td>.33</td><td>.50</td><td></td></tr><tr><td>01/15/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>27</td><td>1.99</td><td>1.99</td><td>2.00</td><td></td></tr><tr><td>01/15/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>543</td><td>1.09</td><td>.99</td><td>1.50</td><td>33</td></tr><tr><td>01/15/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>368</td><td>2.01</td><td>1.99</td><td>2.49</td><td></td></tr><tr><td>01/15/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>469</td><td>1.67</td><td>1.49</td><td>1.74</td><td></td></tr><tr><td>01/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>68</td><td>.46</td><td>.33</td><td>.50</td><td></td></tr><tr><td>01/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>21</td><td>.89</td><td>.89</td><td>.89</td><td></td></tr><tr><td>01/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>66</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>01/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>62</td><td>.89</td><td>.89</td><td>.89</td><td></td></tr><tr><td>01/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>96</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>01/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>26</td><td>1.83</td><td>1.50</td><td>2.00</td><td></td></tr><tr><td>01/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>547</td><td>1.33</td><td>.99</td><td>1.58</td><td></td></tr><tr><td>01/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>96</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>01/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>255</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>01/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>2 lb bag</td><td>107</td><td>2.69</td><td>2.69</td><td>2.69</td><td></td></tr><tr><td>01/29/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>167</td><td>.45</td><td>.33</td><td>.50</td><td></td></tr><tr><td>01/29/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>15</td><td>.96</td><td>.89</td><td>1.00</td><td></td></tr><tr><td>01/29/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>59</td><td>.34</td><td>.33</td><td>.50</td><td></td></tr><tr><td>01/29/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>241</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>01/29/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>560</td><td>1.58</td><td>.99</td><td>1.99</td><td></td></tr><tr><td>01/29/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>718</td><td>1.99</td><td>1.99</td><td>1.99</td><td>59</td></tr><tr><td>01/29/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>15</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>02/05/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>7</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>02/05/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>53</td><td>.35</td><td>.33</td><td>.50</td><td></td></tr><tr><td>02/05/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>15</td><td>2.49</td><td>2.49</td><td>2.49</td><td></td></tr><tr><td>02/05/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>731</td><td>1.32</td><td>.69</td><td>1.50</td><td></td></tr><tr><td>02/05/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>490</td><td>2.57</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>02/05/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>617</td><td>1.63</td><td>1.50</td><td>1.69</td><td></td></tr><tr><td>02/12/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>53</td><td>.32</td><td>.25</td><td>.33</td><td></td></tr><tr><td>02/12/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>14</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>02/12/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>364</td><td>1.99</td><td>1.99</td><td>1.99</td><td>67</td></tr><tr><td>02/12/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>75</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>02/19/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>163</td><td>.47</td><td>.33</td><td>.50</td><td></td></tr><tr><td>02/19/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>40</td><td>1.25</td><td>.69</td><td>1.49</td><td></td></tr><tr><td>02/19/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>48</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>02/19/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>130</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>02/19/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>777</td><td>.99</td><td>.99</td><td>1.00</td><td>54</td></tr><tr><td>02/19/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>11</td><td>1.98</td><td>1.98</td><td>1.98</td><td></td></tr><tr><td>02/19/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>25</td><td>1.68</td><td>1.50</td><td>1.99</td><td></td></tr><tr><td>02/26/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>13</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>02/26/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>22</td><td>1.27</td><td>.79</td><td>1.49</td><td></td></tr><tr><td>02/26/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>87</td><td>.38</td><td>.33</td><td>.50</td><td></td></tr><tr><td>02/26/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>96</td><td>1.79</td><td>1.79</td><td>1.79</td><td></td></tr><tr><td>02/26/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>15</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>02/26/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>327</td><td>1.05</td><td>.79</td><td>1.25</td><td>75</td></tr><tr><td>02/26/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>744</td><td>1.62</td><td>1.49</td><td>1.69</td><td></td></tr><tr><td>03/04/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>212</td><td>.85</td><td>.33</td><td>.99</td><td></td></tr><tr><td>03/04/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>55</td><td>.81</td><td>.79</td><td>.89</td><td></td></tr><tr><td>03/04/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>121</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>03/04/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>107</td><td>.79</td><td>.79</td><td>.79</td><td></td></tr><tr><td>03/04/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>399</td><td>1.43</td><td>1.25</td><td>1.50</td><td></td></tr><tr><td>03/04/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>422</td><td>1.99</td><td>1.99</td><td>1.99</td><td>100</td></tr><tr><td>03/04/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>409</td><td>2.10</td><td>1.49</td><td>2.50</td><td></td></tr><tr><td>03/11/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>62</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>03/11/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>2</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>03/11/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>64</td><td>.38</td><td>.33</td><td>.59</td><td></td></tr><tr><td>03/11/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>75</td><td>1.69</td><td>1.69</td><td>1.69</td><td></td></tr><tr><td>03/11/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>9</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>03/11/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>493</td><td>1.25</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>03/11/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>307</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>03/11/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>250</td><td>1.49</td><td>1.25</td><td>1.50</td><td></td></tr><tr><td>03/18/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>7</td><td>.39</td><td>.39</td><td>.39</td><td></td></tr><tr><td>03/18/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>149</td><td>1.13</td><td>.99</td><td>1.49</td><td></td></tr><tr><td>03/18/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>131</td><td>.36</td><td>.33</td><td>.69</td><td></td></tr><tr><td>03/18/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>241</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>03/18/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>367</td><td>1.05</td><td>.79</td><td>1.25</td><td></td></tr><tr><td>03/18/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>559</td><td>2.21</td><td>1.99</td><td>2.88</td><td>75</td></tr><tr><td>03/18/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>14</td><td>1.19</td><td>.79</td><td>1.49</td><td></td></tr><tr><td>03/25/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>11</td><td>.42</td><td>.33</td><td>.49</td><td></td></tr><tr><td>03/25/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>93</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>03/25/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>216</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>03/25/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>176</td><td>1.52</td><td>1.49</td><td>1.99</td><td></td></tr><tr><td>03/25/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>535</td><td>1.37</td><td>.99</td><td>1.99</td><td></td></tr><tr><td>03/25/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>499</td><td>1.99</td><td>1.99</td><td>2.50</td><td>85</td></tr><tr><td>03/25/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>82</td><td>1.47</td><td>1.25</td><td>1.50</td><td></td></tr><tr><td>04/01/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>115</td><td>.34</td><td>.33</td><td>.49</td><td></td></tr><tr><td>04/01/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>422</td><td>1.29</td><td>1.29</td><td>1.29</td><td></td></tr><tr><td>04/01/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>88</td><td>1.09</td><td>1.00</td><td>1.50</td><td></td></tr><tr><td>04/01/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>11</td><td>1.98</td><td>1.98</td><td>1.98</td><td></td></tr><tr><td>04/01/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>134</td><td>1.61</td><td>1.50</td><td>2.50</td><td></td></tr><tr><td>04/08/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>2</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>04/08/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>114</td><td>.35</td><td>.33</td><td>.50</td><td></td></tr><tr><td>04/08/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>231</td><td>1.55</td><td>1.48</td><td>2.49</td><td></td></tr><tr><td>04/08/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>392</td><td>1.13</td><td>.99</td><td>1.25</td><td></td></tr><tr><td>04/08/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>378</td><td>1.50</td><td>1.49</td><td>1.50</td><td>36</td></tr><tr><td>04/15/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>42</td><td>1.49</td><td>1.49</td><td>1.49</td><td></td></tr><tr><td>04/15/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>7</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>04/15/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>116</td><td>.35</td><td>.33</td><td>.69</td><td></td></tr><tr><td>04/15/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>143</td><td>1.62</td><td>1.49</td><td>2.50</td><td></td></tr><tr><td>04/15/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>490</td><td>1.17</td><td>.49</td><td>1.50</td><td>36</td></tr><tr><td>04/15/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>16</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>04/15/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>63</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>04/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>16</td><td>.39</td><td>.39</td><td>.39</td><td></td></tr><tr><td>04/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>2</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>04/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>7</td><td>.69</td><td>.69</td><td>.69</td><td></td></tr><tr><td>04/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>157</td><td>.35</td><td>.33</td><td>.69</td><td></td></tr><tr><td>04/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>241</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>04/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>243</td><td>2.02</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>04/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>195</td><td>1.58</td><td>1.50</td><td>2.50</td><td></td></tr><tr><td>04/29/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>13</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>04/29/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>104</td><td>.34</td><td>.33</td><td>.46</td><td></td></tr><tr><td>04/29/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>244</td><td>1.69</td><td>1.69</td><td>1.69</td><td></td></tr><tr><td>04/29/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>370</td><td>1.17</td><td>.99</td><td>1.89</td><td>2</td></tr><tr><td>04/29/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>129</td><td>1.27</td><td>1.25</td><td>1.50</td><td></td></tr><tr><td>04/29/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>333</td><td>1.99</td><td>1.99</td><td>2.00</td><td>73</td></tr><tr><td>04/29/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>9</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>05/06/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>9</td><td>.50</td><td>.50</td><td>.50</td><td></td></tr><tr><td>05/06/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>147</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>05/06/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>422</td><td>1.49</td><td>1.49</td><td>1.49</td><td>100</td></tr><tr><td>05/06/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>231</td><td>1.10</td><td>.98</td><td>1.25</td><td></td></tr><tr><td>05/06/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>178</td><td>1.99</td><td>1.99</td><td>1.99</td><td>100</td></tr><tr><td>05/13/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>182</td><td>.95</td><td>.49</td><td>.99</td><td></td></tr><tr><td>05/13/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>41</td><td>1.00</td><td>.99</td><td>1.00</td><td></td></tr><tr><td>05/13/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>58</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>05/13/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>42</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>05/13/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>15</td><td>2.49</td><td>2.49</td><td>2.49</td><td></td></tr><tr><td>05/13/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>127</td><td>1.52</td><td>1.49</td><td>1.99</td><td>6</td></tr><tr><td>05/13/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>821</td><td>1.10</td><td>.79</td><td>1.50</td><td>30</td></tr><tr><td>05/13/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>15</td><td>1.59</td><td>.99</td><td>1.99</td><td></td></tr><tr><td>05/20/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>15</td><td>.50</td><td>.50</td><td>.50</td><td></td></tr><tr><td>05/20/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>27</td><td>1.49</td><td>1.49</td><td>1.49</td><td></td></tr><tr><td>05/20/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>99</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>05/20/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>129</td><td>1.52</td><td>1.49</td><td>1.89</td><td></td></tr><tr><td>05/20/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>157</td><td>1.02</td><td>.99</td><td>1.49</td><td></td></tr><tr><td>05/20/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>2</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>05/20/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>241</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>05/27/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>66</td><td>.28</td><td>.25</td><td>.50</td><td></td></tr><tr><td>05/27/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>9</td><td>1.99</td><td>1.99</td><td>1.99</td><td>100</td></tr><tr><td>05/27/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>443</td><td>1.05</td><td>.99</td><td>1.25</td><td></td></tr><tr><td>05/27/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>244</td><td>1.99</td><td>1.99</td><td>1.99</td><td>100</td></tr><tr><td>05/27/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>251</td><td>1.68</td><td>1.49</td><td>1.69</td><td>3</td></tr><tr><td>06/03/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>167</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>06/03/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>147</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>06/03/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>258</td><td>.98</td><td>.69</td><td>.99</td><td></td></tr><tr><td>06/03/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>2</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>06/03/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>418</td><td>1.58</td><td>1.50</td><td>1.69</td><td>43</td></tr><tr><td>06/10/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>29</td><td>1.46</td><td>.99</td><td>1.49</td><td></td></tr><tr><td>06/10/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>93</td><td>.40</td><td>.33</td><td>.59</td><td></td></tr><tr><td>06/10/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>15</td><td>2.69</td><td>2.69</td><td>2.69</td><td></td></tr><tr><td>06/10/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>187</td><td>1.00</td><td>1.00</td><td>1.00</td><td></td></tr><tr><td>06/10/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>447</td><td>1.68</td><td>1.50</td><td>1.69</td><td>40</td></tr><tr><td>06/17/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>25</td><td>.43</td><td>.39</td><td>.50</td><td></td></tr><tr><td>06/17/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>6</td><td>.50</td><td>.50</td><td>.50</td><td></td></tr><tr><td>06/17/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>56</td><td>.35</td><td>.33</td><td>.50</td><td></td></tr><tr><td>06/17/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>182</td><td>1.10</td><td>.99</td><td>1.25</td><td></td></tr><tr><td>06/17/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>16</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>06/24/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>39</td><td>1.00</td><td>1.00</td><td>1.00</td><td></td></tr><tr><td>06/24/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>69</td><td>.37</td><td>.33</td><td>.50</td><td></td></tr><tr><td>06/24/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>272</td><td>.99</td><td>.98</td><td>1.00</td><td></td></tr><tr><td>06/24/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>255</td><td>1.99</td><td>1.98</td><td>1.99</td><td>96</td></tr><tr><td>06/24/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>15</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>07/01/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>15</td><td>.50</td><td>.50</td><td>.50</td><td></td></tr><tr><td>07/01/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>63</td><td>.34</td><td>.33</td><td>.50</td><td></td></tr><tr><td>07/01/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>2</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>07/01/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>253</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>07/01/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>185</td><td>1.52</td><td>1.50</td><td>1.99</td><td></td></tr><tr><td>07/08/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>44</td><td>.39</td><td>.39</td><td>.39</td><td></td></tr><tr><td>07/08/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>31</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>07/08/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>68</td><td>.81</td><td>.79</td><td>.99</td><td></td></tr><tr><td>07/08/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>100</td><td>1.36</td><td>.98</td><td>1.50</td><td></td></tr><tr><td>07/08/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>107</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>07/08/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>153</td><td>1.81</td><td>1.79</td><td>1.99</td><td></td></tr><tr><td>07/08/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>2 lb bag</td><td>3</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>07/15/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>5</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>07/15/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>27</td><td>1.49</td><td>1.49</td><td>1.49</td><td></td></tr><tr><td>07/15/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>100</td><td>.47</td><td>.33</td><td>.89</td><td></td></tr><tr><td>07/15/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>371</td><td>.99</td><td>.99</td><td>1.00</td><td></td></tr><tr><td>07/15/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>244</td><td>1.99</td><td>1.99</td><td>1.99</td><td>100</td></tr><tr><td>07/15/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>99</td><td>1.70</td><td>1.50</td><td>2.50</td><td></td></tr><tr><td>07/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>211</td><td>.86</td><td>.39</td><td>.99</td><td></td></tr><tr><td>07/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>21</td><td>.69</td><td>.69</td><td>.69</td><td></td></tr><tr><td>07/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>71</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>07/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>68</td><td>.79</td><td>.79</td><td>.79</td><td></td></tr><tr><td>07/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>253</td><td>1.51</td><td>1.49</td><td>1.99</td><td>96</td></tr><tr><td>07/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>148</td><td>.99</td><td>.99</td><td>1.00</td><td></td></tr><tr><td>07/22/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>189</td><td>1.99</td><td>1.98</td><td>1.99</td><td>94</td></tr><tr><td>07/29/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>9</td><td>.79</td><td>.79</td><td>.79</td><td></td></tr><tr><td>07/29/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>62</td><td>.34</td><td>.33</td><td>.50</td><td></td></tr><tr><td>07/29/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>13</td><td>.50</td><td>.50</td><td>.50</td><td></td></tr><tr><td>07/29/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>6</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>07/29/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>120</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>07/29/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>599</td><td>1.27</td><td>.98</td><td>1.48</td><td></td></tr><tr><td>07/29/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>487</td><td>2.01</td><td>1.50</td><td>2.50</td><td></td></tr><tr><td>08/05/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>29</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>08/05/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>2</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>08/05/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>112</td><td>.34</td><td>.33</td><td>.50</td><td></td></tr><tr><td>08/05/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>120</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>08/05/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,048</td><td>1.20</td><td>.98</td><td>1.50</td><td>17</td></tr><tr><td>08/05/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>107</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>08/05/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>197</td><td>1.56</td><td>1.49</td><td>1.99</td><td>5</td></tr><tr><td>08/12/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>29</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>08/12/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>61</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>08/12/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>96</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>08/12/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>512</td><td>1.33</td><td>.98</td><td>1.49</td><td></td></tr><tr><td>08/12/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>246</td><td>1.99</td><td>1.99</td><td>1.99</td><td>99</td></tr><tr><td>08/12/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>322</td><td>3.38</td><td>.88</td><td>3.99</td><td></td></tr><tr><td>08/19/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>6</td><td>.50</td><td>.50</td><td>.50</td><td></td></tr><tr><td>08/19/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>71</td><td>.95</td><td>.89</td><td>1.00</td><td></td></tr><tr><td>08/19/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>174</td><td>.34</td><td>.33</td><td>.50</td><td></td></tr><tr><td>08/19/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>241</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>08/19/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>360</td><td>1.30</td><td>.79</td><td>1.50</td><td></td></tr><tr><td>08/19/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>285</td><td>1.99</td><td>1.99</td><td>1.99</td><td>62</td></tr><tr><td>08/19/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>357</td><td>1.69</td><td>1.50</td><td>2.50</td><td>50</td></tr><tr><td>08/26/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>7</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>08/26/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>39</td><td>1.00</td><td>1.00</td><td>1.00</td><td></td></tr><tr><td>08/26/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>39</td><td>.38</td><td>.33</td><td>.50</td><td></td></tr><tr><td>08/26/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>6</td><td>.49</td><td>.49</td><td>.49</td><td></td></tr><tr><td>08/26/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>15</td><td>3.49</td><td>3.49</td><td>3.49</td><td></td></tr><tr><td>08/26/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>198</td><td>1.16</td><td>.99</td><td>1.29</td><td></td></tr><tr><td>08/26/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>62</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>09/02/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>5</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>09/02/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>60</td><td>1.00</td><td>.99</td><td>1.00</td><td></td></tr><tr><td>09/02/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>116</td><td>.40</td><td>.33</td><td>.89</td><td></td></tr><tr><td>09/02/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>9</td><td>1.69</td><td>1.69</td><td>1.69</td><td></td></tr><tr><td>09/02/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>743</td><td>1.11</td><td>.98</td><td>1.50</td><td></td></tr><tr><td>09/02/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>75</td><td>2.29</td><td>2.29</td><td>2.29</td><td></td></tr><tr><td>09/02/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>490</td><td>2.10</td><td>1.69</td><td>2.50</td><td>50</td></tr><tr><td>09/09/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>179</td><td>.96</td><td>.50</td><td>.99</td><td></td></tr><tr><td>09/09/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>11</td><td>.69</td><td>.69</td><td>.69</td><td></td></tr><tr><td>09/09/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>81</td><td>.37</td><td>.33</td><td>.69</td><td></td></tr><tr><td>09/09/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>15</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>09/09/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>130</td><td>.98</td><td>.98</td><td>.98</td><td></td></tr><tr><td>09/09/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>2</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>09/09/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>638</td><td>1.65</td><td>1.48</td><td>1.99</td><td></td></tr><tr><td>09/16/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>35</td><td>.36</td><td>.33</td><td>.50</td><td></td></tr><tr><td>09/16/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>41</td><td>1.00</td><td>.99</td><td>1.00</td><td></td></tr><tr><td>09/16/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>112</td><td>.33</td><td>.25</td><td>.50</td><td></td></tr><tr><td>09/16/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>241</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>09/16/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>719</td><td>1.15</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>09/16/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>244</td><td>1.99</td><td>1.99</td><td>1.99</td><td>100</td></tr><tr><td>09/16/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>180</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>09/23/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>154</td><td>1.05</td><td>.33</td><td>1.25</td><td></td></tr><tr><td>09/23/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>54</td><td>1.16</td><td>1.00</td><td>1.59</td><td></td></tr><tr><td>09/23/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>7</td><td>.59</td><td>.59</td><td>.59</td><td></td></tr><tr><td>09/23/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>112</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>09/23/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>120</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>09/23/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>174</td><td>1.49</td><td>1.39</td><td>1.50</td><td></td></tr><tr><td>09/23/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>665</td><td>1.30</td><td>.98</td><td>1.99</td><td></td></tr><tr><td>09/23/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>11</td><td>1.98</td><td>1.98</td><td>1.98</td><td></td></tr><tr><td>09/23/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>47</td><td>1.31</td><td>1.29</td><td>1.50</td><td></td></tr><tr><td>09/30/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>29</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>09/30/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>383</td><td>1.25</td><td>1.00</td><td>1.28</td><td></td></tr><tr><td>09/30/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>58</td><td>.34</td><td>.33</td><td>.50</td><td></td></tr><tr><td>09/30/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>178</td><td>1.49</td><td>1.49</td><td>1.49</td><td></td></tr><tr><td>09/30/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>30</td><td>1.72</td><td>1.39</td><td>1.99</td><td>30</td></tr><tr><td>09/30/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>100</td><td>1.13</td><td>.99</td><td>1.99</td><td></td></tr><tr><td>09/30/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>100</td><td>1.87</td><td>1.50</td><td>2.00</td><td></td></tr><tr><td>09/30/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>2 lb bag</td><td>3</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>10/07/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>344</td><td>1.28</td><td>1.28</td><td>1.28</td><td></td></tr><tr><td>10/07/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>101</td><td>.40</td><td>.33</td><td>.79</td><td></td></tr><tr><td>10/07/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>35</td><td>2.05</td><td>.99</td><td>2.99</td><td></td></tr><tr><td>10/07/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>699</td><td>1.03</td><td>.98</td><td>1.25</td><td>35</td></tr><tr><td>10/07/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>27</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>10/14/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>11</td><td>.41</td><td>.33</td><td>.50</td><td></td></tr><tr><td>10/14/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>394</td><td>1.27</td><td>.79</td><td>1.49</td><td></td></tr><tr><td>10/14/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>61</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>10/14/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>194</td><td>1.78</td><td>1.49</td><td>1.99</td><td></td></tr><tr><td>10/14/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>62</td><td>.99</td><td>.98</td><td>.99</td><td></td></tr><tr><td>10/14/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>62</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>10/14/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>138</td><td>1.40</td><td>.79</td><td>1.48</td><td></td></tr><tr><td>10/14/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>2 lb bag</td><td>110</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>10/21/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>29</td><td>.39</td><td>.33</td><td>.50</td><td></td></tr><tr><td>10/21/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>15</td><td>2.49</td><td>2.49</td><td>2.49</td><td></td></tr><tr><td>10/21/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>640</td><td>1.03</td><td>.98</td><td>1.25</td><td></td></tr><tr><td>10/21/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>178</td><td>1.99</td><td>1.99</td><td>1.99</td><td>100</td></tr><tr><td>10/21/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>255</td><td>2.48</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>10/28/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>17</td><td>.79</td><td>.79</td><td>.79</td><td></td></tr><tr><td>10/28/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>54</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>10/28/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>96</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>10/28/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>3</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>10/28/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>497</td><td>1.21</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>10/28/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>244</td><td>1.99</td><td>1.99</td><td>1.99</td><td>100</td></tr><tr><td>10/28/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>9</td><td>1.25</td><td>1.25</td><td>1.25</td><td></td></tr><tr><td>10/28/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>2 lb bag</td><td>253</td><td>1.99</td><td>1.99</td><td>1.99</td><td>96</td></tr><tr><td>11/04/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>387</td><td>.81</td><td>.33</td><td>.87</td><td></td></tr><tr><td>11/04/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>39</td><td>1.00</td><td>1.00</td><td>1.00</td><td></td></tr><tr><td>11/04/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>93</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>11/04/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>7</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>11/04/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>572</td><td>1.06</td><td>.98</td><td>1.50</td><td>31</td></tr><tr><td>11/04/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>338</td><td>1.51</td><td>1.48</td><td>1.99</td><td></td></tr><tr><td>11/04/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>2 lb bag</td><td>347</td><td>3.48</td><td>2.99</td><td>3.48</td><td></td></tr><tr><td>11/11/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>373</td><td>.75</td><td>.33</td><td>.78</td><td></td></tr><tr><td>11/11/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>6</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>11/11/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>18</td><td>.38</td><td>.33</td><td>.50</td><td></td></tr><tr><td>11/11/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>241</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>11/11/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>96</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>11/11/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>158</td><td>1.36</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>11/11/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>260</td><td>1.99</td><td>1.99</td><td>2.00</td><td>94</td></tr><tr><td>11/11/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>90</td><td>1.51</td><td>.99</td><td>1.99</td><td></td></tr><tr><td>11/11/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>2 lb bag</td><td>344</td><td>3.48</td><td>3.48</td><td>3.48</td><td></td></tr><tr><td>11/18/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>182</td><td>.95</td><td>.49</td><td>.99</td><td></td></tr><tr><td>11/18/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>142</td><td>.36</td><td>.33</td><td>.50</td><td></td></tr><tr><td>11/18/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>5</td><td>1.39</td><td>1.39</td><td>1.39</td><td></td></tr><tr><td>11/18/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>391</td><td>1.29</td><td>.49</td><td>1.49</td><td></td></tr><tr><td>11/18/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>651</td><td>2.05</td><td>1.98</td><td>2.50</td><td>27</td></tr><tr><td>11/18/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>473</td><td>1.44</td><td>.98</td><td>1.69</td><td></td></tr><tr><td>11/25/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>5</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>11/25/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>15</td><td>1.59</td><td>1.59</td><td>1.59</td><td></td></tr><tr><td>11/25/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>9</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>11/25/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>90</td><td>.38</td><td>.33</td><td>.50</td><td></td></tr><tr><td>11/25/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>137</td><td>.79</td><td>.79</td><td>.79</td><td></td></tr><tr><td>11/25/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>344</td><td>1.58</td><td>1.58</td><td>1.58</td><td></td></tr><tr><td>11/25/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>5</td><td>1.39</td><td>1.39</td><td>1.39</td><td></td></tr><tr><td>11/25/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>107</td><td>1.31</td><td>.79</td><td>1.49</td><td></td></tr><tr><td>11/25/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>102</td><td>2.37</td><td>1.98</td><td>2.50</td><td></td></tr><tr><td>12/02/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>35</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>12/02/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>9</td><td>1.99</td><td>1.99</td><td>1.99</td><td>100</td></tr><tr><td>12/02/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>50</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>12/02/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>344</td><td>1.58</td><td>1.58</td><td>1.58</td><td></td></tr><tr><td>12/02/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>75</td><td>1.03</td><td>.99</td><td>1.18</td><td>9</td></tr><tr><td>12/02/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>891</td><td>1.53</td><td>1.25</td><td>2.00</td><td>1</td></tr><tr><td>12/02/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>2 lb bag</td><td>246</td><td>3.99</td><td>3.99</td><td>3.99</td><td></td></tr><tr><td>12/09/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>20</td><td>.37</td><td>.33</td><td>.50</td><td></td></tr><tr><td>12/09/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>6</td><td>.49</td><td>.49</td><td>.49</td><td></td></tr><tr><td>12/09/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>11</td><td>.41</td><td>.33</td><td>.50</td><td></td></tr><tr><td>12/09/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>344</td><td>1.58</td><td>1.58</td><td>1.58</td><td></td></tr><tr><td>12/09/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>15</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>12/09/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>255</td><td>.99</td><td>.98</td><td>.99</td><td>96</td></tr><tr><td>12/09/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>16</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>12/09/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>376</td><td>1.73</td><td>1.25</td><td>2.00</td><td></td></tr><tr><td>12/09/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>2 lb bag</td><td>3</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>12/16/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>15</td><td>.55</td><td>.33</td><td>.89</td><td></td></tr><tr><td>12/16/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>229</td><td>.39</td><td>.33</td><td>.79</td><td></td></tr><tr><td>12/16/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>344</td><td>1.58</td><td>1.58</td><td>1.58</td><td></td></tr><tr><td>12/16/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>9</td><td>1.99</td><td>1.99</td><td>1.99</td><td>100</td></tr><tr><td>12/16/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>169</td><td>1.49</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>12/16/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>545</td><td>2.09</td><td>1.99</td><td>2.50</td><td>77</td></tr><tr><td>12/16/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>137</td><td>1.50</td><td>1.49</td><td>1.50</td><td></td></tr><tr><td>12/23/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>29</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>12/23/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>240</td><td>.36</td><td>.25</td><td>.50</td><td></td></tr><tr><td>12/23/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>507</td><td>1.33</td><td>.69</td><td>1.50</td><td></td></tr><tr><td>12/23/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>612</td><td>2.27</td><td>1.99</td><td>2.99</td><td>69</td></tr><tr><td>12/23/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>155</td><td>1.52</td><td>1.49</td><td>1.99</td><td>6</td></tr><tr><td>12/30/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>29</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>12/30/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>39</td><td>1.00</td><td>1.00</td><td>1.00</td><td></td></tr><tr><td>12/30/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>41</td><td>.33</td><td>.33</td><td>.33</td><td></td></tr><tr><td>12/30/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>24</td><td>2.62</td><td>1.99</td><td>2.99</td><td>38</td></tr><tr><td>12/30/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>183</td><td>1.16</td><td>.89</td><td>1.50</td><td></td></tr><tr><td>12/30/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>403</td><td>2.12</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>12/30/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>894</td><td>1.54</td><td>.98</td><td>1.69</td><td>47</td></tr><tr><td>12/30/2016</td><td>SOUTHWEST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>2 lb bag</td><td>3</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td> </td></tr>
</table></body></html>
<file_sep>/raw_data/CARROTS_NORTHEAST+U.S._2018.html
<html><body><table border=1>
<tr><th>Date</th><th>Region</th><th>Class</th><th>Commodity</th><th>Variety</th><th>Organic</th><th>Environment</th><th>Unit</th><th>Number of Stores</th><th>Weighted Avg Price</th><th>Low Price</th><th>High Price</th><th>% Marked Local</th></tr><tr><td>01/05/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>261</td><td>.79</td><td>.50</td><td>.99</td><td></td></tr><tr><td>01/05/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>1,293</td><td>1.56</td><td>.99</td><td>1.99</td><td></td></tr><tr><td>01/05/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>11</td><td>.49</td><td>.48</td><td>.50</td><td></td></tr><tr><td>01/05/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>12</td><td>1.14</td><td>.98</td><td>1.29</td><td></td></tr><tr><td>01/05/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>175</td><td>2.07</td><td>1.99</td><td>2.69</td><td></td></tr><tr><td>01/05/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>826</td><td>1.35</td><td>.98</td><td>1.90</td><td></td></tr><tr><td>01/05/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>1,006</td><td>2.19</td><td>1.84</td><td>2.99</td><td></td></tr><tr><td>01/05/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>1,179</td><td>1.83</td><td>1.29</td><td>2.99</td><td></td></tr><tr><td>01/12/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>186</td><td>.97</td><td>.79</td><td>1.50</td><td></td></tr><tr><td>01/12/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>242</td><td>1.21</td><td>.99</td><td>1.67</td><td></td></tr><tr><td>01/12/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>41</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>01/12/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>150</td><td>1.30</td><td>1.29</td><td>1.49</td><td></td></tr><tr><td>01/12/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>21</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>01/12/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>18</td><td>2.33</td><td>2.00</td><td>2.49</td><td></td></tr><tr><td>01/12/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,485</td><td>1.43</td><td>.99</td><td>1.69</td><td></td></tr><tr><td>01/12/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>1,698</td><td>2.33</td><td>1.84</td><td>2.99</td><td></td></tr><tr><td>01/12/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>845</td><td>2.03</td><td>.98</td><td>2.50</td><td></td></tr><tr><td>01/12/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>2 lb bag</td><td>20</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>01/19/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>157</td><td>.78</td><td>.75</td><td>.99</td><td></td></tr><tr><td>01/19/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>422</td><td>1.50</td><td>1.48</td><td>1.50</td><td></td></tr><tr><td>01/19/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>13</td><td>1.88</td><td>1.50</td><td>2.50</td><td></td></tr><tr><td>01/19/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>37</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>01/19/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>70</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>01/19/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,513</td><td>1.19</td><td>.97</td><td>1.67</td><td></td></tr><tr><td>01/19/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>1,086</td><td>2.18</td><td>1.84</td><td>2.99</td><td></td></tr><tr><td>01/19/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>667</td><td>2.04</td><td>1.50</td><td>2.50</td><td></td></tr><tr><td>01/26/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>96</td><td>.70</td><td>.50</td><td>.79</td><td></td></tr><tr><td>01/26/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>345</td><td>1.34</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>01/26/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>7</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>01/26/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>307</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>01/26/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>82</td><td>1.25</td><td>.99</td><td>2.00</td><td></td></tr><tr><td>01/26/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>16</td><td>2.69</td><td>2.69</td><td>2.69</td><td></td></tr><tr><td>01/26/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,220</td><td>1.55</td><td>1.00</td><td>2.00</td><td></td></tr><tr><td>01/26/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>1,187</td><td>2.12</td><td>1.84</td><td>2.99</td><td></td></tr><tr><td>01/26/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>608</td><td>2.27</td><td>1.29</td><td>2.50</td><td></td></tr><tr><td>02/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>96</td><td>.97</td><td>.80</td><td>.99</td><td></td></tr><tr><td>02/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>80</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>02/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>2</td><td>.50</td><td>.50</td><td>.50</td><td></td></tr><tr><td>02/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>90</td><td>1.67</td><td>1.50</td><td>1.99</td><td></td></tr><tr><td>02/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>43</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>02/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>2,213</td><td>1.19</td><td>.88</td><td>1.99</td><td></td></tr><tr><td>02/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>250</td><td>2.10</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>02/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>940</td><td>1.97</td><td>1.49</td><td>2.99</td><td></td></tr><tr><td>02/09/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>184</td><td>.89</td><td>.59</td><td>1.50</td><td></td></tr><tr><td>02/09/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>9</td><td>1.29</td><td>1.29</td><td>1.29</td><td></td></tr><tr><td>02/09/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>33</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>02/09/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>130</td><td>1.15</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>02/09/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>13</td><td>2.26</td><td>2.00</td><td>2.49</td><td></td></tr><tr><td>02/09/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,477</td><td>1.33</td><td>.98</td><td>1.99</td><td></td></tr><tr><td>02/09/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>522</td><td>2.45</td><td>1.79</td><td>2.99</td><td></td></tr><tr><td>02/09/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>468</td><td>2.23</td><td>1.29</td><td>2.99</td><td></td></tr><tr><td>02/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>157</td><td>.80</td><td>.79</td><td>.99</td><td></td></tr><tr><td>02/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>138</td><td>1.50</td><td>1.29</td><td>2.50</td><td></td></tr><tr><td>02/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>37</td><td>.65</td><td>.65</td><td>.65</td><td></td></tr><tr><td>02/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>31</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>02/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>144</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>02/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>28</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>02/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,157</td><td>1.42</td><td>.98</td><td>1.79</td><td></td></tr><tr><td>02/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>626</td><td>2.45</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>02/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>1,185</td><td>2.12</td><td>1.49</td><td>2.50</td><td></td></tr><tr><td>02/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>2</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>02/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>488</td><td>2.30</td><td>1.49</td><td>2.99</td><td></td></tr><tr><td>02/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>21</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>02/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>53</td><td>1.04</td><td>.99</td><td>1.49</td><td></td></tr><tr><td>02/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>145</td><td>1.86</td><td>1.67</td><td>2.50</td><td></td></tr><tr><td>02/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>206</td><td>1.33</td><td>.99</td><td>1.99</td><td></td></tr><tr><td>02/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,122</td><td>1.33</td><td>1.00</td><td>1.69</td><td></td></tr><tr><td>02/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>541</td><td>2.56</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>02/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>556</td><td>2.16</td><td>1.49</td><td>2.99</td><td></td></tr><tr><td>03/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>88</td><td>1.00</td><td>.79</td><td>1.50</td><td></td></tr><tr><td>03/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>770</td><td>1.23</td><td>.98</td><td>2.50</td><td></td></tr><tr><td>03/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>28</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>03/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>181</td><td>1.28</td><td>.99</td><td>1.69</td><td></td></tr><tr><td>03/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>43</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>03/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>6</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>03/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>973</td><td>1.20</td><td>.88</td><td>1.69</td><td></td></tr><tr><td>03/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>673</td><td>2.88</td><td>2.50</td><td>2.99</td><td></td></tr><tr><td>03/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>799</td><td>2.09</td><td>1.49</td><td>2.99</td><td></td></tr><tr><td>03/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>165</td><td>.75</td><td>.67</td><td>.79</td><td></td></tr><tr><td>03/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>740</td><td>1.17</td><td>.98</td><td>1.99</td><td></td></tr><tr><td>03/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>39</td><td>.94</td><td>.68</td><td>.99</td><td></td></tr><tr><td>03/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>76</td><td>1.63</td><td>.99</td><td>1.99</td><td></td></tr><tr><td>03/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>20</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>03/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>7</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>03/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>858</td><td>1.48</td><td>.79</td><td>1.99</td><td></td></tr><tr><td>03/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>624</td><td>2.36</td><td>1.99</td><td>3.59</td><td></td></tr><tr><td>03/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>850</td><td>2.10</td><td>.99</td><td>2.50</td><td></td></tr><tr><td>03/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>106</td><td>.85</td><td>.67</td><td>1.29</td><td></td></tr><tr><td>03/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>539</td><td>1.01</td><td>.98</td><td>1.50</td><td></td></tr><tr><td>03/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>94</td><td>1.37</td><td>.99</td><td>1.49</td><td></td></tr><tr><td>03/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>6</td><td>.68</td><td>.68</td><td>.68</td><td></td></tr><tr><td>03/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>22</td><td>1.45</td><td>1.29</td><td>1.50</td><td></td></tr><tr><td>03/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>136</td><td>2.49</td><td>2.49</td><td>2.49</td><td></td></tr><tr><td>03/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>7</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>03/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,334</td><td>1.26</td><td>.79</td><td>1.69</td><td></td></tr><tr><td>03/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>551</td><td>2.23</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>03/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>381</td><td>1.90</td><td>1.49</td><td>2.49</td><td></td></tr><tr><td>03/30/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>91</td><td>.79</td><td>.79</td><td>.79</td><td></td></tr><tr><td>03/30/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>21</td><td>1.65</td><td>1.49</td><td>1.67</td><td></td></tr><tr><td>03/30/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>214</td><td>1.37</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>03/30/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>255</td><td>.69</td><td>.69</td><td>.69</td><td></td></tr><tr><td>03/30/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>52</td><td>1.45</td><td>1.29</td><td>1.50</td><td></td></tr><tr><td>03/30/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>20</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>03/30/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>21</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>03/30/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,255</td><td>1.79</td><td>.89</td><td>2.50</td><td></td></tr><tr><td>03/30/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>1,177</td><td>2.35</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>03/30/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>423</td><td>2.06</td><td>.99</td><td>2.49</td><td></td></tr><tr><td>03/30/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>2 lb bag</td><td>88</td><td>2.49</td><td>2.49</td><td>2.49</td><td></td></tr><tr><td>04/06/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>50</td><td>.79</td><td>.79</td><td>.79</td><td></td></tr><tr><td>04/06/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>80</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>04/06/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>103</td><td>1.22</td><td>.67</td><td>1.50</td><td></td></tr><tr><td>04/06/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>2</td><td>.50</td><td>.50</td><td>.50</td><td></td></tr><tr><td>04/06/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>12</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>04/06/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>35</td><td>2.00</td><td>1.99</td><td>2.00</td><td></td></tr><tr><td>04/06/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>643</td><td>1.82</td><td>.98</td><td>3.00</td><td></td></tr><tr><td>04/06/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>758</td><td>2.33</td><td>1.99</td><td>2.49</td><td></td></tr><tr><td>04/06/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>650</td><td>2.08</td><td>1.79</td><td>2.49</td><td></td></tr><tr><td>04/13/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>294</td><td>.74</td><td>.69</td><td>.79</td><td></td></tr><tr><td>04/13/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>63</td><td>1.61</td><td>1.29</td><td>2.50</td><td></td></tr><tr><td>04/13/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>6</td><td>1.67</td><td>1.67</td><td>1.67</td><td></td></tr><tr><td>04/13/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>8</td><td>1.29</td><td>1.29</td><td>1.29</td><td></td></tr><tr><td>04/13/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>136</td><td>2.49</td><td>2.49</td><td>2.49</td><td></td></tr><tr><td>04/13/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>28</td><td>2.00</td><td>1.99</td><td>2.00</td><td></td></tr><tr><td>04/13/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,275</td><td>1.25</td><td>.99</td><td>2.50</td><td></td></tr><tr><td>04/13/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>175</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>04/13/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>865</td><td>1.95</td><td>1.49</td><td>2.50</td><td></td></tr><tr><td>04/20/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>172</td><td>.78</td><td>.67</td><td>.99</td><td></td></tr><tr><td>04/20/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>43</td><td>1.69</td><td>1.69</td><td>1.69</td><td></td></tr><tr><td>04/20/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>6</td><td>.69</td><td>.69</td><td>.69</td><td></td></tr><tr><td>04/20/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>18</td><td>1.29</td><td>1.29</td><td>1.29</td><td></td></tr><tr><td>04/20/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>43</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>04/20/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>28</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>04/20/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>941</td><td>1.35</td><td>1.00</td><td>1.50</td><td></td></tr><tr><td>04/20/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>453</td><td>2.55</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>04/20/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>402</td><td>1.88</td><td>.99</td><td>2.50</td><td></td></tr><tr><td>04/27/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>87</td><td>.73</td><td>.65</td><td>.79</td><td></td></tr><tr><td>04/27/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>161</td><td>1.63</td><td>1.49</td><td>1.99</td><td></td></tr><tr><td>04/27/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>46</td><td>1.55</td><td>1.25</td><td>1.69</td><td></td></tr><tr><td>04/27/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>16</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>04/27/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,374</td><td>1.36</td><td>.99</td><td>2.50</td><td></td></tr><tr><td>04/27/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>730</td><td>2.54</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>04/27/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>722</td><td>1.89</td><td>1.29</td><td>2.50</td><td></td></tr><tr><td>05/04/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>72</td><td>1.49</td><td>1.49</td><td>1.49</td><td></td></tr><tr><td>05/04/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>6</td><td>.69</td><td>.69</td><td>.69</td><td></td></tr><tr><td>05/04/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>56</td><td>1.03</td><td>.99</td><td>1.25</td><td></td></tr><tr><td>05/04/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>218</td><td>2.34</td><td>1.69</td><td>2.50</td><td></td></tr><tr><td>05/04/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>88</td><td>2.03</td><td>1.99</td><td>2.49</td><td></td></tr><tr><td>05/04/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>660</td><td>1.87</td><td>.99</td><td>2.99</td><td></td></tr><tr><td>05/04/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>81</td><td>2.49</td><td>2.49</td><td>2.49</td><td></td></tr><tr><td>05/04/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>349</td><td>1.90</td><td>1.69</td><td>2.00</td><td></td></tr><tr><td>05/11/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>11</td><td>.72</td><td>.50</td><td>.79</td><td></td></tr><tr><td>05/11/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>232</td><td>2.33</td><td>1.67</td><td>2.50</td><td></td></tr><tr><td>05/11/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>21</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>05/11/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>65</td><td>1.46</td><td>1.29</td><td>1.50</td><td></td></tr><tr><td>05/11/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>3</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>05/11/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>35</td><td>2.00</td><td>1.99</td><td>2.00</td><td></td></tr><tr><td>05/11/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>616</td><td>1.34</td><td>.99</td><td>1.67</td><td></td></tr><tr><td>05/11/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>327</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>05/11/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>336</td><td>2.34</td><td>1.50</td><td>2.50</td><td></td></tr><tr><td>05/18/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>64</td><td>1.64</td><td>1.49</td><td>1.99</td><td></td></tr><tr><td>05/18/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>2</td><td>.50</td><td>.50</td><td>.50</td><td></td></tr><tr><td>05/18/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>115</td><td>1.31</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>05/18/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>3</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>05/18/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>52</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>05/18/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>886</td><td>1.18</td><td>.99</td><td>1.67</td><td></td></tr><tr><td>05/18/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>531</td><td>2.98</td><td>2.50</td><td>2.99</td><td></td></tr><tr><td>05/18/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>524</td><td>1.84</td><td>1.29</td><td>2.29</td><td></td></tr><tr><td>05/25/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>93</td><td>.81</td><td>.79</td><td>.99</td><td></td></tr><tr><td>05/25/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>232</td><td>1.57</td><td>1.50</td><td>2.50</td><td></td></tr><tr><td>05/25/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>2</td><td>.50</td><td>.50</td><td>.50</td><td></td></tr><tr><td>05/25/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>7</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>05/25/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>43</td><td>2.08</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>05/25/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>464</td><td>1.50</td><td>.97</td><td>1.99</td><td></td></tr><tr><td>05/25/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>334</td><td>2.87</td><td>2.50</td><td>2.99</td><td></td></tr><tr><td>05/25/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>242</td><td>1.67</td><td>1.49</td><td>1.99</td><td></td></tr><tr><td>06/01/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>65</td><td>.78</td><td>.67</td><td>.79</td><td></td></tr><tr><td>06/01/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>38</td><td>.99</td><td>.99</td><td>1.00</td><td></td></tr><tr><td>06/01/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>36</td><td>2.00</td><td>1.99</td><td>2.00</td><td></td></tr><tr><td>06/01/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,085</td><td>1.43</td><td>.99</td><td>1.69</td><td></td></tr><tr><td>06/01/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>583</td><td>1.83</td><td>.99</td><td>2.50</td><td></td></tr><tr><td>06/08/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>459</td><td>.56</td><td>.42</td><td>.79</td><td></td></tr><tr><td>06/08/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>192</td><td>1.60</td><td>.99</td><td>2.50</td><td></td></tr><tr><td>06/08/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>16</td><td>1.38</td><td>1.25</td><td>1.50</td><td></td></tr><tr><td>06/08/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>64</td><td>1.99</td><td>1.99</td><td>2.00</td><td></td></tr><tr><td>06/08/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>489</td><td>1.73</td><td>.79</td><td>2.00</td><td></td></tr><tr><td>06/08/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>13</td><td>2.61</td><td>2.50</td><td>2.99</td><td></td></tr><tr><td>06/08/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>605</td><td>2.06</td><td>1.49</td><td>2.50</td><td></td></tr><tr><td>06/15/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>138</td><td>.79</td><td>.79</td><td>.79</td><td></td></tr><tr><td>06/15/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>24</td><td>1.03</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>06/15/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>68</td><td>1.10</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>06/15/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,550</td><td>1.52</td><td>.97</td><td>2.50</td><td></td></tr><tr><td>06/15/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>149</td><td>2.65</td><td>2.29</td><td>2.99</td><td></td></tr><tr><td>06/15/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>396</td><td>1.92</td><td>1.69</td><td>2.00</td><td></td></tr><tr><td>06/22/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>112</td><td>.73</td><td>.69</td><td>.79</td><td></td></tr><tr><td>06/22/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>268</td><td>1.84</td><td>.99</td><td>1.99</td><td></td></tr><tr><td>06/22/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>58</td><td>1.10</td><td>.99</td><td>1.49</td><td></td></tr><tr><td>06/22/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>3</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>06/22/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>7</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>06/22/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>685</td><td>1.86</td><td>.98</td><td>2.50</td><td></td></tr><tr><td>06/22/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>670</td><td>2.68</td><td>2.49</td><td>2.99</td><td></td></tr><tr><td>06/22/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>257</td><td>1.70</td><td>1.50</td><td>1.79</td><td></td></tr><tr><td>06/29/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>102</td><td>.79</td><td>.79</td><td>.79</td><td></td></tr><tr><td>06/29/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>79</td><td>1.46</td><td>.99</td><td>1.67</td><td></td></tr><tr><td>06/29/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>133</td><td>1.33</td><td>.99</td><td>2.99</td><td></td></tr><tr><td>06/29/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>3</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>06/29/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>671</td><td>1.80</td><td>.99</td><td>2.50</td><td></td></tr><tr><td>06/29/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>932</td><td>2.56</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>06/29/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>529</td><td>2.06</td><td>1.49</td><td>2.49</td><td></td></tr><tr><td>06/29/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>2 lb bag</td><td>20</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>07/06/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>52</td><td>.79</td><td>.79</td><td>.79</td><td></td></tr><tr><td>07/06/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>22</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>07/06/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>19</td><td>1.49</td><td>1.49</td><td>1.49</td><td></td></tr><tr><td>07/06/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>13</td><td>2.53</td><td>2.00</td><td>2.99</td><td></td></tr><tr><td>07/06/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,165</td><td>1.35</td><td>.98</td><td>1.69</td><td></td></tr><tr><td>07/06/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>9</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>07/06/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>279</td><td>1.69</td><td>1.67</td><td>1.99</td><td></td></tr><tr><td>07/13/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>236</td><td>.76</td><td>.69</td><td>.79</td><td></td></tr><tr><td>07/13/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>89</td><td>1.51</td><td>.99</td><td>1.69</td><td></td></tr><tr><td>07/13/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>33</td><td>2.20</td><td>.99</td><td>2.99</td><td></td></tr><tr><td>07/13/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>893</td><td>1.26</td><td>.98</td><td>1.68</td><td></td></tr><tr><td>07/13/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>72</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>07/13/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>656</td><td>2.18</td><td>1.50</td><td>2.50</td><td></td></tr><tr><td>07/20/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>21</td><td>.79</td><td>.79</td><td>.79</td><td></td></tr><tr><td>07/20/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>22</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>07/20/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>28</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>07/20/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>42</td><td>1.46</td><td>1.19</td><td>1.50</td><td></td></tr><tr><td>07/20/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>43</td><td>1.69</td><td>1.69</td><td>1.69</td><td></td></tr><tr><td>07/20/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>667</td><td>1.84</td><td>.99</td><td>2.50</td><td></td></tr><tr><td>07/20/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>75</td><td>2.26</td><td>2.19</td><td>2.99</td><td></td></tr><tr><td>07/20/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>188</td><td>1.78</td><td>1.50</td><td>1.99</td><td></td></tr><tr><td>07/27/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>237</td><td>.95</td><td>.79</td><td>1.00</td><td></td></tr><tr><td>07/27/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>22</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>07/27/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>26</td><td>.67</td><td>.67</td><td>.67</td><td></td></tr><tr><td>07/27/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>80</td><td>1.03</td><td>.97</td><td>1.49</td><td></td></tr><tr><td>07/27/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>16</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>07/27/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>566</td><td>1.47</td><td>.98</td><td>1.67</td><td></td></tr><tr><td>07/27/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>487</td><td>2.56</td><td>2.49</td><td>2.99</td><td></td></tr><tr><td>07/27/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>572</td><td>2.23</td><td>1.69</td><td>2.99</td><td></td></tr><tr><td>08/03/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>22</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>08/03/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>7</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>08/03/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>59</td><td>2.08</td><td>2.00</td><td>2.50</td><td></td></tr><tr><td>08/03/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>456</td><td>2.05</td><td>.99</td><td>2.50</td><td></td></tr><tr><td>08/03/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>666</td><td>2.05</td><td>1.84</td><td>2.99</td><td></td></tr><tr><td>08/03/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>596</td><td>1.88</td><td>1.29</td><td>2.99</td><td></td></tr><tr><td>08/10/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>115</td><td>.79</td><td>.50</td><td>.99</td><td></td></tr><tr><td>08/10/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>70</td><td>1.46</td><td>.99</td><td>1.67</td><td></td></tr><tr><td>08/10/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>48</td><td>1.02</td><td>.99</td><td>1.29</td><td></td></tr><tr><td>08/10/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>3</td><td>2.49</td><td>2.49</td><td>2.49</td><td></td></tr><tr><td>08/10/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,209</td><td>1.66</td><td>.98</td><td>2.50</td><td></td></tr><tr><td>08/10/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>514</td><td>1.84</td><td>1.84</td><td>1.99</td><td></td></tr><tr><td>08/10/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>192</td><td>1.56</td><td>1.29</td><td>1.69</td><td></td></tr><tr><td>08/10/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>2 lb bag</td><td>43</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>08/17/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>81</td><td>.96</td><td>.67</td><td>1.50</td><td></td></tr><tr><td>08/17/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>206</td><td>1.91</td><td>.99</td><td>2.50</td><td></td></tr><tr><td>08/17/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>48</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>08/17/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>56</td><td>2.00</td><td>1.99</td><td>2.00</td><td></td></tr><tr><td>08/17/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>857</td><td>1.61</td><td>.99</td><td>2.50</td><td></td></tr><tr><td>08/17/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>415</td><td>2.49</td><td>2.49</td><td>2.49</td><td></td></tr><tr><td>08/17/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>283</td><td>1.98</td><td>1.50</td><td>2.29</td><td></td></tr><tr><td>08/24/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>101</td><td>.82</td><td>.79</td><td>.99</td><td></td></tr><tr><td>08/24/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>108</td><td>1.53</td><td>.99</td><td>1.67</td><td></td></tr><tr><td>08/24/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>10</td><td>1.69</td><td>1.69</td><td>1.69</td><td></td></tr><tr><td>08/24/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>7</td><td>.79</td><td>.79</td><td>.79</td><td></td></tr><tr><td>08/24/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>218</td><td>2.79</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>08/24/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>14</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>08/24/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>935</td><td>1.31</td><td>.97</td><td>2.49</td><td></td></tr><tr><td>08/24/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>483</td><td>2.15</td><td>2.00</td><td>2.99</td><td></td></tr><tr><td>08/24/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>979</td><td>1.61</td><td>.99</td><td>2.49</td><td></td></tr><tr><td>08/31/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>22</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>08/31/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>10</td><td>1.69</td><td>1.69</td><td>1.69</td><td></td></tr><tr><td>08/31/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>66</td><td>.78</td><td>.69</td><td>.80</td><td></td></tr><tr><td>08/31/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>3</td><td>1.49</td><td>1.49</td><td>1.49</td><td></td></tr><tr><td>08/31/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>14</td><td>2.74</td><td>2.49</td><td>2.99</td><td></td></tr><tr><td>08/31/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,223</td><td>1.31</td><td>.99</td><td>1.69</td><td></td></tr><tr><td>08/31/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>132</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>08/31/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>487</td><td>2.25</td><td>1.50</td><td>2.50</td><td></td></tr><tr><td>09/07/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>144</td><td>.80</td><td>.79</td><td>.99</td><td></td></tr><tr><td>09/07/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>265</td><td>1.55</td><td>.99</td><td>1.99</td><td></td></tr><tr><td>09/07/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>31</td><td>1.56</td><td>1.50</td><td>1.69</td><td></td></tr><tr><td>09/07/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>6</td><td>.68</td><td>.68</td><td>.68</td><td></td></tr><tr><td>09/07/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>19</td><td>2.34</td><td>1.49</td><td>2.50</td><td></td></tr><tr><td>09/07/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>60</td><td>2.05</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>09/07/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>852</td><td>1.58</td><td>.99</td><td>1.69</td><td></td></tr><tr><td>09/07/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>72</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>09/07/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>437</td><td>1.88</td><td>1.50</td><td>2.00</td><td></td></tr><tr><td>09/14/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>56</td><td>.82</td><td>.79</td><td>.89</td><td></td></tr><tr><td>09/14/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>224</td><td>1.68</td><td>.99</td><td>1.79</td><td></td></tr><tr><td>09/14/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>6</td><td>.68</td><td>.68</td><td>.68</td><td></td></tr><tr><td>09/14/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>116</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>09/14/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>86</td><td>1.84</td><td>1.69</td><td>1.99</td><td></td></tr><tr><td>09/14/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>28</td><td>2.25</td><td>2.00</td><td>2.99</td><td></td></tr><tr><td>09/14/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,023</td><td>1.30</td><td>.99</td><td>2.00</td><td></td></tr><tr><td>09/14/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>424</td><td>2.00</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>09/14/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>1,126</td><td>1.78</td><td>1.39</td><td>2.99</td><td></td></tr><tr><td>09/21/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>149</td><td>.79</td><td>.67</td><td>.99</td><td></td></tr><tr><td>09/21/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>183</td><td>1.44</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>09/21/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>8</td><td>1.69</td><td>1.69</td><td>1.69</td><td></td></tr><tr><td>09/21/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>7</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>09/21/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>136</td><td>2.49</td><td>2.49</td><td>2.49</td><td></td></tr><tr><td>09/21/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>13</td><td>2.23</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>09/21/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>660</td><td>1.37</td><td>.77</td><td>1.69</td><td></td></tr><tr><td>09/21/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>72</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>09/21/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>610</td><td>2.16</td><td>1.69</td><td>2.50</td><td></td></tr><tr><td>09/28/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>234</td><td>.95</td><td>.79</td><td>1.00</td><td></td></tr><tr><td>09/28/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>784</td><td>1.53</td><td>.89</td><td>1.79</td><td></td></tr><tr><td>09/28/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>290</td><td>1.07</td><td>.99</td><td>1.69</td><td></td></tr><tr><td>09/28/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>17</td><td>1.08</td><td>.99</td><td>1.29</td><td></td></tr><tr><td>09/28/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>86</td><td>2.33</td><td>2.29</td><td>2.50</td><td></td></tr><tr><td>09/28/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,213</td><td>1.25</td><td>.99</td><td>1.78</td><td></td></tr><tr><td>09/28/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>164</td><td>2.88</td><td>2.50</td><td>2.99</td><td></td></tr><tr><td>09/28/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>403</td><td>2.24</td><td>1.69</td><td>2.50</td><td></td></tr><tr><td>10/05/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>81</td><td>.72</td><td>.67</td><td>.79</td><td></td></tr><tr><td>10/05/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>998</td><td>1.44</td><td>.99</td><td>1.99</td><td></td></tr><tr><td>10/05/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>28</td><td>1.69</td><td>1.69</td><td>1.69</td><td></td></tr><tr><td>10/05/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>261</td><td>.98</td><td>.69</td><td>.99</td><td></td></tr><tr><td>10/05/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>103</td><td>1.06</td><td>.99</td><td>1.49</td><td></td></tr><tr><td>10/05/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>43</td><td>1.69</td><td>1.69</td><td>1.69</td><td></td></tr><tr><td>10/05/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>28</td><td>2.00</td><td>1.99</td><td>2.00</td><td></td></tr><tr><td>10/05/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per pound</td><td>6</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>10/05/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>492</td><td>1.46</td><td>.98</td><td>1.69</td><td></td></tr><tr><td>10/05/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>500</td><td>2.58</td><td>2.49</td><td>2.99</td><td></td></tr><tr><td>10/05/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>313</td><td>1.89</td><td>1.50</td><td>2.49</td><td></td></tr><tr><td>10/12/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>58</td><td>.82</td><td>.79</td><td>.99</td><td></td></tr><tr><td>10/12/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>1,074</td><td>1.42</td><td>.99</td><td>1.79</td><td></td></tr><tr><td>10/12/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>255</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>10/12/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>43</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>10/12/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>28</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>10/12/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>970</td><td>1.25</td><td>.99</td><td>1.68</td><td></td></tr><tr><td>10/12/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>151</td><td>2.73</td><td>2.50</td><td>2.99</td><td></td></tr><tr><td>10/12/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>696</td><td>2.17</td><td>1.50</td><td>2.50</td><td></td></tr><tr><td>10/19/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>66</td><td>.78</td><td>.50</td><td>.79</td><td></td></tr><tr><td>10/19/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>197</td><td>1.70</td><td>.99</td><td>1.79</td><td></td></tr><tr><td>10/19/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>93</td><td>1.91</td><td>.99</td><td>1.99</td><td></td></tr><tr><td>10/19/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>255</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>10/19/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>7</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>10/19/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>19</td><td>1.91</td><td>1.50</td><td>1.99</td><td></td></tr><tr><td>10/19/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>21</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>10/19/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>973</td><td>1.59</td><td>.89</td><td>2.50</td><td></td></tr><tr><td>10/19/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>330</td><td>2.75</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>10/19/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>290</td><td>1.81</td><td>1.50</td><td>1.99</td><td></td></tr><tr><td>10/26/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>2</td><td>.69</td><td>.69</td><td>.69</td><td></td></tr><tr><td>10/26/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>22</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>10/26/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>7</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>10/26/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>181</td><td>.99</td><td>.69</td><td>1.00</td><td></td></tr><tr><td>10/26/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>48</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>10/26/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>187</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>10/26/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>7</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>10/26/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per pound</td><td>8</td><td>1.29</td><td>1.29</td><td>1.29</td><td></td></tr><tr><td>10/26/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,877</td><td>1.44</td><td>.99</td><td>2.00</td><td></td></tr><tr><td>10/26/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>9</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>10/26/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>664</td><td>2.06</td><td>1.49</td><td>2.50</td><td></td></tr><tr><td>11/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>162</td><td>.73</td><td>.59</td><td>1.00</td><td></td></tr><tr><td>11/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>341</td><td>1.62</td><td>.99</td><td>1.79</td><td></td></tr><tr><td>11/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>86</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>11/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>43</td><td>.69</td><td>.69</td><td>.69</td><td></td></tr><tr><td>11/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>48</td><td>2.81</td><td>1.29</td><td>2.99</td><td></td></tr><tr><td>11/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>49</td><td>2.29</td><td>2.00</td><td>2.50</td><td></td></tr><tr><td>11/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,038</td><td>1.53</td><td>.99</td><td>2.50</td><td></td></tr><tr><td>11/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>327</td><td>2.88</td><td>2.50</td><td>2.99</td><td></td></tr><tr><td>11/02/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>313</td><td>1.93</td><td>1.49</td><td>2.49</td><td></td></tr><tr><td>11/09/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>15</td><td>1.19</td><td>.69</td><td>1.50</td><td></td></tr><tr><td>11/09/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>507</td><td>1.52</td><td>.99</td><td>1.79</td><td></td></tr><tr><td>11/09/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>33</td><td>1.00</td><td>1.00</td><td>1.00</td><td></td></tr><tr><td>11/09/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>7</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>11/09/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>930</td><td>1.63</td><td>.97</td><td>1.99</td><td></td></tr><tr><td>11/09/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>990</td><td>2.63</td><td>1.74</td><td>3.49</td><td></td></tr><tr><td>11/09/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>671</td><td>2.09</td><td>1.50</td><td>2.50</td><td></td></tr><tr><td>11/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>16</td><td>.79</td><td>.79</td><td>.79</td><td></td></tr><tr><td>11/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>341</td><td>1.57</td><td>.99</td><td>2.00</td><td></td></tr><tr><td>11/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>177</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>11/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>16</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>11/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>80</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>11/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,181</td><td>1.64</td><td>.49</td><td>2.50</td><td></td></tr><tr><td>11/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>1,351</td><td>2.34</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>11/16/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>366</td><td>1.94</td><td>1.50</td><td>2.29</td><td></td></tr><tr><td>11/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>268</td><td>.76</td><td>.50</td><td>.79</td><td></td></tr><tr><td>11/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>446</td><td>1.50</td><td>.99</td><td>2.50</td><td></td></tr><tr><td>11/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>116</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>11/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>468</td><td>1.96</td><td>.98</td><td>2.50</td><td></td></tr><tr><td>11/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>72</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>11/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>210</td><td>2.11</td><td>1.50</td><td>2.50</td><td></td></tr><tr><td>11/23/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>2 lb bag</td><td>38</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>11/30/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>113</td><td>.80</td><td>.75</td><td>.99</td><td></td></tr><tr><td>11/30/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>159</td><td>1.43</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>11/30/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>86</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>11/30/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>2</td><td>.78</td><td>.78</td><td>.78</td><td></td></tr><tr><td>11/30/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>6</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>11/30/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>19</td><td>2.58</td><td>1.99</td><td>2.69</td><td></td></tr><tr><td>11/30/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>63</td><td>2.44</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>11/30/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>627</td><td>1.85</td><td>.99</td><td>2.50</td><td></td></tr><tr><td>11/30/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>495</td><td>2.42</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>11/30/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>509</td><td>1.99</td><td>1.50</td><td>2.00</td><td></td></tr><tr><td>12/07/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>116</td><td>.79</td><td>.69</td><td>1.00</td><td></td></tr><tr><td>12/07/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>641</td><td>1.57</td><td>.99</td><td>2.99</td><td></td></tr><tr><td>12/07/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>2</td><td>.50</td><td>.50</td><td>.50</td><td></td></tr><tr><td>12/07/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>8</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>12/07/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>16</td><td>2.89</td><td>2.89</td><td>2.89</td><td></td></tr><tr><td>12/07/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,046</td><td>1.43</td><td>.97</td><td>1.67</td><td></td></tr><tr><td>12/07/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>750</td><td>2.56</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>12/07/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>921</td><td>2.04</td><td>1.29</td><td>2.99</td><td></td></tr><tr><td>12/14/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>122</td><td>.72</td><td>.50</td><td>.89</td><td></td></tr><tr><td>12/14/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>92</td><td>1.38</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>12/14/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>86</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>12/14/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>43</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>12/14/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>43</td><td>1.69</td><td>1.69</td><td>1.69</td><td></td></tr><tr><td>12/14/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>99</td><td>2.47</td><td>2.00</td><td>2.50</td><td></td></tr><tr><td>12/14/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>396</td><td>1.39</td><td>.79</td><td>1.67</td><td></td></tr><tr><td>12/14/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>166</td><td>2.43</td><td>2.00</td><td>2.99</td><td></td></tr><tr><td>12/14/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>503</td><td>2.24</td><td>1.69</td><td>2.50</td><td></td></tr><tr><td>12/21/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>55</td><td>.80</td><td>.79</td><td>.89</td><td></td></tr><tr><td>12/21/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>22</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>12/21/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>48</td><td>1.29</td><td>1.29</td><td>1.29</td><td></td></tr><tr><td>12/21/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>187</td><td>1.92</td><td>1.69</td><td>1.99</td><td></td></tr><tr><td>12/21/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>192</td><td>2.97</td><td>2.50</td><td>2.99</td><td></td></tr><tr><td>12/21/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>757</td><td>1.37</td><td>.88</td><td>1.67</td><td></td></tr><tr><td>12/21/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>756</td><td>2.12</td><td>1.49</td><td>2.99</td><td></td></tr><tr><td>12/21/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>940</td><td>2.07</td><td>1.50</td><td>2.50</td><td></td></tr><tr><td>12/28/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>37</td><td>.57</td><td>.50</td><td>.89</td><td></td></tr><tr><td>12/28/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>289</td><td>1.92</td><td>.99</td><td>2.00</td><td></td></tr><tr><td>12/28/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>92</td><td>1.27</td><td>.99</td><td>1.29</td><td></td></tr><tr><td>12/28/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>36</td><td>2.79</td><td>2.50</td><td>2.99</td><td></td></tr><tr><td>12/28/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>2,308</td><td>1.23</td><td>.66</td><td>3.00</td><td></td></tr><tr><td>12/28/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>215</td><td>2.16</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>12/28/2018</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>566</td><td>1.93</td><td>1.50</td><td>2.99</td><td></td></tr><tr><td> </td></tr>
</table></body></html>
<file_sep>/raw_data/CARROTS_NORTHEAST+U.S._2017.html
<html><body><table border=1>
<tr><th>Date</th><th>Region</th><th>Class</th><th>Commodity</th><th>Variety</th><th>Organic</th><th>Environment</th><th>Unit</th><th>Number of Stores</th><th>Weighted Avg Price</th><th>Low Price</th><th>High Price</th><th>% Marked Local</th></tr><tr><td>01/06/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>205</td><td>.79</td><td>.67</td><td>.89</td><td></td></tr><tr><td>01/06/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>821</td><td>1.37</td><td>.99</td><td>1.99</td><td></td></tr><tr><td>01/06/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>3</td><td>1.49</td><td>1.49</td><td>1.49</td><td></td></tr><tr><td>01/06/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>138</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>01/06/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>205</td><td>1.93</td><td>1.79</td><td>2.69</td><td></td></tr><tr><td>01/06/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,244</td><td>1.45</td><td>.67</td><td>1.67</td><td></td></tr><tr><td>01/06/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>195</td><td>2.00</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>01/06/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>1,004</td><td>1.80</td><td>1.49</td><td>2.00</td><td></td></tr><tr><td>01/06/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>2 lb bag</td><td>58</td><td>1.98</td><td>1.98</td><td>1.98</td><td></td></tr><tr><td>01/13/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>253</td><td>1.17</td><td>.50</td><td>1.50</td><td></td></tr><tr><td>01/13/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>275</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>01/13/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>144</td><td>1.00</td><td>.99</td><td>1.19</td><td></td></tr><tr><td>01/13/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>82</td><td>2.18</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>01/13/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>34</td><td>2.43</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>01/13/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,413</td><td>1.46</td><td>.98</td><td>1.67</td><td></td></tr><tr><td>01/13/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>190</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>01/13/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>350</td><td>1.67</td><td>1.50</td><td>1.99</td><td></td></tr><tr><td>01/13/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>2 lb bag</td><td>22</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>01/20/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>1,102</td><td>.95</td><td>.67</td><td>2.99</td><td></td></tr><tr><td>01/20/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>5</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>01/20/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>6</td><td>.59</td><td>.59</td><td>.59</td><td></td></tr><tr><td>01/20/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>234</td><td>1.25</td><td>.99</td><td>1.99</td><td></td></tr><tr><td>01/20/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>226</td><td>1.87</td><td>1.79</td><td>1.99</td><td></td></tr><tr><td>01/20/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>839</td><td>1.39</td><td>.99</td><td>1.67</td><td></td></tr><tr><td>01/20/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>247</td><td>2.14</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>01/20/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>866</td><td>1.73</td><td>1.50</td><td>2.00</td><td></td></tr><tr><td>01/27/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>79</td><td>.81</td><td>.79</td><td>.88</td><td></td></tr><tr><td>01/27/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>512</td><td>1.49</td><td>1.29</td><td>1.50</td><td></td></tr><tr><td>01/27/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>6</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>01/27/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>7</td><td>.69</td><td>.69</td><td>.69</td><td></td></tr><tr><td>01/27/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>154</td><td>1.81</td><td>1.79</td><td>1.99</td><td></td></tr><tr><td>01/27/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,090</td><td>1.02</td><td>.49</td><td>1.50</td><td></td></tr><tr><td>01/27/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>1,631</td><td>2.36</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>01/27/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>455</td><td>1.88</td><td>1.50</td><td>2.29</td><td></td></tr><tr><td>02/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>95</td><td>.63</td><td>.50</td><td>.99</td><td></td></tr><tr><td>02/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>136</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>02/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>30</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>02/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>58</td><td>1.98</td><td>1.98</td><td>1.98</td><td></td></tr><tr><td>02/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>24</td><td>1.62</td><td>1.49</td><td>2.00</td><td></td></tr><tr><td>02/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,440</td><td>1.14</td><td>.49</td><td>1.69</td><td></td></tr><tr><td>02/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>1,976</td><td>2.35</td><td>1.99</td><td>2.94</td><td></td></tr><tr><td>02/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>566</td><td>1.79</td><td>1.50</td><td>2.00</td><td></td></tr><tr><td>02/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>2 lb bag</td><td>9</td><td>2.79</td><td>2.79</td><td>2.79</td><td></td></tr><tr><td>02/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>166</td><td>.70</td><td>.67</td><td>.88</td><td></td></tr><tr><td>02/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>230</td><td>1.58</td><td>1.29</td><td>1.79</td><td></td></tr><tr><td>02/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>5</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>02/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>30</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>02/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>49</td><td>1.81</td><td>1.49</td><td>2.00</td><td></td></tr><tr><td>02/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,221</td><td>1.51</td><td>1.29</td><td>1.67</td><td></td></tr><tr><td>02/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>931</td><td>2.63</td><td>1.99</td><td>2.94</td><td></td></tr><tr><td>02/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>251</td><td>1.72</td><td>1.50</td><td>2.00</td><td></td></tr><tr><td>02/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>21</td><td>.61</td><td>.40</td><td>.69</td><td></td></tr><tr><td>02/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>637</td><td>1.28</td><td>.59</td><td>2.50</td><td></td></tr><tr><td>02/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>71</td><td>1.49</td><td>1.49</td><td>1.49</td><td></td></tr><tr><td>02/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>59</td><td>.78</td><td>.69</td><td>.79</td><td></td></tr><tr><td>02/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>12</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>02/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>21</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>02/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>69</td><td>1.86</td><td>1.49</td><td>1.99</td><td></td></tr><tr><td>02/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>823</td><td>1.36</td><td>.99</td><td>1.79</td><td></td></tr><tr><td>02/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>1,168</td><td>2.11</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>02/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>484</td><td>1.75</td><td>1.50</td><td>2.29</td><td></td></tr><tr><td>02/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>223</td><td>.66</td><td>.50</td><td>.89</td><td></td></tr><tr><td>02/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>297</td><td>1.48</td><td>.99</td><td>2.50</td><td></td></tr><tr><td>02/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>6</td><td>.49</td><td>.49</td><td>.49</td><td></td></tr><tr><td>02/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>215</td><td>.99</td><td>.79</td><td>1.19</td><td></td></tr><tr><td>02/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>86</td><td>1.89</td><td>1.49</td><td>1.99</td><td></td></tr><tr><td>02/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,197</td><td>1.44</td><td>.99</td><td>1.67</td><td></td></tr><tr><td>02/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>449</td><td>2.29</td><td>1.99</td><td>2.79</td><td></td></tr><tr><td>02/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>461</td><td>1.61</td><td>.99</td><td>2.00</td><td></td></tr><tr><td>03/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>450</td><td>.97</td><td>.79</td><td>1.50</td><td></td></tr><tr><td>03/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>455</td><td>1.39</td><td>.99</td><td>1.99</td><td></td></tr><tr><td>03/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>61</td><td>1.39</td><td>1.29</td><td>1.50</td><td></td></tr><tr><td>03/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>29</td><td>.98</td><td>.98</td><td>.98</td><td></td></tr><tr><td>03/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>635</td><td>1.25</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>03/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>1,107</td><td>2.07</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>03/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>1,336</td><td>1.78</td><td>1.29</td><td>2.29</td><td></td></tr><tr><td>03/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>562</td><td>.98</td><td>.67</td><td>1.50</td><td></td></tr><tr><td>03/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>112</td><td>1.70</td><td>.98</td><td>1.99</td><td></td></tr><tr><td>03/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>31</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>03/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>180</td><td>1.10</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>03/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>264</td><td>2.11</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>03/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>41</td><td>2.64</td><td>2.50</td><td>2.99</td><td></td></tr><tr><td>03/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>2,098</td><td>1.18</td><td>.49</td><td>1.79</td><td></td></tr><tr><td>03/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>630</td><td>2.36</td><td>1.99</td><td>3.49</td><td></td></tr><tr><td>03/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>633</td><td>1.72</td><td>1.49</td><td>2.00</td><td></td></tr><tr><td>03/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>170</td><td>.67</td><td>.29</td><td>.79</td><td></td></tr><tr><td>03/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>715</td><td>1.07</td><td>.59</td><td>1.50</td><td></td></tr><tr><td>03/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>108</td><td>1.37</td><td>.99</td><td>2.00</td><td></td></tr><tr><td>03/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>22</td><td>1.79</td><td>1.79</td><td>1.79</td><td></td></tr><tr><td>03/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>60</td><td>2.26</td><td>2.00</td><td>2.50</td><td></td></tr><tr><td>03/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,631</td><td>1.33</td><td>.79</td><td>1.67</td><td></td></tr><tr><td>03/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>9</td><td>3.49</td><td>3.49</td><td>3.49</td><td></td></tr><tr><td>03/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>936</td><td>1.94</td><td>1.50</td><td>2.50</td><td></td></tr><tr><td>03/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>233</td><td>.70</td><td>.50</td><td>.79</td><td></td></tr><tr><td>03/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>63</td><td>2.19</td><td>2.19</td><td>2.19</td><td></td></tr><tr><td>03/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>166</td><td>2.31</td><td>1.47</td><td>2.49</td><td></td></tr><tr><td>03/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>41</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>03/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>82</td><td>1.21</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>03/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>21</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>03/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>31</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>03/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,595</td><td>1.41</td><td>.94</td><td>1.79</td><td></td></tr><tr><td>03/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>367</td><td>2.47</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>03/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>737</td><td>1.74</td><td>1.49</td><td>2.29</td><td></td></tr><tr><td>03/31/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>72</td><td>.75</td><td>.50</td><td>.79</td><td></td></tr><tr><td>03/31/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>204</td><td>1.63</td><td>1.50</td><td>1.69</td><td></td></tr><tr><td>03/31/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>41</td><td>1.36</td><td>.99</td><td>1.49</td><td></td></tr><tr><td>03/31/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>71</td><td>.85</td><td>.67</td><td>.99</td><td></td></tr><tr><td>03/31/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>177</td><td>1.02</td><td>.89</td><td>1.50</td><td></td></tr><tr><td>03/31/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>29</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>03/31/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>43</td><td>2.48</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>03/31/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per pound</td><td>503</td><td>.86</td><td>.86</td><td>.86</td><td></td></tr><tr><td>03/31/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,140</td><td>1.41</td><td>.99</td><td>1.67</td><td></td></tr><tr><td>03/31/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>163</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>03/31/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>1,081</td><td>1.86</td><td>.99</td><td>2.29</td><td></td></tr><tr><td>04/07/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>234</td><td>.66</td><td>.50</td><td>.99</td><td></td></tr><tr><td>04/07/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>170</td><td>1.49</td><td>1.19</td><td>1.50</td><td></td></tr><tr><td>04/07/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>150</td><td>1.53</td><td>.99</td><td>2.00</td><td></td></tr><tr><td>04/07/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>6</td><td>.49</td><td>.49</td><td>.49</td><td></td></tr><tr><td>04/07/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>580</td><td>.90</td><td>.86</td><td>1.50</td><td></td></tr><tr><td>04/07/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>41</td><td>2.14</td><td>2.00</td><td>2.49</td><td></td></tr><tr><td>04/07/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,486</td><td>1.32</td><td>.99</td><td>1.67</td><td></td></tr><tr><td>04/07/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>430</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>04/07/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>1,282</td><td>1.70</td><td>.99</td><td>2.29</td><td></td></tr><tr><td>04/14/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>20</td><td>.66</td><td>.50</td><td>.79</td><td></td></tr><tr><td>04/14/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>248</td><td>1.40</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>04/14/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>146</td><td>1.50</td><td>1.49</td><td>1.50</td><td></td></tr><tr><td>04/14/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>533</td><td>.90</td><td>.86</td><td>1.50</td><td></td></tr><tr><td>04/14/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>136</td><td>2.49</td><td>2.49</td><td>2.49</td><td></td></tr><tr><td>04/14/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>51</td><td>1.99</td><td>1.99</td><td>2.00</td><td></td></tr><tr><td>04/14/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per pound</td><td>31</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>04/14/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,349</td><td>1.24</td><td>.49</td><td>2.50</td><td></td></tr><tr><td>04/14/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>881</td><td>2.34</td><td>1.88</td><td>2.99</td><td></td></tr><tr><td>04/14/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>602</td><td>1.80</td><td>1.59</td><td>2.00</td><td></td></tr><tr><td>04/21/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>221</td><td>.72</td><td>.50</td><td>.79</td><td></td></tr><tr><td>04/21/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>312</td><td>1.49</td><td>1.29</td><td>1.50</td><td></td></tr><tr><td>04/21/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>141</td><td>1.11</td><td>.89</td><td>1.50</td><td></td></tr><tr><td>04/21/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>60</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>04/21/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,293</td><td>1.42</td><td>.75</td><td>1.67</td><td></td></tr><tr><td>04/21/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>620</td><td>2.17</td><td>1.67</td><td>2.99</td><td></td></tr><tr><td>04/21/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>1,299</td><td>1.72</td><td>1.50</td><td>2.00</td><td></td></tr><tr><td>04/28/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>102</td><td>1.28</td><td>.67</td><td>2.00</td><td></td></tr><tr><td>04/28/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>202</td><td>1.65</td><td>.99</td><td>2.48</td><td></td></tr><tr><td>04/28/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>55</td><td>1.37</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>04/28/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>22</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>04/28/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>60</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>04/28/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,532</td><td>1.15</td><td>.99</td><td>2.00</td><td></td></tr><tr><td>04/28/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>359</td><td>2.11</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>04/28/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>636</td><td>1.92</td><td>.99</td><td>2.49</td><td></td></tr><tr><td>05/05/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>331</td><td>.79</td><td>.49</td><td>1.00</td><td></td></tr><tr><td>05/05/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>171</td><td>1.44</td><td>1.00</td><td>1.50</td><td></td></tr><tr><td>05/05/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>78</td><td>1.25</td><td>1.00</td><td>1.50</td><td></td></tr><tr><td>05/05/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>331</td><td>2.42</td><td>1.99</td><td>2.79</td><td></td></tr><tr><td>05/05/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>64</td><td>2.27</td><td>2.00</td><td>2.50</td><td></td></tr><tr><td>05/05/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>601</td><td>1.38</td><td>.99</td><td>1.99</td><td></td></tr><tr><td>05/05/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>190</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>05/05/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>354</td><td>1.80</td><td>1.50</td><td>2.00</td><td></td></tr><tr><td>05/12/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>247</td><td>.76</td><td>.50</td><td>.79</td><td></td></tr><tr><td>05/12/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>20</td><td>1.48</td><td>1.47</td><td>1.50</td><td></td></tr><tr><td>05/12/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>101</td><td>1.84</td><td>1.50</td><td>1.99</td><td></td></tr><tr><td>05/12/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>47</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>05/12/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>91</td><td>2.34</td><td>2.00</td><td>2.50</td><td></td></tr><tr><td>05/12/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,738</td><td>1.36</td><td>.49</td><td>1.69</td><td></td></tr><tr><td>05/12/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>199</td><td>2.01</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>05/12/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>340</td><td>1.99</td><td>1.50</td><td>2.00</td><td></td></tr><tr><td>05/19/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>146</td><td>.70</td><td>.67</td><td>1.19</td><td></td></tr><tr><td>05/19/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>202</td><td>2.07</td><td>.99</td><td>2.49</td><td></td></tr><tr><td>05/19/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>111</td><td>1.28</td><td>1.19</td><td>1.50</td><td></td></tr><tr><td>05/19/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>21</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>05/19/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>196</td><td>2.42</td><td>2.00</td><td>2.50</td><td></td></tr><tr><td>05/19/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>2,152</td><td>1.32</td><td>.99</td><td>1.99</td><td></td></tr><tr><td>05/19/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>190</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>05/19/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>498</td><td>1.84</td><td>1.50</td><td>2.00</td><td></td></tr><tr><td>05/26/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>16</td><td>.79</td><td>.79</td><td>.79</td><td></td></tr><tr><td>05/26/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>5</td><td>1.29</td><td>1.29</td><td>1.29</td><td></td></tr><tr><td>05/26/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>54</td><td>1.44</td><td>1.19</td><td>1.50</td><td></td></tr><tr><td>05/26/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>21</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>05/26/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>81</td><td>2.47</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>05/26/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,000</td><td>1.54</td><td>1.19</td><td>1.99</td><td></td></tr><tr><td>05/26/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>500</td><td>2.50</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>05/26/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>290</td><td>1.88</td><td>1.50</td><td>2.00</td><td></td></tr><tr><td>06/02/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>222</td><td>.76</td><td>.40</td><td>.79</td><td></td></tr><tr><td>06/02/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>25</td><td>1.39</td><td>1.19</td><td>1.50</td><td></td></tr><tr><td>06/02/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>224</td><td>1.07</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>06/02/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>177</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>06/02/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>64</td><td>2.03</td><td>2.00</td><td>2.49</td><td></td></tr><tr><td>06/02/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>461</td><td>1.28</td><td>.99</td><td>1.69</td><td></td></tr><tr><td>06/02/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>503</td><td>2.41</td><td>1.88</td><td>2.99</td><td></td></tr><tr><td>06/02/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>489</td><td>1.90</td><td>1.50</td><td>2.00</td><td></td></tr><tr><td>06/09/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>138</td><td>.67</td><td>.67</td><td>.67</td><td></td></tr><tr><td>06/09/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>86</td><td>1.50</td><td>1.47</td><td>1.50</td><td></td></tr><tr><td>06/09/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>24</td><td>.75</td><td>.69</td><td>.77</td><td></td></tr><tr><td>06/09/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>9</td><td>1.49</td><td>1.49</td><td>1.49</td><td></td></tr><tr><td>06/09/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>29</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>06/09/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per pound</td><td>31</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>06/09/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>902</td><td>1.17</td><td>.88</td><td>1.79</td><td></td></tr><tr><td>06/09/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>1,072</td><td>2.16</td><td>2.00</td><td>2.50</td><td></td></tr><tr><td>06/09/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>843</td><td>1.86</td><td>1.50</td><td>2.00</td><td></td></tr><tr><td>06/16/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>142</td><td>.78</td><td>.69</td><td>.79</td><td></td></tr><tr><td>06/16/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>182</td><td>2.47</td><td>1.50</td><td>2.50</td><td></td></tr><tr><td>06/16/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>18</td><td>.77</td><td>.77</td><td>.77</td><td></td></tr><tr><td>06/16/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>77</td><td>1.19</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>06/16/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>60</td><td>2.26</td><td>2.00</td><td>2.50</td><td></td></tr><tr><td>06/16/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,426</td><td>1.46</td><td>1.00</td><td>1.50</td><td></td></tr><tr><td>06/16/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>595</td><td>2.34</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>06/16/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>1,147</td><td>1.82</td><td>1.50</td><td>2.00</td><td></td></tr><tr><td>06/23/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>325</td><td>1.02</td><td>.40</td><td>1.50</td><td></td></tr><tr><td>06/23/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>146</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>06/23/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>18</td><td>.77</td><td>.77</td><td>.77</td><td></td></tr><tr><td>06/23/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>8</td><td>1.25</td><td>1.25</td><td>1.25</td><td></td></tr><tr><td>06/23/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>12</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>06/23/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,507</td><td>1.21</td><td>.99</td><td>1.69</td><td></td></tr><tr><td>06/23/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>195</td><td>2.00</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>06/23/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>1,168</td><td>1.81</td><td>.99</td><td>2.00</td><td></td></tr><tr><td>06/30/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>35</td><td>.80</td><td>.77</td><td>.99</td><td></td></tr><tr><td>06/30/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>18</td><td>.77</td><td>.77</td><td>.77</td><td></td></tr><tr><td>06/30/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>47</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>06/30/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>47</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>06/30/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,035</td><td>1.36</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>06/30/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>702</td><td>2.33</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>06/30/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>247</td><td>1.88</td><td>1.50</td><td>2.99</td><td></td></tr><tr><td>06/30/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>2 lb bag</td><td>22</td><td>3.50</td><td>3.50</td><td>3.50</td><td></td></tr><tr><td>07/07/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>23</td><td>.79</td><td>.79</td><td>.79</td><td></td></tr><tr><td>07/07/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>224</td><td>1.90</td><td>1.50</td><td>2.00</td><td></td></tr><tr><td>07/07/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>31</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>07/07/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>23</td><td>.77</td><td>.77</td><td>.78</td><td></td></tr><tr><td>07/07/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>138</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>07/07/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>47</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>07/07/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>29</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>07/07/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>800</td><td>1.47</td><td>.98</td><td>2.99</td><td></td></tr><tr><td>07/07/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>190</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>07/07/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>425</td><td>1.90</td><td>1.50</td><td>2.00</td><td></td></tr><tr><td>07/14/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>16</td><td>.72</td><td>.66</td><td>.79</td><td></td></tr><tr><td>07/14/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>18</td><td>.77</td><td>.77</td><td>.77</td><td></td></tr><tr><td>07/14/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>154</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>07/14/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,025</td><td>1.43</td><td>.59</td><td>1.79</td><td></td></tr><tr><td>07/14/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>199</td><td>2.01</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>07/14/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>1,180</td><td>2.08</td><td>1.50</td><td>2.50</td><td></td></tr><tr><td>07/21/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>47</td><td>.75</td><td>.75</td><td>.75</td><td></td></tr><tr><td>07/21/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>138</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>07/21/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>29</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>07/21/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>24</td><td>.73</td><td>.59</td><td>.77</td><td></td></tr><tr><td>07/21/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>37</td><td>1.47</td><td>1.29</td><td>1.50</td><td></td></tr><tr><td>07/21/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>12</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>07/21/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,288</td><td>1.27</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>07/21/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>956</td><td>2.00</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>07/21/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>745</td><td>2.01</td><td>.99</td><td>2.50</td><td></td></tr><tr><td>07/28/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>5</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>07/28/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>47</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>07/28/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>54</td><td>1.02</td><td>.99</td><td>1.19</td><td></td></tr><tr><td>07/28/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>154</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>07/28/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,070</td><td>1.31</td><td>.48</td><td>1.67</td><td></td></tr><tr><td>07/28/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>3</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>07/28/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>1,084</td><td>2.03</td><td>1.50</td><td>2.50</td><td></td></tr><tr><td>08/04/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>138</td><td>.75</td><td>.75</td><td>.75</td><td></td></tr><tr><td>08/04/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>5</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>08/04/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>71</td><td>1.29</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>08/04/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>775</td><td>1.33</td><td>.88</td><td>1.69</td><td></td></tr><tr><td>08/04/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>433</td><td>2.28</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>08/04/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>489</td><td>1.61</td><td>.99</td><td>1.99</td><td></td></tr><tr><td>08/04/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>2 lb bag</td><td>118</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>08/11/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>65</td><td>.81</td><td>.79</td><td>.99</td><td></td></tr><tr><td>08/11/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>55</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>08/11/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>142</td><td>1.28</td><td>.99</td><td>1.29</td><td></td></tr><tr><td>08/11/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>154</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>08/11/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>766</td><td>1.66</td><td>1.25</td><td>2.00</td><td></td></tr><tr><td>08/11/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>190</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>08/11/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>1,203</td><td>1.89</td><td>1.50</td><td>2.50</td><td></td></tr><tr><td>08/18/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>126</td><td>.78</td><td>.67</td><td>.79</td><td></td></tr><tr><td>08/18/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>5</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>08/18/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>30</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>08/18/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>314</td><td>2.99</td><td>2.99</td><td>2.99</td><td></td></tr><tr><td>08/18/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>5</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>08/18/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>604</td><td>1.25</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>08/18/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>605</td><td>2.34</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>08/18/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>1,157</td><td>2.00</td><td>.99</td><td>2.50</td><td></td></tr><tr><td>08/25/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>256</td><td>.71</td><td>.50</td><td>.99</td><td></td></tr><tr><td>08/25/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>35</td><td>.94</td><td>.88</td><td>.99</td><td></td></tr><tr><td>08/25/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>30</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>08/25/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>85</td><td>2.07</td><td>1.99</td><td>2.49</td><td></td></tr><tr><td>08/25/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,087</td><td>.97</td><td>.49</td><td>1.50</td><td></td></tr><tr><td>08/25/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>1,124</td><td>2.10</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>08/25/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>745</td><td>2.11</td><td>1.49</td><td>2.99</td><td></td></tr><tr><td>09/01/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>60</td><td>1.07</td><td>.99</td><td>1.49</td><td></td></tr><tr><td>09/01/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>73</td><td>2.03</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>09/01/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>368</td><td>1.50</td><td>1.29</td><td>1.50</td><td></td></tr><tr><td>09/01/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>605</td><td>2.34</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>09/01/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>806</td><td>2.08</td><td>1.50</td><td>3.99</td><td></td></tr><tr><td>09/08/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>22</td><td>.81</td><td>.69</td><td>.99</td><td></td></tr><tr><td>09/08/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>185</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>09/08/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>9</td><td>1.69</td><td>1.69</td><td>1.69</td><td></td></tr><tr><td>09/08/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>49</td><td>1.72</td><td>1.29</td><td>1.99</td><td></td></tr><tr><td>09/08/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>65</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>09/08/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,260</td><td>1.44</td><td>.99</td><td>1.78</td><td></td></tr><tr><td>09/08/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>1,336</td><td>2.14</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>09/08/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>679</td><td>1.79</td><td>1.49</td><td>2.50</td><td></td></tr><tr><td>09/15/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>170</td><td>.77</td><td>.69</td><td>.79</td><td></td></tr><tr><td>09/15/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>313</td><td>1.58</td><td>1.29</td><td>1.67</td><td></td></tr><tr><td>09/15/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>14</td><td>1.44</td><td>.99</td><td>1.69</td><td></td></tr><tr><td>09/15/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>11</td><td>.56</td><td>.40</td><td>.69</td><td></td></tr><tr><td>09/15/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>97</td><td>1.42</td><td>.99</td><td>2.00</td><td></td></tr><tr><td>09/15/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>25</td><td>2.41</td><td>1.99</td><td>2.49</td><td></td></tr><tr><td>09/15/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>105</td><td>2.06</td><td>1.99</td><td>2.49</td><td></td></tr><tr><td>09/15/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,775</td><td>1.64</td><td>1.25</td><td>2.00</td><td></td></tr><tr><td>09/15/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>215</td><td>2.05</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>09/15/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>1,232</td><td>1.66</td><td>1.50</td><td>2.49</td><td></td></tr><tr><td>09/22/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>243</td><td>.78</td><td>.50</td><td>.99</td><td></td></tr><tr><td>09/22/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>203</td><td>1.38</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>09/22/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>17</td><td>1.83</td><td>1.69</td><td>1.99</td><td></td></tr><tr><td>09/22/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>6</td><td>1.29</td><td>1.29</td><td>1.29</td><td></td></tr><tr><td>09/22/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>7</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>09/22/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>37</td><td>2.50</td><td>2.49</td><td>2.50</td><td></td></tr><tr><td>09/22/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>980</td><td>1.38</td><td>.99</td><td>1.69</td><td></td></tr><tr><td>09/22/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>934</td><td>2.02</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>09/22/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>567</td><td>1.69</td><td>1.29</td><td>2.50</td><td></td></tr><tr><td>09/29/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>68</td><td>.79</td><td>.67</td><td>.99</td><td></td></tr><tr><td>09/29/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>620</td><td>1.07</td><td>.98</td><td>1.59</td><td></td></tr><tr><td>09/29/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>155</td><td>1.53</td><td>1.50</td><td>1.99</td><td></td></tr><tr><td>09/29/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>138</td><td>1.13</td><td>.99</td><td>1.29</td><td></td></tr><tr><td>09/29/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>51</td><td>1.71</td><td>1.69</td><td>1.99</td><td></td></tr><tr><td>09/29/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>27</td><td>2.49</td><td>2.49</td><td>2.49</td><td></td></tr><tr><td>09/29/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,533</td><td>1.26</td><td>.99</td><td>1.79</td><td></td></tr><tr><td>09/29/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>258</td><td>2.12</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>09/29/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>817</td><td>1.69</td><td>.99</td><td>2.00</td><td></td></tr><tr><td>09/29/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>2 lb bag</td><td>22</td><td>3.50</td><td>3.50</td><td>3.50</td><td></td></tr><tr><td>10/06/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>37</td><td>.79</td><td>.79</td><td>.79</td><td></td></tr><tr><td>10/06/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>702</td><td>1.03</td><td>.98</td><td>1.50</td><td></td></tr><tr><td>10/06/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>31</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>10/06/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>249</td><td>.98</td><td>.40</td><td>.99</td><td></td></tr><tr><td>10/06/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>67</td><td>1.57</td><td>1.49</td><td>1.79</td><td></td></tr><tr><td>10/06/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>277</td><td>2.14</td><td>1.79</td><td>2.49</td><td></td></tr><tr><td>10/06/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>22</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>10/06/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>842</td><td>1.31</td><td>.99</td><td>1.99</td><td></td></tr><tr><td>10/06/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>925</td><td>2.02</td><td>1.99</td><td>2.50</td><td></td></tr><tr><td>10/06/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>701</td><td>1.79</td><td>1.50</td><td>2.00</td><td></td></tr><tr><td>10/13/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>414</td><td>.92</td><td>.50</td><td>1.00</td><td></td></tr><tr><td>10/13/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>969</td><td>1.14</td><td>.98</td><td>1.50</td><td></td></tr><tr><td>10/13/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>45</td><td>1.76</td><td>1.29</td><td>1.99</td><td></td></tr><tr><td>10/13/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>85</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>10/13/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>880</td><td>1.44</td><td>.98</td><td>1.67</td><td></td></tr><tr><td>10/13/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>274</td><td>2.01</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>10/13/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>710</td><td>1.91</td><td>.99</td><td>2.50</td><td></td></tr><tr><td>10/20/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>229</td><td>.71</td><td>.50</td><td>.89</td><td></td></tr><tr><td>10/20/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>39</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>10/20/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>8</td><td>.79</td><td>.79</td><td>.79</td><td></td></tr><tr><td>10/20/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>12</td><td>1.29</td><td>1.29</td><td>1.29</td><td></td></tr><tr><td>10/20/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,334</td><td>1.14</td><td>.49</td><td>1.67</td><td></td></tr><tr><td>10/20/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>376</td><td>2.47</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>10/20/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>647</td><td>1.81</td><td>1.50</td><td>2.50</td><td></td></tr><tr><td>10/27/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>206</td><td>.69</td><td>.50</td><td>.99</td><td></td></tr><tr><td>10/27/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>47</td><td>.88</td><td>.88</td><td>.88</td><td></td></tr><tr><td>10/27/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>71</td><td>1.49</td><td>1.49</td><td>1.49</td><td></td></tr><tr><td>10/27/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>201</td><td>1.85</td><td>1.79</td><td>1.99</td><td></td></tr><tr><td>10/27/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>849</td><td>1.24</td><td>.98</td><td>1.50</td><td></td></tr><tr><td>10/27/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>1,214</td><td>2.19</td><td>1.89</td><td>2.99</td><td></td></tr><tr><td>10/27/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>599</td><td>1.86</td><td>1.50</td><td>2.00</td><td></td></tr><tr><td>11/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>123</td><td>.72</td><td>.69</td><td>.79</td><td></td></tr><tr><td>11/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>608</td><td>1.04</td><td>.98</td><td>1.50</td><td></td></tr><tr><td>11/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>8</td><td>.69</td><td>.69</td><td>.69</td><td></td></tr><tr><td>11/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>19</td><td>1.49</td><td>1.49</td><td>1.49</td><td></td></tr><tr><td>11/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>60</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>11/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,624</td><td>1.04</td><td>.49</td><td>1.99</td><td></td></tr><tr><td>11/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>499</td><td>2.54</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>11/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>183</td><td>1.73</td><td>.99</td><td>2.29</td><td></td></tr><tr><td>11/03/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>2 lb bag</td><td>22</td><td>3.50</td><td>3.50</td><td>3.50</td><td></td></tr><tr><td>11/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>84</td><td>.57</td><td>.50</td><td>.59</td><td></td></tr><tr><td>11/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>596</td><td>1.08</td><td>.98</td><td>1.67</td><td></td></tr><tr><td>11/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>85</td><td>1.49</td><td>1.49</td><td>1.49</td><td></td></tr><tr><td>11/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>60</td><td>2.00</td><td>2.00</td><td>2.00</td><td></td></tr><tr><td>11/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>345</td><td>.98</td><td>.88</td><td>1.50</td><td></td></tr><tr><td>11/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>578</td><td>2.41</td><td>1.99</td><td>3.49</td><td></td></tr><tr><td>11/10/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>363</td><td>1.54</td><td>1.49</td><td>1.99</td><td></td></tr><tr><td>11/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>744</td><td>1.25</td><td>.98</td><td>1.99</td><td></td></tr><tr><td>11/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>24</td><td>.70</td><td>.49</td><td>.77</td><td></td></tr><tr><td>11/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>5</td><td>1.49</td><td>1.49</td><td>1.49</td><td></td></tr><tr><td>11/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>197</td><td>2.00</td><td>1.79</td><td>2.99</td><td></td></tr><tr><td>11/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>765</td><td>1.49</td><td>.89</td><td>1.79</td><td></td></tr><tr><td>11/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>833</td><td>2.64</td><td>1.99</td><td>3.49</td><td></td></tr><tr><td>11/17/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>592</td><td>1.92</td><td>1.49</td><td>2.99</td><td></td></tr><tr><td>11/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>186</td><td>.71</td><td>.50</td><td>.77</td><td></td></tr><tr><td>11/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>2</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>11/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>30</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>11/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>5</td><td>1.49</td><td>1.49</td><td>1.49</td><td></td></tr><tr><td>11/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>22</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>11/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,093</td><td>1.29</td><td>.49</td><td>1.67</td><td></td></tr><tr><td>11/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>681</td><td>2.60</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>11/24/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>355</td><td>1.82</td><td>1.50</td><td>2.29</td><td></td></tr><tr><td>12/01/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>154</td><td>.80</td><td>.67</td><td>.89</td><td></td></tr><tr><td>12/01/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>107</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>12/01/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per bunch</td><td>5</td><td>1.49</td><td>1.49</td><td>1.49</td><td></td></tr><tr><td>12/01/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>131</td><td>2.52</td><td>2.48</td><td>2.69</td><td></td></tr><tr><td>12/01/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>935</td><td>1.24</td><td>.99</td><td>1.69</td><td></td></tr><tr><td>12/01/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>428</td><td>2.55</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>12/01/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>63</td><td>1.75</td><td>1.50</td><td>1.99</td><td></td></tr><tr><td>12/08/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>379</td><td>.89</td><td>.67</td><td>.99</td><td></td></tr><tr><td>12/08/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>242</td><td>1.53</td><td>1.49</td><td>1.59</td><td></td></tr><tr><td>12/08/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>15</td><td>1.29</td><td>1.29</td><td>1.29</td><td></td></tr><tr><td>12/08/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>68</td><td>2.21</td><td>1.99</td><td>2.69</td><td></td></tr><tr><td>12/08/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>6</td><td>2.50</td><td>2.50</td><td>2.50</td><td></td></tr><tr><td>12/08/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,478</td><td>1.05</td><td>.49</td><td>2.00</td><td></td></tr><tr><td>12/08/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>440</td><td>2.54</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>12/08/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>405</td><td>1.79</td><td>1.50</td><td>2.50</td><td></td></tr><tr><td>12/08/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>2 lb bag</td><td>17</td><td>3.99</td><td>3.99</td><td>3.99</td><td></td></tr><tr><td>12/15/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>24</td><td>.91</td><td>.89</td><td>.99</td><td></td></tr><tr><td>12/15/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>257</td><td>1.23</td><td>.99</td><td>1.50</td><td></td></tr><tr><td>12/15/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>77</td><td>1.97</td><td>1.49</td><td>2.00</td><td></td></tr><tr><td>12/15/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>1,316</td><td>1.25</td><td>.68</td><td>2.99</td><td></td></tr><tr><td>12/15/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>503</td><td>2.31</td><td>1.99</td><td>2.99</td><td></td></tr><tr><td>12/15/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>546</td><td>2.09</td><td>1.49</td><td>2.49</td><td></td></tr><tr><td>12/22/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>162</td><td>.76</td><td>.75</td><td>.99</td><td></td></tr><tr><td>12/22/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>305</td><td>2.13</td><td>1.49</td><td>2.50</td><td></td></tr><tr><td>12/22/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>30</td><td>1.50</td><td>1.50</td><td>1.50</td><td></td></tr><tr><td>12/22/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>85</td><td>1.49</td><td>1.49</td><td>1.49</td><td></td></tr><tr><td>12/22/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>per bunch</td><td>65</td><td>1.96</td><td>1.49</td><td>2.00</td><td></td></tr><tr><td>12/22/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>869</td><td>1.34</td><td>.99</td><td>2.00</td><td></td></tr><tr><td>12/22/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>868</td><td>2.23</td><td>1.69</td><td>2.99</td><td></td></tr><tr><td>12/22/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>836</td><td>1.72</td><td>1.29</td><td>2.99</td><td></td></tr><tr><td>12/29/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>1 lb bag</td><td>47</td><td>.75</td><td>.75</td><td>.75</td><td></td></tr><tr><td>12/29/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>2 lb bag</td><td>177</td><td>1.99</td><td>1.99</td><td>1.99</td><td></td></tr><tr><td>12/29/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td> </td><td> </td><td>per pound</td><td>30</td><td>.50</td><td>.50</td><td>.50</td><td></td></tr><tr><td>12/29/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>1 lb bag</td><td>138</td><td>.99</td><td>.99</td><td>.99</td><td></td></tr><tr><td>12/29/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td> </td><td>Y</td><td> </td><td>2 lb bag</td><td>21</td><td>2.69</td><td>2.69</td><td>2.69</td><td></td></tr><tr><td>12/29/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>1 lb bag</td><td>2,133</td><td>1.23</td><td>.99</td><td>2.50</td><td></td></tr><tr><td>12/29/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td> </td><td> </td><td>2 lb bag</td><td>1,272</td><td>2.15</td><td>1.84</td><td>2.99</td><td></td></tr><tr><td>12/29/2017</td><td>NORTHEAST U.S.</td><td>VEGETABLES</td><td>CARROTS</td><td>BABY PEELED</td><td>Y</td><td> </td><td>1 lb bag</td><td>1,282</td><td>1.80</td><td>1.50</td><td>2.99</td><td></td></tr><tr><td> </td></tr>
</table></body></html>
<file_sep>/scrape_week.py
import requests
import os
import time
import random
import sys
import pandas as pd
from datetime import datetime
from dateutil.relativedelta import relativedelta
def get_current_date():
today = datetime.now()
return today.month, today.day, today.year
def fetch_data(producename, regionname):
"""Given a region and produce item, fetches a year of data and MAKES A DATAFRAME OF IT.
Skips any cities/items/year combos that have already been downloaded. Slightly hardened against
timeouts,etc. from the USDA server, which is a bit flaky.
"""
month, day, year = get_current_date()
url = 'https://www.marketnews.usda.gov/mnp/fv-report-retail?repType=&run=&portal=fv&locChoose=&commodityClass=&startIndex=1&type=retail&class=ALL&commodity='+str(producename)+'®ion='+str(regionname)+'&organic=ALL&repDate='+str(month)+'%2F'+str(month)+'%2F'+str(year)+'&endDate=12%2F31%2F'+str(year)+'&compareLy=No&format=excel&rowDisplayMax=100000'
try:
r = requests.get(url, allow_redirects=True, timeout=300)
new_data = pd.read_html(r.content, header=0, parse_dates=True, index_col='Date')[0]
return new_data, True
except requests.exceptions.Timeout:
print('request timed out, trying again...')
try:
r = requests.get(url, allow_redirects=True, timeout=300)
new_data = pd.read_html(r.content, header=0, parse_dates=True, index_col='Date')[0]
return new_data, True
except requests.exceptions.Timeout:
print('request timed out again, exiting...')
sys.exit()
def load_and_clean(region, veg, dir='./concat_data/'):
filepath = dir + region + "_" + veg + "_ALL.csv"
try:
df = pd.read_csv(filepath, parse_dates=True, index_col='Date')
except FileNotFoundError:
print("No data found for {} {}, skipping")
return None, False
# Drop null rows
df.drop(df[df.index.isna() == True].index, inplace=True)
print(sum(df.index.isna() == True))
# Drop Unnamed column
df.drop(['Unnamed: 0'], axis=1, inplace=True)
return df, True
def yearsago(years, from_date=None):
if from_date is None:
from_date = datetime.now()
return from_date - relativedelta(years=years)
def update_data(regionname, producename, savedir='./concat_data/'):
"""
Performs the web scrape to grab the newest data for a given region and veggie,
and combines it with the old data for that region & veggie and returns the
combined dataframe with data +11 years ago cut off, and also OVERWRITES the backup csv of the old data
"""
new_df = fetch_data('APPLES', 'NORTHEAST+U.S.')[0]
old_df = load_and_clean('NORTHEAST+U.S.', 'APPLES')[0]
print('Old data:\n', old_df.tail(5))
print('New data:\n', new_df.head(5))
combined_df = pd.concat([old_df, new_df], ignore_index=False)
# Chop off the data more than 11 years prior 11 year data might
# still be needed for 10yr average if the dates dont line up
combined_df = combined_df[combined_df.index > yearsago(11)]
# Save combined_df
filepath = savedir + str(regionname) + '_' + str(producename) + '_ALL.csv'
combined_df.to_csv(filepath)
# Return combined_df
return combined_df
if __name__ == "__main__":
print(update_data('NORTHEAST+U.S.', 'APPLES').tail(20))
<file_sep>/README.md
### Update Mar 24: ###
See branch: `cloudStorage`
Haven't written an update in a minute but here's where we stand after the last push:
- Script works by scraping a week and reading the csv of the older data from Cloud Storage. FWIW after the first read the type of the file in cloud storage is changed from `text/csv` to `application/octet`. Don't know if this would be an issue but should be fine as long as the csv's are getting correctly updated each week. We'll know next week if the code scraped from 3/19 is in there along with the code from 3/27.
- `main.py` is now the exact same code as `test_script.py`. Changes to the production code should be documented, changed in this `main.py` in the repo, comitted, THEN copy-pasted to the GCF inline editor.
- A function `get_latest_cpi()` was added to the script that sends a simple GET request to the Federal Reserve in St. Louis's server for the latest version of the CPI data that we use to adjust for inflation. If there is a server error, the script just uses the last version of the csv that was saved (this file lives in local cloud function storage on GCP, next to `requirements.txt`, etc. and will likely stay there in production, I don't see any need to store it elsewhere)
#### Still todo: ####
- It's time to go ahead and generalize, I will scrape manually for all veggies & regions on my local machine and manually upload the csv's I get to cloud storage.
- After that the cloud function code should be changed to generalize for all veggies & regions.
- There might be a delay between when the data is collected and when it is actually published on the USDA server. For example even though the date is Friday, the server might not be updated for a while (even the next 48 hrs) which would result in us not having the most recent data if we run the scrape on Friday before the data is actually posted. If this is the case, we might want to look into changing the Pub/Sub to be in the middle of the week, so that we give the server ample time to be updated with the latest Friday data.
### Update Feb 20: ###
The script `test_script.py` was updated to scrape for new data for the current week. This data is then appended on the end of the rest of the data for that region & produce item, and the data older than 11 years back from the current date is dropped. The CSV file for the given produce item and region is overwritten with the new data, as a backup. The new data is then used for calculations and dumps a json object of the results in a file named REGION_PRODUCEITEM.json in the directory `json_data/`.
#### Still todo: ####
- Change to connect to firestore and dump the resulting json there
- Hang on to the json data from last week, just in case.
- Adjust for inflation
- Clean up the code a little bit to make it more readable
### Update Feb 21: ###
Added code to perform calculations using the inflation-adjusted prices if desired. Uses CPI data from https://fred.stlouisfed.org/series/CPIAUCNS (this data is updated monthly, might want to think about also automating a monthly scrape for the new CPI
#### Still todo: ####
- Change to connect to firestore and dump the resulting json there
- Add write/read rules to firestore (security)
- Hang on to the json data from last week, just in case.
- Optionally add a scrape for the newest CPI
- Clean up the code a little bit to make it more readable
<file_sep>/test_script.py
import os
import requests
import pandas as pd
import numpy as np
import json
from datetime import datetime
from datetime import timedelta
from dateutil.relativedelta import relativedelta
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
from google.cloud import storage
DIR = "./concat_data/"
JSON_DIR = "./json_data/"
test_regions = ['NORTHEAST+U.S.', 'SOUTHWEST+U.S.']
test_producenames = ['CARROTS', 'APPLES']
def get_current_date():
"""
Gets the current date.
"""
today = datetime.now()
return today.month, today.day, today.year
def update_data(regionname, producename, savedir='/concat_data/', test=False, bucket=None):
"""
Calls web scrape to grab the newest data for a given region and veggie,
and combines it with the old data for that region & veggie and returns the
combined dataframe with data +11 years ago cut off, and also OVERWRITES the backup csv of the old data.
Params:
regionname: The name of the region to be scraped (e.g. SOUTHWEST+U.S.)
producename: The name of the produce item to be scraped (e.g. APPLES)
savedir: relpath to save directory of the csv data. This works on cloud or on local repo.
test: If true, optionally skip scraping and just return the old csv data.
Calls:
load_and_clean()
fetch_data()
NOTE: It's recommended to make a local backup of the csv data before changing / testing this function.
Otherwise you risk overwriting data you can't get back.
"""
if test:
old_df = load_and_clean(regionname, producename)[0]
return old_df
new_df = fetch_data(producename, regionname)[0]
old_df = load_and_clean(regionname, producename, bucket=bucket)[0]
print('Old data:\n', old_df.tail(5))
print('New data:\n', new_df.head(5))
combined_df = pd.concat([old_df, new_df], ignore_index=False)
# Chop off the data more than 11 years prior 11 year data might
# still be needed for 10yr average if the dates dont line up
combined_df = combined_df[combined_df.index > yearsago(11)]
# Save combined_df
filepath = savedir + str(regionname) + '_' + str(producename) + '_ALL.csv'
if bucket != None:
filepath = 'gs://'+ bucket + filepath
else:
filepath = '.' + filepath
combined_df.to_csv(filepath)
# Return combined_df
return combined_df
def fetch_data(producename, regionname):
"""
Given a region and produce item, fetches the newest week of data and stores it in a DataFrame.
Slightly hardened against timeouts,etc. from the USDA server, which is a bit flaky.
Params:
regionname: The name of the region to be scraped (e.g. SOUTHWEST+U.S.)
producename: The name of the produce item to be scraped (e.g. APPLES)
Returns:
0: The new dataframe made from this data, or NoneType if server timedout.
1: True if the execution was successful, otherwise False.
Calls:
get_current_date()
"""
month, day, year = get_current_date()
url = 'https://www.marketnews.usda.gov/mnp/fv-report-retail?repType=&run=&portal=fv&locChoose=&commodityClass=&startIndex=1&type=retail&class=ALL&commodity='+str(producename)+'®ion='+str(regionname)+'&organic=ALL&repDate='+str(month)+'%2F'+str(day)+'%2F'+str(year)+'&endDate=12%2F31%2F'+str(year)+'&compareLy=No&format=excel&rowDisplayMax=100000'
try:
r = requests.get(url, allow_redirects=True, timeout=300)
new_data = pd.read_html(r.content, header=0, parse_dates=True, index_col='Date')[0]
print('scraped data: \n', new_data)
return new_data, True
except requests.exceptions.Timeout:
print('request timed out, trying again...')
try:
r = requests.get(url, allow_redirects=True, timeout=300)
new_data = pd.read_html(r.content, header=0, parse_dates=True, index_col='Date')[0]
return new_data, True
except requests.exceptions.Timeout:
print('request timed out again, exiting...')
return None, False
def load_and_clean(region, veg, dir='/concat_data/', bucket=None):
"""
Load a csv of old data and wrangle into the right format for processing.
The data should end up in the same format as that returned by fetch_data().
Params:
region: The name of the region to be retrieved (e.g. SOUTHWEST+U.S.)
veg: The name of the produce item to be retrieved (e.g. APPLES)
dir: Relpath to the directory where the csv's are stored.
Returns:
0: The new dataframe made from this data, or NoneType if FileNotFoundError occurs.
1: True if the data was retrieved & execution was successful, otherwise False.
"""
filepath = dir + region + "_" + veg + "_ALL.csv" # local directory
try:
if bucket != None:
filepath = 'gs://' + bucket + filepath
else:
filepath = '.' + filepath
df = pd.read_csv(filepath, parse_dates=True, index_col='Date')
except FileNotFoundError:
print("No data found for {} {}, skipping".format(region, veg))
return None, False
#Drop null rows
if sum(df.index.isna() == True) > 0:
df.drop(df[df.index.isna() == True].index, inplace=True)
# Drop Unnamed column
if 'Unnamed: 0' in df.columns:
df.drop(['Unnamed: 0'], axis=1, inplace=True)
return df, True
# Create the appropriate timedeltas
"""
Following function taken from https://stackoverflow.com/questions/765797/python-timedelta-in-years
Given the number of years ago from from_date, get the date that was exactly that many years ago
"""
def yearsago(years, from_date=None):
if from_date is None:
from_date = datetime.now()
return from_date - relativedelta(years=years)
"""
Following function modified from https://stackoverflow.com/questions/765797/python-timedelta-in-years
Given the number of months ago from from_date, get the date that was exactly that many years ago
"""
def monthsago(months, from_date=None):
if from_date is None:
from_date = datetime.now()
return from_date + relativedelta(months=(-months))
# Helper function for calculating % change
def pct_change(oldprice, newprice):
return ((newprice - oldprice)/oldprice)*100
def calc_averages(region, veg, df, adjusted=True):
"""
Calculate the averages for a given region + veggie, organic, nonorganic, and all, and save
as 3 rows in a dataframe (will change to connect to firebase as well)
Params:
region: Region to caculate for
veg: Commodity to calculate for
df: DataFrame to use for the calculations
adjusted: If true, adjust for inflation when calculating values.
Final values are reported in present-day dollars.
Returns a dictionary of the values of interest on successful execution
"""
# Get the data from today or most recent day with data
current_day = datetime.today()
orig_today = datetime(current_day.year, current_day.month, current_day.day)
today = datetime(current_day.year, current_day.month, current_day.day)
while not sum(df.index == today) > 0:
today -= timedelta(days=1)
if today != orig_today:
print("No new data for {} {}, using most recent price from {}".format(veg, region, str(today)))
today_df = df.loc[today]
price_today = np.mean(today_df['Weighted Avg Price'])
print("Price today: $" + str(round(price_today,2)))
if adjusted:
adj_price_today = np.mean(today_df['IA Avg Price'])
print("Price today (adjusted for inflation): $" + str(round(adj_price_today,2)))
# Calculate 10 yr average
df_10yr = pd.DataFrame()
asterisk = False
for i in range(10,-1,-1):
year_exists = True
date_back = yearsago(i, from_date=today)
orig_date_back = date_back
# Scoot back to the most recent date that contains data
while not sum(df.index == date_back) > 0:
date_back -= timedelta(days=1)
if orig_date_back - date_back >= timedelta(days=365):
print("No data for {} years back".format(i))
asterisk = True
year_exists = False
break
if year_exists:
df_piece = df[df.index == date_back]
df_10yr = pd.concat([df_10yr, df_piece], axis=0)
print(df_10yr.index.value_counts())
df_10yr_avg = df_10yr.groupby(df_10yr.index).mean()
if df_10yr_avg.index[0] > yearsago(10, from_date=today):
print("Data does not contain a price from 10 yrs ago for {} {}, using the earliest price point within 10 years that can find for pct change calculation".format(veg, region))
asterisk = True
price_10yr_ago = df_10yr_avg.iloc[0]['Weighted Avg Price']
final_10yr_avg = np.mean(df_10yr_avg['Weighted Avg Price'])
print(region, veg, "10 yr average: $" + str(round(final_10yr_avg, 2)))
if adjusted:
adj_price_10yr_ago = df_10yr_avg.iloc[0]['IA Avg Price']
adj_final_10yr_avg = np.mean(df_10yr_avg['IA Avg Price'])
print(region, veg, "adj 10 yr average: $" + str(round(adj_final_10yr_avg, 2)))
# Get data from closest to exactly 3 months ago as possible
date_back_3mo = monthsago(3, from_date=today)
while not sum(df.index == date_back_3mo) > 0:
date_back_3mo -= timedelta(days=1)
df_3mo = df[df.index == date_back_3mo]
print(df_3mo)
# Get data from closest to exactly 1 month ago as possible
date_back_1mo = monthsago(1, from_date=today)
while not sum(df.index == date_back_1mo) > 0:
date_back_1mo -= timedelta(days=1)
df_1mo = df[df.index == date_back_1mo]
print(df_1mo)
# Calculate 3mo and 1mo ago avg price
final_3mo_avg = np.mean(df_3mo['Weighted Avg Price'])
final_1mo_avg = np.mean(df_1mo['Weighted Avg Price'])
print(region, veg, "3 months ago: $" + str(round(final_3mo_avg, 2)))
print(region, veg, "1 months ago: $" + str(round(final_1mo_avg, 2)))
if adjusted:
adj_final_3mo_avg = np.mean(df_3mo['IA Avg Price'])
adj_final_1mo_avg = np.mean(df_1mo['IA Avg Price'])
print(region, veg, "adj 3 months ago: $" + str(round(adj_final_3mo_avg, 2)))
print(region, veg, "adj 1 months ago: $" + str(round(adj_final_1mo_avg, 2)))
# Calculate percent changes
if adjusted:
pct_change_10yr = pct_change(adj_price_10yr_ago, adj_price_today)
pct_change_3mo = pct_change(adj_final_3mo_avg, adj_price_today)
pct_change_1mo = pct_change(adj_final_1mo_avg, adj_price_today)
else:
pct_change_10yr = pct_change(price_10yr_ago, price_today)
pct_change_3mo = pct_change(final_3mo_avg, price_today)
pct_change_1mo = pct_change(final_1mo_avg, price_today)
new_cols = ['Date Added','Region', 'Commodity', '10yr_avg', '3mo_ago', '1mo_ago', 'pct_change (10yr)', 'pct_change (3mo)', 'pct_change (1mo)', 'price_today', '10_yr asterisk', 'adjusted']
if adjusted:
vals = [current_day.strftime('%Y-%m-%d'), region, veg, adj_final_10yr_avg, adj_final_3mo_avg, adj_final_1mo_avg, pct_change_10yr, pct_change_3mo, pct_change_1mo, adj_price_today, asterisk, True]
else:
vals = [current_day.strftime('%Y-%m-%d'), region, veg, adj_final_10yr_avg, adj_final_3mo_avg, adj_final_1mo_avg, pct_change_10yr, pct_change_3mo, pct_change_1mo, adj_price_today, asterisk, True]
results_dict = dict(zip(new_cols, vals))
print(results_dict)
return results_dict
def nearest_date(dates, targdate):
"""
Given a pd series of dates and a target date, returns date from the series closest to target date (and distance)
"""
for i in dates:
i = i.to_pydatetime()
nearest = min(dates, key=lambda x: abs(x - targdate))
timedelta = abs(nearest - targdate)
return nearest, timedelta
"""
Add columns to the data with the prices adjusted for inflation in terms of present-day dollars.
"""
def adjust_inflation(data, coeffs):
adjusted = data.reset_index().sort_values(by='Date')
merged_df = pd.merge_asof(adjusted, coeffs, left_on='Date', right_on='DATE')
# Normalize CPI with most recent CPI being 1.0
merged_df["IA Avg Price"] = (merged_df['Weighted Avg Price']/merged_df['CPIAUCNS'])
merged_df = merged_df.set_index('Date')
merged_df = merged_df.sort_index()
print(merged_df.info())
return merged_df
"""
Load CPI Data from a local/CloudStorage csv, scrape new CPI if needed.
Clean and adjust so everything is in present-day dollars
"""
def load_cpi_data():
get_latest_cpi()
coeffs = pd.read_csv('./CPI_DATA.csv')
coeffs['DATE'] = pd.to_datetime(coeffs['DATE'])
coeffs = coeffs.sort_values(by='DATE')
coeffs = coeffs.reset_index(drop=True)
most_recent = coeffs.iloc[-1]['CPIAUCNS']
coeffs['CPIAUCNS'] = coeffs['CPIAUCNS'].divide(most_recent)
return coeffs
def init_firestore():
project_id = 'farmlink-304820'
cred = credentials.ApplicationDefault()
firebase_admin.initialize_app(cred, {
'projectId': project_id,
})
return firestore.client()
def init_storage():
client = storage.Client()
bucket_name = 'farmlink-304820.appspot.com'
return bucket_name
"""
Scrape the latest CPI (All Urban Consumers) data from Fed St. Louis website
"""
def get_latest_cpi():
date = datetime.now().strftime('%Y-%m-%d')
url = 'https://fred.stlouisfed.org/graph/fredgraph.csv?bgcolor=%23e1e9f0&chart_type=line&drp=0&fo=open%20sans&graph_bgcolor=%23ffffff&height=450&mode=fred&recession_bars=on&txtcolor=%23444444&ts=12&tts=12&width=748&nt=0&thu=0&trc=0&show_legend=yes&show_axis_titles=yes&show_tooltip=yes&id=CPIAUCNS&scale=left&cosd=1913-01-01&coed='+date+'&line_color=%234572a7&link_values=false&line_style=solid&mark_type=none&mw=3&lw=2&ost=-99999&oet=99999&mma=0&fml=a&fq=Monthly&fam=avg&fgst=lin&fgsnd=2020-02-01&line_index=1&transformation=lin&vintage_date=2021-03-24&revision_date=2021-03-24&nd=1913-01-01'
try:
r = requests.get(url, allow_redirects=True, timeout=300)
open('./CPI_DATA.csv', 'wb').write(r.content)
return True
except requests.exceptions.Timeout:
print('request timed out, trying again...')
try:
r = requests.get(url, allow_redirects=True, timeout=300)
open('./CPI_DATA.csv', 'wb').write(r.content)
return True
except requests.exceptions.Timeout:
print('request timed out again, exiting...')
print('Error getting CPI, CPI from last run will be used')
return False
def farmlink_usda_scrape(event=None, context=None, test=False):
"""
Entry point for the cloud function. In production, the default values for event and context should be
removed as these are used by PubSub / GCP
Also in production, JSON will not be saved, we will be pushing to Firestore.
"""
coeffs = load_cpi_data()
if not test:
db = init_firestore()
bucket = init_storage()
else:
bucket = None
for r in test_regions:
data = {}
for v in test_producenames:
input_df = update_data(r, v, bucket=bucket)
adjusted_df = adjust_inflation(input_df, coeffs)
result = calc_averages(r, v, adjusted_df,adjusted=True)
data[v] = result
if test:
path = JSON_DIR + r + '.json'
with open(path, 'w') as fp:
json.dump(data, fp)
else:
try:
doc_ref = db.collection(u'farmlink_transactions').document(r)
except:
print("connecting to firestore failed for ", r)
doc_ref.set(data)
if __name__ == "__main__":
farmlink_usda_scrape(test=True)
|
1dacb7bca4bc43ecf06921f6e30f6abe47f5049c
|
[
"Markdown",
"Python",
"Text",
"HTML"
] | 7 |
Text
|
jstallings2/farmlink-pipeline
|
63695966302534ba49dc4fe4f7956faa7d432868
|
bc8ac38f93f43106826d6ac794871de48c32c148
|
refs/heads/master
|
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BlockScript : MonoBehaviour {
public bool shouldSpin;
public bool isSpinning;
public float spinSpeed = 70.0f;
void Awake () {
isSpinning = true;
}
// Use this for initialization
void Start () {
}
public void ScaleAndMove (float size) {
StartCoroutine (ScaleAndMoveI (size));
}
public IEnumerator ScaleAndMoveI (float size ) {
float mtime = 1.0f;
float stime = 1.0f;
Vector3 originalScale = transform.localScale;
// Vector3 destinationScale = new Vector3(size, size, size);
// x1.3 Scale
Vector3 destinationScale = new Vector3(transform.localScale.x * 1.333f, transform.localScale.y * 1.333f, transform.localScale.z * 1.333f);
Vector3 tar = new Vector3 (0, transform.position.y - 1.0f, 0);
float currentTime = 0.0f;
do
{
transform.localScale = Vector3.Lerp(originalScale, destinationScale, currentTime / mtime);
transform.position = Vector3.MoveTowards(transform.position, tar, currentTime / stime);
currentTime += Time.deltaTime;
// while (transform.position != tar)
// {
// float step = 1.5f * Time.deltaTime;
// transform.position = Vector3.MoveTowards(transform.position, tar, step);
// yield return null;
// // print ("DONE MOVING");
// }
yield return null;
} while (currentTime <= stime);
}
IEnumerator Spin () {
while (true) {
yield return null;
}
}
void Update () {
if (isSpinning && shouldSpin) {
transform.Rotate (Vector3.up * Time.deltaTime * spinSpeed);
} else {
print ("Can't spin!");
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BlockManager : MonoBehaviour {
public GameObject Block1;
public GameObject Block2;
public GameObject PrevBlock;
public GameObject NewBlock;
public GameObject CurBlock;
public GameObject blockFab;
public GameObject BlockGroup;
public float spinSpeed = 50.0f;
public float give = 30.0f;
private float inverseMoveTime;
public int curBlock;
Coroutine SpinBlockRoutine = null;
// Awake
void Awake () {
curBlock = 2;
}
// Start Game
public void StartGame () {
CurBlock = Block2;
StartCoroutine(MoveBlock(CurBlock));
// SpinBlockRoutine = StartCoroutine(SpinBlock(Block2));
StartCoroutine(CheckRot(Block2));
}
// Update is called once per frame
void Update () {
}
// protected IEnumerator MoveBlock(Transform block, Vector3 tar)
// {
// float sqrRemainingDistance = (transform.position - tar).sqrMagnitude;
//
// while (sqrRemainingDistance > float.Epsilon)
// {
// float step = 0.5F * Time.deltaTime;
// block.position = Vector3.MoveTowards(block.position, tar, step);
// yield return null;
// }
//
// }
protected IEnumerator MoveBlock(GameObject block)
{
float curblocksize = CurBlock.GetComponent<Renderer> ().bounds.size.y;
print ("Cur block bounds y = " + curblocksize);
Vector3 tar = new Vector3 (0, PrevBlock.transform.position.y + PrevBlock.GetComponent<Renderer>().bounds.size.y /2, 0);
// Vector3 tar = new Vector3 (0, PrevBlock.transform.position.y, 0);
// print (PrevBlock.GetComponent<Renderer>().bounds.size);
while (block.transform.position != tar)
{
float step = 1.5f * Time.deltaTime;
block.transform.position = Vector3.MoveTowards(block.transform.position, tar, step);
yield return null;
// print ("DONE MOVING");
}
}
// IEnumerator SpinBlock (GameObject block) {
//
// print ("SPIN");
//
// while (true) {
//
//
// yield return null;
//
// }
//
// }
IEnumerator CheckRot(GameObject block) {
for(;;) {
yield return new WaitForSeconds(.02f);
}
}
IEnumerator SnapBlock (GameObject block) {
// print ("SNAP SNAP");
Vector3 to = new Vector3(0, 0, 0);
block.transform.eulerAngles = Vector3.Lerp(transform.rotation.eulerAngles, to, Time.deltaTime);
yield return null;
}
IEnumerator Shift () {
while (true) {
}
}
public void NextBlock () {
curBlock += 1;
NewBlock = Instantiate(blockFab, new Vector3(0, 2.5f, 0), Quaternion.Euler(0, 0, 0));
NewBlock.name = "Block " + curBlock;
CurBlock = NewBlock;
StartCoroutine(MoveBlock(NewBlock));
// StartCoroutine(SpinBlock(NewBlock));
}
public bool CheckAlign () {
bool aligned;
float yRot = Block2.transform.localRotation.eulerAngles.y;
if (yRot >= (360.0f - give) && yRot <= 360.0f || yRot >= 0.0f && yRot <= give) {
// print ("Stopped spinning at " + Block2.transform.localRotation.eulerAngles.y);
// StopCoroutine(SpinBlockRoutine);
BlockScript cbs = CurBlock.GetComponent<BlockScript>();
cbs.isSpinning = false;
BlockScript pbs = PrevBlock.GetComponent<BlockScript>();
cbs.ScaleAndMove (1.00f);
pbs.ScaleAndMove (1.5f);
StartCoroutine(SnapBlock(CurBlock));
PrevBlock = CurBlock;
// NextBlock ();
return true;
} else {
return false;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TouchTest : MonoBehaviour {
// void Start () {
//
// }
//
// // Update is called once per frame
// void Update () {
//
//// if (Input.GetButtonDown ("Fire1")) {
//// print ("TAPPED");
//// }
//
// if (Input.GetKeyDown("space"))
// {
// // StopCoroutine(coroutine);
// print ("~click~");
//
//
// }
//
// }
//
//// IEnumerator ResetText() {
////
//// while (true) {
////
//// yield return new WaitForSeconds (1);
//// testText.text = "No Finger";
//// }
////
//// yield return null;
////
//// }
}
<file_sep># pyramid-game
A pyramid stack game influenced by Ketchapp's hit game, Stack.
test
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager: MonoBehaviour {
public static GameManager instance = null;
public BlockManager blockScript;
private int level = 1;
public bool isAligned;
void Awake () {
//Check if instance already exists
if (instance == null)
//if not, set instance to this
instance = this;
//If instance already exists and it's not this:
else if (instance != this)
//Then destroy this. This enforces our singleton pattern, meaning there can only ever be one instance of a GameManager.
Destroy(gameObject);
//Sets this to not be destroyed when reloading scene
DontDestroyOnLoad(gameObject);
isAligned = false;
blockScript = GetComponent<BlockManager>();
InitGame ();
}
void InitGame () {
blockScript.StartGame();
}
void Update () {
if (Input.GetKeyDown("space"))
{
// StopCoroutine(coroutine);
print ("~click~");
isAligned = blockScript.CheckAlign();
// blockScript.CheckAlign();
print ("Are we aligned? = " + isAligned);
}
}
}
|
c39f3da6b4b3e47b2f519beb3a58e92334a8b67e
|
[
"Markdown",
"C#"
] | 5 |
C#
|
bleecher/pyramid-game
|
8377fa6eaf17c1e6705cc8ecafe14ed6dc5b8b29
|
040d10991e4e2f3fdb068fa7d1346a355a339414
|
refs/heads/main
|
<file_sep>document.getElementById("next").addEventListener("click", function () {
document.getElementById("cplus").innerHTML = "-";
document.getElementById("expandmain").style.display = "block";
});
document.getElementById("prev").addEventListener("click", function () {
document.getElementById("cplus").innerHTML = "+";
document.getElementById("expandmain").style.display = "none";
});
document.getElementById("pplus").addEventListener("click", function () {
document.getElementById("pplus").innerHTML = "-";
document.getElementById("expandmainp").style.display = "block";
});
|
335d8e8b834f7c37feb0d3b96ba08b19e52337a3
|
[
"JavaScript"
] | 1 |
JavaScript
|
adil9516/task-vara
|
b71fa8176304fbc44fc46d77198b9b09a0e80480
|
f98d03ec66dc152032d4498dbda3d3b8b008d0bc
|
refs/heads/main
|
<file_sep># IA
_Este es el repositorio donde se subirán algunos trabajos para el curso de Inteligencia Artificial (CS261)._
## Autor ✒️
* **<NAME>** - *Documentación* - [YahairaGomez](https://github.com/YahairaGomez)
* **<NAME>** - *Documentación* - [alexa1999](https://github.com/alexa1999)
* **<NAME>** - *Documentación* - [RayzaRodriguez](https://github.com/RayzaRodriguez)
<file_sep>from tkinter import *
from copy import copy, deepcopy
from time import sleep
colors = ["red", "black"]
"""
Tablero:
0 -> colors[0] (red)
1 -> colors[1] (black) (user)
2 -> empty
"""
def utility_func(tablero):
machine = 0
user = 0
for fila in tablero:
for columna in fila:
if columna == 0:
machine += 1
elif columna == 1:
user += 1
return machine-user
def get_possible_moves(tablero, turn):
#turn = 0: AI
#turn = 1: user
#just like their numbers
moves = []
for row in range(len(tablero)):
for col in range(len(tablero[0])):
if tablero[row][col] != turn:
continue
#possible moves:
#[row+1][col+1]
#[row+1][col-1]
#[row-1][col+1]
#[row-1][col-1]
add = False
if (row+1) <= 7 and (col+1) <= 7:
if tablero[row+1][col+1] != turn:
cur_move = deepcopy(tablero)
if (cur_move[row+1][col+1] != 2): #eating
if (row+2 <= 7 and col+2 <= 7):
if (cur_move[row+2][col+2] == 2):
#position after eating: it's free
cur_move[row+2][col+2] = turn
cur_move[row+1][col+1] = 2
add = True
else:
cur_move[row+1][col+1] = turn
add = True
cur_move[row][col] = 2
if add:
moves.append(cur_move)
add = False
if (row+1) <= 7 and (col-1) >= 0:
if tablero[row+1][col-1] != turn:
cur_move = deepcopy(tablero)
if (cur_move[row+1][col-1] != turn and cur_move[row+1][col-1] != 2): #eating
if (row+2 <= 7 and col-2 >= 0):
if (cur_move[row+2][col-2] == 2):
cur_move[row+2][col-2] = turn
cur_move[row+1][col-1] = 2
add = True
else:
cur_move[row+1][col-1] = turn
add = True
cur_move[row][col] = 2
if add:
moves.append(cur_move)
add = False
if (row-1) >= 0 and (col+1) <= 7:
if tablero[row-1][col+1] != turn:
cur_move = deepcopy(tablero)
if (cur_move[row-1][col+1] != turn and cur_move[row-1][col+1] != 2):
if (row-2 >= 0 and col+2 <= 7):
if cur_move[row-2][col+2] == 2:
cur_move[row-2][col+2] = turn
cur_move[row-1][col+1] = 2
add = True
else:
cur_move[row-1][col+1] = turn
add = True
cur_move[row][col] = 2
if add:
moves.append(cur_move)
add = False
if (row-1) >= 0 and (col-1) >= 0:
if tablero[row-1][col-1] != turn:
cur_move = deepcopy(tablero)
if (cur_move[row-1][col-1] != turn and cur_move[row-1][col-1] != 2):
if (row-2 >= 7 and col-2 >= 0):
if cur_move[row-2][col+2] == 2:
cur_move[row-2][col-2] = turn
cur_move[row-1][col-1] = 2
add = True
else:
cur_move[row-1][col-1] = turn
add = True
cur_move[row][col] = 2
if add:
moves.append(cur_move)
return moves
class Node():
def __init__(self, data):
self.data = data
self.child = []
self.utility = 0
def build_tree(cur_tablero, turn, cur_node, cur_level, max_level):
if (cur_level >= max_level):
return
#getting childs
cur_level_moves = get_possible_moves(cur_tablero, turn)
for cur_move in cur_level_moves:
cur_child = Node(cur_move)
cur_child.utility = utility_func(cur_child.data)
cur_node.child.append(cur_child) #storing childs
if turn == 0:
turn = 1
else:
turn = 0
for child in cur_node.child: #recursively creating other childs
cur_node = child
build_tree(child.data, turn, cur_node, cur_level+1, max_level)
class Tree():
def __init__(self):
self.root = None
def build(self, tablero, levels):
turn = 0
self.root = Node(tablero)
cur_node = self.root
cur_tablero = tablero
cur_node.utility = utility_func(cur_node.data)
build_tree(cur_tablero, turn, cur_node, 0, levels)
def get_min_or_max(cur_father, mm): #mm = 0, min; 1, max
values = []
for child in cur_father.child:
values.append(utility_func(child.data))
if (mm == 0):
mini = min(values)
return (mini, values.index(mini))
else:
maxi = max(values)
return (maxi, values.index(maxi))
def min_max(node, level, mm):
if (level == 0) or len(node.child) == 0:
return node.utility
values = []
for child in node.child:
values.append(child.utility)
if mm == 0:
value = -9999
for i in range(len(node.child)): #for all childs
value = max(value, min_max(node.child[i], level-1, 1))
return value
else:
value = 9999
for i in range(len(node.child)):
value = min(value, min_max(node.child[i], level-1, 0))
return value
class Ficha():
def __init__(self, color):
self.color = colors[color]
def draw(self, x,y):
fcha = Canvas(bg = self.color, height = 15, width = 15)
fcha.grid(row = x, column = y)
class Tablero():
def __init__(self):
self.tablero = [ [2 for i in range(8)] for j in range(8) ]
for i in range(0,8,2):
#red thingies
self.tablero[0][i+1] = 0
self.tablero[1][i] = 0
self.tablero[2][i+1] = 0
#black thingies
self.tablero[5][i] = 1
self.tablero[6][i+1] = 1
self.tablero[7][i] = 1
self.cur_play = False
self.click_positions = [ 0,0 ] #pos_1, pos_2
def play(self, row, col, difficulty):
if not self.cur_play:
if (self.tablero[row][col] != 1):
print(str(row) + " row, col: " + str(col))
print(str(self.tablero[row][col]))
print("Not your piece!")
return
self.click_positions[0] = row
self.click_positions[1] = col
self.cur_play = True
else:
if (self.tablero[row][col] == 1):
print("Not a valid position, try again!")
self.click_positions = [ 0,0 ] #pos_1, pos_2
self.cur_play = False
return
row_1 = self.click_positions[0]
col_1 = self.click_positions[1]
st_1 = row_1 == row+1 and col_1 == col+1
st_2 = row_1 == row-1 and col_1 == col+1
st_3 = row_1 == row-1 and col_1 == col-1
st_4 = row_1 == row+1 and col_1 == col-1
final_st = st_1 or st_2 or st_3 or st_4
if not final_st:
print("Not a valid move. Try again.")
self.click_positions = [ 0,0 ] #pos_1, pos_2
self.cur_play = False
return
st_5 = True
if st_1:
print("Statement1")
if st_2:
print("Statement2")
if (st_3):
print("Statement3")
if st_4:
print("Statement4")
if self.tablero[row][col] == 0: #enemy
print("col: " + str(col_1) + ", row: " + str(row_1))
if st_3 and row_1+2 <= 7 and col_1+2 <= 7:
print("Condition1")
if self.tablero[row_1+2][col_1+2] == 2:
self.tablero[row_1][col_1] = 2
self.tablero[row][col] = 2
self.tablero[row+1][col+1] = 1
st_5 = False
elif st_4 and row_1-2 >= 0 and col_1+2 <= 7:
print("Condition2")
if self.tablero[row_1-2][col_1+2] == 2:
self.tablero[row_1][col_1] = 2
self.tablero[row][col] = 2
self.tablero[row-1][col+1] = 1
st_5 = False
elif st_1 and row_1-2 >= 0 and col_1-2 >= 0:
print("Condition3")
if self.tablero[row_1-2][col_1-2] == 2:
self.tablero[row_1][col_1] = 2
self.tablero[row][col] = 2
self.tablero[row-1][col-1] = 1
st_5 = False
elif st_2 and row_1+2 <= 7 and col_1-2 >= 0:
print("Condition4")
if self.tablero[row_1+2][col_1-2] == 2:
self.tablero[row_1][col_1] = 2
self.tablero[row][col] = 2
self.tablero[row+1][col-1] = 1
st_5 = False
elif st_5:
print("Not a valid move. Try again.")
self.click_positions = [ 0,0 ] #pos_1, pos_2
self.cur_play = False
return
else:
self.tablero[row_1][col_1] = 2
self.tablero[row][col] = 1
self.click_positions = [ 0,0 ] #pos_1, pos_2
self.cur_play = False
print("Piece moved.")
#self.draw()
print(utility_func(self.tablero))
print("Cur difficulty: " + str(difficulty))
#sleep(5)
###minmax calculations
cur_tree = Tree()
cur_tree.build(self.tablero, difficulty)
cur_value = min_max(cur_tree.root, difficulty, 0)
for child in cur_tree.root.child:
if child.utility == cur_value:
self.tablero = child.data
break
self.draw()
def draw_fichas(self):
for fila in range(8):
for columna in range(8):
if (self.tablero[fila][columna] != 2):
temp_ficha = Ficha(self.tablero[fila][columna])
temp_ficha.draw(fila, columna)
def draw(self):
#difficulty = Scale(from_=1, to=10,orient=HORIZONTAL)
#difficulty.set(1)
#difficulty.grid(row=9,column=0,columnspan=8)
for fila in range(8):
for columna in range(8):
bt = Button()
if fila % 2 == 0:
if columna % 2 == 0:
bt = Button(bg = "white")
else:
bt = Button(bg = "brown")
else:
if columna % 2 == 0:
bt = Button(bg = "brown")
else:
bt = Button(bg = "white")
bt.configure(activebackground = "gray", height = 3,
width = 3, command = lambda x = fila, y = columna:
self.play(x, y, difficulty.get()))
bt.grid(row = fila, column = columna)
print("Buttons drawed")
self.draw_fichas()
root = Tk()
tablero = Tablero()
tablero.draw()
difficulty = Scale(from_=1, to=10,orient=HORIZONTAL)
#difficulty.set(1)
difficulty.grid(row=9,column=0,columnspan=8)
root.mainloop()
|
932acd82bb2948220b4084ba04bcb1bb4f90c9c7
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
alexa1999/IA
|
d2ad998c309b1a96b5f309e2197025a1a79998bd
|
c9f5fa1cebda44665d72928341bc481825ea6c11
|
refs/heads/master
|
<file_sep>package utils;
import com.esotericsoftware.yamlbeans.YamlException;
import com.esotericsoftware.yamlbeans.YamlReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class YamlUtils {
static TestLog log = new TestLog();
public static HashMap<String, Object> getSetUp(HashMap<String, Object> aClass, String type) {
if (aClass.containsKey(type)) {
return (HashMap<String, Object>) aClass.get(type);
}
log.error(aClass + "未配置该字段");
return new HashMap<>();
}
public static ArrayList<HashMap<String, Object>> getClassNodes(String path) throws
FileNotFoundException, YamlException {
YamlReader yamlReader = new YamlReader(new FileReader(path));
Map yamlMap = (Map) yamlReader.read();
ArrayList<HashMap<String, Object>> classNodes = (ArrayList<HashMap<String, Object>>) yamlMap.get("classes");
return classNodes;
}
public static HashMap<String, Object> getClass(String path, String className) throws
FileNotFoundException, YamlException {
HashMap<String, Object> aClass = new HashMap<>();
YamlReader yamlReader = new YamlReader(new FileReader(path));
Map yamlMap = (Map) yamlReader.read();
ArrayList<HashMap<String, Object>> classNodes = (ArrayList<HashMap<String, Object>>) yamlMap.get("classes");
for (int i = 0; i < classNodes.size(); i++) {
HashMap<String, Object> classNode = classNodes.get(i);//获取class节点
aClass = (HashMap<String, Object>) classNode.get("class");
if (className.equals(aClass.get("className"))) {
return aClass;
}
log.error(className + "未配置该测试类");
}
return aClass;
}
public static void main(String[] args) {
HashMap<String, Object> aClass;
HashMap<String, Object> methodSetUp = new HashMap<>();
HashMap<String, Object> calssSetUp = new HashMap<>();
String path = "src\\main\\resources\\ClassSetUp.yaml";
try {
aClass = YamlUtils.getClass(path, "DemoTest");
methodSetUp = YamlUtils.getSetUp(aClass, "methodSetUp");
calssSetUp = YamlUtils.getSetUp(aClass, "classSetUp");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (YamlException e) {
e.printStackTrace();
}
System.out.println(calssSetUp);
System.out.println(methodSetUp);
}
}
<file_sep>log4j.rootLogger=INFO, stdout, fileout, error
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %c : %m%n
log4j.appender.fileout=org.apache.log4j.FileAppender
log4j.appender.fileout.File=f:/interfaceTestInfo.log
log4j.appender.file.DatePattern=yyyy-MM-dd'.log'
log4j.appender.fileout.layout=org.apache.log4j.PatternLayout
log4j.appender.fileout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %c : %m%n
log4j.appender.error=org.apache.log4j.DailyRollingFileAppender
log4j.appender.error.File=F:/interfaceTestError.log
log4j.appender.error.Threshold=ERROR
log4j.appender.error.DatePattern=yyyy-MM-dd'.log'
log4j.appender.error.layout=org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %c : %m%n<file_sep>package practice1;
public class Mutil {
}
<file_sep>package practice1;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class Decryption {
public static void main(String[] args) {
Random random = new Random();
List<String> passwords = new ArrayList<>();
String password = String.valueOf(random.nextInt(1000));
System.out.println("密码是:" + password);
Thread ecryptionThread = new Thread() {
@Override
public void run() {
boolean cnt = true;
while (cnt) {
String number = String.valueOf(random.nextInt(1000));
// System.out.println("本次随机密码是" + number);
if (password.equals(number)) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
cnt = false;
System.out.println("找到密码了" + number);
} else {
passwords.add(number);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
Thread daemonThread = new Thread() {
@Override
public void run() {
while (true){
if (passwords.isEmpty()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.println("密码可能是:" + passwords);
passwords.clear();
}
}
}
};
daemonThread.setPriority(Thread.MAX_PRIORITY);
ecryptionThread.setPriority(Thread.MIN_PRIORITY);
daemonThread.setDaemon(true);
ecryptionThread.start();
daemonThread.start();
}
}
<file_sep>package entity;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class Award {
public String adviserAwardMonth; //渠道奖励月份
public String adviserName; //渠道名称
public String assistMarketingEmpAmt;//协助营销员工金额
public String assistMarketingEmpManagerAmt;//协助营销经理金额
public String assistMarketingEmpManagerName;//协助营销经理名称
public String assistMarketingEmpManagerQuitDate;//协助营销经理离职日期
public String assistMarketingEmpManagerRatio;//协助营销经理比例
public String assistMarketingEmpName;//协助营销员工
public String assistMarketingEmpQuitDate;//协助营销员工离职日期
public String assistMarketingEmpRatio;//协助营销员工比例
public String assistMarketingOrgAmt;//协助营销公司金额
public String assistMarketingOrgName;//协助营销公司
public String assistMarketingOrgRatio;//协助营销公司比例
public String consultantAwardMonth;//顾问奖励月份
public String customerCooperationDate;//客户合作日期
public String customerIndustry;//客户行业
public String customerName;//客户名称
public String customerSource;//客户来源
public String customerSourceAmt;//客户来源金额
public String customerSourceName;//客户来源
public String customerSourceRatio;//客户来源比例
public String employeeCommissionMonth;//员工提成发放月份
public String entpAwardAmt;//企业奖励金额
public String entpAwardMonth;//企业奖励月份
public String entpAwardRatio;//企业奖励比例
public String entpCode;//企业编码
public String entpName;//企业名称
public String entpSettleTime;//企业入驻日期
public String entpType;//企业组织类型
public String governmentAwardAmt;//政务奖励金额
public String governmentAwardRatio;//政务奖励比例
public String grossIncomeAmt;//毛收入
public String incomeConfirmMonth;//确认收入月份
public String investorAwardAmt;//渠道奖励金额
public String investorAwardRatio;//渠道奖励比例
public String localAmt;//地方留存金额
public String localRatio;//地方留存比例
public String marketingEmpAmt;//主营销金额
public String marketingEmpManagerAmt;//主营销经理金额
public String marketingEmpManagerName;//主营销经理
public String marketingEmpManagerQuitDate;//主营销经理离职日期
public String marketingEmpManagerRatio;//主营销经理比例
public String marketingEmpName;//主营销
public String marketingEmpQuitDate;//主营销离职日期
public String marketingEmpRatio;//主营销比例
public String marketingOrgAmt;//营销公司金额
public String marketingOrgName;//营销公司
public String marketingOrgRatio;//营销公司比例
public String newAchievementYear;//新客所在年份
public String newCustomerYear;//新客所在年份
public String parkAmt;//园区留存金额
public String parkAwardAmt;//园区奖励金额
public String parkAwardMonth;//园区奖励月份
public String parkAwardRatio;//园区奖励比例
public String parkConsultantAwardAmt;//园区顾问奖励金额
public String parkConsultantAwardRatio;//园区顾问奖励比例
public String parkName;//合作园区name
public String parkRatio;//园区留存比例
public String secondPartyName;//渠道签约公司(协议签订乙方)
public String serviceOrgAmt;//企服公司金额
public String serviceOrgName;//企服公司
public String serviceOrgRatio;//企服公司比例
public String taxAmt;//税额
public String taxPaymentMonth;//税款缴纳月份
public String taxType;//税种
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<name>demo</name>
<groupId>org.example</groupId>
<artifactId>demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<allure.version>2.13.8</allure.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<aspectj.version>1.9.2</aspectj.version>
<suiteXmlFile>testng.xml</suiteXmlFile>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
<configuration>
<argLine>
-javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
</argLine>
<suiteXmlFiles>
<!--该文件位于工程根目录时,直接填写名字,其它位置要加上路径-->
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
<properties>
<property>
<name>usedefaultlisteners</name>
<value>false</value>
</property>
</properties>
</configuration>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<dependencies>
<!-- 报告生成插件 -->
<dependency>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-testng</artifactId>
<version>${allure.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-java-commons</artifactId>
<version>2.13.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.14.3</version>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>4.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans -->
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- jackson begin -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.8</version>
</dependency>
<!-- jackson end -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>com.github.sanjusoftware</groupId>
<artifactId>yamlbeans</artifactId>
<version>1.11</version>
</dependency>
<dependency>
<groupId>geronimo-spec</groupId>
<artifactId>geronimo-spec-jta</artifactId>
<version>1.0.1B-rc4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.2</version>
</dependency>
</dependencies>
</project>
<file_sep>package business;
import com.esotericsoftware.yamlbeans.YamlReader;
import utils.TestLog;
import java.io.*;
import java.util.*;
//通过解析xml文件自动生成对象库代码
public class PageObjectAutoCodeForYaml {
TestLog log = new TestLog(this.getClass());
static String path = "src/main/java/org/webdriver/patatiumappui/pageObjectConfig/UILibrary.yaml";
public static void autoCode() throws Exception {
File file = new File(path);
if (!file.exists()) {
throw new IOException("Can't find " + path);
}
YamlReader yamlReader = new YamlReader(new FileReader(file));
Object yamlObject = yamlReader.read();
Map yamlMap = (Map) yamlObject;
ArrayList<HashMap<String, Object>> pages = (ArrayList<HashMap<String, Object>>) yamlMap.get("pages");//page列表
}
public static void main(String[] args) throws Exception {
// TODO 自动生成的方法存根
}
}
<file_sep>package business;
public class Demo {
int s1;
static int s2 = 100;
public Demo(int s1) {
this.s1 = s1;
System.out.println("构造器");
}
{
System.out.println("普通代码块");
s1 = s1 + 1;
s2 = s2 + 1;
}
static {
System.out.println("静态代码块");
s2 = s2 + 1;
}
public void test1(){
System.out.println("test1");
}
public static void test2(){
System.out.println("test2");
}
public static void main(String[] args) {
String builder="sadsdsadd%s";
String th= builder.replace("%s","sasd");
System.out.println(th);
}
}
<file_sep>package utils;
import request.Request;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class TestBaseCase {
public static Map<String,Object> testCaseMap = new HashMap();
//方法描述
Request request = new Request();
public static String description;
public TestLog log = new TestLog(this.getClass().getSuperclass());
@BeforeSuite
public void setup() {
log.info("------------------判断是否需要登录---------------");
/* if (!this.isTokenEffective()) {
request.login();
}*/
/*log.info("------------------生成数据---------------");
this.GenerateData();*/
log.info("------------------开始执行测试---------------");
}
@AfterSuite
public void tearDown() {
log.info("关闭server");
log.info("-------------结束测试,并关闭退出driver及自动化 server-------------");
}
public boolean isTokenEffective() {
String result = request.get("https://api.test.ustax.tech/ums/employee/resources?systemType=1");
String code = new JsonUtils().getValue("code", result).toString();
if (code != "10000") {
return false;
}
return true;
}
private void GenerateData() {
String tels = RandomUtils.getNumber(11);
String customerName = RandomUtils.getRandomString(5);
String companyName = RandomUtils.getRandomString(5);
String sql1 = "SELECT count(1) FROM crm_customer WHERE `name`=?;";
String sql2 = "SELECT count(1) FROM ems_enterprise WHERE `names`=?;";
TestJDBC.load();
try {
while (TestJDBC.query(sql1, customerName).getRow() > 0) customerName = RandomUtils.getRandomString(5);
while (TestJDBC.query(sql2, companyName).getRow() > 0) companyName = RandomUtils.getRandomString(5);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
StringBuffer buffer = new StringBuffer();
buffer.append("classes:\n" +
" - class:\n" +
" className: \"DemoTest\"\n" +
" description: \"测试入驻企业\"\n" +
" classSetUp: {contactName: \"%s\", qq: \"%s\", tels: \"%s\", weChat: \"%s\", customerName: \"%s\", companyName: \"%s\",parkId: \"1316213784702005249\" }\n" +
" methodSetUp: {}");
String yaml = buffer.toString();
String sb = String.format(yaml, tels, tels, tels, tels, customerName, companyName);
File pageObjectFile = new File("src\\main\\resources\\DemoTest.yaml");
if (pageObjectFile.exists()) {
pageObjectFile.delete();
}
try {
FileWriter fileWriter = new FileWriter(pageObjectFile, false);
BufferedWriter output = new BufferedWriter(fileWriter);
output.write(sb);
output.flush();
output.close();
} catch (IOException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
System.out.println(sb);
TestLog log = new TestLog(this.getClass());
log.info("自动生成测试内容成功");
}
}
<file_sep>package excelEntity;
import exception.MyException;
import lombok.Data;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import utils.TestLog;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author mikezhou
* @description 从excel中获取的数据
*/
@Data
public class ExcelRequisition {
TestLog log = new TestLog(this.getClass());
Row row;
public ExcelRequisition(Row row) {
this.row = row;
this.setDescription();
this.setTestcaseName();
this.setIsExecute();
this.setType();
this.setExcelUrl();
this.setExcelBody();
this.setSaveResult();
this.setExcelCheckRule();
this.setExcelExpect();
}
private String description;
private String testcaseName;
private String isExecute;
private String type;
private ExcelUrl excelUrl;
private ExcelBody excelBody;
private SaveResult saveResult;
private ExcelCheckRule excelCheckRule;
private ExcelExpect excelExpect;
public enum anEnum {
DESCRIPTION(0),
TESTCASENAME(1),
ISEXECUTE(2),
TYPE(3),
URL(4),
BODY(5),
SAVERESULT(6),
CHECKRULE(7),
EXPECT(8);
public int row;
anEnum(int row) {
this.row = row;
}
}
public void setDescription() {
Cell cell = row.getCell(ExcelRequisition.anEnum.DESCRIPTION.row);
if (this.getCellValue(cell).equals("")) {
try {
throw new MyException("描述不能为空");
} catch (MyException e) {
e.printStackTrace();
}
log.info("描述为空");
}
this.description = this.getCellValue(cell);
}
public void setTestcaseName() {
Cell cell = row.getCell(ExcelRequisition.anEnum.TESTCASENAME.row);
this.testcaseName = this.getCellValue(cell);
}
public void setIsExecute() {
Cell cell = row.getCell(ExcelRequisition.anEnum.ISEXECUTE.row);
this.isExecute = this.getCellValue(cell);
}
public void setType() {
Cell cell = row.getCell(ExcelRequisition.anEnum.TYPE.row);
this.type = this.getCellValue(cell);
}
public void setExcelUrl() {
List<Parameter> parameterList = new ArrayList<>();
Cell cell = row.getCell(ExcelRequisition.anEnum.URL.row);
Pattern p = Pattern.compile("(\\$)([\\w]+)(.*?)(\\$)");
String path = this.getCellValue(cell);
Matcher m = p.matcher(path);
while (m.find()) {
String group = m.group();//规则中${值}中的 值 一样 的数据不
String key = null;
String className;
String args;
if (group.contains(":")) {
key = group.split(":")[0].replace("$", "");
className = group.split(":")[1].replaceAll("\\((.*?)\\)", "").replace("$", "");
args = group.split(":")[1].substring(group.split(":")[1].indexOf("(") + 1, group.split(":")[1].indexOf(")"));
} else {
className = group.replaceAll("\\((.*?)\\)\\$", "").replace("$", "");
args = group.substring(group.indexOf("(") + 1, group.indexOf(")"));
}
Parameter parameter = Parameter.builder()
.key(key)
.className(className)
.args(args)
.build();
parameterList.add(parameter);
}
ExcelUrl excelUrl = ExcelUrl.builder()
.path(path)
.parameters(parameterList)
.build();
this.excelUrl = excelUrl;
}
public void setExcelBody() {
List<Parameter> parameterList = new ArrayList<>();
Cell cell = row.getCell(anEnum.BODY.row);
Pattern p = Pattern.compile("(\\$)([\\w]+)(.*?)(\\$)");
String body = this.getCellValue(cell);
Matcher m = p.matcher(body);
while (m.find()) {
String group = m.group();//规则中${值}中的 值 一样 的数据不
String key = null;
String className;
String args;
if (group.contains(":")) {
key = group.split(":")[0].replace("$", "");
className = group.split(":")[1].replaceAll("\\((.*?)\\)", "").replace("$", "");
args = group.split(":")[1].substring(group.split(":")[1].indexOf("(") + 1, group.split(":")[1].indexOf(")"));
} else {
className = group.replaceAll("\\((.*?)\\)\\$", "").replace("$", "");
args = group.substring(group.indexOf("(") + 1, group.indexOf(")"));
}
Parameter parameter = Parameter.builder()
.key(key)
.className(className)
.args(args)
.build();
parameterList.add(parameter);
}
ExcelBody excelBody = ExcelBody.builder()
.body(body)
.parameters(parameterList)
.build();
this.excelBody = excelBody;
}
public void setSaveResult() {
List<Result> resultList = new ArrayList<>();
Cell cell = row.getCell(anEnum.SAVERESULT.row);
String ResultString = this.getCellValue(cell);
if (ResultString == "" || ResultString.isEmpty() || ResultString == null) {
this.saveResult = null;
} else {
if (ResultString.contains(",")) {
String[] saves = ResultString.split(",");
for (int i = 0; i < saves.length; i++) {
String key = saves[i].split(":")[0];
String jsonPath = saves[i].split(":")[1];
Result result = Result.builder()
.key(key)
.jsonPath(jsonPath)
.build();
resultList.add(result);
}
} else {
String key = ResultString.split(":")[0];
String jsonPath = ResultString.split(":")[1];
Result result = Result.builder()
.key(key)
.jsonPath(jsonPath)
.build();
resultList.add(result);
}
this.saveResult = SaveResult.builder().results(resultList).build();
}
}
public void setExcelCheckRule() {
List<CheckRule> checkRuleList = new ArrayList<>();
Cell cell = row.getCell(anEnum.CHECKRULE.row);
String checkRuleString = this.getCellValue(cell);
if (checkRuleString.isEmpty() || checkRuleString.equals("")) {
this.excelCheckRule = null;
} else {
if (checkRuleString.contains(",")) {
String[] checkRules = checkRuleString.split(",");
for (int i = 0; i < checkRules.length; i++) {
String type = checkRules[i].split(":")[0];
String jsonPath = null;
if (type == CheckRule.VALUE) {
jsonPath = checkRules[i].split(":")[1];
}
checkRuleList.add(CheckRule.builder().type(type).JsonPath(jsonPath).build());
}
} else {
String type = checkRuleString.split(":")[0];
String jsonPath = null;
if (type == CheckRule.VALUE) {
jsonPath = checkRuleString.split(":")[1];
}
checkRuleList.add(CheckRule.builder().type(type).JsonPath(jsonPath).build());
}
this.excelCheckRule = ExcelCheckRule.builder().checkRuleList(checkRuleList).build();
}
}
public void setExcelExpect() {
List<Expect> expectList = new ArrayList<>();
Cell cell = row.getCell(anEnum.EXPECT.row);
String expectString = this.getCellValue(cell);
if (expectString.equals("") || expectString.isEmpty()) {
this.excelExpect = null;
} else {
if (expectString.contains("&&")) {
String[] expects = expectString.split("&&");
for (int i = 0; i < expects.length; i++) {
String value = expects[i];
expectList.add(Expect.builder().value(value).build());
}
} else {
String value = expectString;
expectList.add(Expect.builder().value(value).build());
}
this.excelExpect = ExcelExpect.builder().expectList(expectList).build();
}
}
public String getCellValue(Cell cell) {
String cellValue = "";
DataFormatter formatter = new DataFormatter();
if (cell != null) {
switch (cell.getCellTypeEnum()) {
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
cellValue = formatter.formatCellValue(cell);
} else {
double value = cell.getNumericCellValue();
int intValue = (int) value;
cellValue = value - intValue == 0 ?
String.valueOf(intValue) : String.valueOf(value);
}
break;
case STRING:
cellValue = cell.getStringCellValue().replaceAll("\n", "");
break;
case BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case FORMULA:
cellValue = String.valueOf(cell.getCellFormula());
break;
case _NONE:
cellValue = "";
break;
case BLANK:
cellValue = "";
break;
case ERROR:
cellValue = "";
break;
default:
cellValue = cell.toString().trim();
break;
}
}
return cellValue.trim();
}
}
<file_sep>package practice1;
public class TestThread4 {
public static void main(String[] args) {
Hero3 gareen = new Hero3();
gareen.name = "盖伦";
gareen.hp = 616;
gareen.damage = 1;
Hero3 teemo = new Hero3();
teemo.name = "提莫";
teemo.hp = 300;
teemo.damage = 1;
Hero3 bh = new Hero3();
bh.name = "赏金猎人";
bh.hp = 500;
bh.damage = 1;
Hero3 leesin = new Hero3();
leesin.name = "盲僧";
leesin.hp = 455;
leesin.damage = 1;
Thread thread1 = new Thread() {
@Override
public void run() {
while (!teemo.isDead()) {
gareen.attackHero(teemo);
}
}
};
thread1.start();
new Thread(() -> {
while (!leesin.isDead()) {
Thread.yield();
bh.attackHero(leesin);
}
}).start();
}
}
<file_sep>package controller;
import com.alibaba.fastjson.JSONObject;
import com.jayway.jsonpath.JsonPath;
import entity.Response;
import excelEntity.*;
import exception.MyException;
import hook.Reflect;
import org.testng.Assert;
import utils.JsonUtils;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import static excelEntity.CheckRule.*;
public class Assembly {
public static List<ActualAssert> setAllAssertion(ExcelCheckRule excelCheckRule, ExcelExpect excelExpect, Response response) {
if (null == excelCheckRule) {
return null;
}
List<CheckRule> checkRuleList = excelCheckRule.getCheckRuleList();
List<Expect> excelExpectList = excelExpect.getExpectList();
if (checkRuleList.size() != excelExpectList.size()) {
try {
throw new MyException("校验规则数量与预期数量不匹配:" + "校验:" + checkRuleList.size() + "预期参数:" + excelExpectList.size());
} catch (MyException e) {
e.printStackTrace();
}
}
List<ActualAssert> actualAssertList = new ArrayList<>();
for (int i = 0; i < checkRuleList.size(); i++) {
ActualAssert actualAssert = Assembly.setActualAssert(checkRuleList.get(i), excelExpectList.get(i), response);
actualAssertList.add(actualAssert);
}
return actualAssertList;
}
public static ActualAssert setActualAssert(CheckRule checkRule, Expect except, Response response) {
Object actulResult;
Object expectResult;
switch (checkRule.getType()) {
case CheckRule.ALL:
actulResult = response.getJsonResponse().replaceAll("\n", "");
expectResult = except.getValue();
break;
case CODE:
actulResult = response.getCode();
expectResult = except.getValue();
break;
case JSON:
JSONObject actualJson = JSONObject.parseObject(response.getJsonResponse());
actulResult = JsonUtils.getJsonKey(null, actualJson);
JSONObject actualJson1 = JSONObject.parseObject(except.getValue());
expectResult = JsonUtils.getJsonKey(null, actualJson1);
break;
case VALUE:
actulResult = JsonPath.read(response.getJsonResponse(), checkRule.getJsonPath());
expectResult = JsonPath.read(except.getValue(), checkRule.getJsonPath());
break;
default:
actulResult = response.getCode();
expectResult = 10000;
break;
}
return ActualAssert.builder().actulResult(actulResult).expectResult(expectResult).build();
}
public static String replace(String MethodName, Object... value) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
String replacement = Reflect.replace(MethodName, value);
return replacement;
}
/**
* 获取响应
*/
public static Response setResponse(String rerponse) {
String code = JsonPath.read(rerponse, "$.code").toString();
Object data = JsonPath.read(rerponse, "$.data");
String error = JsonPath.read(rerponse, "$.error");
String msg = JsonPath.read(rerponse, "$.msg");
boolean succeed = JsonPath.read(rerponse, "$.succeed");
Response response = Response.builder()
.code(code)
.data(data)
.error(error)
.msg(msg)
.succeed(succeed)
.jsonResponse(rerponse)
.build();
return response;
}
}
<file_sep>package excelEntity;
import lombok.Builder;
import lombok.Data;
import java.util.List;
@Data
@Builder
public class ExcelExpect {
List<Expect> expectList;
}
<file_sep>import com.jayway.jsonpath.JsonPath;
import controller.Assembly;
import com.esotericsoftware.yamlbeans.YamlException;
import entity.Response;
import excelEntity.*;
import entity.Requisition;
import io.qameta.allure.Epic;
import io.qameta.allure.Feature;
import io.qameta.allure.Severity;
import io.qameta.allure.Story;
import request.Request;
import org.apache.poi.ss.usermodel.Sheet;
import org.testng.Assert;
import org.testng.annotations.*;
import utils.ExcelUtils;
import utils.TestBaseCase;
import utils.YamlUtils;
import java.io.*;
import java.util.*;
import static io.qameta.allure.SeverityLevel.TRIVIAL;
public class DemoTest extends TestBaseCase {
String className = this.getClass().getName();
HashMap<String, Object> aClass = new HashMap<>();
@BeforeClass
public void beforeClass() {
String path = "src\\main\\resources\\" + className + ".yaml";
try {
aClass = YamlUtils.getClass(path, className);
testCaseMap.putAll(YamlUtils.getSetUp(aClass, "classSetUp"));
} catch (FileNotFoundException | YamlException e) {
e.printStackTrace();
}
System.out.println("beforeClass完成");
}
@BeforeMethod
public void beforeMethod() {
try {
testCaseMap.putAll(YamlUtils.getSetUp(aClass, "methodSetUp"));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("beforeMethod完成");
}
@Test(groups = "第一组", dataProvider = "data")
public void test(ExcelRequisition excelRequisition) {
System.out.println("开始测试" + excelRequisition.getDescription());
Requisition requisition = new Requisition(excelRequisition);
SaveResult saveResult = excelRequisition.getSaveResult();
//发起请求
Request request = new Request();
String result = request.sendRequest(requisition.getType(), requisition.getUrl(), requisition.getBody());
Response response = Assembly.setResponse(result);
List<ActualAssert> actualAssertList = Assembly.setAllAssertion(excelRequisition.getExcelCheckRule(), excelRequisition.getExcelExpect(), response);
//校验
if (null == excelRequisition.getExcelCheckRule()) {
Assert.assertEquals(response.getCode(), "10000", "默认校验code不通过:" +requisition+ response.getJsonResponse()+"\n");
} else {
for (ActualAssert a : actualAssertList
) {
Assert.assertEquals(a.getActulResult().toString(), a.getExpectResult().toString(),requisition+ response.getJsonResponse()+"\n");
}
}
//保存需保存响应
if (null == saveResult) {
} else {
for (Result r : saveResult.getResults()
) {
testCaseMap.put(r.getKey(), JsonPath.read(response.getJsonResponse(), r.getJsonPath()));
}
}
}
@Test(groups = "第二组")
@Epic("输入点啥")
@Story("Story啊")
@Feature("啥啊")
@Severity(TRIVIAL)
public void test2() {
System.out.println("test2");
}
@DataProvider(name = "data")
public Iterator<Object[]> dataProvider() {
String path = "F:\\UITest\\新格式.xlsx";
ExcelUtils utils = new ExcelUtils(path);
Sheet sheet = utils.getSheet();
List<Object> item = new ArrayList<>();
List<Object[]> testCase = new ArrayList<>();
utils.getSheetData();
for (int i = 1; i <= sheet.getLastRowNum() + 1; i++) {
System.out.println("开始初始化数据:" + i);
if (null == sheet.getRow(i)) {
continue;
}
ExcelRequisition excelRequisition = new ExcelRequisition(sheet.getRow(i));
if (excelRequisition.getIsExecute().equals("false")) {
continue;
}
item.add(excelRequisition);
}
for (Object u : item) {
//做一个形式转换
testCase.add(new Object[]{u});
}
return testCase.iterator();
}
@AfterMethod
public void afterMethod() {
System.out.println("afterMethod完成");
}
}
<file_sep>package excelEntity;
import lombok.Builder;
import lombok.Data;
import java.util.List;
@Data
@Builder
public class ExcelBody {
String body;
List<Parameter> parameters;
}
<file_sep>package business;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import entity.Filter;
import exception.MyException;
import request.Request;
import org.apache.poi.ss.usermodel.Sheet;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import utils.MyAssert;
import utils.ExcelUtils;
import utils.PropertiesUtils;
import utils.TestLog;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Compare {
ExcelUtils excel;
TestLog logger = new TestLog(this.getClass());
static String aParkName = "";
@DataProvider(name = "dataProvider"/*, parallel = true*/)
public Object[][] DataProvider() {
String excelPath = new PropertiesUtils().getProperties("excelPath");
excel = new ExcelUtils(excelPath);
excel.getSheetData();
List<Map<String, String>> list = excel.getMapData();
Sheet sheet = excel.getSheet();
int rowNum = sheet.getLastRowNum();
Object[][] data = new Object[rowNum][0];
for (int i = 0; i < list.size(); i++) {
data[i] = new Object[]{list.get(i)};
}
/* Request request = new Request();
request.login();
*/
//读取每一行
/* for (int i = 0; i < rowNum; i++) {
data[i] = new Object[]{sheet.getRow(i)};
}*/
return data;
}
@Test(dataProvider = "dataProvider"/*, threadPoolSize = 5*/)
public void compare(HashMap<String, String> expectedAward) {
Filter filter = this.setfilterConditon(expectedAward);
this.setEntpId(filter);
List<JSONObject> parkAward = this.getParkAwardReal(filter);
MyAssert.begin();
logger.info("预期" + expectedAward);
logger.info("实际" + parkAward);
//园区奖励结算
this.assertParkAward(expectedAward, parkAward, filter);
//员工、企业、渠道、产业顾问校验
//this.assertFourAward(expectedAward, filter);
MyAssert.end();
}
public static Double formatDouble(String value, int ratio) {
if (value == null) {
return 0.00;
} else if (value.isEmpty()) {
return 0.00;
}
DecimalFormat df = new DecimalFormat("#.00");
df.setRoundingMode(RoundingMode.FLOOR);
return Double.valueOf(df.format(Double.valueOf(value) * ratio));
// return String.format("%.2f", Double.valueOf(o) * ratio);
}
public Filter setfilterConditon(HashMap<String, String> expectedAward) {
Double taxAmt = Double.valueOf(expectedAward.get("完税额"));
Filter filter = Filter.builder()
.entpName(expectedAward.get("企业"))
.taxMonth(expectedAward.get("税款缴纳月"))
.taxTypeName(expectedAward.get("奖励税种"))
.parkAwardAmt(expectedAward.get("园区应返税金额"))
.entpCode(expectedAward.get("档案编号"))
.parkName(expectedAward.get("入驻园区"))
.taxAmt(String.format("%.2f", taxAmt)).build();
filter.setTaxTypeId();
// this.setEntpId(filter);
return filter;
}
public void setEntpId(Filter filter) {
HashMap<String, String> allEntp = null;
if (!aParkName.equals(filter.getParkName())) {
allEntp = new Request().getAllEntpMap(filter.getParkName());
aParkName = filter.getParkName();
}
if (allEntp.containsKey(filter.getEntpCode())) {
filter.setEntpId(allEntp.get(filter.getEntpCode()));
} else {
JSONArray result = JSON.parseObject(new Request().getEntpId(filter.getEntpCode())).getJSONObject("data").getJSONArray("records");
if (result.size() != 0) {
String id = result.getJSONObject(0).getString("id");
if (null != id) {
filter.setEntpId(id);
} else {
try {
throw new MyException(filter + filter.getEntpCode() + "企业不存在");
} catch (MyException e) {
logger.error("ERROR:" + filter + "\"" + "企业不存在");
e.printStackTrace();
}
}
} else {
logger.error("ERROR:" + filter + "\"" + "结果为空");
}
}
}
public JSONObject getEmpReal(String empName, Filter filter) {
Request request = new Request();
String result = request.getEmpBonus(null, filter.getEntpId(), filter.getTaxType(), this.dateFormate(filter.getTaxMonth()), empName);
List records = JSON.parseObject(result).getJSONObject("data").getJSONArray("records");
if (!records.isEmpty()) {
for (Object s : records
) {
String RealTaxAmt = JSON.parseObject(s.toString()).get("taxAmt").toString();
if (RealTaxAmt.equals(filter.getTaxAmt())) {
return JSON.parseObject(s.toString());
}
}
}
return null;
}
public JSONObject getEntpReal(Filter filter) {
Request request = new Request();
String result = request.getEntpBonus(null, filter.getEntpId(), filter.getTaxType(), this.dateFormate(filter.getTaxMonth()));
List records = JSON.parseObject(result).getJSONObject("data").getJSONArray("records");
if (!records.isEmpty()) {
for (Object s : records
) {
String RealTaxAmt = JSON.parseObject(s.toString()).get("taxAmt").toString();
if (RealTaxAmt.equals(filter.getTaxAmt())) {
return JSON.parseObject(s.toString());
}
}
}
return null;
}
public JSONObject getAdviseReal(Filter filter) {
Request request = new Request();
String result = request.getAdviseBonus(null, filter.getEntpId(), filter.getTaxType(), this.dateFormate(filter.getTaxMonth()));
List records = JSON.parseObject(result).getJSONObject("data").getJSONArray("records");
if (!records.isEmpty()) {
for (Object s : records
) {
String RealTaxAmt = JSON.parseObject(s.toString()).get("taxAmt").toString();
if (RealTaxAmt.equals(filter.getTaxAmt())) {
return JSON.parseObject(s.toString());
}
}
}
return null;
}
public JSONObject getConsultantReal(Filter filter) {
Request request = new Request();
String result = request.getConsultantBonus(null, filter.getEntpId(), filter.getTaxType(), this.dateFormate(filter.getTaxMonth()));
List records = JSON.parseObject(result).getJSONObject("data").getJSONArray("records");
if (!records.isEmpty()) {
for (Object s : records
) {
String RealTaxAmt = JSON.parseObject(s.toString()).get("taxAmt").toString();
if (RealTaxAmt.equals(filter.getTaxAmt())) {
return JSON.parseObject(s.toString());
}
}
}
return null;
}
public List<JSONObject> getParkAwardReal(Filter filter) {
Request request = new Request();
String result = request.getParkAward(filter.getEntpId(), filter.getTaxType(), this.dateFormate(filter.getTaxMonth()));
if (null == JSON.parseObject(result).getJSONObject("data")) {
logger.error("ERROR:" + filter.getEntpName() + filter.getTaxType() + filter.getTaxMonth() + "返回结果为空");
System.out.println("错误日志" + result);
Assert.assertFalse(null == JSON.parseObject(result).getJSONObject("data"), filter + "返回结果为空");
}
List records = JSON.parseObject(result).getJSONObject("data").getJSONArray("records");
// JSONObject parkAward = null;
List<JSONObject> parkAwards = new ArrayList<>();
if (records.isEmpty()) {
logger.error("ERROR:" + filter.getEntpName() + filter.getTaxType() + filter.getTaxMonth() + "数据不存在");
Assert.assertFalse(records.isEmpty(), filter + "数据不存在");
} else {
for (Object s : records
) {
String realTaxAmt = JSON.parseObject(s.toString()).get("taxAmt").toString();
if (realTaxAmt.equals(filter.getTaxAmt())) {
// parkAward = JSON.parseObject(s.toString());
parkAwards.add(JSON.parseObject(s.toString()));
}
}
}
return parkAwards;
}
public String dateFormate(String month) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
DateFormat Format = new SimpleDateFormat("yyyy-MM-dd");
String taxMonth = null;
try {
taxMonth = dateFormat.format(Format.parse(month));
} catch (ParseException e) {
e.printStackTrace();
}
return taxMonth;
}
/*public void getExpected() {
excel = new ExcelUtils("F:\\数据\\山东昌乐.xlsx", "Sheet1");
}*/
/*public void assertFourAward(HashMap<String, String> expectedAward, Filter filter) {
if (!expectedAward.get("招商人员").isEmpty() && expectedAward.get("招商人员") != "0") {
JSONObject empRealAward = this.getEmpReal(expectedAward.get("招商人员"), filter);
MyAssert.verifyEquals(
formatDouble(empRealAward.getString("bonusAmt"), 1),
formatDouble(expectedAward.get("招商人员提成金额"), 1),
"招商人员提成金额");
}
if (!expectedAward.get("招商科长").isEmpty() && expectedAward.get("招商科长") != "0") {
JSONObject empRealAward = this.getEmpReal(expectedAward.get("招商科长"), filter);
MyAssert.verifyEquals(
formatDouble(empRealAward.getString("bonusAmt"), 1),
formatDouble(expectedAward.get("招商科长提成金额"), 1),
"招商科长提成金额");
}
if (!expectedAward.get("关联招商人员").isEmpty() && expectedAward.get("关联招商人员") != "0") {
JSONObject empRealAward = this.getEmpReal(expectedAward.get("关联招商人员"), filter);
MyAssert.verifyEquals(
formatDouble(empRealAward.getString("bonusAmt"), 1),
formatDouble(expectedAward.get("关联招商人员提成金额"), 1),
"关联招商人员提成金额");
}
if (!expectedAward.get("关联招商科长").isEmpty() && expectedAward.get("关联招商科长") != "0") {
JSONObject empRealAward = this.getEmpReal(expectedAward.get("关联招商科长"), filter);
MyAssert.verifyEquals(
formatDouble(empRealAward.getString("bonusAmt"), 1),
formatDouble(expectedAward.get("关联招商科长提成金额"), 1),
"关联招商科长提成金额");
}
if (!expectedAward.get("企业返税金额").isEmpty() && expectedAward.get("企业返税金额") != "0.00" && expectedAward.get("企业返税金额") != "-") {
JSONObject entpRealAward = this.getEntpReal(filter);
MyAssert.verifyEquals(
formatDouble(entpRealAward.getString("rewardAmt"), 1),
formatDouble(expectedAward.get("企业返税金额"), 1),
"企业返税金额");
}
//String award = expectedAward.get("渠道奖励比例");
if (!expectedAward.get("渠道奖励金额").isEmpty() && expectedAward.get("渠道奖励金额") != "0.00" && expectedAward.get("渠道奖励金额") != "-") {
JSONObject adviseRealAward = this.getAdviseReal(filter);
MyAssert.verifyEquals(formatDouble(adviseRealAward.getString("rewardAmt"), 1),
formatDouble(expectedAward.get("渠道奖励金额"), 1),
"渠道奖励金额");
}
if (!expectedAward.get("顾问奖励金额").isEmpty() && expectedAward.get("顾问奖励金额") != "0.00" && expectedAward.get("顾问奖励金额") != "-") {
JSONObject consultantRealAward = this.getConsultantReal(filter);
MyAssert.verifyEquals(
formatDouble(consultantRealAward.getString("rewardAmt"), 1),
formatDouble(expectedAward.get("顾问奖励金额"), 1),
"顾问奖励金额");
}
}*/
public void assertParkAward(HashMap<String, String> expectedAward, List<JSONObject> parkAwards, Filter filter) {
/* assertion.verifyEquals(
formatDouble(ParkAward.getString("localAmt"), 1),
formatDouble(expectedAward.get("地方留存金额"), 1),
"地方留存金额");*/
/*assertion.verifyEquals(
formatDouble(ParkAward.getString("parkAmt"), 1),
formatDouble(expectedAward.get("园区留存金额"), 1),
"园区留存金额");*/
Double awardAmt = formatDouble(expectedAward.get("完税额"), 1);
Double parkAwardAmt = 0.00;
Double entpAwardAmt = 0.00;
Double investorAwardAmt = 0.00;
Double parkConsultantAwardAmt = 0.00;
Double grossIncomeAmt = 0.00;
Double governmentAwardAmt = 0.00;
Double customerSourceAmt = 0.00;
Double marketingOrgAmt = 0.00;
Double serviceOrgAmt = 0.00;
Double assistMarketingOrgAmt = 0.00;
Double marketingEmpAmt = 0.00;
Double marketingEmpManagerAmt = 0.00;
Double assistMarketingEmpAmt = 0.00;
Double assistMarketingEmpManagerAmt = 0.00;
for (JSONObject parkAward : parkAwards
) {
parkAwardAmt += formatDouble(parkAward.getString("parkAwardAmt"), 1);
entpAwardAmt += formatDouble(parkAward.getString("entpAwardAmt"), 1);
investorAwardAmt += formatDouble(parkAward.getString("investorAwardAmt"), 1);
parkConsultantAwardAmt += formatDouble(parkAward.getString("parkConsultantAwardAmt"), 1);
grossIncomeAmt += formatDouble(parkAward.getString("grossIncomeAmt"), 1);
governmentAwardAmt += formatDouble(parkAward.getString("governmentAwardAmt"), 1);
customerSourceAmt += formatDouble(parkAward.getString("customerSourceAmt"), 1);
marketingOrgAmt += formatDouble(parkAward.getString("marketingOrgAmt"), 1);
serviceOrgAmt += formatDouble(parkAward.getString("serviceOrgAmt"), 1);
assistMarketingOrgAmt += formatDouble(parkAward.getString("assistMarketingOrgAmt"), 1);
marketingEmpAmt += formatDouble(parkAward.getString("marketingEmpAmt"), 1);
marketingEmpManagerAmt += formatDouble(parkAward.getString("marketingEmpManagerAmt"), 1);
assistMarketingEmpAmt += formatDouble(parkAward.getString("assistMarketingEmpAmt"), 1);
assistMarketingEmpManagerAmt += formatDouble(parkAward.getString("assistMarketingEmpManagerAmt"), 1);
}
String emp = expectedAward.get("企业");
if (emp.contains("武汉诺行天下汽车服务有限公司") || emp.contains("李泰润")) return;
MyAssert.verifyEquals(
parkAwardAmt,
formatDouble(expectedAward.get("园区应返税金额"), 1),
awardAmt,
filter + "园区应返税金额");
MyAssert.verifyEquals(
entpAwardAmt,
formatDouble(expectedAward.get("企业返税金额"), 1),
awardAmt,
filter + "企业返税金额");
MyAssert.verifyEquals(
investorAwardAmt,
formatDouble(expectedAward.get("渠道奖励金额"), 1),
awardAmt,
filter + "渠道奖励金额");
MyAssert.verifyEquals(
parkConsultantAwardAmt,
formatDouble(expectedAward.get("顾问奖励金额"), 1),
awardAmt,
filter + "顾问奖励金额");
/*MyAssert.verifyEquals(
grossIncomeAmt,
formatDouble(expectedAward.get("集团毛收入"), 1),
filter + "集团毛收入");
MyAssert.verifyEquals(
governmentAwardAmt,
formatDouble(expectedAward.get("政务毛利"), 1),
filter + "政务毛利");
MyAssert.verifyEquals(
customerSourceAmt,
formatDouble(expectedAward.get("客户来源金额"), 1),
filter + "客户来源金额");
MyAssert.verifyEquals(
marketingOrgAmt,
formatDouble(expectedAward.get("引进分成金额"), 1),
filter + "引进分成金额");
MyAssert.verifyEquals(
serviceOrgAmt,
formatDouble(expectedAward.get("企服公司分成金额"), 1),
filter + "企服公司分成金额");
MyAssert.verifyEquals(
assistMarketingOrgAmt,
formatDouble(expectedAward.get("关联引进分成金额"), 1),
filter + "关联引进分成金额");
MyAssert.verifyEquals(
marketingEmpAmt,
formatDouble(expectedAward.get("招商人员提成金额"), 1),
filter + "招商人员提成金额");
MyAssert.verifyEquals(
marketingEmpManagerAmt,
formatDouble(expectedAward.get("招商科长提成金额"), 1),
filter + "招商科长提成金额");
MyAssert.verifyEquals(
assistMarketingEmpAmt,
formatDouble(expectedAward.get("关联招商人员提成金额"), 1),
filter + "关联招商人员提成金额");
MyAssert.verifyEquals(
assistMarketingEmpManagerAmt,
formatDouble(expectedAward.get("关联招商科长提成金额"), 1),
filter + "关联招商科长提成金额");*/
}
}
<file_sep>package listener;
import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;
public class RetryAnalyzer implements IRetryAnalyzer {
int maxRetryCount = 3;
int currentRetryCount = 0;
@Override
public boolean retry(ITestResult result) {
if (currentRetryCount < maxRetryCount) {
currentRetryCount++;
return true;
} else {
return false;
}
}
}
|
1dbb53dc9d45f75daafc9b54faeb5b0331b14ef4
|
[
"Java",
"Maven POM",
"INI"
] | 17 |
Java
|
mike041/demo
|
8bdc9895a07b47d501d45cdabd0203a5d511272c
|
c93ded4a755ad6afcab77ae770383246d5036edf
|
refs/heads/master
|
<repo_name>koptilnya/gmod-mouse-steering<file_sep>/lua/entities/koptilnya_mouse_steering.lua
AddCSLuaFile()
DEFINE_BASECLASS("base_gmodentity")
ENT.Type = "anim"
ENT.Author = "Opti1337"
ENT.Contact = "<EMAIL>"
ENT.PrintName = "Mouse Steering"
if SERVER then
function ENT:Initialize()
self:DrawShadow(false)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:PhysicsInit(SOLID_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self.driver = nil
self.X = 0
self:SetOverlayText("Mouse Steering")
self:Setup(40, 1, 0, 1)
end
function ENT:Think()
if IsValid(self.relativeEntity) then
self:SetAngles(self.relativeEntity:LocalToWorldAngles(Angle(0, self.steerAngle, 0)))
else
self:SetAngles(Angle(0, self.steerAngle, 0))
end
self:NextThink(CurTime())
return true
end
function ENT:Setup(maxAngle, sensitivity, deadzone, exponent)
self.maxAngle = maxAngle
self.sensitivity = sensitivity
self.deadzone = deadzone
self.exponent = exponent
end
function ENT:SetRelativeEntity(ent)
if not IsValid(ent) then
return
end
self.relativeEntity = ent
end
function ENT:Steer(steer)
self.steerAngle = -steer * self.maxAngle
end
-- hook.Add("PlayerEnteredVehicle", "koptilnya_mouse_steering_entervehicle", function(ply, vehicle)
-- local mouseSteering = vehicle.AttachedMouseSteering
-- if mouseSteering ~= nil then
-- if IsValid(mouseSteering) then
-- mouseSteering.driver = vehicle:GetDriver()
-- else
-- vehicle.AttachedMouseSteering = nil
-- end
-- end
-- end)
-- hook.Add("PlayerLeaveVehicle", "koptilnya_mouse_steering_leavevehicle", function(ply, vehicle)
-- local mouseSteering = vehicle.AttachedMouseSteering
-- if mouseSteering ~= nil then
-- if IsValid(mouseSteering) then
-- mouseSteering.driver = nil
-- else
-- vehicle.AttachedMouseSteering = nil
-- end
-- end
-- end)
local X = 0
hook.Add("StartCommand", "koptilnya_startcommand", function(ply, cmd)
if not IsValid(ply) then
return
end
if not ply:InVehicle() then
return
end
local vehicle = ply:GetVehicle()
if not IsValid(vehicle) then
return
end
local mouseSteering = vehicle.AttachedMouseSteering
if not IsValid(mouseSteering) then
return
end
local frametime = FrameTime()
local deltaX = cmd:GetMouseX()
X = math.Clamp(X + deltaX * frametime * 0.05 * mouseSteering.sensitivity, -1, 1)
local steer = ((math.max(math.abs(X) - mouseSteering.deadzone / 16, 0) ^ mouseSteering.exponent) / (1 - mouseSteering.deadzone / 16)) *
((X > 0) and 1 or -1)
mouseSteering:Steer(steer)
end)
-- hook.Add("CreateMove", "koptilnya_mouse_steering_setupmove", function(ucmd)
-- end)
else
function ENT:Initialize()
self:SetPredictable(true)
end
end
<file_sep>/lua/weapons/gmod_tool/stools/koptilnya_mouse_steering.lua
TOOL.Name = "#tool.koptilnya_mouse_steering.name"
TOOL.Category = "Koptilnya"
TOOL.Command = nil
TOOL.Information = {{name = "left", stage = 0}}
TOOL.ClientConVar = {
model = "models/hunter/plates/plate025x025.mdl",
max_angle = 40,
sensitivity = 1,
deadzone = 0,
exponent = 1
}
function TOOL:LeftClick(trace)
if self:GetStage() ~= 0 then
return false
end
if SERVER then
ent = ents.Create("koptilnya_mouse_steering")
ent:SetPos(trace.HitPos)
ent:SetAngles(trace.HitNormal:Angle())
ent:Spawn()
ent:SetModel(self:GetClientInfo("model"))
ent:SetCollisionGroup(COLLISION_GROUP_WORLD)
ent.nocollide = true
local min = ent:OBBMins()
ent:SetPos(trace.HitPos - trace.HitNormal * min.z)
ent:SetPlayer(self:GetOwner())
ent:Setup(self:GetClientNumber("max_angle"), self:GetClientNumber("sensitivity"), self:GetClientNumber("deadzone"), self:GetClientNumber("exponent"))
undo.Create("koptilnya_mouse_steering")
undo.AddEntity(ent)
undo.SetPlayer(self:GetOwner())
undo.Finish()
end
return true
end
function TOOL:RightClick(trace)
if not IsValid(trace.Entity) then
return false
end
if SERVER then
if self:GetStage() == 0 then
if trace.Entity:GetClass() == "koptilnya_mouse_steering" then
self.Controller = trace.Entity
self:SetStage(1)
else
return false
end
elseif self:GetStage() == 1 then
self:SetStage(0)
if self:GetOwner():KeyDown(IN_SPEED) then
self.Controller:SetRelativeEntity(trace.Entity)
else
if trace.Entity:IsVehicle() then
trace.Entity.AttachedMouseSteering = self.Controller
else
return false
end
end
end
end
return true
end
function TOOL:Reload(trace)
if SERVER then
self:SetStage(0)
if trace.Entity:IsValid() and trace.Entity:IsVehicle() and trace.Entity.AttachedMouseSteering ~= nil then
trace.Entity.AttachedMouseSteering = nil
else
return false
end
end
return true
end
function TOOL.BuildCPanel(CPanel)
CPanel:AddControl("Header", {Description = "Mouse Steering"})
CPanel:AddControl("Slider", {Label = "Max Angle", Command = "koptilnya_mouse_steering_max_angle", Type = "Float", Min = 0.1, Max = 89})
CPanel:AddControl("Slider", {Label = "Sensitivity", Command = "koptilnya_mouse_steering_sensitivity", Type = "Float", Min = 0.1, Max = 10})
CPanel:AddControl("Slider", {Label = "Deadzone", Command = "koptilnya_mouse_steering_deadzone", Type = "Float", Min = 0, Max = 16})
CPanel:AddControl("Slider", {Label = "Exponent", Command = "koptilnya_mouse_steering_exponent", Type = "Float", Min = 1, Max = 4})
end
if CLIENT then
language.Add("tool.koptilnya_mouse_steering.name", "Mouse Steering")
language.Add("tool.koptilnya_mouse_steering.desc", "))))))))))))))")
language.Add("tool.koptilnya_mouse_steering.left", "Spawn a controller")
end
|
31f2b786ee6be95bcb14bd66ab4ac710926b8d2e
|
[
"Lua"
] | 2 |
Lua
|
koptilnya/gmod-mouse-steering
|
6c3fe5876849ec04d27680489ecafb5633aa493c
|
ddbb9640cf5d9c7554669f90c0c2ef328ae54dae
|
refs/heads/master
|
<file_sep>#include <stdio.h>
#include "board.h"
#include "peripherals.h"
#include "pin_mux.h"
#include "clock_config.h"
#include "MKL25Z4.h"
#include "fsl_debug_console.h"
#include "fsl_tpm.h"
#define Renglon_1 5u
#define Renglon_2 4u
#define Renglon_3 3u
#define Renglon_4 2u
#define Columna_1 11u
#define Columna_2 10u
#define Columna_3 9u
#define Columna_4 8u
void DelayTPM();
int main(void) {
BOARD_InitBootPins();
BOARD_InitBootClocks();
BOARD_InitBootPeripherals();
BOARD_InitDebugConsole();
tpm_config_t config;
TPM_GetDefaultConfig(&config);
config.prescale= kTPM_Prescale_Divide_128;
TPM_Init(TPM0, &config);
TPM_Init(TPM1, &config);
PRINTF("Teclado Matricial\n");
uint8_t renglon[4];
/* Enter an infinite loop, just incrementing a counter. */
while(1) {
//Poner la columna 1 en bajo
GPIO_ClearPinsOutput(GPIOB, 1u << Columna_1);
//Leer los renglones
renglon[0] = GPIO_ReadPinInput(GPIOE, Renglon_1);
renglon[1] = GPIO_ReadPinInput(GPIOE, Renglon_2);
renglon[2] = GPIO_ReadPinInput(GPIOE, Renglon_3);
renglon[3] = GPIO_ReadPinInput(GPIOE, Renglon_4);
if(!renglon[0]){
printf("1");
DelayTPM();
}
if(!renglon[1]){
printf("4");
DelayTPM();
}
if(!renglon[2]){
printf("7");
DelayTPM();
}
if(!renglon[3]){
printf("*");
DelayTPM();
}
//Poner la columna 2 en bajo
GPIO_SetPinsOutput(GPIOB, 1u << Columna_1);
GPIO_ClearPinsOutput(GPIOB, 1u << Columna_2);
//Leer los renglones
renglon[0] = GPIO_ReadPinInput(GPIOE, Renglon_1);
renglon[1] = GPIO_ReadPinInput(GPIOE, Renglon_2);
renglon[2] = GPIO_ReadPinInput(GPIOE, Renglon_3);
renglon[3] = GPIO_ReadPinInput(GPIOE, Renglon_4);
if(!renglon[0]){
printf("2");
DelayTPM();
}
if(!renglon[1]){
printf("5");
DelayTPM();
}
if(!renglon[2]){
printf("8");
DelayTPM();
}
if(!renglon[3]){
printf("0");
DelayTPM();
}
//Poner la columna 3 en bajo
GPIO_SetPinsOutput(GPIOB, 1u << Columna_2);
GPIO_ClearPinsOutput(GPIOB, 1u << Columna_3);
//Leer los renglones
renglon[0] = GPIO_ReadPinInput(GPIOE, Renglon_1);
renglon[1] = GPIO_ReadPinInput(GPIOE, Renglon_2);
renglon[2] = GPIO_ReadPinInput(GPIOE, Renglon_3);
renglon[3] = GPIO_ReadPinInput(GPIOE, Renglon_4);
if(!renglon[0]){
printf("3");
DelayTPM();
}
if(!renglon[1]){
printf("6");
DelayTPM();
}
if(!renglon[2]){
printf("9");
DelayTPM();
}
if(!renglon[3]){
printf("#");
DelayTPM();
}
//Poner la columna 4 en bajo
GPIO_SetPinsOutput(GPIOB, 1u << Columna_3);
GPIO_ClearPinsOutput(GPIOB, 1u << Columna_4);
//Leer los renglones
renglon[0] = GPIO_ReadPinInput(GPIOE, Renglon_1);
renglon[1] = GPIO_ReadPinInput(GPIOE, Renglon_2);
renglon[2] = GPIO_ReadPinInput(GPIOE, Renglon_3);
renglon[3] = GPIO_ReadPinInput(GPIOE, Renglon_4);
if(!renglon[0]){
printf("A");
DelayTPM();
}
if(!renglon[1]){
printf("B");
DelayTPM();
}
if(!renglon[2]){
printf("C");
DelayTPM();
}
if(!renglon[3]){
printf("D");
DelayTPM();
}
GPIO_SetPinsOutput(GPIOB, 1u << Columna_4);
}
return 0 ;
}
void DelayTPM(){
uint32_t Mask= 1u<<8u;
uint32_t Mask_Off = Mask;
TPM_SetTimerPeriod(TPM1, 100u);
TPM_StartTimer(TPM1, kTPM_SystemClock);
while(!(TPM1->STATUS & Mask)){ //Wait
}
if(TPM1->STATUS & Mask){
TPM1->STATUS &=Mask_Off;
TPM_StopTimer(TPM1);
TPM1->CNT=0;
}
}
<file_sep>/***********************************************************************************************************************
* This file was generated by the MCUXpresso Config Tools. Any manual edits made to this file
* will be overwritten if the respective MCUXpresso Config Tools is used to update this file.
**********************************************************************************************************************/
/* clang-format off */
/*
* TEXT BELOW IS USED AS SETTING FOR TOOLS *************************************
!!GlobalInfo
product: Pins v7.0
processor: MKL25Z128xxx4
package_id: MKL25Z128VLK4
mcu_data: ksdk2_0
processor_version: 7.0.1
board: FRDM-KL25Z
pin_labels:
- {pin_num: '3', pin_signal: PTE2/SPI1_SCK, label: 'J9[9]', identifier: Renglon_4}
- {pin_num: '4', pin_signal: PTE3/SPI1_MISO/SPI1_MOSI, label: 'J9[11]', identifier: Renglon_3}
- {pin_num: '5', pin_signal: PTE4/SPI1_PCS0, label: 'J9[13]', identifier: Renglon_2}
- {pin_num: '6', pin_signal: PTE5, label: 'J9[15]', identifier: Renglon_1}
- {pin_num: '47', pin_signal: PTB8/EXTRG_IN, label: 'J9[1]', identifier: Columna_4;Columna_1}
- {pin_num: '48', pin_signal: PTB9, label: 'J9[3]', identifier: Columna_3;Columna_2}
- {pin_num: '49', pin_signal: PTB10/SPI1_PCS0, label: 'J9[5]', identifier: Columna_2;Columna_3}
- {pin_num: '50', pin_signal: PTB11/SPI1_SCK, label: 'J9[7]', identifier: Columna_1;Columna_4}
* BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS ***********
*/
/* clang-format on */
#include "fsl_common.h"
#include "fsl_port.h"
#include "fsl_gpio.h"
#include "pin_mux.h"
/* FUNCTION ************************************************************************************************************
*
* Function Name : BOARD_InitBootPins
* Description : Calls initialization functions.
*
* END ****************************************************************************************************************/
void BOARD_InitBootPins(void)
{
BOARD_InitPins();
}
/* clang-format off */
/*
* TEXT BELOW IS USED AS SETTING FOR TOOLS *************************************
BOARD_InitPins:
- options: {callFromInitBoot: 'true', coreID: core0, enableClock: 'true'}
- pin_list:
- {pin_num: '28', peripheral: UART0, signal: TX, pin_signal: TSI0_CH3/PTA2/UART0_TX/TPM2_CH1}
- {pin_num: '27', peripheral: UART0, signal: RX, pin_signal: TSI0_CH2/PTA1/UART0_RX/TPM2_CH0}
- {pin_num: '47', peripheral: GPIOB, signal: 'GPIO, 8', pin_signal: PTB8/EXTRG_IN, identifier: Columna_1, direction: OUTPUT, gpio_init_state: 'true'}
- {pin_num: '48', peripheral: GPIOB, signal: 'GPIO, 9', pin_signal: PTB9, identifier: Columna_2, direction: OUTPUT, gpio_init_state: 'true'}
- {pin_num: '49', peripheral: GPIOB, signal: 'GPIO, 10', pin_signal: PTB10/SPI1_PCS0, identifier: Columna_3, direction: OUTPUT, gpio_init_state: 'true'}
- {pin_num: '50', peripheral: GPIOB, signal: 'GPIO, 11', pin_signal: PTB11/SPI1_SCK, identifier: Columna_4, direction: OUTPUT, gpio_init_state: 'true'}
- {pin_num: '3', peripheral: GPIOE, signal: 'GPIO, 2', pin_signal: PTE2/SPI1_SCK, direction: INPUT, pull_enable: disable}
- {pin_num: '4', peripheral: GPIOE, signal: 'GPIO, 3', pin_signal: PTE3/SPI1_MISO/SPI1_MOSI, direction: INPUT, pull_enable: disable}
- {pin_num: '5', peripheral: GPIOE, signal: 'GPIO, 4', pin_signal: PTE4/SPI1_PCS0, direction: INPUT, pull_enable: disable}
- {pin_num: '6', peripheral: GPIOE, signal: 'GPIO, 5', pin_signal: PTE5, direction: INPUT, pull_enable: disable}
* BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS ***********
*/
/* clang-format on */
/* FUNCTION ************************************************************************************************************
*
* Function Name : BOARD_InitPins
* Description : Configures pin routing and optionally pin electrical features.
*
* END ****************************************************************************************************************/
void BOARD_InitPins(void)
{
/* Port A Clock Gate Control: Clock enabled */
CLOCK_EnableClock(kCLOCK_PortA);
/* Port B Clock Gate Control: Clock enabled */
CLOCK_EnableClock(kCLOCK_PortB);
/* Port E Clock Gate Control: Clock enabled */
CLOCK_EnableClock(kCLOCK_PortE);
gpio_pin_config_t Columna_1_config = {
.pinDirection = kGPIO_DigitalOutput,
.outputLogic = 1U
};
/* Initialize GPIO functionality on pin PTB8 (pin 47) */
GPIO_PinInit(BOARD_INITPINS_Columna_1_GPIO, BOARD_INITPINS_Columna_1_PIN, &Columna_1_config);
gpio_pin_config_t Columna_2_config = {
.pinDirection = kGPIO_DigitalOutput,
.outputLogic = 1U
};
/* Initialize GPIO functionality on pin PTB9 (pin 48) */
GPIO_PinInit(BOARD_INITPINS_Columna_2_GPIO, BOARD_INITPINS_Columna_2_PIN, &Columna_2_config);
gpio_pin_config_t Columna_3_config = {
.pinDirection = kGPIO_DigitalOutput,
.outputLogic = 1U
};
/* Initialize GPIO functionality on pin PTB10 (pin 49) */
GPIO_PinInit(BOARD_INITPINS_Columna_3_GPIO, BOARD_INITPINS_Columna_3_PIN, &Columna_3_config);
gpio_pin_config_t Columna_4_config = {
.pinDirection = kGPIO_DigitalOutput,
.outputLogic = 1U
};
/* Initialize GPIO functionality on pin PTB11 (pin 50) */
GPIO_PinInit(BOARD_INITPINS_Columna_4_GPIO, BOARD_INITPINS_Columna_4_PIN, &Columna_4_config);
gpio_pin_config_t Renglon_4_config = {
.pinDirection = kGPIO_DigitalInput,
.outputLogic = 0U
};
/* Initialize GPIO functionality on pin PTE2 (pin 3) */
GPIO_PinInit(BOARD_INITPINS_Renglon_4_GPIO, BOARD_INITPINS_Renglon_4_PIN, &Renglon_4_config);
gpio_pin_config_t Renglon_3_config = {
.pinDirection = kGPIO_DigitalInput,
.outputLogic = 0U
};
/* Initialize GPIO functionality on pin PTE3 (pin 4) */
GPIO_PinInit(BOARD_INITPINS_Renglon_3_GPIO, BOARD_INITPINS_Renglon_3_PIN, &Renglon_3_config);
gpio_pin_config_t Renglon_2_config = {
.pinDirection = kGPIO_DigitalInput,
.outputLogic = 0U
};
/* Initialize GPIO functionality on pin PTE4 (pin 5) */
GPIO_PinInit(BOARD_INITPINS_Renglon_2_GPIO, BOARD_INITPINS_Renglon_2_PIN, &Renglon_2_config);
gpio_pin_config_t Renglon_1_config = {
.pinDirection = kGPIO_DigitalInput,
.outputLogic = 0U
};
/* Initialize GPIO functionality on pin PTE5 (pin 6) */
GPIO_PinInit(BOARD_INITPINS_Renglon_1_GPIO, BOARD_INITPINS_Renglon_1_PIN, &Renglon_1_config);
/* PORTA1 (pin 27) is configured as UART0_RX */
PORT_SetPinMux(BOARD_INITPINS_DEBUG_UART_RX_PORT, BOARD_INITPINS_DEBUG_UART_RX_PIN, kPORT_MuxAlt2);
/* PORTA2 (pin 28) is configured as UART0_TX */
PORT_SetPinMux(BOARD_INITPINS_DEBUG_UART_TX_PORT, BOARD_INITPINS_DEBUG_UART_TX_PIN, kPORT_MuxAlt2);
/* PORTB10 (pin 49) is configured as PTB10 */
PORT_SetPinMux(BOARD_INITPINS_Columna_3_PORT, BOARD_INITPINS_Columna_3_PIN, kPORT_MuxAsGpio);
/* PORTB11 (pin 50) is configured as PTB11 */
PORT_SetPinMux(BOARD_INITPINS_Columna_4_PORT, BOARD_INITPINS_Columna_4_PIN, kPORT_MuxAsGpio);
/* PORTB8 (pin 47) is configured as PTB8 */
PORT_SetPinMux(BOARD_INITPINS_Columna_1_PORT, BOARD_INITPINS_Columna_1_PIN, kPORT_MuxAsGpio);
/* PORTB9 (pin 48) is configured as PTB9 */
PORT_SetPinMux(BOARD_INITPINS_Columna_2_PORT, BOARD_INITPINS_Columna_2_PIN, kPORT_MuxAsGpio);
/* PORTE2 (pin 3) is configured as PTE2 */
PORT_SetPinMux(BOARD_INITPINS_Renglon_4_PORT, BOARD_INITPINS_Renglon_4_PIN, kPORT_MuxAsGpio);
PORTE->PCR[2] = ((PORTE->PCR[2] &
/* Mask bits to zero which are setting */
(~(PORT_PCR_PE_MASK | PORT_PCR_ISF_MASK)))
/* Pull Enable: Internal pullup or pulldown resistor is not enabled on the corresponding pin. */
| PORT_PCR_PE(kPORT_PullDisable));
/* PORTE3 (pin 4) is configured as PTE3 */
PORT_SetPinMux(BOARD_INITPINS_Renglon_3_PORT, BOARD_INITPINS_Renglon_3_PIN, kPORT_MuxAsGpio);
PORTE->PCR[3] = ((PORTE->PCR[3] &
/* Mask bits to zero which are setting */
(~(PORT_PCR_PE_MASK | PORT_PCR_ISF_MASK)))
/* Pull Enable: Internal pullup or pulldown resistor is not enabled on the corresponding pin. */
| PORT_PCR_PE(kPORT_PullDisable));
/* PORTE4 (pin 5) is configured as PTE4 */
PORT_SetPinMux(BOARD_INITPINS_Renglon_2_PORT, BOARD_INITPINS_Renglon_2_PIN, kPORT_MuxAsGpio);
PORTE->PCR[4] = ((PORTE->PCR[4] &
/* Mask bits to zero which are setting */
(~(PORT_PCR_PE_MASK | PORT_PCR_ISF_MASK)))
/* Pull Enable: Internal pullup or pulldown resistor is not enabled on the corresponding pin. */
| PORT_PCR_PE(kPORT_PullDisable));
/* PORTE5 (pin 6) is configured as PTE5 */
PORT_SetPinMux(BOARD_INITPINS_Renglon_1_PORT, BOARD_INITPINS_Renglon_1_PIN, kPORT_MuxAsGpio);
PORTE->PCR[5] = ((PORTE->PCR[5] &
/* Mask bits to zero which are setting */
(~(PORT_PCR_PE_MASK | PORT_PCR_ISF_MASK)))
/* Pull Enable: Internal pullup or pulldown resistor is not enabled on the corresponding pin. */
| PORT_PCR_PE(kPORT_PullDisable));
SIM->SOPT5 = ((SIM->SOPT5 &
/* Mask bits to zero which are setting */
(~(SIM_SOPT5_UART0TXSRC_MASK | SIM_SOPT5_UART0RXSRC_MASK)))
/* UART0 transmit data source select: UART0_TX pin. */
| SIM_SOPT5_UART0TXSRC(SOPT5_UART0TXSRC_UART_TX)
/* UART0 receive data source select: UART0_RX pin. */
| SIM_SOPT5_UART0RXSRC(SOPT5_UART0RXSRC_UART_RX));
}
/***********************************************************************************************************************
* EOF
**********************************************************************************************************************/
|
dd8797dcbd40cac896e16c0d26743b59ffcbed7e
|
[
"C"
] | 2 |
C
|
LalodeAvila369/FRDMKL25Z_Keypad_Keypad
|
156a6045dbae1d5ff4b45fe73aed155584eb0542
|
f219b9b5a334a263d10001db6a6f76c5887057c0
|
refs/heads/master
|
<file_sep>#!/usr/bin/env node
console.log("leery is here, never fear");
|
4b9f50888b9886349e6c4b9a56bc594261ee94a7
|
[
"JavaScript"
] | 1 |
JavaScript
|
lloyd/leery
|
fec93b35afd00756c34b8e207e402ac77dee5e77
|
64678e46988d216b82208eff676db0dc178435e8
|
refs/heads/master
|
<repo_name>2752599920/todo<file_sep>/src/router/index.js
import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
import AddTODO from "../components/AddTODO.vue";
import TodoList from "../views/TodoList.vue"
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "Home",
component: Home
},
{
path: "/TodoList",
name: "TodoList",
component: TodoList
},
{
path: "/AddTODO",
name: "AddTODO",
component: AddTODO
},
];
const router = new VueRouter({
// mode: "history",
base: process.env.BASE_URL,
routes
});
export default router;
|
a63c813cad3ce1ce4452fc41b9e611880a8eba8d
|
[
"JavaScript"
] | 1 |
JavaScript
|
2752599920/todo
|
515fd36d1546840fc3da9bfe5bd892b9ea135a73
|
aba16951e51bbeceb92a6cb207dc235d8e1e7142
|
refs/heads/master
|
<repo_name>abrenicamarkjoshua/UIserviceLayerWinForms<file_sep>/UIserviceLayerWinForms/winforms/draggableForm.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UIserviceLayerWinForms.winforms
{
public class draggableForm : Form
{
protected bool draggable = false;
protected int mousex;
protected int mousey;
public draggableForm()
{
this.MouseDown += mousedown;
this.MouseMove += mousemove;
this.MouseUp += mouseup;
}
public void mousemove(object sender, EventArgs e)
{
if (draggable)
{
this.Top = System.Windows.Forms.Cursor.Position.Y - mousey;
this.Left = System.Windows.Forms.Cursor.Position.X - mousex;
}
}
public virtual void mousedown(object sender, EventArgs e){
draggable = true;
mousex = System.Windows.Forms.Cursor.Position.X - this.Left;
mousey = System.Windows.Forms.Cursor.Position.Y - this.Top;
}
public void mouseup(object sender, EventArgs e)
{
draggable = false;
}
}
}
<file_sep>/UIserviceLayerWinForms/winforms/draggableTextBoxAlongParent.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UIserviceLayerWinForms.winforms
{
public class draggableTextBoxAlongParent : RichTextBox
{
protected bool draggable = false;
protected int mousex;
protected int mousey;
protected int parentMouseX;
protected int parentMouseY;
public draggableTextBoxAlongParent()
{
this.MouseDown += mousedown;
this.MouseMove += mousemove;
this.MouseUp += mouseup;
}
void move(Control parent)
{
if (parent is Form)
{
parent.Top = System.Windows.Forms.Cursor.Position.Y - parentMouseY;
parent.Left = System.Windows.Forms.Cursor.Position.X - parentMouseX;
} else{
move(parent.Parent);
}
}
public void mousemove(object sender, EventArgs e)
{
if (draggable)
{
//this.Top = System.Windows.Forms.Cursor.Position.Y - mousey;
//this.Left = System.Windows.Forms.Cursor.Position.X - mousex;
move(this.Parent);
}
}
void setParentMouseLocation(Control parent)
{
if (parent is Form)
{
parentMouseX = System.Windows.Forms.Cursor.Position.X - parent.Left;
parentMouseY = System.Windows.Forms.Cursor.Position.Y - parent.Top;
}
else
{
setParentMouseLocation(parent.Parent);
}
}
public virtual void mousedown(object sender, EventArgs e){
draggable = true;
setParentMouseLocation(this.Parent);
}
public void mouseup(object sender, EventArgs e)
{
draggable = false;
}
}
}
|
991e15bf7f590583222a6516e2c27184c726b75f
|
[
"C#"
] | 2 |
C#
|
abrenicamarkjoshua/UIserviceLayerWinForms
|
35b12d646a6242c6c89136a75cb81049c06b0ce6
|
01e3fcf96854d15566ae0b41927be4f5c8708570
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class uploadtest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
string strfile = FileUpload1.FileName;
string pathname = System.Web.HttpContext.Current.Server.MapPath("img");
FileUpload1.SaveAs(pathname + "\\" + strfile);
string sql = string.Format("insert into t_Menu (menuname,money) values ('{0}',11) ",strfile);
SqlHelp.ExecuteNonQuery(sql);
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class order : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
this.DataBind();
}
private void DataBind()
{
string sql = "select * from t_Menu";
DataSet ds = SqlHelp.Query(sql);
Repeater1.DataSource = ds;
Repeater1.DataBind();
}
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName.Equals("caiID"))
{
string id = e.CommandArgument.ToString();
Response.Redirect(string.Format("pay.aspx?caiID={0}",id));
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class reg : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
}
/*
* btnReg动作执行
* 实现注册功能
* 调用SqlHelp类方法executeNonQuery()
*/
protected void btnReg_Click(object sender, EventArgs e)
{
string sql = string.Format("insert into t_User (username,userpass,age) values( '{0}','{1}','{2}')", txtUserName.Text, txtUserPwd.Text, txtUserAge.Text);
try
{
int result;
result = SqlHelp.ExecuteNonQuery(sql);
if (result > 0)
{
MsgBoxOK("注册成功!");
}
else
{
MsgBoxError("注册失败!");
}
}
catch (Exception ex)
{
MsgBoxError("注册失败!");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class reg : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
/*
* btnReg动作执行
* 实现注册功能
* 调用SqlHelp类方法executeNonQuery()
*/
protected void btnReg_Click(object sender, EventArgs e)
{
string sql = string.Format("insert into t_user (username,userpwd,useremail) values('{0}','{1}','{2}')", txtUserName.Text, txtUserPwd.Text, txtUserEmail.Text);
int result;
result=SqlHelp.ExecuteNonQuery(sql);
if (result > 0)
{
lbmessage.Text = "注册成功!";
}
else
{
lbmessage.Text = "注册失败!";
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class useradd : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnReg_Click(object sender, EventArgs e)
{
string sql = string.Format("insert into t_User (username,userpass,age) values( '{0}','{1}','{2}')", txtUserName.Text, txtUserPwd.Text, txtUserAge.Text);
try
{
int result;
result = SqlHelp.ExecuteNonQuery(sql);
if (result > 0)
{
MsgBoxOK("注册成功!");
Response.Redirect("userlist.aspx");
}
else
{
MsgBoxError("注册失败!");
}
}
catch (Exception ex)
{
MsgBoxError("注册失败!");
}
}
private void MsgBoxOK(string msg)
{
string msgg2 = @" $.Zebra_Dialog('<strong>正确</strong>" + msg + "', {"
+ @"'type': 'confirmation', 'title': '这里是标题' });";
string strScript = "<script language='Javascript'>" + msgg2 + "</script>";
Page.RegisterStartupScript("alert", strScript);
}
private void MsgBoxError(string msg)
{
string msgg2 = @" $.Zebra_Dialog('<strong>错误</strong>" + msg + "', {"
+ @"'type': 'error', 'title': '这里是标题' });";
string strScript = "<script language='Javascript'>" + msgg2 + "</script>";
Page.RegisterStartupScript("alert", strScript);
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class menuEdit : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
int id = Int32.Parse(Request.QueryString["id"]);
if (!string.IsNullOrEmpty(id.ToString()))
{
string sql = string.Format("select * from t_Menu where id={0}", id);
DataSet ds = SqlHelp.Query(sql);
DataTable dt = ds.Tables[0];
if (dt.Rows.Count > 0)
{
this.txtCai.Text = dt.Rows[0]["menuname"].ToString();
this.txtMoney.Text = dt.Rows[0]["money"].ToString();
}
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
int id = Int32.Parse(Request.QueryString["id"]);
string sql = string.Format("update t_Menu set menuname='{0}',money={1} where id={2}", txtCai.Text, txtMoney.Text, id);
if (SqlHelp.ExecuteNonQuery(sql) > 0)
{
MsgBoxOK("修改成功!", "menu.aspx");
}
else
{
MsgBoxError("修改失败!");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
///BasePage 的摘要说明
/// </summary>
public class BasePage : System.Web.UI.Page
{
public BasePage()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
public void MsgBoxOK(string msg)
{
string msgg2 = @" $.Zebra_Dialog('<strong>正确</strong>" + msg + "', {"
+ @"'type': 'confirmation', 'title': '这里是标题' });";
string strScript = "<script language='Javascript'>" + msgg2 + "</script>";
Page.RegisterStartupScript("alert", strScript);
}
public void MsgBoxOK(string msg,string url)
{
string msgg2 = @" $.Zebra_Dialog('<strong>正确</strong>" + msg + "', {"
+ @"'type': 'confirmation', 'title': '这里是标题' });";
string strScript = "<script language='Javascript'>" + msgg2 +"window.location.href='"+url+ "'</script>";
Page.RegisterStartupScript("alert", strScript);
}
public void MsgBoxError(string msg)
{
string msgg2 = @" $.Zebra_Dialog('<strong>错误</strong>" + msg + "', {"
+ @"'type': 'error', 'title': '这里是标题' });";
string strScript = "<script language='Javascript'>" + msgg2 + "</script>";
Page.RegisterStartupScript("alert", strScript);
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class install01 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
btnNext.Visible = false;
}
protected void btnCreate_Click(object sender, EventArgs e)
{
string strAdress = string.Format("Data Source={0};Initial Catalog=master;User ID=sa;Password=<PASSWORD>;Integrated Security=True", txtServer.Text);
//1.sqlconnection对象
try
{
SqlConnection conn = new SqlConnection(strAdress);
conn.Open();
string sql = string.Format("create database {0}", txtDataBase.Text);
SqlCommand sqlcmd = new SqlCommand(sql, conn);
sqlcmd.ExecuteNonQuery();
conn.Close();
lbmessage.Text = "数据库连接正常!";
}
catch (Exception ex)
{
lbmessage.Text= ex.ToString();
}
// string saveAdress = string.Format("Data Source={0};Initial Catalog={1};Integrated Security=True", txtServer.Text,txtDataBase.Text);
string saveAddress = string.Format("Data Source={0};Initial Catalog={1},User ID={2},password={3}Integrated Security=True", txtServer.Text,txtDataBase,userName.Text,userPwd.Text);
new ConfigUtil().Save(saveAdress);
btnNext.Visible = true;
btnCreate.Visible = false;
}
protected void btnNext_Click(object sender, EventArgs e)
{
Response.Redirect("install02.aspx");
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.SqlClient;
public partial class install02 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
/*
* 获取reatetable.txt物理路径,
* 读取文件内容
*/
string strAddress = System.Web.HttpContext.Current.Server.MapPath("createTable.txt");
FileStream fs = new FileStream(strAddress,FileMode.Open);
StreamReader sr = new StreamReader(fs);
this.TextBox1.Text = sr.ReadToEnd();
sr.Close();
fs.Close();
}
protected void btnExcute_Click(object sender, EventArgs e)
{
/*
* 建立数据库链接,并将txtbox的数据做为sql命令,执行。
*/
string str = new ConfigUtil().GetAddrss(); //获取数据库源
string sql = TextBox1.Text;
try
{
SqlConnection conn = new SqlConnection(str);
conn.Open();
SqlCommand sqlcmd = new SqlCommand(sql, conn);
sqlcmd.ExecuteNonQuery();
conn.Close();
Label1.Text = "success!";
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
}<file_sep>这是我微软实训项目,一天一个小节。最后是一个整个项目。
<file_sep>/*
* 作者:石文涛
* 内容:SqlHelp类
* 功能:executeScalar方法实现查询数据库返回string值
* excutenonQuery方法实现查询数据库返回int值
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
/// <summary>
///SqlHelp 的摘要说明
///
/// </summary>
public class SqlHelp
{
/*
* excuteScalar返回为string类型的数据库查询
* SqlConnection对象,SqlCommand对象
*/
public static string ExecuteScalar(string sql)
{
try
{
string strAddress = new ConfigUtil().GetAddrss();
SqlConnection conn=new SqlConnection(strAddress);
conn.Open();
SqlCommand sqlcmd=new SqlCommand(sql,conn);
string result=(string)sqlcmd.ExecuteScalar();
conn.Close();
return result;
}
catch (Exception ex)
{
return null;
}
}
/*
* executeNonQuery返回为int类型的数据库查询
* SqlConnection对象,SqlCommand对象
*/
public static int ExecuteNonQuery(string sql)
{
try
{
string strAddress = new ConfigUtil().GetAddrss();
SqlConnection conn = new SqlConnection(strAddress);
conn.Open();
SqlCommand sqlcmd = new SqlCommand(sql, conn);
int result = sqlcmd.ExecuteNonQuery();
conn.Close();
return result;
}
catch
{
return 0;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class menu : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
this.DataBind();
}
private void DataBind()
{
string sql = "select * from t_Menu";
DataSet ds = SqlHelp.Query(sql);
this.GridView1.DataSource = ds;
this.GridView1.DataBind();
}
protected void btnadd_Click(object sender, EventArgs e)
{
Response.Redirect("menuadd.aspx");
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("upd"))
{
string id = e.CommandArgument.ToString();
Response.Redirect(string.Format("menuEdit.aspx?id={0}", id));
}
if (e.CommandName.Equals("del"))
{
int id = Int32.Parse(e.CommandArgument.ToString());
string sql = string.Format("delete from t_Menu where id={0}", id);
if (SqlHelp.ExecuteNonQuery(sql) > 0)
{
MsgBoxOK("删除成功!");
this.DataBind();
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class menuadd : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
string strfile = FileUpload1.FileName;
string pathname = System.Web.HttpContext.Current.Server.MapPath("img");
FileUpload1.SaveAs(pathname + "\\" + strfile);
string sql = string.Format("insert into t_Menu (menuname,money,picturename) values( '{0}','{1}','{2}')", txtCai.Text, txtMoney.Text,strfile);
try
{
int result;
result = SqlHelp.ExecuteNonQuery(sql);
if (result > 0)
{
MsgBoxOK("添加成功");
Response.Redirect("menu.aspx");
}
else
{
MsgBoxError("添加失败!");
}
}
catch (Exception ex)
{
MsgBoxError("添加");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class edit : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
int id =Int32.Parse(Request.QueryString["id"]);
if (!string.IsNullOrEmpty(id.ToString()))
{
string sql = string.Format("select * from t_User where id={0}", id);
DataSet ds = SqlHelp.Query(sql);
DataTable dt = ds.Tables[0];
if (dt.Rows.Count > 0)
{
this.txtUserName.Text = dt.Rows[0]["username"].ToString();
this.txtUserPwd.Text = dt.Rows[0]["userpass"].ToString();
this.txtUserAge.Text = dt.Rows[0]["age"].ToString();
}
}
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
int id =Int32.Parse(Request.QueryString["id"]);
string sql = string.Format("update t_User set username='{0}',userpass='{1}',age={2} where id={3}", txtUserName.Text, txtUserPwd.Text,txtUserAge.Text,id);
if (SqlHelp.ExecuteNonQuery(sql) > 0)
{
MsgBoxOK("修改成功!", "userlist.aspx");
}
else
{
MsgBoxError("修改失败!");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class ordermanger :BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
this.DataBind();
}
private void DataBind()
{
string sql = "select * from t_Order";
DataSet ds = SqlHelp.Query(sql);
this.GridView1.DataSource = ds;
this.GridView1.DataBind();
}
protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("yes"))
{
string id = e.CommandArgument.ToString();
string sql = string.Format("update t_Order set status='已签收' where id={0}", Int32.Parse(id));
SqlHelp.ExecuteNonQuery(sql);
this.Page_Load(sender,e);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
/*
* 登录按钮的执行动作
* 实现查询数据库
* 调用SqlHelp类executeScalar方法
*/
protected void btnLogin_Click(object sender, EventArgs e)
{
string sql=string.Format("select pass from t_User where name='{0}'",txtUserName.Text);
string result=SqlHelp.ExecuteScalar(sql);
if(result==txtUserPwd.Text)
{
lbmessage.Text = "成功登录";
}
else
{
lbmessage.Text = "登录失败!";
}
}
protected void btnCreate_Click(object sender, EventArgs e)
{
Response.Redirect("reg.aspx");
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
/// <summary>
///ConfigUtil 的摘要说明
/// </summary>
public class ConfigUtil
{
public ConfigUtil()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
private string configfileName = System.Web.HttpContext.Current.Server.MapPath("address.txt");
public void Save(string strAddress)
{
FileStream fs = new FileStream(configfileName,FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(strAddress);
sw.Close();
fs.Close();
}
public string GetAddrss()
{
FileStream fs = new FileStream(configfileName, FileMode.Open);
StreamReader sr = new StreamReader(fs);
string result;
result = sr.ReadLine();
sr.Close();
fs.Close();
return result;
}
}<file_sep>/*
* 作者:石文涛
* 内容:SqlHelp类
* 功能:executeScalar方法实现查询数据库返回string值
* excutenonQuery方法实现查询数据库返回int值
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
/// <summary>
///SqlHelp 的摘要说明
///
/// </summary>
public class SqlHelp
{
/*
* excuteScalar返回为string类型的数据库查询
* SqlConnection对象,SqlCommand对象
*/
private static string strAddress = "Data Source=.\\SQLEXPRESS;Initial Catalog=stu;User ID=sa;Password=<PASSWORD>";
public static string ExecuteScalar(string sql)
{
try
{
SqlConnection conn = new SqlConnection(strAddress);
conn.Open();
SqlCommand sqlcmd=new SqlCommand(sql,conn);
string result=(string)sqlcmd.ExecuteScalar();
conn.Close();
return result;
}
catch (Exception ex)
{
return null;
}
}
/*
* executeNonQuery返回为int类型的数据库查询
* SqlConnection对象,SqlCommand对象
*/
public static int ExecuteNonQuery(string sql)
{
try
{
SqlConnection conn = new SqlConnection(strAddress);
conn.Open();
SqlCommand sqlcmd = new SqlCommand(sql, conn);
int result = sqlcmd.ExecuteNonQuery();
conn.Close();
return result;
}
catch
{
return 0;
}
}
public static DataSet Query(string sql)
{
try
{
SqlConnection conn = new SqlConnection(strAddress);
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter sqldata = new SqlDataAdapter(sql, conn);
sqldata.Fill(ds);
conn.Close();
return ds;
}
catch (Exception ex)
{
return null;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class pay :BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
this.Data();
}
public void Data()
{
if (Page.IsPostBack == false)
{
int caiID = Int32.Parse(Request.QueryString["caiID"]);
string sql = string.Format("select * from t_Menu where id={0}", caiID);
DataSet ds = SqlHelp.Query(sql);
DataTable dt = ds.Tables[0];
if (dt.Rows.Count > 0)
{
this.lbcainame.Text = dt.Rows[0]["menuname"].ToString();
this.lbmoney.Text = dt.Rows[0]["money"].ToString();
}
txtname.Text = Session["username"].ToString();
}
}
protected void btnorder_Click(object sender, EventArgs e)
{
string username = Session["username"].ToString();
string sql_money = string.Format("select money from t_User where username='{0}'", username);
Object obj= SqlHelp.ExecuteScalar(sql_money);
string result =obj.ToString();
int money =Int32.Parse( result);
int txtmoney=Int32.Parse(lmcount.Text);
if (money >=txtmoney)
{
money = money - txtmoney;
string sql = string.Format("INSERT INTO t_Order (cainame,number,count,ordername,ordertel,orderaddress,ordertime,status) values ('{0}',{1},{2},'{3}','{4}','{5}','{6}','未签收')", lbcainame.Text, txtnumber.Text, lmcount.Text, txtname.Text, txttel.Text, txtaddress.Text, DateTime.Now.ToString());
string sql_change = string.Format("update t_User set money={0} where username='{1}'", money, username);
if (SqlHelp.ExecuteNonQuery(sql) > 0&&SqlHelp.ExecuteNonQuery(sql_change)>0)
{
MsgBoxOK("下单成功!");
}
else
{
MsgBoxError("下单失败!");
}
}
else
{
MsgBoxError("下单失败,余额不足!");
}
}
protected void btnreturn_Click(object sender, EventArgs e)
{
Response.Redirect("order.aspx");
}
protected void txtnumber_TextChanged(object sender, EventArgs e)
{
int num = Int32.Parse(txtnumber.Text);
float price = float.Parse(lbmoney.Text);
float count = 0;
count = price * (float)num;
this.lmcount.Text = count.ToString();
}
}
|
28ac35894fdcbd2b2a399c41bf259fd739797ece
|
[
"Markdown",
"C#"
] | 19 |
C#
|
Qian-Elizabeth/netWeb
|
d09a2b808337e09641c4db13697d12962921600f
|
66f225bcbf924c543d53949a8822b6100ae65658
|
refs/heads/master
|
<repo_name>Maxmiz123/fs-bnb-api<file_sep>/models/user.js
var mysqlConn = require("../database/database");
//Task object constructor
var User = function(user) {
this.name = user.name;
this.surname = user.surname;
this.cellPhone = user.cellPhone;
this.email = user.email;
this.password = <PASSWORD>;
this.role = user.role;
this.date_created = new Date();
};
module.exports = User;
User.createUser = function(newUser, result) {
mysqlConn.query("INSERT INTO user set ?", newUser, function(err, res) {
if (err) {
console.log("error: ", err);
result(err, null);
} else {
console.log(res.insertId);
result(null, res.insertId);
}
});
};
User.getAllUsers = function(result) {
mysqlConn.query("Select * from user", function(err, res) {
if (err) {
console.log("error: ", err);
result(err, null);
} else {
console.log("Users : ", res);
result(null, res);
}
});
};
User.getUserById = function(userId, result) {
mysqlConn.query("Select * from user where id = ? ", userId, function(
err,
res
) {
if (err) {
console.log("error: ", err);
result(err, null);
} else {
result(null, res);
}
});
};
User.updateUserById = function(userId, user, result) {
mysqlConn.query(
"UPDATE user SET user = ? WHERE id = ?",
[user, userId],
function(err, res) {
if (err) {
console.log("error: ", err);
result(null, err);
} else {
result(null, res);
}
}
);
};
User.removeUser = function(userId, result) {
mysqlConn.query("DELETE FROM user WHERE id = ?", userId, function(err, res) {
if (err) {
console.log("error: ", err);
result(null, err);
} else {
result(null, res);
}
});
};<file_sep>/api/users-routes.js
const UserService = require("../services/user-service");
const userService = new UserService();
router.get("/", (req, res) => {
userService
.getUsers()
.then(result => {
//var parseData = JSON.parse(result);
res.send(result);
})
.catch(err => {
res.status(400).json({ msg: err.message });
});
});
modle.exports = router;
<file_sep>/services/validation-service.js
class ValidationService {
constructor() {}
validateEmail(email) {
return true;
}
validatePassword(password){
return true;
}
}
module.exports = ValidationService;<file_sep>/index.js
const express = require("express");
const fs = require("fs");
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
var users = new Array();
var properties = new Array();
var bookings = new Array();
// app.post("/read/file", (req, res) => {
// fs.readFile("./data/file.json", function(err, data) {
// if (err) {
// return res.status(500).json({message: "Unable to open the file"});
// }
// var jsonFromString = JSON.parse(data);
// jsonFromString.users.push({id: 1});
// fs.writeFile("./data/file.json", JSON.stringify(jsonFromString), function(err) {
// if (err) {
// return res.status(500).json({message: "Unable to write the file"});
// }
// return res.status(200).json(jsonFromString);
// });
// });
// });
app.get("/api/users/:id", (req, res) => {
const userId = req.params.id;
const numberUserId = parseInt(userId);
if(isNaN(numberUserId)) {
return res.status(400).json({message: "I am expecting an integer"});
}
if (!userId) {
return res.status(400).json({message: "Please pass in a userId"});
}
for (var k = 0; k < users.length; k++) {
const aUser = users[k];
if (aUser.id == userId) {
return res.status(200).json(aUser);
}
}
return res.status(404).json({message: "User not found"});
});
app.post("/api/users", (req, res) => {
const user = req.body;
const bodyFirstname = user.firstname;
const bodyLastname = user.lastname;
const bodyEmail = user.email;
const bodyPassword = <PASSWORD>.<PASSWORD>;
var errors = [];
if (!bodyFirstname) {
errors.push({message: "Invalid request: Firstname is required"});
}
if (!bodyLastname) {
errors.push({message: "Invalid request: Lastname is required"});
}
if (!bodyPassword) {
errors.push({message: "Invalid request: Password is required"});
}
if (!bodyEmail) {
errors.push({message: "Invalid request: Email is required"});
}
if (errors.length > 0) {
return res.status(400).json({errorMessages: errors});
}
for (var k = 0; k < users.length; k++) {
const aUser = users[k];
if (aUser.email === bodyEmail) {
return res.status(400).json({message: "Invalid Request: User exists with that email"});
}
}
var newUser = {
id: users.length + 1,
firstname: bodyFirstname,
lastname: bodyLastname,
email: bodyEmail,
password: <PASSWORD>
};
users.push(newUser);
res.json(newUser);
});
app.post("/api/auth", (req, res) => {
const user = req.body;
const bodyEmail = user.email;
const bodyPassword = <PASSWORD>;
for (var k = 0; k < users.length; k++) {
const aUser = users[k];
if (aUser.email === bodyEmail && aUser.password === <PASSWORD>) {
return res.status(200).json({aUser});
}
res.send("POST Auth api");
}});
// const PropertyRouter = express.Router();
app.post("/api/properties", (req, res) => {
const property = req.body;
const propertyName = property.propertyName;
const propertyLocation = property.propertyLocation;
const propertyImage = property.propertyImage;
const propertyPrice = property.propertyPrice;
var newProperty = {
id: properties.length + 1,
name: propertyName,
location: propertyLocation,
image_url: propertyImage,
price: propertyPrice
};
properties.push(newProperty);
res.json(newProperty);
// res.send("POST Properties api");
});
// app.use("/parent", PropertyRouter);
app.listen(3000, () => {
console.log("Server is running");
});
app.get("/api/properties/:id", (req, res) => {
for (var k = 0; k < properties.length; k++) {
const property = properties[k];
if (property.id === parseInt(req.params.id)) {
return res.status(200).json({property});
}
}
});
app.delete("/api/properties/:id", (req, res) => {
var length = properties.length;
properties = properties.filter(property =>
!(property.id == parseInt(req.params.id)));
if (length == properties.length) {
res.status(400).json({status: "User doesn't exist"});
} else {
res.status(200).json({status: "user deleted"});
}
});
app.post("/api/properties/:id/bookings", (req, res) => {
const booking = req.body;
const dateFrom = booking.dateFrom;
const dateTo = booking.dateTo;
const userId = booking.userId;
var newBooking = {
id: properties.length + 1,
dateFrom: dateFrom,
dateTo: dateTo,
userId: userId,
propertyId: parseInt(req.params.id),
status: "NEW",
};
bookings.push(newBooking);
res.status(200).json(newBooking)
});
app.get("/api/properties/:id/bookings", (req, res) => {
var output = bookings.filter(booking =>
booking.propertyId == parseInt(req.params.id));
res.status(200).json(output);
});
|
53e52ff9fd0541b3270df3ae8a089617275be6a0
|
[
"JavaScript"
] | 4 |
JavaScript
|
Maxmiz123/fs-bnb-api
|
b2fde84e7d3af3a4ebfc88b16c6e08b61046d30b
|
bda83be9a54889bb67a619219a18ac1de758b3cd
|
refs/heads/master
|
<repo_name>nielsmaerten/nightscout-assistant<file_sep>/packages/cloud-functions/nightscout.js
// @ts-check
const fetch = require("node-fetch");
const admin = require("firebase-admin");
const URL = require("url").URL;
const intl = require("intl");
const { performance } = require("perf_hooks");
const functions = require("firebase-functions");
// Gets the current glucose for a user,
// and returns it as a pronounceable response
const getNightscoutStatus = async (userProfile, userEmail, t) => {
// Return a promise that should always resolve.
// Even if something goes wrong, we still need to tell the user why instead of just crashing.
return new Promise(async resolve => {
// Exit if no NS url has been provided yet
if (!userProfile || !userProfile.nsUrl) {
resolve({
response: t("errors.noNsSite"),
success: false,
error: "no-ns-site"
});
return;
}
const nsUrl = userProfile.nsUrl;
try {
// Get settings
const unit = userProfile.unit || "mg/dl";
const apiSecret = userProfile.secretHash;
// Build API request url
const apiUrl = new URL(nsUrl);
apiUrl.pathname = "/api/v1/entries/current.json";
// Call the API
const tQueryStart = performance.now();
// @ts-ignore
let response = await fetch(apiUrl, {
headers: {
"API-SECRET": apiSecret
}
});
// Nightscout v14.1.0 rejects incorrect apiSecrets, even when not read protected
// Try again without the apiSecret if response came back unauthorized
// https://github.com/nielsmaerten/nightscout-assistant/issues/114
if (response.status === 401) {
// @ts-ignore
response = await fetch(apiUrl);
}
const tQueryTime = Math.floor(performance.now() - tQueryStart);
// Exit if the request failed
if (!response.ok) {
throw new Error(
`HTTP ${response.status}: ${response.statusText} - ${apiUrl}`
);
}
// Parse JSON response
const json = (await response.json())[0];
// Format the response into a pronounceable answer
const convResponse = formatResponse(json, unit, t);
resolve({
response: convResponse,
success: true,
tQueryTime,
error: "none"
});
} catch (e) {
const errorResponse = handleError(e, userEmail, nsUrl, t);
resolve({ response: errorResponse, success: false, error: "api-error" });
}
});
};
const getUserProfile = async userEmail => {
const snapshot = await admin
.app()
.firestore()
.collection("users")
.doc(userEmail)
.get();
const data = snapshot.data();
// If no nsSite defined AND user is an aogReviewer:
// use sample data
const aogAgentRegex = /^aog\.platform.*@gmail\.com$/;
const isReviewer = aogAgentRegex.test(userEmail);
const hasNsUrl = Boolean(data.nsUrl);
if (!hasNsUrl && isReviewer) {
const testData = functions.config().testdata;
data.nsUrl = testData.nsurl;
data.unit = "mg/dl"
}
return data;
};
const updateUserProfile = async (userProfile, userEmail) => {
await admin
.app()
.firestore()
.collection("users")
.doc(userEmail)
.update(userProfile);
};
function formatResponse(d, unit, t) {
// Init a localized version of moment
let locale = determineLocale(t.lng);
let moment = require("moment");
moment.locale(locale);
// Get localized numberFormat
const nf = new intl.NumberFormat(locale).format;
// Get components of the response
const ago = moment(d.date).fromNow();
const value = d.sgv || d.mbg;
const bg = unit === "mg/dl" ? value : Math.round((value / 18) * 10) / 10;
const trend = t("trends." + d.direction, { defaultValue: null });
// Exit if no valid BG
if (isNaN(bg)) {
return t("errors.noBgReading");
}
// Formulate response
if (trend) {
return t("answers.withTrend", { bg: nf(bg), trend, ago });
} else {
return t("answers.noTrend", { bg: nf(bg), ago });
}
}
function determineLocale(lnCode) {
switch (lnCode) {
// For Norwegian, fall back to Norwegian Bokmål
case "no-NO":
return "nb";
default:
return lnCode;
}
}
function handleError(error, userEmail, nsUrl, t) {
let errorMsg = String(error.message || "");
console.log(
`
Error for user: %s
Nightscout url: %s
Error message : %s
Error details : %s
`,
userEmail,
nsUrl,
errorMsg,
error
);
// Invalid URL format
if (errorMsg.startsWith("Invalid URL:")) {
return `<speak>
${t("errors.invalidUrl.p1")}
<break time="600ms"/>
${t("errors.invalidUrl.p2")}
</speak>`;
}
// Not found
if (
errorMsg.startsWith("HTTP 404:") ||
errorMsg.indexOf("ENOTFOUND") !== -1
) {
return t("errors.notFound");
}
// Unauthorized
if (errorMsg.startsWith("HTTP 401:")) {
return t("errors.unauthorized");
}
// NS site crashed
if (errorMsg.startsWith("HTTP 5")) {
return t("errors.nsSiteError");
}
// Unknown error
console.error("UNKNOWN ERROR:", error);
return t("errors.unknown-error");
}
module.exports = {
getNightscoutStatus,
getUserProfile,
updateUserProfile
};
<file_sep>/packages/webapp/src/router.js
import Vue from "vue";
import Router from "vue-router";
import Home from "./views/Home.vue";
import Terms from "./views/Terms.vue";
import store from "@/store";
Vue.use(Router);
const router = new Router({
mode: "hash",
base: process.env.BASE_URL,
routes: [
{
path: "/",
redirect: "/en/home"
},
{
path: "/terms",
redirect: "/en/terms"
},
{
path: "/:lng",
redirect: "/:lng/home"
},
{
path: "/:lng/home",
name: "home",
component: Home
},
{
path: "/:lng/terms",
name: "terms",
component: Terms
}
]
});
router.beforeEach((to, from, next) => {
if (store.state.languages.active !== to.params.lng) {
store.dispatch("changeLanguage", to.params.lng);
}
next();
});
export default router;
<file_sep>/packages/webapp/src/store.js
import Vue from "vue";
import Vuex from "vuex";
import i18next from "i18next";
const constants = require("./constants");
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
app: {
gaEnabled: false
},
languages: {
active: undefined,
available: constants.languages.available,
loaded: []
},
user: {
settings: {
nsUrl: undefined,
unit: undefined,
secretHash: undefined
},
isAuthenticated: false,
email: undefined
}
},
mutations: {
setAuthStatus(state, isAuthenticated) {
state.user.isAuthenticated = isAuthenticated;
},
setLanguage(state, language) {
state.languages.active = language;
},
setUser(state, email) {
state.user.email = email;
state.user.isAuthenticated = true;
},
setUserSettings(state, data) {
state.user.nsUrl = data.nsUrl;
state.user.unit = data.unit;
},
enableGa(state) {
state.app.gaEnabled = true;
}
},
actions: {
async changeLanguage(context, lng) {
await i18next.changeLanguage(lng);
context.commit("setLanguage", lng);
}
}
});
export default store;
<file_sep>/.github/ISSUE_TEMPLATE/new-locale.md
---
name: New locale
about: Checklist for deploying the Action to a new locale
title: 'Add new locale: [LN-code]'
labels: enhancement
assignees: ''
---
## Translations
- [ ] New translations approved on Crowdin
- [ ] Translations merged into _master_ and _www_ branch
- [ ] If Routines are supported, locale code added to `lngsSupportingRoutines` array
- [ ] _www_ branch deployed to GitHub Pages
- [ ] Translator credit added to README / package.json
## Google Review requirements
- [ ] [Prepare for deployment - Google's Checklist](https://developers.google.com/actions/distribute/#prepare_for_deployment)
**Highlights:**
- [ ] Privacy policy fully translated
- [ ] Display name and Invocation consistent across site, Action and Directory info
- [ ] Directory information up-to-date
- [ ] Testing instructions up-to-date
## Testing
- [ ] Unit test added
- [ ] Invocation works in the new language
- [ ] Tested on real device in alpha
## General deployment
- [ ] _master_ branch deployed to Firebase
- [ ] Dialogflow fullfilment url pointing to Firebase Function
<file_sep>/packages/cloud-functions/i18n/index.js
const i18next = require("i18next").default;
module.exports.i18next = i18next;
module.exports.initLocale = async function() {
await i18next.init({
debug: false,
interpolation: {
defaultVariables: {
homepageUrl: "http://git.io/nightscoutstatus"
}
},
resources: {
da: require("./locales/da.json"),
de: require("./locales/de.json"),
en: require("./locales/en.json"),
es: require("./locales/es.json"),
fr: require("./locales/fr.json"),
hi: require("./locales/hi.json"),
id: require("./locales/id.json"),
it: require("./locales/it.json"),
ja: require("./locales/ja.json"),
ko: require("./locales/ko.json"),
nl: require("./locales/nl.json"),
no: require("./locales/no.json"),
pl: require("./locales/pl.json"),
pt: require("./locales/pt.json"),
ru: require("./locales/ru.json"),
sv: require("./locales/sv.json"),
th: require("./locales/th.json"),
uk: require("./locales/uk.json"),
zh: require("./locales/zh.json")
}
});
};
<file_sep>/README.md
# Nightscout for Google Home & Google Assistant
### ⚠ _Heads up!_ Nightscout Status has been replaced by [Gluco Check](https://github.com/nielsmaerten/gluco-check#readme).
We recommend you [upgrade to Gluco Check](https://glucocheck.app) if it's available in your preferred language.
If your language is not supported, you [can help us translate](https://pages.glucocheck.app/translations).
Nightscout Status was [taken offline](https://pages.glucocheck.app/nightscout-status) by Google in October 2021.
---
## Ask Google about your glucose:
> "Hey Google, talk to Nightscout Status"
>> "109 and stable as of 4 minutes ago."
## Getting started
1. Go to https://git.io/nightscoutstatus
2. Sign in with your Google Account
3. Enter your Nightscout URL
4. Say: _"OK Google, Talk to Nightscout Status"_
5. **(Optional)** You can shorten this using [Routines](https://support.google.com/googlehome/answer/7029585?co=GENIE.Platform%3DAndroid&hl=en) (for example: _"Ok Google, check my sugar"_)
## Terms
Privacy policy: https://nielsmaerten.github.io/nightscout-assistant/#/en/terms
Google Assistant is a trademark of Google Inc.
This service is not affiliated to the Nightscout Project
## Translations
- <NAME> (Swedish)
- <NAME> (Italian)
- JonnyJohnson (German)
- Davmartes (Spanish)
- <NAME> (Japanese)
- <NAME> (French)
- <NAME> (Portuguese)
- Kasiawu (Polish)
- Troldmanden (Danish)
- <NAME> (Norwegian)
- Can you help us translate? Visit https://crowdin.com/project/nightscout-status
<file_sep>/packages/webapp/src/main.js
import Vue from "vue";
import i18next from "i18next";
import VueI18Next from "@panter/vue-i18next";
import XHR from "i18next-xhr-backend";
import App from "./App.vue";
import router from "./router";
import store from "./store";
Vue.config.productionTip = false;
Vue.use(VueI18Next);
i18next.use(XHR).init({
fallbackLng: "en",
defaultNS: "translation",
backend: {
loadPath: location.origin + "/nightscout-assistant/locales/{{lng}}.json"
}
});
const i18n = new VueI18Next(i18next);
new Vue({
router,
store,
i18n,
render: h => h(App)
}).$mount("#app");
<file_sep>/packages/cloud-functions/test/stubs/nightscout.js
const sinon = require("sinon");
const proxyquire = require("proxyquire");
// Stub HTTP calls to Nightscout APIs with this canned response:
let stubs = {
"node-fetch": sinon.stub().returns({
ok: true,
json: sinon.stub().returns([
{
sgv: 100,
direction: "Flat"
}
])
})
};
module.exports = proxyquire("../../nightscout", stubs);
|
2903b082c60b14e2f646667d879ae13432035ce1
|
[
"JavaScript",
"Markdown"
] | 8 |
JavaScript
|
nielsmaerten/nightscout-assistant
|
55f7bbc1c86f2de6d6f41ff7b5f0edddbaf912ea
|
e6e3a90e5cc8d4bcd77f0a79cd03996356d020cd
|
refs/heads/master
|
<repo_name>bbrowning/knative-openshift-ingress<file_sep>/pkg/apis/route/v1/addtoscheme_route_v1.go
package v1
import (
"github.com/openshift-knative/knative-openshift-ingress/pkg/apis"
routev1 "github.com/openshift/api/route/v1"
)
func init() {
apis.AddToSchemes = append(apis.AddToSchemes, routev1.SchemeBuilder.AddToScheme)
}
<file_sep>/pkg/apis/route/group.go
// Package route contains route API versions
package route
<file_sep>/pkg/apis/networking/group.go
// Package networking contains networking API versions
package networking
<file_sep>/pkg/controller/common/reconciler.go
package common
import (
"context"
"fmt"
"github.com/openshift-knative/knative-openshift-ingress/pkg/controller/resources"
routev1 "github.com/openshift/api/route/v1"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"knative.dev/pkg/logging"
"knative.dev/serving/pkg/apis/networking"
networkingv1alpha1 "knative.dev/serving/pkg/apis/networking/v1alpha1"
"knative.dev/serving/pkg/apis/serving"
"sigs.k8s.io/controller-runtime/pkg/client"
)
type BaseIngressReconciler struct {
Client client.Client
}
func (r *BaseIngressReconciler) ReconcileIngress(ctx context.Context, ci networkingv1alpha1.IngressAccessor) error {
logger := logging.FromContext(ctx)
if ci.GetDeletionTimestamp() != nil {
return r.reconcileDeletion(ctx, ci)
}
logger.Infof("Reconciling ingress :%v", ci)
exposed := ci.GetSpec().Visibility == networkingv1alpha1.IngressVisibilityExternalIP
if exposed {
ingressLabels := ci.GetLabels()
selector := map[string]string{
networking.IngressLabelKey: ci.GetName(),
serving.RouteLabelKey: ingressLabels[serving.RouteLabelKey],
serving.RouteNamespaceLabelKey: ingressLabels[serving.RouteNamespaceLabelKey],
}
listOpts := &client.ListOptions{
LabelSelector: labels.SelectorFromSet(selector),
}
var existing routev1.RouteList
if err := r.Client.List(ctx, listOpts, &existing); err != nil {
return err
}
existingMap := routeMap(existing, selector)
routes, err := resources.MakeRoutes(ci)
if err != nil {
return err
}
for _, route := range routes {
logger.Infof("Creating/Updating OpenShift Route for host %s", route.Spec.Host)
if err := r.reconcileRoute(ctx, ci, route); err != nil {
return fmt.Errorf("failed to create route for host %s: %v", route.Spec.Host, err)
}
delete(existingMap, route.Name)
}
// If routes remains in existingMap, it must be obsoleted routes. Clean them up.
for _, rt := range existingMap {
logger.Infof("Deleting obsoleted route for host: %s", rt.Spec.Host)
if err := r.deleteRoute(ctx, &rt); err != nil {
return err
}
}
} else {
if err := r.deleteRoutes(ctx, ci); err != nil {
return err
}
}
logger.Info("Ingress successfully synced")
return nil
}
func routeMap(routes routev1.RouteList, selector map[string]string) map[string]routev1.Route {
mp := make(map[string]routev1.Route, len(routes.Items))
for _, route := range routes.Items {
// TODO: This routeFilter is used only for testing as fake client does not support list option
// and we can't bump the osdk version quickly. ref:
// https://github.com/openshift-knative/knative-openshift-ingress/pull/24#discussion_r341804021
if routeLabelFilter(route, selector) {
mp[route.Name] = route
}
}
return mp
}
// routeLabelFilter verifies if the route has required labels.
func routeLabelFilter(route routev1.Route, selector map[string]string) bool {
labels := route.GetLabels()
for k, v := range selector {
if labels[k] != v {
return false
}
}
return true
}
func (r *BaseIngressReconciler) deleteRoute(ctx context.Context, route *routev1.Route) error {
logger := logging.FromContext(ctx)
logger.Infof("Deleting OpenShift Route for host %s", route.Spec.Host)
if err := r.Client.Delete(ctx, route); err != nil {
return fmt.Errorf("failed to delete obsoleted route for host %s: %v", route.Spec.Host, err)
}
logger.Infof("Deleted OpenShift Route %q in namespace %q", route.Name, route.Namespace)
return nil
}
func (r *BaseIngressReconciler) deleteRoutes(ctx context.Context, ci networkingv1alpha1.IngressAccessor) error {
listOpts := &client.ListOptions{
LabelSelector: labels.SelectorFromSet(map[string]string{
networking.IngressLabelKey: ci.GetName(),
}),
}
var routeList routev1.RouteList
if err := r.Client.List(ctx, listOpts, &routeList); err != nil {
return err
}
for _, route := range routeList.Items {
if err := r.deleteRoute(ctx, &route); err != nil {
return err
}
}
return nil
}
func (r *BaseIngressReconciler) reconcileRoute(ctx context.Context, ci networkingv1alpha1.IngressAccessor, desired *routev1.Route) error {
logger := logging.FromContext(ctx)
// Check if this Route already exists
route := &routev1.Route{}
err := r.Client.Get(ctx, types.NamespacedName{Name: desired.Name, Namespace: desired.Namespace}, route)
if err != nil && errors.IsNotFound(err) {
err = r.Client.Create(ctx, desired)
if err != nil {
logger.Errorf("Failed to create OpenShift Route %q in namespace %q: %v", desired.Name, desired.Namespace, err)
return err
}
logger.Infof("Created OpenShift Route %q in namespace %q", desired.Name, desired.Namespace)
} else if err != nil {
return err
} else if !equality.Semantic.DeepEqual(route.Spec, desired.Spec) {
// Don't modify the informers copy
existing := route.DeepCopy()
existing.Spec = desired.Spec
existing.Annotations = desired.Annotations
err = r.Client.Update(ctx, existing)
if err != nil {
logger.Errorf("Failed to update OpenShift Route %q in namespace %q: %v", desired.Name, desired.Namespace, err)
return err
}
}
return nil
}
func (r *BaseIngressReconciler) reconcileDeletion(ctx context.Context, ci networkingv1alpha1.IngressAccessor) error {
// TODO: something with a finalizer? We're using owner refs for
// now, but really shouldn't be using owner refs from
// cluster-scoped ClusterIngress to a namespace-scoped K8s
// Service.
return nil
}
<file_sep>/pkg/apis/networking/v1alpha1/addtoscheme_networking_v1alpha1.go
package v1alpha1
import (
"github.com/openshift-knative/knative-openshift-ingress/pkg/apis"
networkingv1alpha1 "knative.dev/serving/pkg/apis/networking/v1alpha1"
)
func init() {
apis.AddToSchemes = append(apis.AddToSchemes, networkingv1alpha1.SchemeBuilder.AddToScheme)
}
|
81978ed2aef3e672bd502861f482a7fb33b65b1d
|
[
"Go"
] | 5 |
Go
|
bbrowning/knative-openshift-ingress
|
8eda6301461d0de05471745281e07350873b78ea
|
4cf6d8719895705828ef138c6a8653f7a65a8852
|
refs/heads/master
|
<file_sep>// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
//#pragma once
//#include "targetver.h"
//#include <stdio.h>
//#include <tchar.h>
#ifndef _MAIN_H
#define _MAIN_H
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gl\gl.h> // Header File For The OpenGL32 Library
#include <gl\glu.h> // Header File For The GLu32 Library
//#include <string> // Used for our STL string objects
//#include <fstream> // Used for our ifstream object to load text files
//using namespace std;
#include "gl/glext.h"
#define SCREEN_WIDTH 1024 // We want our screen width 800 pixels
#define SCREEN_HEIGHT 768 // We want our screen height 600 pixels
#define SCREEN_DEPTH 32 // We want 16 bits per pixel
extern bool g_bFullScreen; // Set full screen as default
extern HWND g_hWnd; // This is the handle for the window
extern RECT g_rRect; // This holds the window dimensions
extern HDC g_hDC; // General HDC - (handle to device context)
extern HGLRC g_hRC; // General OpenGL_DC - Our Rendering Context for OpenGL
extern HINSTANCE g_hInstance; // This holds our window hInstance
extern int window_width;
extern int window_height;
#include "src/camera/Camera.h"
//#include "src/camera/Camera.h"
//#include "CShader.h"
#include "src/shaders/shader.h"
// This is our MAIN() for windows
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hprev, PSTR cmdline, int ishow);
// The window proc which handles all of window's messages.
LRESULT CALLBACK WinProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
// This controls our main program loop
WPARAM MainLoop();
// This changes the screen to full screen mode
void ChangeToFullScreen();
// This is our own function that makes creating a window modular and easy
HWND CreateMyWindow(LPSTR strWindowName, int width, int height, DWORD dwStyle, bool bFullScreen, HINSTANCE hInstance);
// This allows us to configure our window for OpenGL and back buffering
bool bSetupPixelFormat(HDC hdc);
// This inits our screen translations and projections
void SizeOpenGLScreen(int width, int height);
// This sets up OpenGL
void InitializeOpenGL(int width, int height);
// This initializes the whole program
void Init(HWND hWnd);
// This draws everything to the screen
void RenderScene();
// This frees all our memory in our program
void DeInit();
#endif
/////////////////////////////////////////////////////////////////////////////////
//
// * QUICK NOTES *
//
// We included shader.h to this file, nothing else.
//
//
// © 2000-2005 GameTutorials<file_sep>---Demo navigation---
Hold RIGHT mouse button to rotate camera
W,A,S,D to move camera
SPACE - enable/disable culling
'H' - enable/disable objects rendering (and transfering data to gpu)
'0' - enable/disable multithreading
'1' - use simple c++, CPU, Bounding Spheres culling
'2' - use simple c++, CPU, AABB culling
'3' - use simple c++, CPU, OBB culling
'4' - use SSE Bounding Spheres culling
'5' - use SSE AABB culling
'6' - use SSE OBB culling
'7' - use GPU culling
---Author---
Code written by <NAME>. December, 2016
www.wizards-laboratory.com
E-mail: <EMAIL><file_sep>#pragma once
#include <windows.h>
class Timer
{
public:
Timer(void);
~Timer(void);
void StartTiming();
double TimeElapsed();
double TimeElapsedInMS();
private:
UINT64 StartTime;
double ElapsedTime;
};
void InitTimeOperation();<file_sep>#include "timer.h"
Timer::Timer(void)
{
}
Timer::~Timer(void)
{
}
static UINT64 freq; //timer frequency
void InitTimeOperation()
{
LARGE_INTEGER s;
QueryPerformanceFrequency(&s);
freq=s.QuadPart;
}
UINT64 Time()
{
LARGE_INTEGER s;
QueryPerformanceCounter(&s);
return s.QuadPart;
}
UINT64 GetTicksTime()
{
LARGE_INTEGER s;
QueryPerformanceCounter(&s);
return ((s.QuadPart)*1000000/freq);
}
void Timer::StartTiming()
{
LARGE_INTEGER s;
QueryPerformanceCounter(&s);
StartTime=s.QuadPart;
}
//in seconds
double Timer::TimeElapsed()
{
ElapsedTime=(double)((Time()-StartTime)/freq);
return ElapsedTime;
}
double Timer::TimeElapsedInMS()
{
ElapsedTime = (double)((Time() - StartTime) * 1000.0 / freq);
return ElapsedTime;
}<file_sep>#ifndef _UTILITIES_H
#define _UTILITIES_H
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <process.h>
#include <mmsystem.h>
#include <math.h>
#include <gl\gl.h> // Header File For The OpenGL32 Library
#include <gl\glu.h> // Header File For The GLu32 Library
#include "../glext/glext.h"
#define del_it(a) if (a) { delete a; a = NULL; }
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------vertex buffer
const int VBO_STRUCT_MAX_ELEMENTS = 10;
//describes shader vertex declaration element
struct VboElement
{
int number_of_elements;
int pointer_offset;
GLenum elem_type;
};
//structure that contains Vertex buffer data, description
struct RenderElementDescription
{
int struct_size;
int num_verts;
void *data_pointer;
GLenum vbo_usage;
VboElement elements[VBO_STRUCT_MAX_ELEMENTS];
int num_vbo_elements;
void init(int in_struct_size, int in_num_verts, void* in_data_pointer, GLenum in_vbo_usage, int in_num_vbo_elements, VboElement *in_elements)
{
struct_size = in_struct_size;
num_verts = in_num_verts;
data_pointer = in_data_pointer;
vbo_usage = in_vbo_usage;
num_vbo_elements = in_num_vbo_elements;
for (int i = 0; i < num_vbo_elements; i++)
{
elements[i].number_of_elements = in_elements[i].number_of_elements;
elements[i].pointer_offset = in_elements[i].pointer_offset;
elements[i].elem_type = in_elements[i].elem_type;
}
}
};
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------other
//create texture
void create_simple_texture(GLuint &tex_id, int width, int height, GLenum internal_format, GLenum format, GLint filtration1, GLint filtration2, GLint wrap, GLenum type);
//create VAO, vertex array
void create_render_element(GLuint &vao_id,
GLuint &vbo_id, RenderElementDescription &desc,
bool use_ibo, GLuint &ibo_id, int num_indices, int *indices);
//shader
GLuint init_shader(const char* vertex_shader_file, const char* frag_shader_file, const char* geometry_shader_file = NULL, bool call_link_shader = true);
void link_shader(GLuint shaderProgram);
//debug
void clearDebugLog();
void CALLBACK DebugCallback(unsigned int source, unsigned int type, unsigned int id,
unsigned int severity, int length,
const char* message, const void* userParam);
#endif<file_sep>#include "Utilities.h"
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------textures
void create_simple_texture(GLuint &tex_id, int width, int height, GLenum internal_format, GLenum format, GLint filtration1, GLint filtration2, GLint wrap, GLenum type)
{
glGenTextures(1, &tex_id);
glBindTexture(GL_TEXTURE_2D, tex_id);
glTexParameterIiv(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, &filtration1);
glTexParameterIiv(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, &filtration2);
glTexParameterIiv(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, &wrap);
glTexParameterIiv(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, &wrap);
glTexParameterIiv(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, &wrap);
glTexImage2D(GL_TEXTURE_2D, 0, internal_format, width, height, 0, format, type, 0);
glBindTexture(GL_TEXTURE_2D, 0);
}
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------vertex buffers
void create_render_element(GLuint &vao_id,
GLuint &vbo_id, RenderElementDescription &desc,
bool use_ibo, GLuint &ibo_id, int num_indices, int *indices)
{
//create vertex buffer
glGenBuffers(1, &vbo_id);
glBindBuffer(GL_ARRAY_BUFFER, vbo_id);
glBufferData(GL_ARRAY_BUFFER, desc.struct_size * desc.num_verts, desc.data_pointer, desc.vbo_usage);
//create index buffer
if (use_ibo)
{
glGenBuffers(1, &ibo_id);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_id);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(int)* num_indices, &indices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
//create vertex array
glGenVertexArrays(1, &vao_id);
glBindVertexArray(vao_id);
if (use_ibo)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_id);
glBindBuffer(GL_ARRAY_BUFFER, vbo_id);
//bind vertex attributes
for (int i = 0; i < desc.num_vbo_elements; i++)
{
glEnableVertexAttribArray(i);
glVertexAttribPointer((GLuint)i, desc.elements[i].number_of_elements, desc.elements[i].elem_type, GL_FALSE, desc.struct_size, (GLvoid*)(desc.elements[i].pointer_offset));
}
glBindVertexArray(0);
}
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------shaders
void _print_programme_info_log(GLuint programme)
{
int max_length = 2048;
int actual_length = 0;
char log[2048];
glGetProgramInfoLog(programme, max_length, &actual_length, log);
printf("program info log for GL index %u:\n%s", programme, log);
}
bool is_valid(GLuint programme)
{
glValidateProgram(programme);
int params = -1;
glGetProgramiv(programme, GL_VALIDATE_STATUS, ¶ms);
printf("program %i GL_VALIDATE_STATUS = %i\n", programme, params);
if (GL_TRUE != params)
{
_print_programme_info_log(programme);
return false;
}
return true;
}
const char* GL_type_to_string(GLenum type)
{
switch (type)
{
case GL_BOOL: return "bool";
case GL_INT: return "int";
case GL_FLOAT: return "float";
case GL_FLOAT_VEC2: return "vec2";
case GL_FLOAT_VEC3: return "vec3";
case GL_FLOAT_VEC4: return "vec4";
case GL_FLOAT_MAT2: return "mat2";
case GL_FLOAT_MAT3: return "mat3";
case GL_FLOAT_MAT4: return "mat4";
case GL_SAMPLER_2D: return "sampler2D";
case GL_SAMPLER_3D: return "sampler3D";
case GL_SAMPLER_CUBE: return "samplerCube";
case GL_SAMPLER_2D_SHADOW: return "sampler2DShadow";
default: break;
}
return "other";
}
void shader_print_all_info(GLuint programme)
{
printf("shader programme %i info:\n", programme);
int params = -1;
glGetProgramiv(programme, GL_LINK_STATUS, ¶ms);
printf("GL_LINK_STATUS = %i\n", params);
glGetProgramiv(programme, GL_ATTACHED_SHADERS, ¶ms);
printf("GL_ATTACHED_SHADERS = %i\n", params);
glGetProgramiv(programme, GL_ACTIVE_ATTRIBUTES, ¶ms);
printf("GL_ACTIVE_ATTRIBUTES = %i\n", params);
for (int i = 0; i < params; i++)
{
char name[64];
int max_length = 64;
int actual_length = 0;
int size = 0;
GLenum type;
glGetActiveAttrib(
programme,
i,
max_length,
&actual_length,
&size,
&type,
name
);
if (size > 1)
{
for (int j = 0; j < size; j++)
{
char long_name[64];
sprintf(long_name, "%s[%i]", name, j);
int location = glGetAttribLocation(programme, long_name);
printf(" %i) type:%s name:%s location:%i\n",
i, GL_type_to_string(type), long_name, location);
}
}
else
{
int location = glGetAttribLocation(programme, name);
printf(" %i) type:%s name:%s location:%i\n",
i, GL_type_to_string(type), name, location);
}
}
glGetProgramiv(programme, GL_ACTIVE_UNIFORMS, ¶ms);
printf("GL_ACTIVE_UNIFORMS = %i\n", params);
for (int i = 0; i < params; i++)
{
char name[64];
int max_length = 64;
int actual_length = 0;
int size = 0;
GLenum type;
glGetActiveUniform(
programme,
i,
max_length,
&actual_length,
&size,
&type,
name
);
if (size > 1) {
for (int j = 0; j < size; j++)
{
char long_name[64];
sprintf(long_name, "%s[%i]", name, j);
int location = glGetUniformLocation(programme, long_name);
printf(" %i) type:%s name:%s location:%i\n",
i, GL_type_to_string(type), long_name, location);
}
}
else
{
int location = glGetUniformLocation(programme, name);
printf(" %i) type:%s name:%s location:%i\n",
i, GL_type_to_string(type), name, location);
}
}
_print_programme_info_log(programme);
printf("\n\n");
}
char* load_file(const char* file_name)
{
//read file
FILE *file = fopen(file_name, "rb");
if (!file)
{
fprintf(stderr, "Shader::Shader(): can`t open \"%s\" file\n", file_name);
return NULL;
}
fseek(file, 0, SEEK_END);
int size = ftell(file);
char *data = new char[size + 1];
data[size] = '\0';
fseek(file, 0, SEEK_SET);
fread(data, 1, size, file);
fclose(file);
return data;
}
void printShaderInfoLog(GLuint obj)
{
int infologLength = 0;
int charsWritten = 0;
char *infoLog;
glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &infologLength);
if (infologLength > 0)
{
infoLog = (char *)malloc(infologLength);
glGetShaderInfoLog(obj, infologLength, &charsWritten, infoLog);
fprintf(stderr, "ShaderInfoLog\n%s\n", &infoLog[0]);
free(infoLog);
}
}
GLuint createShader(GLenum type, const GLchar* src)
{
GLuint shader = glCreateShader(type);
glShaderSource(shader, 1, &src, nullptr);
glCompileShader(shader);
GLint compiled;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
fprintf(stderr, "---Shader error in vertex shader \"%s\" file\n", "name");
printShaderInfoLog(shader);
}
return shader;
}
GLuint init_shader(const char* vertex_shader_file, const char* frag_shader_file, const char* geometry_shader_file, bool call_link_shader)
{
char tmp_str[64];
//load vertex shader
const char *shaders_folder = "data/shaders/";
sprintf(&tmp_str[0], "%s%s.txt", shaders_folder, vertex_shader_file);
const char* VS_src = load_file(&tmp_str[0]);
if (!VS_src)
return -1;
//load pixel shader
sprintf(&tmp_str[0], "%s%s.txt", shaders_folder, frag_shader_file);
const char* PS_src = load_file(&tmp_str[0]);
if (!PS_src)
return -1;
//load geometry shader
char* GS_src = NULL;
if (geometry_shader_file)
{
sprintf(&tmp_str[0], "%s%s.txt", shaders_folder, geometry_shader_file);
GS_src = load_file(&tmp_str[0]);
if (!GS_src)
return -1;
}
//create shader, program
GLuint vertexShader = createShader(GL_VERTEX_SHADER, VS_src);
GLuint fragmentShader = createShader(GL_FRAGMENT_SHADER, PS_src);
GLuint geometryShader = geometry_shader_file ? createShader(GL_GEOMETRY_SHADER, GS_src) : -1;
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
if (geometry_shader_file)
glAttachShader(shaderProgram, geometryShader);
glBindAttribLocationARB(shaderProgram, 0, "s_attribute_0");
glBindAttribLocationARB(shaderProgram, 1, "s_attribute_1");
glBindAttribLocationARB(shaderProgram, 2, "s_attribute_2");
glBindAttribLocationARB(shaderProgram, 3, "s_attribute_3");
glBindAttribLocationARB(shaderProgram, 4, "s_attribute_4");
glBindAttribLocationARB(shaderProgram, 5, "s_attribute_5");
glBindAttribLocationARB(shaderProgram, 6, "s_attribute_6");
glBindAttribLocationARB(shaderProgram, 0, "s_pos");
glBindAttribLocationARB(shaderProgram, 1, "s_normal");
glBindAttribLocationARB(shaderProgram, 2, "s_uv");
glAttachShader(shaderProgram, fragmentShader);
if (call_link_shader)
link_shader(shaderProgram);
return shaderProgram;
}
void link_shader(GLuint shaderProgram)
{
glLinkProgram(shaderProgram);
//check if link successed
GLint linked;
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &linked);
if (!linked) {
fprintf(stderr, "Shader::Shader(): GLSL relink error\n\n");
return;
}
glValidateProgram(shaderProgram);
GLint validated;
glGetObjectParameterivARB(shaderProgram, GL_OBJECT_VALIDATE_STATUS_ARB, &validated);
if (!validated) {
fprintf(stderr, "Shader::Shader(): GLSL relink error\n\n");
return;
}
//bind textures
glUseProgram(shaderProgram);
for (int i = 0; i < 20; i++) {
char texture[32];
sprintf(texture, "s_texture_%d", i);
GLint location = glGetUniformLocation(shaderProgram, texture);
if (location >= 0)
glUniform1i(location, i);
}
glUseProgram(0);
}
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------debuging
bool opengl_debug_mode_enabled = false;
void clearDebugLog()
{
FILE* f;
f = fopen("Debug.txt", "w");
if (f)
fclose(f);
}
void DebugOutputToFile(unsigned int source, unsigned int type, unsigned int id,
unsigned int severity, const char* message)
{
FILE* f;
f = fopen("Debug.txt", "a");
if (f)
{
char debSource[16], debType[20], debSev[7];
if (source == GL_DEBUG_SOURCE_API_ARB)
strcpy(debSource, "OpenGL");
else if (source == GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB)
strcpy(debSource, "Windows");
else if (source == GL_DEBUG_SOURCE_SHADER_COMPILER_ARB)
strcpy(debSource, "Shader Compiler");
else if (source == GL_DEBUG_SOURCE_THIRD_PARTY_ARB)
strcpy(debSource, "Third Party");
else if (source == GL_DEBUG_SOURCE_APPLICATION_ARB)
strcpy(debSource, "Application");
else if (source == GL_DEBUG_SOURCE_OTHER_ARB)
strcpy(debSource, "Other");
if (type == GL_DEBUG_TYPE_ERROR_ARB)
strcpy(debType, "Error");
else if (type == GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB)
strcpy(debType, "Deprecated behavior");
else if (type == GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB)
strcpy(debType, "Undefined behavior");
else if (type == GL_DEBUG_TYPE_PORTABILITY_ARB)
strcpy(debType, "Portability");
else if (type == GL_DEBUG_TYPE_PERFORMANCE_ARB)
strcpy(debType, "Performance");
else if (type == GL_DEBUG_TYPE_OTHER_ARB)
strcpy(debType, "Other");
if (severity == GL_DEBUG_SEVERITY_HIGH_ARB)
strcpy(debSev, "High");
else if (severity == GL_DEBUG_SEVERITY_MEDIUM_ARB)
strcpy(debSev, "Medium");
else if (severity == GL_DEBUG_SEVERITY_LOW_ARB)
strcpy(debSev, "Low");
fprintf(f, "Source:%s\tType:%s\tID:%d\tSeverity:%s\tMessage:%s\n",
debSource, debType, id, debSev, message);
fclose(f);
}
}
void CheckDebugLog()
{
unsigned int count = 10; // max. num. of messages that will be read from the log
int bufsize = 2048;
unsigned int* sources = new unsigned int[count];
unsigned int* types = new unsigned int[count];
unsigned int* ids = new unsigned int[count];
unsigned int* severities = new unsigned int[count];
int* lengths = new int[count];
char* messageLog = new char[bufsize];
unsigned int retVal = glGetDebugMessageLogARB(count, bufsize, sources, types, ids,
severities, lengths, messageLog);
if (retVal > 0)
{
unsigned int pos = 0;
for (unsigned int i = 0; i<retVal; i++)
{
DebugOutputToFile(sources[i], types[i], ids[i], severities[i],
&messageLog[pos]);
pos += lengths[i];
}
}
delete[] sources;
delete[] types;
delete[] ids;
delete[] severities;
delete[] lengths;
delete[] messageLog;
}
void CALLBACK DebugCallback(unsigned int source, unsigned int type, unsigned int id,
unsigned int severity, int length,
const char* message, const void* userParam)
{
DebugOutputToFile(source, type, id, severity, message);
}
<file_sep>#include <windows.h>
#include "Random.h"
//fast random funcs
float RNDtable[65536];
static WORD RNDcurrent=0;
void rndInit(void){ srand(0); for(int i=0;i<65536;i++) RNDtable[i]=((float)rand())/32767.0f; }
float rnd(float from,float to) { RNDcurrent++; return from+(to-from)*RNDtable[RNDcurrent]; if (RNDcurrent>=65535) RNDcurrent=0; }
float rnd01() { RNDcurrent++; return RNDtable[RNDcurrent]; if (RNDcurrent>=65535) RNDcurrent=0; }
void rndSeed(int seed) { RNDcurrent=seed; if (RNDcurrent>=65535) RNDcurrent=0; }
float rndTable(WORD index) {return RNDtable[index];}<file_sep>#ifndef _MAIN_H
#define _MAIN_H
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <process.h>
#include <mmsystem.h>
#include <math.h>
#include <gl\gl.h> // Header File For The OpenGL32 Library
#include <gl\glu.h> // Header File For The GLu32 Library
//#include <gl\glcorearb.h>
#include "../glext/glext.h"
#define SCREEN_WIDTH 1600 //1600 1024 //1900 // We want our screen width 800 pixels
#define SCREEN_HEIGHT 900 //900 768//1000 // We want our screen height 600 pixels
#define SCREEN_DEPTH 32 // We want 16 bits per pixel
extern bool g_bFullScreen; // Set full screen as default
extern HWND g_hWnd; // This is the handle for the window
extern RECT g_rRect; // This holds the window dimensions
extern HDC g_hDC; // General HDC - (handle to device context)
extern HGLRC g_hRC; // General OpenGL_DC - Our Rendering Context for OpenGL
extern HINSTANCE g_hInstance; // This holds our window hInstance
extern int window_width;
extern int window_height;
/*
#include "../camera/frustum.h"
#include "../manager/ShaderManager.h"
#include "../shaders/shader.h"
#include "../manager/TextureManager.h"
#include "../timer/timer.h"
#include "../random/random.h"
#include "../font/font.h"
#include "../manager/fontmanager.h"
#include "../game_logic/map.h"
#include "../game_logic/list.h"
#include "../procedural_textures/perlinNoise.h"
#include "../procedural_textures/noise2d.h"
//#include "../game_logic/CreaturesEditor.h"
#include "../game_logic/Spline.h"
#include "../game_logic/CreateMesh.h"
#include "Utilities.h"
*/
#include "../timer/timer.h"
#include "../random/random.h"
#include "Utilities.h"
#include "../Camera/Camera.h"
#include "../Camera/Frustum.h"
//------------------------------------------------------------------------------------------------------------------------------------------------------shaders
const int MAX_SHADER_UNIFORMS = 10;
enum ShaderUniformVariableType
{
FLOAT_UNIFORM_TYPE,
INT_UNIFORM_TYPE,
};
struct ShaderUniformVariable
{
ShaderUniformVariable() : type(FLOAT_UNIFORM_TYPE), dimmension(4), address(NULL), location(-1), count(1)
{}
ShaderUniformVariableType type;
int dimmension;
void *address;
GLuint location;
int count;
};
struct Shader
{
Shader() : programm_id(-1), num_uniforms(0)
{}
~Shader()
{
}
void add_uniform(const char* name, int size, void *address, ShaderUniformVariableType type = FLOAT_UNIFORM_TYPE, int num_elements = 1)
{
uniform_variables[num_uniforms].type = type;
uniform_variables[num_uniforms].dimmension = size;
uniform_variables[num_uniforms].address = address;
uniform_variables[num_uniforms].location = glGetUniformLocation(programm_id, name);
uniform_variables[num_uniforms].count = num_elements;
num_uniforms++;
}
void bind(bool just_bind = false)
{
glUseProgram(programm_id);
if (just_bind)
return;
for (int i = 0; i < num_uniforms; i++)
{
switch (uniform_variables[i].dimmension)
{
case 1:
if (uniform_variables[i].type == FLOAT_UNIFORM_TYPE)
glUniform1f(uniform_variables[i].location, *static_cast<GLfloat*>(uniform_variables[i].address));
else
glUniform1i(uniform_variables[i].location, *static_cast<GLint*>(uniform_variables[i].address));
break;
case 2:
glUniform2fv(uniform_variables[i].location, uniform_variables[i].count, static_cast<GLfloat*>(uniform_variables[i].address));
break;
case 3:
glUniform3fv(uniform_variables[i].location, uniform_variables[i].count, static_cast<GLfloat*>(uniform_variables[i].address));
break;
case 4:
glUniform4fv(uniform_variables[i].location, uniform_variables[i].count, static_cast<GLfloat*>(uniform_variables[i].address));
break;
case 9:
glUniformMatrix3fv(uniform_variables[i].location, 1, false, static_cast<GLfloat*>(uniform_variables[i].address));
break;
case 16:
glUniformMatrix4fv(uniform_variables[i].location, 1, false, static_cast<GLfloat*>(uniform_variables[i].address));
break;
}
}
//glActiveTexture(GL_TEXTURE0);
//glBindTexture(GL_TEXTURE_2D, tex_id);
//glBindSampler(0, Sampler);
//GLint uniform_mytexture = glGetUniformLocation(selected_shader_program, "tex0");
//glUniform1i(uniform_mytexture, 0);
}
GLuint programm_id;
ShaderUniformVariable uniform_variables[MAX_SHADER_UNIFORMS];
int num_uniforms;
};
//------------------------------------------------------------------------------------------------------------------------------------------------------voids
void CheckDebugLog();
// This is our MAIN() for windows
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hprev, PSTR cmdline, int ishow);
// The window proc which handles all of window's messages.
LRESULT CALLBACK WinProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
// This controls our main program loop
WPARAM MainLoop();
// This changes the screen to full screen mode
void ChangeToFullScreen();
// This is our own function that makes creating a window modular and easy
HWND CreateMyWindow(LPSTR strWindowName, int width, int height, DWORD dwStyle, bool bFullScreen, HINSTANCE hInstance);
// This allows us to configure our window for OpenGL and back buffering
bool bSetupPixelFormat(HDC hdc);
// This inits our screen translations and projections
void SizeOpenGLScreen(int width, int height);
// This sets up OpenGL
void InitializeOpenGL(int width, int height);
// This initializes the whole program
void Init(HWND hWnd);
// This draws everything to the screen
void RenderScene();
// This frees all our memory in our program
void DeInit();
void ShutDown();
void process_key(int key);
extern bool opengl_debug_mode_enabled;
#endif<file_sep>#ifndef __MATHLIB_H__
#define __MATHLIB_H__
#include <math.h>
#define EPSILON 1e-6f
#define PI 3.14159265358979323846f
#define PI2 6.28318530717958647692f
#define PI1_2 1.570796326794897f
#define DEG2RAD (PI / 180.0f)
#define RAD2DEG (180.0f / PI)
#define MAX(a,b) ((a < b) ? (b) : (a))
#define MIN(a,b) ((a < b) ? (a) : (b))
#define CLAMP(value,a,b) (MIN(MAX((value), a),b))
#define MIX(x,y, a) ((x) * (1 - (a)) + (y) * (a))
#define FRACT(x) (x - int(x))
struct vec2;
struct vec3;
struct vec4;
struct mat3;
struct mat4;
/*****************************************************************************/
/* */
/* vec2 */
/* */
/*****************************************************************************/
struct vec2 {
inline vec2() : x(0), y(0) { }
inline vec2(float x, float y) : x(x), y(y) { }
inline vec2(const float *v) : x(v[0]), y(v[1]) { }
inline vec2(const vec2 &v) : x(v.x), y(v.y) { }
inline int operator==(const vec2 &v) { return (fabs(x - v.x) < EPSILON && fabs(y - v.y) < EPSILON); }
inline int operator!=(const vec2 &v) { return !(*this == v); }
inline const vec2 operator*(float f) const { return vec2(x * f, y * f); }
inline const vec2 operator/(float f) const { return vec2(x / f, y / f); }
inline const vec2 operator+(const vec2 &v) const { return vec2(x + v.x, y + v.y); }
inline const vec2 operator-() const { return vec2(-x, -y); }
inline const vec2 operator-(const vec2 &v) const { return vec2(x - v.x, y - v.y); }
inline vec2 &operator*=(float f) { return *this = *this * f; }
inline vec2 &operator/=(float f) { return *this = *this / f; }
inline vec2 &operator+=(const vec2 &v) { return *this = *this + v; }
inline vec2 &operator-=(const vec2 &v) { return *this = *this - v; }
inline float operator*(const vec2 &v) const { return x * v.x + y * v.y; }
inline operator float*() { return (float*)&x; }
inline operator const float*() const { return (float*)&x; }
inline vec2 mul(const vec2 &v) const {
return vec2(x * v.x, y * v.y);
}
inline float &operator[](int i) { return ((float*)&x)[i]; }
inline const float operator[](int i) const { return ((float*)&x)[i]; }
inline float length() const { return sqrtf(x * x + y * y); }
inline float length2() const { return (x * x + y * y); }
inline float normalize() {
float inv, length = sqrtf(x * x + y * y);
if (length < EPSILON) return 0.0;
inv = 1.0f / length;
x *= inv;
y *= inv;
return length;
}
union {
struct {
float x, y;
};
float v[2];
};
};
/*****************************************************************************/
/* */
/* vec3 */
/* */
/*****************************************************************************/
struct vec3 {
inline vec3() : x(0), y(0), z(0) { }
inline vec3(float x, float y, float z) : x(x), y(y), z(z) { }
inline vec3(const float *v) : x(v[0]), y(v[1]), z(v[2]) { }
inline vec3(const vec3 &v) : x(v.x), y(v.y), z(v.z) { }
inline vec3(vec2 v, float z) : x(v.x), y(v.y), z(z) { }
inline vec3(const vec4 &v);
inline int operator==(const vec3 &v) { return (fabs(x - v.x) < EPSILON && fabs(y - v.y) < EPSILON && fabs(z - v.z) < EPSILON); }
inline int operator!=(const vec3 &v) { return !(*this == v); }
inline const vec3 operator*(float f) const { return vec3(x * f, y * f, z * f); }
inline const vec3 operator/(float f) const { return vec3(x / f, y / f, z / f); }
inline const vec3 operator/(vec3 f) const { return vec3(x / f.x, y / f.y, z / f.z); }
inline const vec3 operator+(const vec3 &v) const { return vec3(x + v.x, y + v.y, z + v.z); }
inline const vec3 operator-() const { return vec3(-x, -y, -z); }
inline const vec3 operator-(const vec3 &v) const { return vec3(x - v.x, y - v.y, z - v.z); }
inline vec3 &operator*=(float f) { return *this = *this * f; }
inline vec3 &operator/=(float f) { return *this = *this / f; }
inline vec3 &operator+=(const vec3 &v) { return *this = *this + v; }
inline vec3 &operator-=(const vec3 &v) { return *this = *this - v; }
inline float operator*(const vec3 &v) const { return x * v.x + y * v.y + z * v.z; }
inline float operator*(const vec4 &v) const;
inline vec3 operator^(const vec3 &v) const {
return vec3
(
y * v.z - z * v.y,
z * v.x - x * v.z,
x * v.y - y * v.x
);
}
inline operator float*() { return (float*)&x; }
inline operator const float*() const { return (float*)&x; }
inline float &operator[](int i) { return ((float*)&x)[i]; }
inline const float operator[](int i) const { return ((float*)&x)[i]; }
inline float length() const { return sqrtf(x * x + y * y + z * z); }
inline float length2() const { return x * x + y * y + z * z; }
inline float normalize() {
float len = sqrtf(x * x + y * y + z * z);
if (len < EPSILON) return 0.0;
float inv = 1.0f / len;
x *= inv;
y *= inv;
z *= inv;
return len;
}
inline vec3 get_min(const vec3 &v) const {
return vec3(MIN(x, v.x), MIN(y, v.y), MIN(z, v.z));
}
inline vec3 get_max(const vec3 &v) const {
return vec3(MAX(x, v.x), MAX(y, v.y), MAX(z, v.z));
}
inline vec3 mul(const vec3 &v) const {
return vec3(x * v.x, y * v.y, z * v.z);
}
inline void cross(const vec3 &v1, const vec3 &v2) {
x = v1.y * v2.z - v1.z * v2.y;
y = v1.z * v2.x - v1.x * v2.z;
z = v1.x * v2.y - v1.y * v2.x;
}
union {
struct {
float x, y, z;
};
float v[3];
};
};
inline vec3 normalize(const vec3 &v) {
float length = v.length();
if (length < EPSILON) return vec3(0, 0, 0);
return v / length;
}
inline vec3 cross(const vec3 &v1, const vec3 &v2) {
vec3 ret;
ret.x = v1.y * v2.z - v1.z * v2.y;
ret.y = v1.z * v2.x - v1.x * v2.z;
ret.z = v1.x * v2.y - v1.y * v2.x;
return ret;
}
inline vec3 saturate(const vec3 &v) {
vec3 ret = v;
if (ret.x < 0.0) ret.x = 0.0;
else if (ret.x > 1.0f) ret.x = 1.0f;
if (ret.y < 0.0) ret.y = 0.0;
else if (ret.y > 1.0f) ret.y = 1.0f;
if (ret.z < 0.0) ret.z = 0.0;
else if (ret.z > 1.0f) ret.z = 1.0f;
return ret;
}
/*****************************************************************************/
/* */
/* vec4 */
/* */
/*****************************************************************************/
struct vec4 {
inline vec4() : x(0), y(0), z(0), w(0) { } //w(1)
inline vec4(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) { }
inline vec4(const float *v) : x(v[0]), y(v[1]), z(v[2]), w(v[3]) { }
inline vec4(const vec3 &v) : x(v.x), y(v.y), z(v.z), w(1) { }
inline vec4(const vec3 &v, float w) : x(v.x), y(v.y), z(v.z), w(w) { }
inline vec4(const vec4 &v) : x(v.x), y(v.y), z(v.z), w(v.w) { }
inline vec4(const vec2 &v1, const vec2 &v2) : x(v1.x), y(v1.y), z(v2.x), w(v2.y) { }
inline bool operator==(const vec4 &v) { return (fabs(x - v.x) < EPSILON && fabs(y - v.y) < EPSILON && fabs(z - v.z) < EPSILON && fabs(w - v.w) < EPSILON); }
inline bool operator!=(const vec4 &v) { return !(*this == v); }
inline const vec4 operator*(float f) const { return vec4(x * f, y * f, z * f, w * f); }
inline const vec4 operator/(float f) const { return vec4(x / f, y / f, z / f, w / f); }
inline const vec4 operator+(const vec4 &v) const { return vec4(x + v.x, y + v.y, z + v.z, w + v.w); }
inline const vec4 operator-() const { return vec4(-x, -y, -z, -w); }
inline const vec4 operator-(const vec4 &v) const { return vec4(x - v.x, y - v.y, z - v.z, w - v.w); }
inline vec4 &operator*=(float f) { return *this = *this * f; }
inline vec4 &operator/=(float f) { return *this = *this / f; }
inline vec4 &operator+=(const vec4 &v) { return *this = *this + v; }
inline vec4 &operator-=(const vec4 &v) { return *this = *this - v; }
inline vec4 mul(const vec4 &v) {
return vec4(x * v.x, y * v.y, z * v.z, w * v.w);
}
inline float operator*(const vec3 &v) const { return x * v.x + y * v.y + z * v.z + w; }
inline float operator*(const vec4 &v) const { return x * v.x + y * v.y + z * v.z + w * v.w; }
inline operator float*() { return (float*)&x; }
inline operator const float*() const { return (float*)&x; }
inline float &operator[](int i) { return ((float*)&x)[i]; }
inline const float operator[](int i) const { return ((float*)&x)[i]; }
union {
struct {
float x, y, z, w;
};
float v[4];
};
};
inline vec3::vec3(const vec4 &v) {
x = v.x;
y = v.y;
z = v.z;
}
inline float vec3::operator*(const vec4 &v) const {
return x * v.x + y * v.y + z * v.z + v.w;
}
/*****************************************************************************/
/* */
/* mat4 */
/* */
/*****************************************************************************/
struct mat4 {
mat4() {
mat[0] = 1.0; mat[4] = 0.0; mat[8] = 0.0; mat[12] = 0.0;
mat[1] = 0.0; mat[5] = 1.0; mat[9] = 0.0; mat[13] = 0.0;
mat[2] = 0.0; mat[6] = 0.0; mat[10] = 1.0; mat[14] = 0.0;
mat[3] = 0.0; mat[7] = 0.0; mat[11] = 0.0; mat[15] = 1.0;
}
mat4(float v1, float v2, float v3, float v4, float v5, float v6, float v7, float v8, float v9, float v10, float v11, float v12, float v13, float v14, float v15, float v16) {
mat[0] = v1; mat[4] = v5; mat[8] = v9; mat[12] = v13;
mat[1] = v2; mat[5] = v6; mat[9] = v10; mat[13] = v14;
mat[2] = v3; mat[6] = v7; mat[10] = v11; mat[14] = v15;
mat[3] = v4; mat[7] = v8; mat[11] = v12; mat[15] = v16;
}
mat4(const vec3 &v) {
translate(v);
}
mat4(float x, float y, float z) {
translate(x, y, z);
}
mat4(const vec3 &axis, float angle) {
rotate(axis, angle);
}
mat4(float x, float y, float z, float angle) {
rotate(x, y, z, angle);
}
mat4(const float *m) {
mat[0] = m[0]; mat[4] = m[4]; mat[8] = m[8]; mat[12] = m[12];
mat[1] = m[1]; mat[5] = m[5]; mat[9] = m[9]; mat[13] = m[13];
mat[2] = m[2]; mat[6] = m[6]; mat[10] = m[10]; mat[14] = m[14];
mat[3] = m[3]; mat[7] = m[7]; mat[11] = m[11]; mat[15] = m[15];
}
mat4(const mat4 &m) {
mat[0] = m[0]; mat[4] = m[4]; mat[8] = m[8]; mat[12] = m[12];
mat[1] = m[1]; mat[5] = m[5]; mat[9] = m[9]; mat[13] = m[13];
mat[2] = m[2]; mat[6] = m[6]; mat[10] = m[10]; mat[14] = m[14];
mat[3] = m[3]; mat[7] = m[7]; mat[11] = m[11]; mat[15] = m[15];
}
vec3 operator*(const vec3 &v) const {
vec3 ret;
ret[0] = mat[0] * v[0] + mat[4] * v[1] + mat[8] * v[2] + mat[12];
ret[1] = mat[1] * v[0] + mat[5] * v[1] + mat[9] * v[2] + mat[13];
ret[2] = mat[2] * v[0] + mat[6] * v[1] + mat[10] * v[2] + mat[14];
return ret;
}
vec3 rotate_vector(const vec3 &v) const {
vec3 ret;
ret[0] = mat[0] * v[0] + mat[4] * v[1] + mat[8] * v[2];
ret[1] = mat[1] * v[0] + mat[5] * v[1] + mat[9] * v[2];
ret[2] = mat[2] * v[0] + mat[6] * v[1] + mat[10] * v[2];
return ret;
}
vec4 operator*(const vec4 &v) const {
vec4 ret;
ret[0] = mat[0] * v[0] + mat[4] * v[1] + mat[8] * v[2] + mat[12] * v[3];
ret[1] = mat[1] * v[0] + mat[5] * v[1] + mat[9] * v[2] + mat[13] * v[3];
ret[2] = mat[2] * v[0] + mat[6] * v[1] + mat[10] * v[2] + mat[14] * v[3];
ret[3] = mat[3] * v[0] + mat[7] * v[1] + mat[11] * v[2] + mat[15] * v[3];
return ret;
}
mat4 operator*(float f) const {
mat4 ret;
ret[0] = mat[0] * f; ret[4] = mat[4] * f; ret[8] = mat[8] * f; ret[12] = mat[12] * f;
ret[1] = mat[1] * f; ret[5] = mat[5] * f; ret[9] = mat[9] * f; ret[13] = mat[13] * f;
ret[2] = mat[2] * f; ret[6] = mat[6] * f; ret[10] = mat[10] * f; ret[14] = mat[14] * f;
ret[3] = mat[3] * f; ret[7] = mat[7] * f; ret[11] = mat[11] * f; ret[15] = mat[15] * f;
return ret;
}
mat4 operator*(const mat4 &m) const {
mat4 ret;
ret[0] = mat[0] * m[0] + mat[4] * m[1] + mat[8] * m[2] + mat[12] * m[3];
ret[1] = mat[1] * m[0] + mat[5] * m[1] + mat[9] * m[2] + mat[13] * m[3];
ret[2] = mat[2] * m[0] + mat[6] * m[1] + mat[10] * m[2] + mat[14] * m[3];
ret[3] = mat[3] * m[0] + mat[7] * m[1] + mat[11] * m[2] + mat[15] * m[3];
ret[4] = mat[0] * m[4] + mat[4] * m[5] + mat[8] * m[6] + mat[12] * m[7];
ret[5] = mat[1] * m[4] + mat[5] * m[5] + mat[9] * m[6] + mat[13] * m[7];
ret[6] = mat[2] * m[4] + mat[6] * m[5] + mat[10] * m[6] + mat[14] * m[7];
ret[7] = mat[3] * m[4] + mat[7] * m[5] + mat[11] * m[6] + mat[15] * m[7];
ret[8] = mat[0] * m[8] + mat[4] * m[9] + mat[8] * m[10] + mat[12] * m[11];
ret[9] = mat[1] * m[8] + mat[5] * m[9] + mat[9] * m[10] + mat[13] * m[11];
ret[10] = mat[2] * m[8] + mat[6] * m[9] + mat[10] * m[10] + mat[14] * m[11];
ret[11] = mat[3] * m[8] + mat[7] * m[9] + mat[11] * m[10] + mat[15] * m[11];
ret[12] = mat[0] * m[12] + mat[4] * m[13] + mat[8] * m[14] + mat[12] * m[15];
ret[13] = mat[1] * m[12] + mat[5] * m[13] + mat[9] * m[14] + mat[13] * m[15];
ret[14] = mat[2] * m[12] + mat[6] * m[13] + mat[10] * m[14] + mat[14] * m[15];
ret[15] = mat[3] * m[12] + mat[7] * m[13] + mat[11] * m[14] + mat[15] * m[15];
return ret;
}
mat4 operator+(const mat4 &m) const {
mat4 ret;
ret[0] = mat[0] + m[0]; ret[4] = mat[4] + m[4]; ret[8] = mat[8] + m[8]; ret[12] = mat[12] + m[12];
ret[1] = mat[1] + m[1]; ret[5] = mat[5] + m[5]; ret[9] = mat[9] + m[9]; ret[13] = mat[13] + m[13];
ret[2] = mat[2] + m[2]; ret[6] = mat[6] + m[6]; ret[10] = mat[10] + m[10]; ret[14] = mat[14] + m[14];
ret[3] = mat[3] + m[3]; ret[7] = mat[7] + m[7]; ret[11] = mat[11] + m[11]; ret[15] = mat[15] + m[15];
return ret;
}
mat4 operator-(const mat4 &m) const {
mat4 ret;
ret[0] = mat[0] - m[0]; ret[4] = mat[4] - m[4]; ret[8] = mat[8] - m[8]; ret[12] = mat[12] - m[12];
ret[1] = mat[1] - m[1]; ret[5] = mat[5] - m[5]; ret[9] = mat[9] - m[9]; ret[13] = mat[13] - m[13];
ret[2] = mat[2] - m[2]; ret[6] = mat[6] - m[6]; ret[10] = mat[10] - m[10]; ret[14] = mat[14] - m[14];
ret[3] = mat[3] - m[3]; ret[7] = mat[7] - m[7]; ret[11] = mat[11] - m[11]; ret[15] = mat[15] - m[15];
return ret;
}
mat4 &operator*=(float f) { return *this = *this * f; }
mat4 &operator*=(const mat4 &m) { return *this = *this * m; }
mat4 &operator+=(const mat4 &m) { return *this = *this + m; }
mat4 &operator-=(const mat4 &m) { return *this = *this - m; }
operator float*() { return mat; }
operator const float*() const { return mat; }
float &operator[](int i) { return mat[i]; }
const float operator[](int i) const { return mat[i]; }
mat4 rotation() const {
mat4 ret;
ret[0] = mat[0]; ret[4] = mat[4]; ret[8] = mat[8]; ret[12] = 0;
ret[1] = mat[1]; ret[5] = mat[5]; ret[9] = mat[9]; ret[13] = 0;
ret[2] = mat[2]; ret[6] = mat[6]; ret[10] = mat[10]; ret[14] = 0;
ret[3] = 0; ret[7] = 0; ret[11] = 0; ret[15] = 1;
return ret;
}
mat4 transpose() const {
mat4 ret;
ret[0] = mat[0]; ret[4] = mat[1]; ret[8] = mat[2]; ret[12] = mat[3];
ret[1] = mat[4]; ret[5] = mat[5]; ret[9] = mat[6]; ret[13] = mat[7];
ret[2] = mat[8]; ret[6] = mat[9]; ret[10] = mat[10]; ret[14] = mat[11];
ret[3] = mat[12]; ret[7] = mat[13]; ret[11] = mat[14]; ret[15] = mat[15];
return ret;
}
mat4 transpose_rotation() const {
mat4 ret;
ret[0] = mat[0]; ret[4] = mat[1]; ret[8] = mat[2]; ret[12] = mat[12];
ret[1] = mat[4]; ret[5] = mat[5]; ret[9] = mat[6]; ret[13] = mat[13];
ret[2] = mat[8]; ret[6] = mat[9]; ret[10] = mat[10]; ret[14] = mat[14];
ret[3] = mat[3]; ret[7] = mat[7]; ret[14] = mat[14]; ret[15] = mat[15];
return ret;
}
mat4 invert_view_matrix() const {
mat4 ret;
//transpose rotation
ret[0] = mat[0]; ret[4] = mat[1]; ret[8] = mat[2]; ret[12] = 0.f;
ret[1] = mat[4]; ret[5] = mat[5]; ret[9] = mat[6]; ret[13] = 0.f;
ret[2] = mat[8]; ret[6] = mat[9]; ret[10] = mat[10]; ret[14] = 0.f;
ret[3] = 0.f; ret[7] = 0.f; ret[11] = 0.f; ret[15] = 1.f;
mat4 m_translate;
m_translate.translate(-vec3(mat[12], mat[13], mat[14]));
return ret * m_translate;
}
float det() const {
float det;
det = mat[0] * mat[5] * mat[10];
det += mat[4] * mat[9] * mat[2];
det += mat[8] * mat[1] * mat[6];
det -= mat[8] * mat[5] * mat[2];
det -= mat[4] * mat[1] * mat[10];
det -= mat[0] * mat[9] * mat[6];
return det;
}
mat4 inverse()
{
mat4 res;
double inv[16], det;
int i;
const float *m = &mat[0];
inv[0] = m[5] * m[10] * m[15] -
m[5] * m[11] * m[14] -
m[9] * m[6] * m[15] +
m[9] * m[7] * m[14] +
m[13] * m[6] * m[11] -
m[13] * m[7] * m[10];
inv[4] = -m[4] * m[10] * m[15] +
m[4] * m[11] * m[14] +
m[8] * m[6] * m[15] -
m[8] * m[7] * m[14] -
m[12] * m[6] * m[11] +
m[12] * m[7] * m[10];
inv[8] = m[4] * m[9] * m[15] -
m[4] * m[11] * m[13] -
m[8] * m[5] * m[15] +
m[8] * m[7] * m[13] +
m[12] * m[5] * m[11] -
m[12] * m[7] * m[9];
inv[12] = -m[4] * m[9] * m[14] +
m[4] * m[10] * m[13] +
m[8] * m[5] * m[14] -
m[8] * m[6] * m[13] -
m[12] * m[5] * m[10] +
m[12] * m[6] * m[9];
inv[1] = -m[1] * m[10] * m[15] +
m[1] * m[11] * m[14] +
m[9] * m[2] * m[15] -
m[9] * m[3] * m[14] -
m[13] * m[2] * m[11] +
m[13] * m[3] * m[10];
inv[5] = m[0] * m[10] * m[15] -
m[0] * m[11] * m[14] -
m[8] * m[2] * m[15] +
m[8] * m[3] * m[14] +
m[12] * m[2] * m[11] -
m[12] * m[3] * m[10];
inv[9] = -m[0] * m[9] * m[15] +
m[0] * m[11] * m[13] +
m[8] * m[1] * m[15] -
m[8] * m[3] * m[13] -
m[12] * m[1] * m[11] +
m[12] * m[3] * m[9];
inv[13] = m[0] * m[9] * m[14] -
m[0] * m[10] * m[13] -
m[8] * m[1] * m[14] +
m[8] * m[2] * m[13] +
m[12] * m[1] * m[10] -
m[12] * m[2] * m[9];
inv[2] = m[1] * m[6] * m[15] -
m[1] * m[7] * m[14] -
m[5] * m[2] * m[15] +
m[5] * m[3] * m[14] +
m[13] * m[2] * m[7] -
m[13] * m[3] * m[6];
inv[6] = -m[0] * m[6] * m[15] +
m[0] * m[7] * m[14] +
m[4] * m[2] * m[15] -
m[4] * m[3] * m[14] -
m[12] * m[2] * m[7] +
m[12] * m[3] * m[6];
inv[10] = m[0] * m[5] * m[15] -
m[0] * m[7] * m[13] -
m[4] * m[1] * m[15] +
m[4] * m[3] * m[13] +
m[12] * m[1] * m[7] -
m[12] * m[3] * m[5];
inv[14] = -m[0] * m[5] * m[14] +
m[0] * m[6] * m[13] +
m[4] * m[1] * m[14] -
m[4] * m[2] * m[13] -
m[12] * m[1] * m[6] +
m[12] * m[2] * m[5];
inv[3] = -m[1] * m[6] * m[11] +
m[1] * m[7] * m[10] +
m[5] * m[2] * m[11] -
m[5] * m[3] * m[10] -
m[9] * m[2] * m[7] +
m[9] * m[3] * m[6];
inv[7] = m[0] * m[6] * m[11] -
m[0] * m[7] * m[10] -
m[4] * m[2] * m[11] +
m[4] * m[3] * m[10] +
m[8] * m[2] * m[7] -
m[8] * m[3] * m[6];
inv[11] = -m[0] * m[5] * m[11] +
m[0] * m[7] * m[9] +
m[4] * m[1] * m[11] -
m[4] * m[3] * m[9] -
m[8] * m[1] * m[7] +
m[8] * m[3] * m[5];
inv[15] = m[0] * m[5] * m[10] -
m[0] * m[6] * m[9] -
m[4] * m[1] * m[10] +
m[4] * m[2] * m[9] +
m[8] * m[1] * m[6] -
m[8] * m[2] * m[5];
det = float(m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12]);
if (det == 0)
res;
det = 1.0 / det;
for (i = 0; i < 16; i++)
res[i] = float(inv[i] * det);
return res;
}
void zero() {
mat[0] = 0.0; mat[4] = 0.0; mat[8] = 0.0; mat[12] = 0.0;
mat[1] = 0.0; mat[5] = 0.0; mat[9] = 0.0; mat[13] = 0.0;
mat[2] = 0.0; mat[6] = 0.0; mat[10] = 0.0; mat[14] = 0.0;
mat[3] = 0.0; mat[7] = 0.0; mat[11] = 0.0; mat[15] = 0.0;
}
void identity() {
mat[0] = 1.0; mat[4] = 0.0; mat[8] = 0.0; mat[12] = 0.0;
mat[1] = 0.0; mat[5] = 1.0; mat[9] = 0.0; mat[13] = 0.0;
mat[2] = 0.0; mat[6] = 0.0; mat[10] = 1.0; mat[14] = 0.0;
mat[3] = 0.0; mat[7] = 0.0; mat[11] = 0.0; mat[15] = 1.0;
}
void rotate(const vec3 &axis, float angle) {
float rad = angle * DEG2RAD;
float c = cosf(rad);
float s = sinf(rad);
vec3 v = axis;
v.normalize();
float xx = v.x * v.x;
float yy = v.y * v.y;
float zz = v.z * v.z;
float xy = v.x * v.y;
float yz = v.y * v.z;
float zx = v.z * v.x;
float xs = v.x * s;
float ys = v.y * s;
float zs = v.z * s;
mat[0] = (1.0f - c) * xx + c; mat[4] = (1.0f - c) * xy - zs; mat[8] = (1.0f - c) * zx + ys; mat[12] = 0.0;
mat[1] = (1.0f - c) * xy + zs; mat[5] = (1.0f - c) * yy + c; mat[9] = (1.0f - c) * yz - xs; mat[13] = 0.0;
mat[2] = (1.0f - c) * zx - ys; mat[6] = (1.0f - c) * yz + xs; mat[10] = (1.0f - c) * zz + c; mat[14] = 0.0;
mat[3] = 0.0; mat[7] = 0.0; mat[11] = 0.0; mat[15] = 1.0;
}
void rotate(float x, float y, float z, float angle) {
rotate(vec3(x, y, z), angle);
}
void rotate_x(float angle) {
float rad = angle * DEG2RAD;
float c = cosf(rad);
float s = sinf(rad);
mat[0] = 1.0; mat[4] = 0.0; mat[8] = 0.0; mat[12] = 0.0;
mat[1] = 0.0; mat[5] = c; mat[9] = -s; mat[13] = 0.0;
mat[2] = 0.0; mat[6] = s; mat[10] = c; mat[14] = 0.0;
mat[3] = 0.0; mat[7] = 0.0; mat[11] = 0.0; mat[15] = 1.0;
}
void rotate_y(float angle) {
float rad = angle * DEG2RAD;
float c = cosf(rad);
float s = sinf(rad);
mat[0] = c; mat[4] = 0.0; mat[8] = s; mat[12] = 0.0;
mat[1] = 0.0; mat[5] = 1.0; mat[9] = 0.0; mat[13] = 0.0;
mat[2] = -s; mat[6] = 0.0; mat[10] = c; mat[14] = 0.0;
mat[3] = 0.0; mat[7] = 0.0; mat[11] = 0.0; mat[15] = 1.0;
}
void rotate_z(float angle) {
float rad = angle * DEG2RAD;
float c = cosf(rad);
float s = sinf(rad);
mat[0] = c; mat[4] = -s; mat[8] = 0.0; mat[12] = 0.0;
mat[1] = s; mat[5] = c; mat[9] = 0.0; mat[13] = 0.0;
mat[2] = 0.0; mat[6] = 0.0; mat[10] = 1.0; mat[14] = 0.0;
mat[3] = 0.0; mat[7] = 0.0; mat[11] = 0.0; mat[15] = 1.0;
}
void scale(const vec3 &v) {
mat[0] = v.x; mat[4] = 0.0; mat[8] = 0.0; mat[12] = 0.0;
mat[1] = 0.0; mat[5] = v.y; mat[9] = 0.0; mat[13] = 0.0;
mat[2] = 0.0; mat[6] = 0.0; mat[10] = v.z; mat[14] = 0.0;
mat[3] = 0.0; mat[7] = 0.0; mat[11] = 0.0; mat[15] = 1.0;
}
void scale(float x, float y, float z) {
scale(vec3(x, y, z));
}
void translate(const vec3 &v)
{
mat[0] = 1.0; mat[4] = 0.0; mat[8] = 0.0; mat[12] = v.x;
mat[1] = 0.0; mat[5] = 1.0; mat[9] = 0.0; mat[13] = v.y;
mat[2] = 0.0; mat[6] = 0.0; mat[10] = 1.0; mat[14] = v.z;
mat[3] = 0.0; mat[7] = 0.0; mat[11] = 0.0; mat[15] = 1.0;
}
void translate(float x, float y, float z) {
translate(vec3(x, y, z));
}
void set_translation(const vec3 &v) {
mat[12] = v.x;
mat[13] = v.y;
mat[14] = v.z;
}
vec3 get_translation() {
return vec3(mat[12], mat[13], mat[14]);
}
void reflect(const vec4 &plane) {
float x = plane.x;
float y = plane.y;
float z = plane.z;
float x2 = x * 2.0f;
float y2 = y * 2.0f;
float z2 = z * 2.0f;
mat[0] = 1.0f - x * x2; mat[4] = -y * x2; mat[8] = -z * x2; mat[12] = -plane.w * x2;
mat[1] = -x * y2; mat[5] = 1.0f - y * y2; mat[9] = -z * y2; mat[13] = -plane.w * y2;
mat[2] = -x * z2; mat[6] = -y * z2; mat[10] = 1.0f - z * z2; mat[14] = -plane.w * z2;
mat[3] = 0.0; mat[7] = 0.0; mat[11] = 0.0; mat[15] = 1.0;
}
void reflect(float x, float y, float z, float w) {
reflect(vec4(x, y, z, w));
}
void perspective_extended(float r, float l, float t, float b, float znear, float zfar) {
float r_l = r - l;
float t_b = t - b;
if (fabs(r_l) < 0.01f) r_l = 0.01f;
if (fabs(t_b) < 0.01f) t_b = 0.01f;
mat[0] = 2.0f*znear / r_l; mat[4] = 0.0; mat[8] = (r + l) / r_l; mat[12] = 0.0;
mat[1] = 0.0; mat[5] = 2.0f*znear / t_b; mat[9] = (t + b) / t_b; mat[13] = 0.0;
mat[2] = 0.0; mat[6] = 0.0; mat[10] = -(zfar + znear) / (zfar - znear); mat[14] = -(2.0f * zfar * znear) / (zfar - znear);
mat[3] = 0.0; mat[7] = 0.0; mat[11] = -1.0; mat[15] = 0.0;
}
void perspective(float fov, float aspect, float znear, float zfar) {
if (fabs(fov - 90.0f) < EPSILON) fov = 89.9f;
float y = tanf(fov * PI / 360.0f);
float x = y * aspect;
mat[0] = 1.0f / x; mat[4] = 0.0; mat[8] = 0.0; mat[12] = 0.0;
mat[1] = 0.0; mat[5] = 1.0f / y; mat[9] = 0.0; mat[13] = 0.0;
mat[2] = 0.0; mat[6] = 0.0; mat[10] = -(zfar + znear) / (zfar - znear); mat[14] = -(2.0f * zfar * znear) / (zfar - znear);
mat[3] = 0.0; mat[7] = 0.0; mat[11] = -1.0; mat[15] = 0.0;
}
void OrthographicProjection(float znear, float zfar, float left, float right, float top, float bottom)
{
mat[0] = 2.0f / (right - left); mat[4] = 0.0; mat[8] = 0.0f; mat[12] = -(right + left) / (right - left);
mat[1] = 0.0; mat[5] = 2.0f / (top - bottom); mat[9] = 0.0f; mat[13] = -(top + bottom) / (top - bottom);
mat[2] = 0.0; mat[6] = 0.0; mat[10] = -2.0f / (zfar - znear); mat[14] = -(zfar + znear) / (zfar - znear);
mat[3] = 0.0; mat[7] = 0.0; mat[11] = 0.0; mat[15] = 1.0;
}
void look_at(const vec3 &eye, const vec3 &view, const vec3 &up) {
vec3 x, y, z;
mat4 m0, m1;
z = eye - view;
//z = dir - eye;
z.normalize();
x.cross(up, z);
x.normalize();
y.cross(z, x);
y.normalize();
m0[0] = x.x; m0[4] = x.y; m0[8] = x.z; m0[12] = 0.0;
m0[1] = y.x; m0[5] = y.y; m0[9] = y.z; m0[13] = 0.0;
m0[2] = z.x; m0[6] = z.y; m0[10] = z.z; m0[14] = 0.0;
m0[3] = 0.0; m0[7] = 0.0; m0[11] = 0.0; m0[15] = 1.0;
m1.translate(-eye);
*this = m0 * m1;
}
void look_at(const float *eye, const float *dir, const float *up) {
look_at(vec3(eye), vec3(dir), vec3(up));
}
void look_at_dx(const vec3 &eye, const vec3 &view, const vec3 &up) {
vec3 right, up_vec, forward;
mat4 m0, m1;
forward = view - eye;
forward.normalize();
right.cross(forward, up);
right.normalize();
up_vec.cross(right, forward);
up_vec.normalize();
m0[0] = right.x; m0[4] = right.y; m0[8] = right.z; m0[12] = 0.0;
m0[1] = up_vec.x; m0[5] = up_vec.y; m0[9] = up_vec.z; m0[13] = 0.0;
m0[2] = forward.x; m0[6] = forward.y; m0[10] = forward.z; m0[14] = 0.0;
m0[3] = 0.0; m0[7] = 0.0; m0[11] = 0.0; m0[15] = 1.0;
m1.translate(-eye);
*this = m0 * m1;
}
float mat[16];
};
#endif /* __MATHLIB_H__ */
<file_sep>#include<GL/freeglut.h>
#include <xutility>
#include <iostream>
#include <vector>
#include <algorithm>
//点
typedef struct vector3
{
int x;
int y;
int z;
vector3(int i, int j, int k)
:x(i), y(j), z(k)
{}
vector3()
:x(0), y(0), z(0)
{}
}Vector3;
//旋转参数
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;
std::vector<Vector3> points;
Vector3 start(0, 0, 0);
Vector3 end(25, 17, 5);
void calcPoint(Vector3 start, Vector3 end);
void drawCube(float x, float y, float z)
{
const float sizex = 0.05f;
const float sizey = 0.05f;
const float sizez = 0.05f;
glTranslatef(x, y, z);
glBegin(GL_QUADS);
glColor3f(1.0, 1.0, 0.0);
// FRONT
glVertex3f(-sizex, -sizey, sizez);
glVertex3f(sizex, -sizey, sizez);
glVertex3f(sizex, sizey, sizez);
glVertex3f(-sizex, sizey, sizez);
// BACK
glVertex3f(-sizex, -sizey, -sizez);
glVertex3f(-sizex, sizey, -sizez);
glVertex3f(sizex, sizey, -sizez);
glVertex3f(sizex, -sizey, -sizez);
glColor3f(0.0, 1.0, 0.0);
// LEFT
glVertex3f(-sizex, -sizey, sizez);
glVertex3f(-sizex, sizey, sizez);
glVertex3f(-sizex, sizey, -sizez);
glVertex3f(-sizex, -sizey, -sizez);
// RIGHT
glVertex3f(sizex, -sizey, -sizez);
glVertex3f(sizex, sizey, -sizez);
glVertex3f(sizex, sizey, sizez);
glVertex3f(sizex, -sizey, sizez);
glColor3f(0.0, 0.0, 1.0);
// TOP
glVertex3f(-sizex, sizey, sizez);
glVertex3f(sizex, sizey, sizez);
glVertex3f(sizex, sizey, -sizez);
glVertex3f(-sizex, sizey, -sizez);
// BOTTOM
glVertex3f(-sizex, -sizey, sizez);
glVertex3f(-sizex, -sizey, -sizez);
glVertex3f(sizex, -sizey, -sizez);
glVertex3f(sizex, -sizey, sizez);
glEnd();
glTranslatef(-x, -y, -z);
}
void paint(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
//旋转
glRotatef(xRot, 1.0f, 0.0f, 0.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);
calcPoint(start ,end);
//0.1间隔代表1 否则太大
for(auto a : points)
{
drawCube((float)a.x/10, (float)a.y / 10, (float)a.z / 10);
}
glPopMatrix();
glutSwapBuffers();
}
void SpecialKeys(int key, int x, int y)
{
if (key == GLUT_KEY_UP) xRot -= 5.0f;
if (key == GLUT_KEY_DOWN) xRot += 5.0f;
if (key == GLUT_KEY_LEFT) yRot -= 5.0f;
if (key == GLUT_KEY_RIGHT) yRot += 5.0f;
if (xRot > 356.0f) xRot = 0.0f;
if (xRot < -1.0f) xRot = 355.0f;
if (yRot > 356.0f) yRot = 0.0f;
if (yRot < -1.0f) yRot = 355.0f;
//刷新窗口
glutPostRedisplay();
}
void reshapeFunction(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-2.0, 2.0, -2.0, 2.0, -8.0, 8.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(3.0, 3.0, 3.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
}
void Init()
{
glEnable(GL_DEPTH_TEST);
glClearColor(0.3, 0.3, 0.3, 1.0f);
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutInitWindowPosition(200, 200);
glutInitWindowSize(500, 500);
glutCreateWindow("Bresenham3D ");
Init();
glutReshapeFunc(reshapeFunction);
glutDisplayFunc(paint);
glutSpecialFunc(SpecialKeys);
glutMainLoop();
return 0;
}
void calcPoint(Vector3 start , Vector3 end)
{
Vector3 result;
int steps = 1;
int xd, yd, zd;
int x, y, z;
int ax, ay, az;
int sx, sy, sz;
int dx, dy, dz;
dx = (int)(end.x - start.x);
dy = (int)(end.y - start.y);
dz = (int)(end.z - start.z);
ax = abs(dx) << 1;
ay = abs(dy) << 1;
az = abs(dz) << 1;
sx = ((float)dx) >= 0 ? 1 : -1;
sy = ((float)dy) >= 0 ? 1 : -1;
sz = ((float)dz) >= 0 ? 1 : -1;
x = (int)start.x;
y = (int)start.y;
z = (int)start.z;
if (ax >= std::max(ay, az)) // x dominant
{
yd = ay - (ax >> 1);
zd = az - (ax >> 1);
for (; ; )
{
result.x = (int)(x / steps);
result.y = (int)(y / steps);
result.z = (int)(z / steps);
points.push_back(result);
if (x == (int)end.x)
return;
if (yd >= 0)
{
y += sy;
yd -= ax;
}
if (zd >= 0)
{
z += sz;
zd -= ax;
}
x += sx;
yd += ay;
zd += az;
}
}
else if (ay >= std::max(ax, az)) // y dominant
{
xd = ax - (ay >> 1);
zd = az - (ay >> 1);
for (; ; )
{
result.x = (int)(x / steps);
result.y = (int)(y / steps);
result.z = (int)(z / steps);
points.push_back(result);
if (y == (int)end.y)
return;
if (xd >= 0)
{
x += sx;
xd -= ay;
}
if (zd >= 0)
{
z += sz;
zd -= ay;
}
y += sy;
xd += ax;
zd += az;
}
}
else if (az >= std::max(ax, ay)) // z dominant
{
xd = ax - (az >> 1);
yd = ay - (az >> 1);
for (; ; )
{
result.x = (int)(x / steps);
result.y = (int)(y / steps);
result.z = (int)(z / steps);
points.push_back(result);
if (z == (int)end.z)
return;
if (xd >= 0)
{
x += sx;
xd -= az;
}
if (yd >= 0)
{
y += sy;
yd -= az;
}
z += sz;
xd += ax;
yd += ay;
}
}
}
<file_sep>#ifndef _Random_h
#define _Random_h
#include <windows.h>
void rndInit(void);
float rnd(float from,float to);
float rnd01();
void rndSeed(int seed);
float rndTable(WORD index);
#endif
<file_sep>#include "src/main/main.h"
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------main loop, key handler
LRESULT CALLBACK WinProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
LONG lRet = 0;
switch (uMsg)
{
case WM_SIZE: // If the window is resized
if (!g_bFullScreen) // Do this only if we are NOT in full screen
{
SizeOpenGLScreen(LOWORD(lParam), HIWORD(lParam));// LoWord=Width, HiWord=Height
GetClientRect(hWnd, &g_rRect); // Get the window rectangle
}
break;
case WM_KEYDOWN:
switch (wParam) { // Check if we hit a key
case VK_ESCAPE: // If we hit the escape key
PostQuitMessage(0); // Send a QUIT message to the window
break;
default:
process_key(wParam);
break;
}
break;
case WM_DESTROY: // If the window is destroyed
PostQuitMessage(0); // Send a QUIT Message to the window
break;
default: // Return by default
lRet = (long)DefWindowProc(hWnd, uMsg, wParam, lParam);
break;
}
return lRet; // Return by default
}
WPARAM MainLoop()
{
MSG msg;
while (1) // Do our infinite loop
{ // Check if there was a message
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if (msg.message == WM_QUIT) // If the message wasn't to quit
break;
TranslateMessage(&msg); // Find out what the message does
DispatchMessage(&msg); // Execute the message
}
else // If there wasn't a message
{
RenderScene(); // Render the scene every frame
}
}
if (opengl_debug_mode_enabled)
CheckDebugLog();
DeInit(); // Clean up and free all allocated memory
ShutDown();
return(msg.wParam); // Return from the program
}
//-------------------------------------------------------------------------------------------------------------------------------------app init
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hprev, PSTR cmdline, int ishow);
int main(int argc, char* argv[])
{
HINSTANCE hInst = (HINSTANCE)GetWindowLong(GetActiveWindow(), GWL_HINSTANCE);
WinMain(hInst, NULL, NULL, 1);
return 0;
}
void ChangeToFullScreen()
{
DEVMODE dmSettings; // Device Mode variable
memset(&dmSettings, 0, sizeof(dmSettings)); // Makes Sure Memory's Cleared
if (!EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dmSettings))
{
MessageBox(NULL, "Could Not Enum Display Settings", "Error", MB_OK);
return;
}
dmSettings.dmPelsWidth = SCREEN_WIDTH; // Selected Screen Width
dmSettings.dmPelsHeight = SCREEN_HEIGHT; // Selected Screen Height
int result = ChangeDisplaySettings(&dmSettings, CDS_FULLSCREEN);
if (result != DISP_CHANGE_SUCCESSFUL)
{
MessageBox(NULL, "Display Mode Not Compatible", "Error", MB_OK);
PostQuitMessage(0);
}
}
HWND CreateMyWindow(LPSTR strWindowName, int width, int height, DWORD dwStyle, bool bFullScreen, HINSTANCE hInstance)
{
HWND hWnd;
WNDCLASS wndclass;
memset(&wndclass, 0, sizeof(WNDCLASS)); // Init the size of the class
wndclass.style = CS_HREDRAW | CS_VREDRAW; // Regular drawing capabilities
wndclass.lpfnWndProc = WinProc; // Pass our function pointer as the window procedure
wndclass.hInstance = hInstance; // Assign our hInstance
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); // General icon
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); // An arrow for the cursor
wndclass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); // A white window
wndclass.lpszClassName = "Engine"; // Assign the class name
RegisterClass(&wndclass); // Register the class
if (bFullScreen && !dwStyle) // Check if we wanted full screen mode
{ // Set the window properties for full screen mode
dwStyle = WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
ChangeToFullScreen(); // Go to full screen
ShowCursor(FALSE); // Hide the cursor
}
else if (!dwStyle) // Assign styles to the window depending on the choice
dwStyle = WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
g_hInstance = hInstance; // Assign our global hInstance to the window's hInstance
RECT rWindow;
rWindow.left = 0; // Set Left Value To 0
rWindow.right = width; // Set Right Value To Requested Width
rWindow.top = 0; // Set Top Value To 0
rWindow.bottom = height; // Set Bottom Value To Requested Height
AdjustWindowRect(&rWindow, dwStyle, false); // Adjust Window To True Requested Size
// Create the window
hWnd = CreateWindow("Engine", strWindowName, dwStyle, 0, 0,
rWindow.right - rWindow.left, rWindow.bottom - rWindow.top,
NULL, NULL, hInstance, NULL);
if (!hWnd) return NULL; // If we could get a handle, return NULL
ShowWindow(hWnd, SW_SHOWNORMAL); // Show the window
UpdateWindow(hWnd); // Draw the window
SetFocus(hWnd); // Sets Keyboard Focus To The Window
return hWnd;
}
bool bSetupPixelFormat(HDC hdc)
{
int pixelformat, format;
PIXELFORMATDESCRIPTOR pfd;
memset(&pfd, 0, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = 24;
if ((pixelformat = ChoosePixelFormat(hdc, &pfd)) == FALSE)
{
MessageBox(NULL, "ChoosePixelFormat failed", "Error", MB_OK);
return FALSE;
}
if (SetPixelFormat(hdc, pixelformat, &pfd) == FALSE)
{
MessageBox(NULL, "SetPixelFormat failed", "Error", MB_OK);
return FALSE;
}
return TRUE;
}
#define WGL_CONTEXT_LAYER_PLANE_ARB 0x2093
#define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091
#define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092
#define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
#define WGL_CONTEXT_PROFILE_MASK_ARB 0x9126
void InitializeOpenGL(int width, int height)
{
g_hDC = GetDC(g_hWnd); // This sets our global HDC
// We don't free this hdc until the end of our program
if (!bSetupPixelFormat(g_hDC)) // This sets our pixel format/information
PostQuitMessage(0); // If there's an error, quit
g_hRC = wglCreateContext(g_hDC); // This creates a rendering context from our hdc
wglMakeCurrent(g_hDC, g_hRC); // This makes the rendering context we just created the one we want to use
//get max gl version
int major, minor;
glGetIntegerv(GL_MAJOR_VERSION, &major);
glGetIntegerv(GL_MINOR_VERSION, &minor);
//major = 3; minor = 0;
typedef HGLRC(APIENTRYP PFNWGLCREATECONTEXTATTRIBSARBPROC)(HDC, HGLRC, const int *);
PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = NULL;
int attributes[] =
{
WGL_CONTEXT_MAJOR_VERSION_ARB, major,
WGL_CONTEXT_MINOR_VERSION_ARB, minor,
WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB |
WGL_CONTEXT_DEBUG_BIT_ARB,
WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
0
};
wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)
wglGetProcAddress("wglCreateContextAttribsARB");
if (NULL == wglCreateContextAttribsARB)
{
wglDeleteContext(g_hRC);
return;
}
HGLRC hRC = wglCreateContextAttribsARB(g_hDC, 0, attributes);
if (!hRC)
{
wglDeleteContext(g_hRC);
return;
}
if (!wglMakeCurrent(g_hDC, hRC))
{
wglDeleteContext(g_hRC);
wglDeleteContext(hRC);
return;
}
wglDeleteContext(g_hRC);
}
void DeInit()
{
if (g_hRC)
{
wglMakeCurrent(NULL, NULL); // This frees our rendering memory and sets everything back to normal
wglDeleteContext(g_hRC); // Delete our OpenGL Rendering Context
}
if (g_hDC)
ReleaseDC(g_hWnd, g_hDC); // Release our HDC from memory
if (g_bFullScreen) // If we were in full screen:
{
ChangeDisplaySettings(NULL, 0); // Switch Back To The Desktop
ShowCursor(TRUE); // Show Mouse Pointer
}
UnregisterClass("Engine", g_hInstance); // Free the window class
PostQuitMessage(0); // Post a QUIT message to the window
}
void set_vsync(bool enabled)
{
typedef BOOL(APIENTRY * wglSwapIntervalEXT_Func)(int);
wglSwapIntervalEXT_Func wglSwapIntervalEXT = wglSwapIntervalEXT_Func(wglGetProcAddress("wglSwapIntervalEXT"));
if (wglSwapIntervalEXT) wglSwapIntervalEXT(enabled ? 1 : 0);
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hprev, PSTR cmdline, int ishow)
{
HWND hWnd;
g_bFullScreen = false;
hWnd = CreateMyWindow("Frustum culling", SCREEN_WIDTH, SCREEN_HEIGHT, 0, g_bFullScreen, hInstance);
if (hWnd == NULL) return TRUE;
Init(hWnd);
set_vsync(false);
return (int)MainLoop();
}<file_sep>#ifndef _FRUSTUM_H
#define _FRUSTUM_H
#include <windows.h>
#include <gl\gl.h>
#include <gl\glext.h>
#include "..\glext\glext.h"
#include "..\math\mathlib.h"
class CFrustum
{
public:
CFrustum(){};
~CFrustum(){};
void CalculateFrustum(mat4 &view_matrix, mat4 &proj_matrix);
vec4 frustum_planes[6];
};
#endif<file_sep>#include "main.h"
#include "Utilities.h"
#include <xmmintrin.h>
#include <mmintrin.h>
#include <emmintrin.h>
#include <new.h>
//AABB - axis-aligned bounding box
//OBB - oriented Bounding Box
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------data & settings
//------------screen
#define SCREEN_WIDTH 1600
#define SCREEN_HEIGHT 900
#define SCREEN_DEPTH 32
bool g_bFullScreen = TRUE;
HWND g_hWnd;
RECT g_rRect;
HDC g_hDC;
HGLRC g_hRC;
HINSTANCE g_hInstance;
int window_width;
int window_height;
//------------demo settings
bool use_multithreading = false;
const int num_workers = 4;
bool use_gpu_culling = false;
bool enable_rendering_objects = true;
bool culling_enabled = true;
const bool only_culling_measurements = false;
enum CULLING_MODE
{
SIMPLE_SPHERES,
SIMPLE_AABB,
SIMPLE_OBB,
SSE_SPHERES,
SSE_AABB,
SSE_OBB
};
CULLING_MODE culling_mode = SIMPLE_SPHERES;
//------------time
double total_time = 0.0;
//------------camera
CCamera camera;
CFrustum frustum;
float zNear = 0.1f;
float zFar = 100.f;
mat4 camera_view_matrix, camera_proj_matrix, camera_view_proj_matrix, saved_inv_view_proj_matrix;
//------------area
const float AREA_SIZE = 20.f;
const float half_box_size = 0.05f;
const vec3 box_max = vec3(half_box_size, half_box_size, half_box_size);
const vec3 box_min = -vec3(half_box_size, half_box_size, half_box_size);
const vec3 box_half_size = vec3(half_box_size, half_box_size, half_box_size);
const float bounding_radius = sqrtf(3.f) * half_box_size;
//------------sse
#define sse_align 16
#define ALIGN_SSE __declspec( align( sse_align ) )
ALIGN_SSE struct mat4_sse
{
__m128 col0;
__m128 col1;
__m128 col2;
__m128 col3;
mat4_sse() {}
mat4_sse(mat4 &m)
{
set(m);
}
inline void set(mat4 &m)
{
col0 = _mm_loadu_ps(&m.mat[0]);
col1 = _mm_loadu_ps(&m.mat[4]);
col2 = _mm_loadu_ps(&m.mat[8]);
col3 = _mm_loadu_ps(&m.mat[12]);
}
};
//------------scene geometry
ALIGN_SSE struct BSphere
{
vec3 pos;
float r;
};
ALIGN_SSE struct AABB
{
vec4 box_min;
vec4 box_max;
};
const int MAX_SCENE_OBJECTS = 100000;
BSphere *sphere_data = NULL;
AABB *aabb_data = NULL;
int *culling_res = NULL;
mat4_sse *sse_obj_mat = NULL;
mat4 *obj_mat = NULL;
//------------geometry rendering data
GLuint wire_box_vao_id = -1;
GLuint wire_box_vbo_id = -1;
GLuint wire_box_ibo_id = -1;
GLuint ground_vao_id = -1;
GLuint ground_vbo_id = -1;
GLuint ground_ibo_id = -1;
GLuint geometry_vao_id = -1;
GLuint geometry_vbo_id = -1;
GLuint geometry_ibo_id = -1;
//tbo example https://gist.github.com/roxlu/5090067
GLuint dips_texture_buffer = -1;
GLuint dips_texture_buffer_tex = -1;
GLuint all_instances_data_vao = -1;
GLuint all_instances_data_vbo = -1;
vec4 instance_info[MAX_SCENE_OBJECTS * 2]; //pos + color
vec4 visible_instance_info[MAX_SCENE_OBJECTS * 2]; //just visible instances data
int num_visible_instances = MAX_SCENE_OBJECTS;
//------------shaders
Shader ground_shader;
Shader geometry_shader;
Shader show_frustum_shader;
Shader culling_shader;
GLuint num_visible_instances_query[2];
int frame_index = 0;
//------------multithreading
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------threads
class Worker
{
public:
Worker();
~Worker();
//worker info
HANDLE thread_handle;
unsigned thread_id;
volatile bool stop_work;
HANDLE has_jobs_event;
HANDLE jobs_finished_event;
//make job
void doJob();
int first_processing_oject;
int num_processing_ojects;
};
Worker workers[num_workers];
HANDLE thread_handles[num_workers];
void create_threads();
void threads_close();
void process_multithreading_culling();
void wate_multithreading_culling_done();
void cull_objects(int first_processing_oject, int num_processing_ojects);
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------window stuff
void SizeOpenGLScreen(int width, int height)
{
height = max(height, 1);
window_width = width;
window_height = height;
glViewport(0, 0, width, height);
}
void CheckGLErrors()
{
GLenum err;
while ((err = glGetError()) != GL_NO_ERROR)
fprintf(stderr, "OpenGL Error: %s\n", gluErrorString(err));
}
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------SSE base
//https://github.com/nsf/sseculling/blob/master/Core/Memory.cpp
template <typename T>
inline T *new_sse(size_t size)
{
return static_cast<T*>(_aligned_malloc(sizeof(T)* size, sse_align));
}
template <typename T>
inline void delete_sse(T *ptr)
{
_aligned_free(static_cast<void*>(ptr));
}
template <typename T>
inline T* new_sse_array(int array_size)
{
T* arr = static_cast<T*>(_aligned_malloc(sizeof(T)* array_size, sse_align));
for (size_t i = 0; i < size_t(array_size); i++)
new (&arr[i]) T;
return arr;
}
template <typename T>
inline void delete_sse_array(T *arr, size_t array_size)
{
for (size_t i = 0; i < array_size; i++)
arr[i].~T();//destroy all initialized elements
_aligned_free(static_cast<void*>(arr));
}
template <typename T>
inline T *new_sse32(size_t size)
{
return static_cast<T*>(_aligned_malloc(sizeof(T)* size, 32));
}
//http://stackoverflow.com/questions/38090188/matrix-multiplication-using-sse
//https://gist.github.com/rygorous/4172889
__forceinline __m128 sse_mat4_mul_vec4(mat4_sse &m, __m128 v)
{
__m128 xxxx = _mm_shuffle_ps(v, v, _MM_SHUFFLE(0, 0, 0, 0));
__m128 yyyy = _mm_shuffle_ps(v, v, _MM_SHUFFLE(1, 1, 1, 1));
__m128 zzzz = _mm_shuffle_ps(v, v, _MM_SHUFFLE(2, 2, 2, 2));
__m128 wwww = _mm_shuffle_ps(v, v, _MM_SHUFFLE(3, 3, 3, 3));
return _mm_add_ps(
_mm_add_ps(_mm_mul_ps(xxxx, m.col0), _mm_mul_ps(yyyy, m.col1)),
_mm_add_ps(_mm_mul_ps(zzzz, m.col2), _mm_mul_ps(wwww, m.col3))
);
}
__forceinline void sse_mat4_mul(mat4_sse &dest, mat4_sse &m1, mat4_sse &m2)
{
dest.col0 = sse_mat4_mul_vec4(m1, m2.col0);
dest.col1 = sse_mat4_mul_vec4(m1, m2.col1);
dest.col2 = sse_mat4_mul_vec4(m1, m2.col2);
dest.col3 = sse_mat4_mul_vec4(m1, m2.col3);
}
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------init
void generate_instances()
{
//allocate data
sphere_data = new_sse_array<BSphere>(MAX_SCENE_OBJECTS);
aabb_data = new_sse_array<AABB>(MAX_SCENE_OBJECTS);
culling_res = new_sse<int>(MAX_SCENE_OBJECTS);
memset(&culling_res[0], 0, sizeof(int) * MAX_SCENE_OBJECTS);
sse_obj_mat = new_sse_array<mat4_sse>(MAX_SCENE_OBJECTS);
memset(&sse_obj_mat[0], 0, sizeof(mat4_sse) * MAX_SCENE_OBJECTS);
obj_mat = new mat4[MAX_SCENE_OBJECTS];
//generate instances data
int i;
vec3 pos;
mat4 obj_transform_mat; //identity by default
for (i = 0; i<MAX_SCENE_OBJECTS; i++)
{
//random position inside area
pos = vec3(rnd(-1.f, 1.f)*AREA_SIZE, half_box_size * 0.95f, rnd(-1.f, 1.f)*AREA_SIZE);
instance_info[i * 2 + 0] = vec4(pos, bounding_radius); //pos
instance_info[i * 2 + 1] = vec4(rnd01(), rnd01(), rnd01(), 1.f); //color
sphere_data[i].pos = pos;
sphere_data[i].r = bounding_radius;
aabb_data[i].box_min = vec4(pos - box_half_size, 1.f);
aabb_data[i].box_max = vec4(pos + box_half_size, 1.f);
obj_transform_mat.set_translation(pos);
obj_mat[i] = obj_transform_mat;
sse_obj_mat[i].set(obj_transform_mat);
}
}
struct SimpleVertex
{
vec3 p;
vec3 n;
vec2 uv;
void init(vec3 in_p, vec3 in_n, vec2 in_uv)
{
p = in_p; n = in_n; uv = in_uv;
};
};
void create_instance_geometry()
{
//simple box
int i, j;
SimpleVertex vertex_buffer[24];
int index_buffer[36];
//separate attribs
//verts
vec3 box_iffset = vec3(0, 0, 0);
vec3 box_verts[8] = {
vec3(-half_box_size, -half_box_size, half_box_size),
vec3(half_box_size, -half_box_size, half_box_size),
vec3(half_box_size, half_box_size, half_box_size),
vec3(-half_box_size, half_box_size, half_box_size),
vec3(-half_box_size, -half_box_size, -half_box_size),
vec3(half_box_size, -half_box_size, -half_box_size),
vec3(half_box_size, half_box_size, -half_box_size),
vec3(-half_box_size, half_box_size, -half_box_size),
};
for (i = 0; i < 8; i++)
box_verts[i] += box_iffset;
//indices
int box_verts_i[24] = { 1, 5, 6, 2, 3, 7, 4, 0, 0, 4, 5, 1, 2, 6, 7, 3, 0, 1, 2, 3, 7, 6, 5, 4 };
//normals
vec3 box_face_normals[6] = {
vec3(1, 0, 0),
vec3(-1, 0, 0),
vec3(0, -1, 0),
vec3(0, 1, 0),
vec3(0, 0, 1),
vec3(0, 0, -1)
};
//uv
vec2 uv[4] = { vec2(0.f,0.f), vec2(1.f,0.f), vec2(1.f,1.f), vec2(0.f,1.f) };
//combine to single buffer, combine vertex buffer
for (i = 0; i<24; i++)
{
vertex_buffer[i].p = box_verts[box_verts_i[i]];
vertex_buffer[i].n = box_face_normals[int(i / 4)];
vertex_buffer[i].uv = uv[i % 4];
}
//index buffer
int box_face_indices[6] = { 0, 1, 2, 0, 2, 3 };
for (i = 0; i<6; i++)
for (j = 0; j<6; j++)
index_buffer[i * 6 + j] = box_face_indices[j] + 4 * i;
//create vao
RenderElementDescription desc;
VboElement vbo_elements[3] = { 3,0,GL_FLOAT, 3,sizeof(vec3),GL_FLOAT, 2,sizeof(vec3)*2,GL_FLOAT };
desc.init(sizeof(SimpleVertex), 24, (void*)&vertex_buffer[0], GL_STATIC_DRAW, 3, &vbo_elements[0]);
create_render_element(geometry_vao_id, geometry_vbo_id, desc, true, geometry_ibo_id, 36, &index_buffer[0]);
}
void create_ground()
{
SimpleVertex vertices[4];
memset(&vertices[0], 0, sizeof(SimpleVertex) * 4);
const vec3 groundNormal = vec3(0.f, 1.f, 0.f);
vertices[0].init(vec3(-AREA_SIZE, 0.f, -AREA_SIZE), groundNormal, vec2(0.f, 0.f));
vertices[1].init(vec3(AREA_SIZE, 0.f, -AREA_SIZE), groundNormal, vec2(1.f, 0.f));
vertices[2].init(vec3(AREA_SIZE, 0.f, AREA_SIZE), groundNormal, vec2(1.f, 1.f));
vertices[3].init(vec3(-AREA_SIZE, 0.f, AREA_SIZE), groundNormal, vec2(0.f, 1.f));
int indices[6] = { 0, 1, 2, 0, 2, 3 };
RenderElementDescription desc;
VboElement vbo_elements[3] = { 3,0,GL_FLOAT, 3,sizeof(vec3),GL_FLOAT, 2,sizeof(vec3) * 2,GL_FLOAT };
desc.init(sizeof(SimpleVertex), 4, (void*)&vertices[0], GL_STATIC_DRAW, 3, &vbo_elements[0]);
create_render_element(ground_vao_id, ground_vbo_id, desc, true, ground_ibo_id, 6, &indices[0]);
}
vec4 gl_unit_cube[8] =
{
vec4(-1,-1,-1, 1),
vec4(1,-1,-1, 1),
vec4(1,1,-1, 1),
vec4(-1,1,-1, 1),
vec4(-1,-1,1, 1),
vec4(1,-1,1, 1),
vec4(1,1,1, 1),
vec4(-1,1,1, 1)
};
int unit_box_index_buffer[24] =
{
0,1, 1,2, 2,3, 3,0,
4,5, 5,6, 6,7, 7,4,
0,4, 1,5, 2,6, 3,7
};
void create_cube_wire_box()
{
RenderElementDescription desc;
VboElement vbo_elements[3] = { 4,0,GL_FLOAT };
desc.init(sizeof(vec4), 8, (void*)&gl_unit_cube[0], GL_STATIC_DRAW, 1, &vbo_elements[0]);
create_render_element(wire_box_vao_id, wire_box_vbo_id, desc, true, wire_box_ibo_id, 24, &unit_box_index_buffer[0]);
}
void create_scene()
{
create_ground();
create_instance_geometry();
create_cube_wire_box();
generate_instances();
//create texture buffer which will contain visible instances data
glGenBuffers(1, &dips_texture_buffer);
glBindBuffer(GL_TEXTURE_BUFFER, dips_texture_buffer);
glBufferData(GL_TEXTURE_BUFFER, MAX_SCENE_OBJECTS * 2 * sizeof(vec4), &instance_info[0], GL_STATIC_DRAW);
glGenTextures(1, &dips_texture_buffer_tex);
glBindBuffer(GL_TEXTURE_BUFFER, 0);
//for gpu culling, vbo with all instances data
RenderElementDescription desc;
VboElement vbo_elements[2] = { 4,0,GL_FLOAT, 4,sizeof(vec4),GL_FLOAT };
desc.init(sizeof(vec4)*2, MAX_SCENE_OBJECTS, (void*)&instance_info[0], GL_STATIC_DRAW, 2, &vbo_elements[0]);
create_render_element(all_instances_data_vao, geometry_vbo_id, desc, true, geometry_ibo_id, 0, NULL);
}
void init_shaders()
{
ground_shader.programm_id = init_shader("ground_vs", "ground_ps");
ground_shader.add_uniform("ModelViewProjectionMatrix", 16, &camera_view_proj_matrix.mat[0]);
geometry_shader.programm_id = init_shader("geometry_vs", "geometry_ps");
geometry_shader.add_uniform("ModelViewProjectionMatrix", 16, &camera_view_proj_matrix.mat[0]);
show_frustum_shader.programm_id = init_shader("show_frustum_vs", "show_frustum_ps");
show_frustum_shader.add_uniform("PrevInvModelViewProjectionMatrix", 16, &saved_inv_view_proj_matrix.mat[0]);
show_frustum_shader.add_uniform("ModelViewProjectionMatrix", 16, &camera_view_proj_matrix.mat[0]);
//gpu culling shader
culling_shader.programm_id = init_shader("culling_vs", "culling_ps", "culling_gs");
culling_shader.add_uniform("ModelViewProjectionMatrix", 16, &camera_view_proj_matrix.mat[0]);
culling_shader.add_uniform("frustum_planes", 4, &frustum.frustum_planes[0].x, FLOAT_UNIFORM_TYPE, 6);
//http://steps3d.narod.ru/tutorials/tf3-tutorial.html
//https://open.gl/feedback
//prepare transform feedback
const char *vars[] = { "output_instance_data1", "output_instance_data2" };
glTransformFeedbackVaryings(culling_shader.programm_id, 2, vars, GL_INTERLEAVED_ATTRIBS);
link_shader(culling_shader.programm_id); // relink required
glUseProgram(0);
//queries for getting feedback from gpu - num visible instances
glGenQueries(2, &num_visible_instances_query[0]);
}
void Init(HWND hWnd)
{
int i, j, k;
//init gl
g_hWnd = hWnd; // Assign the window handle to a global window handle
GetClientRect(g_hWnd, &g_rRect); // Assign the windows rectangle to a global RECT
InitializeOpenGL(g_rRect.right, g_rRect.bottom); // Init OpenGL with the global rect
glext_init();
clearDebugLog();
opengl_debug_mode_enabled = glGetDebugMessageLogARB != NULL;
if (opengl_debug_mode_enabled)
{
glDebugMessageCallbackARB(&DebugCallback, NULL);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
}
glEnable(GL_DEPTH_TEST);
SizeOpenGLScreen(g_rRect.right, g_rRect.bottom); // Setup the screen translations and viewport
//rnd
rndInit();
int rnd_seed = (int)timeGetTime() % 65535;
rndSeed(rnd_seed);
//timing
InitTimeOperation();
//camera
camera.PositionCamera(10.f, 10.f, 10.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f);
camera.show_framerate = !only_culling_measurements;
//shaders
init_shaders();
//scene
create_scene();
//init gl states
glDepthFunc(GL_LESS);
//check errors
CheckGLErrors();
//multithreading
create_threads();
}
void ShutDown()
{
threads_close();
//clear all data
delete_sse_array(sphere_data, MAX_SCENE_OBJECTS);
delete_sse_array(aabb_data, MAX_SCENE_OBJECTS);
delete_sse(culling_res);
delete_sse_array(sse_obj_mat, MAX_SCENE_OBJECTS);
if (obj_mat) {
delete[]obj_mat; obj_mat = NULL;
}
//clear buffers
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, wire_box_ibo_id);
glDeleteBuffers(1, &wire_box_ibo_id);
glBindBuffer(GL_ARRAY_BUFFER, wire_box_vbo_id);
glDeleteBuffers(1, &wire_box_vbo_id);
glBindVertexArray(wire_box_vao_id);
glDeleteBuffers(1, &wire_box_vao_id);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ground_ibo_id);
glDeleteBuffers(1, &ground_ibo_id);
glBindBuffer(GL_ARRAY_BUFFER, ground_vbo_id);
glDeleteBuffers(1, &ground_vbo_id);
glBindVertexArray(ground_vao_id);
glDeleteBuffers(1, &ground_vao_id);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, geometry_ibo_id);
glDeleteBuffers(1, &geometry_ibo_id);
glBindBuffer(GL_ARRAY_BUFFER, geometry_vbo_id);
glDeleteBuffers(1, &geometry_vbo_id);
glBindVertexArray(geometry_vao_id);
glDeleteBuffers(1, &geometry_vao_id);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_BUFFER, dips_texture_buffer_tex);
glDeleteTextures(1, &dips_texture_buffer_tex);
glBindBuffer(GL_TEXTURE_BUFFER, dips_texture_buffer);
glDeleteBuffers(1, &dips_texture_buffer);
glBindBuffer(GL_ARRAY_BUFFER, all_instances_data_vbo);
glDeleteBuffers(1, &all_instances_data_vbo);
glBindVertexArray(all_instances_data_vao);
glDeleteBuffers(1, &all_instances_data_vao);
//shaders
glDeleteProgram(ground_shader.programm_id);
glDeleteProgram(geometry_shader.programm_id);
glDeleteProgram(show_frustum_shader.programm_id);
glDeleteProgram(culling_shader.programm_id);
//queries
glDeleteQueries(2, &num_visible_instances_query[0]);
}
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------simple culling
__forceinline bool SphereInFrustum(vec3 &pos, float &radius, vec4 *frustum_planes)
{
bool res = true;
//test all 6 frustum planes
for (int i = 0; i < 6; i++)
{
//calculate distance from sphere center to plane.
//if distance larger then sphere radius - sphere is outside frustum
if (frustum_planes[i].x * pos.x + frustum_planes[i].y * pos.y + frustum_planes[i].z * pos.z + frustum_planes[i].w <= -radius)
res = false;
//return false; //with flag works faster
}
return res;
//return true;
}
__forceinline bool RightParallelepipedInFrustum(vec4 &Min, vec4 &Max, vec4 *frustum_planes)
{
bool inside = true;
//test all 6 frustum planes
for (int i = 0; i<6; i++)
{
//pick closest point to plane and check if it behind the plane
//if yes - object outside frustum
float d = max(Min.x * frustum_planes[i].x, Max.x * frustum_planes[i].x)
+ max(Min.y * frustum_planes[i].y, Max.y * frustum_planes[i].y)
+ max(Min.z * frustum_planes[i].z, Max.z * frustum_planes[i].z)
+ frustum_planes[i].w;
inside &= d > 0;
//return false; //with flag works faster
}
return inside;
}
__forceinline bool RightParallelepipedInFrustum2(vec4 &Min, vec4 &Max, vec4 *frustum_planes)
{
//this is just example of basic idea - how BOX culling works, both AABB and OBB
//Min & Max are 2 world space box points. For AABB-drustum culling
//We may use transformed (by object matrix) to world space 8 box points. Replace Min & Max in equations and we get OBB-frustum.
//test all 6 frustum planes
for (int i = 0; i<6; i++)
{
//try to find such plane for which all 8 box points behind it
//test all 8 box points against frustum plane
//calculate distance from point to plane
//if point infront of the plane (dist > 0) - this is not separating plane
if (frustum_planes[i][0] * Min[0] + frustum_planes[i][1] * Max[1] + frustum_planes[i][2] * Min[2] + frustum_planes[i][3]>0)
continue;
if (frustum_planes[i][0] * Min[0] + frustum_planes[i][1] * Max[1] + frustum_planes[i][2] * Max[2] + frustum_planes[i][3]>0)
continue;
if (frustum_planes[i][0] * Max[0] + frustum_planes[i][1] * Max[1] + frustum_planes[i][2] * Max[2] + frustum_planes[i][3]>0)
continue;
if (frustum_planes[i][0] * Max[0] + frustum_planes[i][1] * Max[1] + frustum_planes[i][2] * Min[2] + frustum_planes[i][3]>0)
continue;
if (frustum_planes[i][0] * Max[0] + frustum_planes[i][1] * Min[1] + frustum_planes[i][2] * Min[2] + frustum_planes[i][3]>0)
continue;
if (frustum_planes[i][0] * Max[0] + frustum_planes[i][1] * Min[1] + frustum_planes[i][2] * Max[2] + frustum_planes[i][3]>0)
continue;
if (frustum_planes[i][0] * Min[0] + frustum_planes[i][1] * Min[1] + frustum_planes[i][2] * Max[2] + frustum_planes[i][3]>0)
continue;
if (frustum_planes[i][0] * Min[0] + frustum_planes[i][1] * Min[1] + frustum_planes[i][2] * Min[2] + frustum_planes[i][3]>0)
continue;
return false;
}
return true;
}
__forceinline bool OBBInFrustum(const vec3 &Min, const vec3 &Max, mat4 &obj_transform_mat, mat4 &cam_modelview_proj_mat)
{
//transform all 8 box points to clip space
//clip space because we easily can test points outside required unit cube
//NOTE: for DirectX we should test z coordinate from 0 to w (-w..w - for OpenGL), look for transformations / clipping box differences
//matrix to transfrom points to clip space
mat4 to_clip_space_mat = cam_modelview_proj_mat * obj_transform_mat;
//transform all 8 box points to clip space
vec4 obb_points[8];
obb_points[0] = to_clip_space_mat * vec4(Min[0], Max[1], Min[2], 1.f);
obb_points[1] = to_clip_space_mat * vec4(Min[0], Max[1], Max[2], 1.f);
obb_points[2] = to_clip_space_mat * vec4(Max[0], Max[1], Max[2], 1.f);
obb_points[3] = to_clip_space_mat * vec4(Max[0], Max[1], Min[2], 1.f);
obb_points[4] = to_clip_space_mat * vec4(Max[0], Min[1], Min[2], 1.f);
obb_points[5] = to_clip_space_mat * vec4(Max[0], Min[1], Max[2], 1.f);
obb_points[6] = to_clip_space_mat * vec4(Min[0], Min[1], Max[2], 1.f);
obb_points[7] = to_clip_space_mat * vec4(Min[0], Min[1], Min[2], 1.f);
bool outside = false, outside_positive_plane, outside_negative_plane;
//we have 6 frustum planes, which in clip space is unit cube (for GL) with -1..1 range
for (int i = 0; i < 3; i++) //3 because we test positive & negative plane at once
{
//if all 8 points outside one of the plane
//actually it is vertex normalization xyz / w, then compare if all 8points coordinates < -1 or > 1
outside_positive_plane =
obb_points[0][i] > obb_points[0].w &&
obb_points[1][i] > obb_points[1].w &&
obb_points[2][i] > obb_points[2].w &&
obb_points[3][i] > obb_points[3].w &&
obb_points[4][i] > obb_points[4].w &&
obb_points[5][i] > obb_points[5].w &&
obb_points[6][i] > obb_points[6].w &&
obb_points[7][i] > obb_points[7].w;
outside_negative_plane =
obb_points[0][i] < -obb_points[0].w &&
obb_points[1][i] < -obb_points[1].w &&
obb_points[2][i] < -obb_points[2].w &&
obb_points[3][i] < -obb_points[3].w &&
obb_points[4][i] < -obb_points[4].w &&
obb_points[5][i] < -obb_points[5].w &&
obb_points[6][i] < -obb_points[6].w &&
obb_points[7][i] < -obb_points[7].w;
outside = outside || outside_positive_plane || outside_negative_plane;
//if (outside_positive_plane || outside_negative_plane)
//return false;
}
return !outside;
//return true;
}
void simple_culling_spheres(BSphere *sphere_data, int num_objects, int *culling_res, vec4 *frustum_planes)
{
for (int i = 0; i < num_objects; i++)
culling_res[i] = !SphereInFrustum(sphere_data[i].pos, sphere_data[i].r, &frustum_planes[0]);
}
void simple_culling_aabb(AABB *aabb_data, int num_objects, int *culling_res, vec4 *frustum_planes)
{
for (int i = 0; i < num_objects; i++)
culling_res[i] = !RightParallelepipedInFrustum(aabb_data[i].box_min, aabb_data[i].box_max, &frustum_planes[0]);
}
void simple_culling_obb(int first_processing_oject, int num_objects, int *culling_res, vec4 *frustum_planes)
{
for (int i = first_processing_oject; i < first_processing_oject + num_objects; i++)
culling_res[i] = !OBBInFrustum(box_min, box_max, obj_mat[i], camera_view_proj_matrix);
}
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------sse culling
void sse_culling_spheres(BSphere *sphere_data, int num_objects, int *culling_res, vec4 *frustum_planes)
{
float *sphere_data_ptr = reinterpret_cast<float*>(&sphere_data[0]);
int *culling_res_sse = &culling_res[0];
//to optimize calculations we gather xyzw elements in separate vectors
__m128 zero_v = _mm_setzero_ps();
__m128 frustum_planes_x[6];
__m128 frustum_planes_y[6];
__m128 frustum_planes_z[6];
__m128 frustum_planes_d[6];
int i, j;
for (i = 0; i < 6; i++)
{
frustum_planes_x[i] = _mm_set1_ps(frustum_planes[i].x);
frustum_planes_y[i] = _mm_set1_ps(frustum_planes[i].y);
frustum_planes_z[i] = _mm_set1_ps(frustum_planes[i].z);
frustum_planes_d[i] = _mm_set1_ps(frustum_planes[i].w);
}
//we process 4 objects per step
for (i = 0; i < num_objects; i += 4)
{
//load bounding sphere data
__m128 spheres_pos_x = _mm_load_ps(sphere_data_ptr);
__m128 spheres_pos_y = _mm_load_ps(sphere_data_ptr + 4);
__m128 spheres_pos_z = _mm_load_ps(sphere_data_ptr + 8);
__m128 spheres_radius = _mm_load_ps(sphere_data_ptr + 12);
sphere_data_ptr += 16;
//but for our calculations we need transpose data, to collect x, y, z and w coordinates in separate vectors
_MM_TRANSPOSE4_PS(spheres_pos_x, spheres_pos_y, spheres_pos_z, spheres_radius);
__m128 spheres_neg_radius = _mm_sub_ps(zero_v, spheres_radius); // negate all elements
//http://fastcpp.blogspot.ru/2011/03/changing-sign-of-float-values-using-sse.html
__m128 intersection_res = _mm_setzero_ps();
for (j = 0; j < 6; j++) //plane index
{
//1. calc distance to plane dot(sphere_pos.xyz, plane.xyz) + plane.w
//2. if distance < sphere radius, then sphere outside frustum
__m128 dot_x = _mm_mul_ps(spheres_pos_x, frustum_planes_x[j]);
__m128 dot_y = _mm_mul_ps(spheres_pos_y, frustum_planes_y[j]);
__m128 dot_z = _mm_mul_ps(spheres_pos_z, frustum_planes_z[j]);
__m128 sum_xy = _mm_add_ps(dot_x, dot_y);
__m128 sum_zw = _mm_add_ps(dot_z, frustum_planes_d[j]);
__m128 distance_to_plane = _mm_add_ps(sum_xy, sum_zw);
__m128 plane_res = _mm_cmple_ps(distance_to_plane, spheres_neg_radius); //dist < -sphere_r ?
intersection_res = _mm_or_ps(intersection_res, plane_res); //if yes - sphere behind the plane & outside frustum
}
//store result
__m128i intersection_res_i = _mm_cvtps_epi32(intersection_res); //convert to integers
_mm_store_si128((__m128i *)&culling_res_sse[i], intersection_res_i); //store result in culling_res_sse[]
}
}
void sse_culling_aabb(AABB *aabb_data, int num_objects, int *culling_res, vec4 *frustum_planes)
{
float *aabb_data_ptr = reinterpret_cast<float*>(&aabb_data[0]);
int *culling_res_sse = &culling_res[0];
//to optimize calculations we gather xyzw elements in separate vectors
__m128 zero_v = _mm_setzero_ps();
__m128 frustum_planes_x[6];
__m128 frustum_planes_y[6];
__m128 frustum_planes_z[6];
__m128 frustum_planes_d[6];
int i, j;
for (i = 0; i < 6; i++)
{
frustum_planes_x[i] = _mm_set1_ps(frustum_planes[i].x);
frustum_planes_y[i] = _mm_set1_ps(frustum_planes[i].y);
frustum_planes_z[i] = _mm_set1_ps(frustum_planes[i].z);
frustum_planes_d[i] = _mm_set1_ps(frustum_planes[i].w);
}
__m128 zero = _mm_setzero_ps();
//we process 4 objects per step
for (i = 0; i < num_objects; i += 4)
{
//load objects data
//load aabb min
__m128 aabb_min_x = _mm_load_ps(aabb_data_ptr);
__m128 aabb_min_y = _mm_load_ps(aabb_data_ptr + 8);
__m128 aabb_min_z = _mm_load_ps(aabb_data_ptr + 16);
__m128 aabb_min_w = _mm_load_ps(aabb_data_ptr + 24);
//load aabb max
__m128 aabb_max_x = _mm_load_ps(aabb_data_ptr + 4);
__m128 aabb_max_y = _mm_load_ps(aabb_data_ptr + 12);
__m128 aabb_max_z = _mm_load_ps(aabb_data_ptr + 20);
__m128 aabb_max_w = _mm_load_ps(aabb_data_ptr + 28);
aabb_data_ptr += 32;
//for now we have points in vectors aabb_min_x..w, but for calculations we need to xxxx yyyy zzzz vectors representation - just transpose data
_MM_TRANSPOSE4_PS(aabb_min_x, aabb_min_y, aabb_min_z, aabb_min_w);
_MM_TRANSPOSE4_PS(aabb_max_x, aabb_max_y, aabb_max_z, aabb_max_w);
__m128 intersection_res = _mm_setzero_ps();
for (j = 0; j < 6; j++) //plane index
{
//this code is similar to what we make in simple culling
//pick closest point to plane and check if it begind the plane. if yes - object outside frustum
//dot product, separate for each coordinate, for min & max aabb points
__m128 aabbMin_frustumPlane_x = _mm_mul_ps(aabb_min_x, frustum_planes_x[j]);
__m128 aabbMin_frustumPlane_y = _mm_mul_ps(aabb_min_y, frustum_planes_y[j]);
__m128 aabbMin_frustumPlane_z = _mm_mul_ps(aabb_min_z, frustum_planes_z[j]);
__m128 aabbMax_frustumPlane_x = _mm_mul_ps(aabb_max_x, frustum_planes_x[j]);
__m128 aabbMax_frustumPlane_y = _mm_mul_ps(aabb_max_y, frustum_planes_y[j]);
__m128 aabbMax_frustumPlane_z = _mm_mul_ps(aabb_max_z, frustum_planes_z[j]);
//we have 8 box points, but we need pick closest point to plane. Just take max
__m128 res_x = _mm_max_ps(aabbMin_frustumPlane_x, aabbMax_frustumPlane_x);
__m128 res_y = _mm_max_ps(aabbMin_frustumPlane_y, aabbMax_frustumPlane_y);
__m128 res_z = _mm_max_ps(aabbMin_frustumPlane_z, aabbMax_frustumPlane_z);
//dist to plane = dot(aabb_point.xyz, plane.xyz) + plane.w
__m128 sum_xy = _mm_add_ps(res_x, res_y);
__m128 sum_zw = _mm_add_ps(res_z, frustum_planes_d[j]);
__m128 distance_to_plane = _mm_add_ps(sum_xy, sum_zw);
__m128 plane_res = _mm_cmple_ps(distance_to_plane, zero); //dist from closest point to plane < 0 ?
intersection_res = _mm_or_ps(intersection_res, plane_res); //if yes - aabb behind the plane & outside frustum
}
//store result
__m128i intersection_res_i = _mm_cvtps_epi32(intersection_res); //convert to integers
_mm_store_si128((__m128i *)&culling_res_sse[i], intersection_res_i); //store result in culling_res_sse[]
}
}
void sse_culling_obb(int firs_processing_object, int num_objects, int *culling_res, mat4 &cam_modelview_proj_mat)
{
mat4_sse sse_camera_mat(cam_modelview_proj_mat);
mat4_sse sse_clip_space_mat;
//box points in local space
__m128 obb_points_sse[8];
obb_points_sse[0] = _mm_set_ps(1.f, box_min[2], box_max[1], box_min[0]);
obb_points_sse[1] = _mm_set_ps(1.f, box_max[2], box_max[1], box_min[0]);
obb_points_sse[2] = _mm_set_ps(1.f, box_max[2], box_max[1], box_max[0]);
obb_points_sse[3] = _mm_set_ps(1.f, box_min[2], box_max[1], box_max[0]);
obb_points_sse[4] = _mm_set_ps(1.f, box_min[2], box_min[1], box_max[0]);
obb_points_sse[5] = _mm_set_ps(1.f, box_max[2], box_min[1], box_max[0]);
obb_points_sse[6] = _mm_set_ps(1.f, box_max[2], box_min[1], box_min[0]);
obb_points_sse[7] = _mm_set_ps(1.f, box_min[2], box_min[1], box_min[0]);
ALIGN_SSE int obj_culling_res[4];
__m128 zero_v = _mm_setzero_ps();
int i, j;
//process one object per step
for (i = firs_processing_object; i < firs_processing_object+num_objects; i++)
{
//clip space matrix = camera_view_proj * obj_mat
sse_mat4_mul(sse_clip_space_mat, sse_camera_mat, sse_obj_mat[i]);
//initially assume that planes are separating
//if any axis is separating - we get 0 in certain outside_* place
__m128 outside_positive_plane = _mm_set1_ps(-1.f); //NOTE: there should be negative value..
__m128 outside_negative_plane = _mm_set1_ps(-1.f); //because _mm_movemask_ps (while storing result) cares abount 'most significant bits' (it is sign of float value)
//for all 8 box points
for (j = 0; j < 8; j++)
{
//transform point to clip space
__m128 obb_transformed_point = sse_mat4_mul_vec4(sse_clip_space_mat, obb_points_sse[j]);
//gather w & -w
__m128 wwww = _mm_shuffle_ps(obb_transformed_point, obb_transformed_point, _MM_SHUFFLE(3, 3, 3, 3)); //get w
__m128 wwww_neg = _mm_sub_ps(zero_v, wwww); // negate all elements
//box_point.xyz > box_point.w || box_point.xyz < -box_point.w ?
//similar to point normalization: point.xyz /= point.w; And compare: point.xyz > 1 && point.xyz < -1
__m128 outside_pos_plane = _mm_cmpge_ps(obb_transformed_point, wwww);
__m128 outside_neg_plane = _mm_cmple_ps(obb_transformed_point, wwww_neg);
//if at least 1 of 8 points in front of the plane - we get 0 in outside_* flag
outside_positive_plane = _mm_and_ps(outside_positive_plane, outside_pos_plane);
outside_negative_plane = _mm_and_ps(outside_negative_plane, outside_neg_plane);
}
//all 8 points xyz < -1 or > 1 ?
__m128 outside = _mm_or_ps(outside_positive_plane, outside_negative_plane);
//store result, if any of 3 axes is separating (i.e. outside != 0) - object outside frustum
//so, object inside frustum only if outside == 0 (there are no separating axes)
culling_res[i] = _mm_movemask_ps(outside) & 0x7; //& 0x7 mask, because we interested only in 3 axes
}
}
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------culling
void do_cpu_culling()
{
//culling
Timer timer;
if (only_culling_measurements)
timer.StartTiming();
if (use_multithreading)
{
process_multithreading_culling();
wate_multithreading_culling_done();
} else
cull_objects(0, MAX_SCENE_OBJECTS);
//computing time
if (only_culling_measurements)
{
//calculate avg dt for 1k frames
static int num_attempts = 0;
static double accumulated_dt = 0.0;
accumulated_dt += timer.TimeElapsedInMS();
num_attempts++;
if (num_attempts == 1000)
{
double avg_dt = accumulated_dt / 1000.0;
char str[64];
sprintf(str, "culling takes: %.2f", float(avg_dt));
SetWindowText(g_hWnd, str);
num_attempts = 0;
accumulated_dt = 0.0;
}
}
//collect & transfer visible instances data to gpu
num_visible_instances = 0;
for (int i = 0; i < MAX_SCENE_OBJECTS; i++) if (culling_res[i] == 0)
{
visible_instance_info[num_visible_instances * 2 + 0] = instance_info[i * 2 + 0];
visible_instance_info[num_visible_instances * 2 + 1] = instance_info[i * 2 + 1];
num_visible_instances++;
}
//copy to gpu
if (enable_rendering_objects)
{
//lock buffer & copy visible instances data
glBindBuffer(GL_TEXTURE_BUFFER, dips_texture_buffer);
float* tbo_data = (float*)glMapBuffer(GL_TEXTURE_BUFFER, GL_WRITE_ONLY);
//copy instances data
memcpy(&tbo_data[0], &visible_instance_info[0], sizeof(vec4)*num_visible_instances * 2);
glUnmapBuffer(GL_TEXTURE_BUFFER);
glBindBuffer(GL_TEXTURE_BUFFER, 0);
}
}
void do_gpu_culling()
{
culling_shader.bind();
int cur_frame = frame_index % 2;
int prev_frame = (frame_index + 1) % 2;
//prepare feedback & query
glEnable(GL_RASTERIZER_DISCARD);
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, dips_texture_buffer);
glBeginQuery(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN, num_visible_instances_query[cur_frame]);
glBeginTransformFeedback(GL_POINTS);
//render cloud of points which we interprent as objects data
glBindVertexArray(all_instances_data_vao);
glDrawArrays(GL_POINTS, 0, MAX_SCENE_OBJECTS);
glBindVertexArray(0);
//disable all
glEndTransformFeedback();
glEndQuery(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN);
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
glDisable(GL_RASTERIZER_DISCARD);
//get feedback from prev frame
num_visible_instances = 0;
glGetQueryObjectiv(num_visible_instances_query[prev_frame], GL_QUERY_RESULT, &num_visible_instances);
//next frame
frame_index++;
}
void cull_objects(int first_processing_oject, int num_processing_ojects)
{
switch (culling_mode)
{
case SIMPLE_SPHERES:
simple_culling_spheres(&sphere_data[first_processing_oject], num_processing_ojects, &culling_res[first_processing_oject], &frustum.frustum_planes[0]);
break;
case SIMPLE_AABB:
simple_culling_aabb(&aabb_data[first_processing_oject], num_processing_ojects, &culling_res[first_processing_oject], &frustum.frustum_planes[0]);
break;
case SIMPLE_OBB:
simple_culling_obb(first_processing_oject, num_processing_ojects, &culling_res[0], &frustum.frustum_planes[0]);
break;
case SSE_SPHERES:
sse_culling_spheres(&sphere_data[first_processing_oject], num_processing_ojects, &culling_res[first_processing_oject], &frustum.frustum_planes[0]);
break;
case SSE_AABB:
sse_culling_aabb(&aabb_data[first_processing_oject], num_processing_ojects, &culling_res[first_processing_oject], &frustum.frustum_planes[0]);
break;
case SSE_OBB:
sse_culling_obb(first_processing_oject, num_processing_ojects, &culling_res[0], camera_view_proj_matrix);
break;
}
}
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------threads
Worker::Worker() : first_processing_oject(0), num_processing_ojects(0)
{
//create 2 events: 1. to signal that we have a job 2.signal that we finished job
has_jobs_event = CreateEvent(NULL, false, false, NULL);
jobs_finished_event = CreateEvent(NULL, false, true, NULL);
}
Worker::~Worker()
{
CloseHandle(has_jobs_event);
CloseHandle(jobs_finished_event);
}
void Worker::doJob()
{
//make our part of work
cull_objects(first_processing_oject, num_processing_ojects);
}
unsigned __stdcall thread_func(void* arguments)
{
printf("In thread...\n");
Worker *worker = static_cast<Worker*>(arguments);
//each worker has endless loop untill we signal to quit (stop_work flag)
while (true)
{
//wait for starting jobs
//if we have no job - just wait (has_jobs_event event). We do not wasting cpu work. Events designed for this.
WaitForSingleObject(worker->has_jobs_event, INFINITE);
//if we have signal to break - exit endless loop
if (worker->stop_work)
break;
//do job
worker->doJob();
//signal that we finished the job
SetEvent(worker->jobs_finished_event);
}
_endthreadex(0);
return 0;
}
void create_threads()
{
//create the threads
//split the work into parts between threads
int worker_num_processing_ojects = MAX_SCENE_OBJECTS / num_workers;
int first_processing_oject = 0;
int i;
for (i = 0; i < num_workers; i++)
{
//create threads
workers[i].thread_handle = (HANDLE)_beginthreadex(NULL, 0, &thread_func, &workers[i], CREATE_SUSPENDED, &workers[i].thread_id);
thread_handles[i] = workers[i].thread_handle;
//set threads parameters
workers[i].first_processing_oject = first_processing_oject;
workers[i].num_processing_ojects = worker_num_processing_ojects;
first_processing_oject += worker_num_processing_ojects;
}
//run workers to do their jobs
for (int i = 0; i < num_workers; i++)
ResumeThread(workers[i].thread_handle);
}
void threads_close()
{
//signal to stop the work for all threads
for (int i = 0; i < num_workers; i++)
{
workers[i].stop_work = true;
SetEvent(workers[i].has_jobs_event);
}
//wait all workers to finish current jobs
WaitForMultipleObjects(num_workers, &thread_handles[0], true, INFINITE);
//remove workers
//_endthreadex is called automatically when the thread returns from the routine passed as a parameter
}
void process_multithreading_culling()
{
//signal workers that they have the job
for (int i = 0; i < num_workers; i++)
SetEvent(workers[i].has_jobs_event);
}
void wate_multithreading_culling_done()
{
//wait threads to do their jobs
HANDLE wait_events[num_workers];
for (int i = 0; i < num_workers; i++)
wait_events[i] = workers[i].jobs_finished_event;
WaitForMultipleObjects(num_workers, &wait_events[0], true, INFINITE);
}
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------render
void process_key(int key)
{
switch(key)
{
case VK_SPACE:
culling_enabled = !culling_enabled;
break;
case 'H':
enable_rendering_objects = !enable_rendering_objects;
break;
case VK_NUMPAD0:
case '0':
use_multithreading = !use_multithreading;
use_gpu_culling = false;
break;
case VK_NUMPAD1:
case '1':
culling_mode = SIMPLE_SPHERES;
use_gpu_culling = false;
break;
case VK_NUMPAD2:
case '2':
culling_mode = SIMPLE_AABB;
use_gpu_culling = false;
break;
case VK_NUMPAD3:
case '3':
culling_mode = SIMPLE_OBB;
use_gpu_culling = false;
break;
case VK_NUMPAD4:
case '4':
culling_mode = SSE_SPHERES;
use_gpu_culling = false;
break;
case VK_NUMPAD5:
case '5':
culling_mode = SSE_AABB;
use_gpu_culling = false;
break;
case VK_NUMPAD6:
case '6':
culling_mode = SSE_OBB;
use_gpu_culling = false;
break;
case VK_NUMPAD7:
case '7':
use_gpu_culling = !use_gpu_culling;
break;
};
}
void RenderScene()
{
int i, j, k;
//time
static double lastTime = timeGetTime() * 0.001;
double timeleft = 0.0;
double currentTime = timeGetTime() * 0.001;
timeleft = currentTime - lastTime;
const double min_dt = 1.0f / 20.0;
if (timeleft > min_dt) timeleft = min_dt;
lastTime = currentTime;
total_time += timeleft;
//camera
camera.Update();
camera_view_matrix.look_at(camera.Position(), camera.View(), camera.UpVector());
camera_proj_matrix.perspective(45.f, (float)window_width / (float)window_height, zNear, zFar);
camera_view_proj_matrix = camera_proj_matrix * camera_view_matrix;
//RENDER
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, window_width, window_height);
glClearColor(110.0f / 255.0f, 149.0f / 255.0f, 224.0f / 255.0f, 0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glDisable(GL_BLEND);
//objects culling
if (culling_enabled)
{
//prepare camera & frustum
saved_inv_view_proj_matrix = camera_view_proj_matrix.inverse();
frustum.CalculateFrustum(camera_view_matrix, camera_proj_matrix);
//switch between gpu and cpu culling
if (use_gpu_culling)
do_gpu_culling();
else
do_cpu_culling();
}
//render ground (just a plane)
ground_shader.bind();
glBindVertexArray(ground_vao_id);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, NULL);
glBindVertexArray(0);
//geometry (colored boxes)
if (enable_rendering_objects)
{
glEnable(GL_CULL_FACE);
geometry_shader.bind();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_BUFFER, dips_texture_buffer_tex);
glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, dips_texture_buffer);
glBindVertexArray(geometry_vao_id);
glDrawElementsInstanced(GL_TRIANGLES, 36, GL_UNSIGNED_INT, NULL, num_visible_instances);
glBindVertexArray(0);
}
//show frustum
if (!culling_enabled)
{
show_frustum_shader.bind();
glBindVertexArray(wire_box_vao_id);
glDrawElements(GL_LINES, 24, GL_UNSIGNED_INT, NULL);
glBindVertexArray(0);
}
glFlush();
SwapBuffers(g_hDC);
}<file_sep>#ifndef __GLEXT_H__
#define __GLEXT_H__
#ifdef _WIN32
#include <windows.h>
#endif
#include <GL/gl.h>
#include <GL/glext.h>
#include <GL/wglext.h>
extern PFNGLGETPROGRAMIVARBPROC glGetProgramivARB;
//min max
extern PFNGLMINMAXPROC glMinmax;
extern PFNGLGETMINMAXPROC glGetMinmax;
// stencil
extern PFNGLACTIVESTENCILFACEEXTPROC glActiveStencilFaceEXT;
//blend
extern PFNGLBLENDEQUATIONPROC glBlendEquation;
extern PFNGLBLENDFUNCSEPARATEEXTPROC glBlendFuncSeparateEXT;
//clear color
extern PFNGLCLEARCOLORIIEXTPROC glClearColorIiEXT;
extern PFNGLCLEARCOLORIUIEXTPROC glClearColorIuiEXT;
extern PFNGLCLEARBUFFERIVPROC glClearBufferiv;
extern PFNGLCLEARBUFFERUIVPROC glClearBufferuiv;
extern PFNGLCLEARBUFFERFVPROC glClearBufferfv;
extern PFNGLCLEARBUFFERFIPROC glClearBufferfi;
// textures
extern PFNGLACTIVETEXTUREARBPROC glActiveTextureARB;
extern PFNGLTEXIMAGE3DPROC glTexImage3D;
extern PFNGLCOPYTEXSUBIMAGE3DEXTPROC glCopyTexSubImage3DEXT;
extern PFNGLCOPYTEXSUBIMAGE3DPROC glCopyTexSubImage3D;
extern PFNGLMULTITEXCOORD3FARBPROC glMultiTexCoord3fARB;
extern PFNGLMULTITEXCOORD4FARBPROC glMultiTexCoord4fARB;
extern PFNGLMULTITEXCOORD4FVARBPROC glMultiTexCoord4fvARB;
extern PFNGLMULTITEXCOORD2FARBPROC glMultiTexCoord2fARB;
extern PFNGLMULTITEXCOORD2FVARBPROC glMultiTexCoord2fvARB;
extern PFNGLCLIENTACTIVETEXTUREARBPROC glClientActiveTextureARB;
extern PFNGLTEXSUBIMAGE3DPROC glTexSubImage3D;
extern PFNGLCOMPRESSEDTEXIMAGE2DPROC glCompressedTexImage2D;
extern PFNGLCOMPRESSEDTEXIMAGE2DARBPROC glCompressedTexImage2DARB;
extern PFNGLTEXPARAMETERIIVPROC glTexParameterIiv;
extern PFNGLGENERATEMIPMAPPROC glGenerateMipmap;
extern PFNGLMEMORYBARRIERPROC glMemoryBarrier;
extern PFNGLTEXTUREBARRIERPROC glTextureBarrier;
extern PFNGLTEXSTORAGE3DPROC glTexStorage3D;
extern PFNGLTEXSTORAGE2DPROC glTexStorage2D;
// arb programs
extern PFNGLGENPROGRAMSARBPROC glGenProgramsARB;
extern PFNGLBINDPROGRAMARBPROC glBindProgramARB;
extern PFNGLDELETEPROGRAMSARBPROC glDeleteProgramsARB;
extern PFNGLPROGRAMSTRINGARBPROC glProgramStringARB;
extern PFNGLPROGRAMENVPARAMETER4FARBPROC glProgramEnvParameter4fARB;
extern PFNGLPROGRAMENVPARAMETER4FVARBPROC glProgramEnvParameter4fvARB;
extern PFNGLPROGRAMLOCALPARAMETER4FARBPROC glProgramLocalParameter4fARB;
extern PFNGLPROGRAMLOCALPARAMETER4FVARBPROC glProgramLocalParameter4fvARB;
//shaders
extern PFNGLATTACHSHADERPROC glAttachShader;
extern PFNGLBINDATTRIBLOCATIONPROC glBindAttribLocation;
extern PFNGLCOMPILESHADERPROC glCompileShader;
extern PFNGLCREATEPROGRAMPROC glCreateProgram;
extern PFNGLCREATESHADERPROC glCreateShader;
extern PFNGLDELETEPROGRAMPROC glDeleteProgram;
extern PFNGLDELETESHADERPROC glDeleteShader;
extern PFNGLDETACHSHADERPROC glDetachShader;
extern PFNGLSHADERSOURCEPROC glShaderSource;
extern PFNGLLINKPROGRAMPROC glLinkProgram;
extern PFNGLUSEPROGRAMPROC glUseProgram;
extern PFNGLPROGRAMUNIFORM1IPROC glProgramUniform1i;
extern PFNGLVALIDATEPROGRAMPROC glValidateProgram;
extern PFNGLGETACTIVEATTRIBPROC glGetActiveAttrib;
extern PFNGLGETACTIVEUNIFORMPROC glGetActiveUniform;
//uniform buffer
extern PFNGLUNIFORMBUFFEREXTPROC glUniformBufferEXT;
//extern PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocationARB;
//texture buffer
extern PFNGLTEXBUFFERARBPROC glTexBufferARB;
//glPrimitiveRestartIndex
extern PFNGLPRIMITIVERESTARTINDEXPROC glPrimitiveRestartIndex;
extern PFNGLPRIMITIVERESTARTINDEXNVPROC glPrimitiveRestartIndexNV;
//instancing
extern PFNGLDRAWELEMENTSINSTANCEDEXTPROC glDrawElementsInstancedEXT;
extern PFNGLDRAWARRAYSINSTANCEDPROC glDrawArraysInstanced;
extern PFNGLDRAWELEMENTSINSTANCEDPROC glDrawElementsInstanced;
extern PFNGLMULTIDRAWELEMENTSINDIRECTPROC glMultiDrawElementsIndirect;
extern PFNGLDRAWARRAYSINDIRECTPROC glDrawArraysIndirect;
extern PFNGLTEXBUFFERPROC glTexBuffer;
//extern PFNGLPRIMITIVERESTARTINDEXPROC glPrimitiveRestartIndex;
extern PFNGLCOPYBUFFERSUBDATAPROC glCopyBufferSubData;
// nv programs
extern PFNGLGENPROGRAMSNVPROC glGenProgramsNV;
extern PFNGLBINDPROGRAMNVPROC glBindProgramNV;
extern PFNGLDELETEPROGRAMSNVPROC glDeleteProgramsNV;
extern PFNGLLOADPROGRAMNVPROC glLoadProgramNV;
extern PFNGLPROGRAMNAMEDPARAMETER4FNVPROC glProgramNamedParameter4fNV;
extern PFNGLPROGRAMNAMEDPARAMETER4FVNVPROC glProgramNamedParameter4fvNV;
// attrib arrays
extern PFNGLENABLEVERTEXATTRIBARRAYARBPROC glEnableVertexAttribArrayARB;
extern PFNGLVERTEXATTRIBPOINTERARBPROC glVertexAttribPointerARB;
extern PFNGLDISABLEVERTEXATTRIBARRAYARBPROC glDisableVertexAttribArrayARB;
extern PFNGLVERTEXATTRIB4FVARBPROC glVertexAttrib4fvARB;
extern PFNGLGETATTRIBLOCATIONARBPROC glGetAttribLocation;
extern PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer;
extern PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray;
extern PFNGLDISABLEVERTEXATTRIBARRAYPROC glDisableVertexAttribArray;
extern PFNGLVERTEXATTRIBDIVISORPROC glVertexAttribDivisor;
// vertex buffer object
extern PFNGLGENBUFFERSARBPROC glGenBuffersARB;
extern PFNGLBINDBUFFERARBPROC glBindBufferARB;
extern PFNGLBUFFERDATAARBPROC glBufferDataARB;
extern PFNGLDELETEBUFFERSARBPROC glDeleteBuffersARB;
extern PFNGLDRAWRANGEELEMENTSPROC glDrawRangeElements;
extern PFNGLMAPBUFFERARBPROC glMapBufferARB;
extern PFNGLUNMAPBUFFERARBPROC glUnmapBufferARB;
extern PFNGLBINDBUFFERRANGEPROC glBindBufferRange;
extern PFNGLBINDBUFFERBASEPROC glBindBufferBase;
extern PFNGLBINDIMAGETEXTUREPROC glBindImageTexture;
extern PFNGLBINDBUFFERPROC glBindBuffer;
extern PFNGLDELETEBUFFERSPROC glDeleteBuffers;
extern PFNGLGENBUFFERSPROC glGenBuffers;
extern PFNGLBUFFERDATAPROC glBufferData;
extern PFNGLMAPBUFFERPROC glMapBuffer;
extern PFNGLUNMAPBUFFERPROC glUnmapBuffer;
extern PFNGLMAPBUFFERRANGEPROC glMapBufferRange;
// vertex array
extern PFNGLBINDVERTEXARRAYPROC glBindVertexArray;
extern PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArray;
extern PFNGLGENVERTEXARRAYSPROC glGenVertexArrays;
//extern PFNGLISVERTEXARRAYPROC glIsVertexArray;
//transform feedback
extern PFNGLBINDTRANSFORMFEEDBACKPROC glBindTransformFeedback;
extern PFNGLDELETETRANSFORMFEEDBACKSPROC glDeleteTransformFeedback;
extern PFNGLGENTRANSFORMFEEDBACKSPROC glGenTransformFeedback;
extern PFNGLBEGINTRANSFORMFEEDBACKPROC glBeginTransformFeedback;
extern PFNGLENDTRANSFORMFEEDBACKPROC glEndTransformFeedback;
extern PFNGLTRANSFORMFEEDBACKVARYINGSPROC glTransformFeedbackVaryings;
extern PFNGLTRANSFORMFEEDBACKATTRIBSNVPROC glTransformFeedbackAttribsNV;
extern PFNGLBINDBUFFERBASENVPROC glBindBufferBaseNV;
extern PFNGLBEGINTRANSFORMFEEDBACKNVPROC glBeginTransformFeedbackNV;
extern PFNGLENDTRANSFORMFEEDBACKNVPROC glEndTransformFeedbackNV;
extern PFNGLBINDBUFFEROFFSETNVPROC glBindBufferOffsetNV;
extern PFNGLACTIVEVARYINGNVPROC glActiveVaryingNV;
extern PFNGLGETVARYINGLOCATIONNVPROC glGetVaryingLocationNV;
extern PFNGLTRANSFORMFEEDBACKVARYINGSNVPROC glTransformFeedbackVaryingsNV;
// occlision query
extern PFNGLGENQUERIESARBPROC glGenQueriesARB;
extern PFNGLDELETEQUERIESARBPROC glDeleteQueriesARB;
extern PFNGLBEGINQUERYARBPROC glBeginQueryARB;
extern PFNGLENDQUERYARBPROC glEndQueryARB;
extern PFNGLGETQUERYIVARBPROC glGetQueryivARB;
extern PFNGLGETQUERYOBJECTIVARBPROC glGetQueryObjectivARB;
extern PFNGLGETQUERYOBJECTUIVARBPROC glGetQueryObjectuivARB;
extern PFNGLGETQUERYOBJECTUI64VPROC glGetQueryObjectui64v;
extern PFNGLQUERYCOUNTERPROC glQueryCounter;
extern PFNGLBEGINQUERYINDEXEDPROC glBeginQueryIndexed;
extern PFNGLENDQUERYINDEXEDPROC glEndQueryIndexed;
extern PFNGLGETQUERYINDEXEDIVPROC glGetQueryIndexediv;
extern PFNGLGENQUERIESPROC glGenQueries;
extern PFNGLDELETEQUERIESPROC glDeleteQueries;
extern PFNGLBEGINQUERYPROC glBeginQuery;
extern PFNGLENDQUERYPROC glEndQuery;
extern PFNGLGETQUERYOBJECTIVPROC glGetQueryObjectiv;
// glsl
extern PFNGLCREATEPROGRAMOBJECTARBPROC glCreateProgramObjectARB;
extern PFNGLCREATESHADEROBJECTARBPROC glCreateShaderObjectARB;
extern PFNGLSHADERSOURCEARBPROC glShaderSourceARB;
extern PFNGLCOMPILESHADERARBPROC glCompileShaderARB;
extern PFNGLATTACHOBJECTARBPROC glAttachObjectARB;
extern PFNGLDETACHOBJECTARBPROC glDetachObjectARB;
extern PFNGLDELETEOBJECTARBPROC glDeleteObjectARB;
extern PFNGLBINDATTRIBLOCATIONARBPROC glBindAttribLocationARB;
extern PFNGLLINKPROGRAMARBPROC glLinkProgramARB;
extern PFNGLGETINFOLOGARBPROC glGetInfoLogARB;
extern PFNGLGETOBJECTPARAMETERIVARBPROC glGetObjectParameterivARB;
extern PFNGLVALIDATEPROGRAMARBPROC glValidateProgramARB;
extern PFNGLUSEPROGRAMOBJECTARBPROC glUseProgramObjectARB;
extern PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocationARB;
extern PFNGLUNIFORM1FARBPROC glUniform1fARB;
extern PFNGLUNIFORM1FVARBPROC glUniform1fvARB;
extern PFNGLUNIFORM2FARBPROC glUniform2fARB;
extern PFNGLUNIFORM2FVARBPROC glUniform2fvARB;
extern PFNGLUNIFORM3FARBPROC glUniform3fARB;
extern PFNGLUNIFORM3FVARBPROC glUniform3fvARB;
extern PFNGLUNIFORM4FARBPROC glUniform4fARB;
extern PFNGLUNIFORM4FVARBPROC glUniform4fvARB;
extern PFNGLUNIFORMMATRIX3FVARBPROC glUniformMatrix3fvARB;
extern PFNGLUNIFORMMATRIX4FVARBPROC glUniformMatrix4fvARB;
extern PFNGLUNIFORM3IVARBPROC glUniform3ivARB;
extern PFNGLUNIFORM4IVARBPROC glUniform4ivARB;
extern PFNGLUNIFORM2IPROC glUniform2i;
extern PFNGLUNIFORMMATRIX2FVPROC glUniformMatrix2fv;
extern PFNGLUNIFORMMATRIX3FVPROC glUniformMatrix3fv;
extern PFNGLUNIFORMMATRIX4FVPROC glUniformMatrix4fv;
extern PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog;
extern PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog;
extern PFNGLGETSHADERIVPROC glGetShaderiv;
extern PFNGLGETPROGRAMIVPROC glGetProgramiv;
extern PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation;
extern PFNGLUNIFORM1IPROC glUniform1i;
extern PFNGLUNIFORM1FPROC glUniform1f;
extern PFNGLUNIFORM2FPROC glUniform2f;
extern PFNGLUNIFORM3FPROC glUniform3f;
extern PFNGLUNIFORM4FPROC glUniform4f;
extern PFNGLUNIFORM1FVPROC glUniform1fv;
extern PFNGLUNIFORM2FVPROC glUniform2fv;
extern PFNGLUNIFORM3FVPROC glUniform3fv;
extern PFNGLUNIFORM4FVPROC glUniform4fv;
extern PFNGLUNIFORM4IVPROC glUniform4iv;
extern PFNGLACTIVETEXTUREPROC glActiveTexture;
//texture sampler
extern PFNGLGENSAMPLERSPROC glGenSamplers;
extern PFNGLDELETESAMPLERSPROC glDeleteSamplers;
extern PFNGLBINDSAMPLERPROC glBindSampler;
extern PFNGLSAMPLERPARAMETERIPROC glSamplerParameteri;
extern PFNGLSAMPLERPARAMETERFVPROC glSamplerParameterfv;
// EXT_depth_bounds_test
extern PFNGLDEPTHBOUNDSEXTPROC glDepthBoundsEXT;
// EXT_framebuffer_object
extern PFNGLISRENDERBUFFEREXTPROC glIsRenderbufferEXT;
extern PFNGLBINDRENDERBUFFEREXTPROC glBindRenderbufferEXT;
extern PFNGLDELETERENDERBUFFERSEXTPROC glDeleteRenderbuffersEXT;
extern PFNGLGENRENDERBUFFERSEXTPROC glGenRenderbuffersEXT;
extern PFNGLRENDERBUFFERSTORAGEEXTPROC glRenderbufferStorageEXT;
extern PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC glGetRenderbufferParameterivEXT;
extern PFNGLISFRAMEBUFFEREXTPROC glIsFramebufferEXT;
extern PFNGLDELETEFRAMEBUFFERSEXTPROC glDeleteFramebuffersEXT;
extern PFNGLFRAMEBUFFERTEXTURE1DEXTPROC glFramebufferTexture1DEXT;
extern PFNGLFRAMEBUFFERTEXTURE3DEXTPROC glFramebufferTexture3DEXT;
extern PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC glFramebufferRenderbufferEXT;
extern PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC glGetFramebufferAttachmentParameterivEXT;
extern PFNGLGENERATEMIPMAPEXTPROC glGenerateMipmapEXT;
extern PFNGLFRAMEBUFFERTEXTURELAYEREXTPROC glFramebufferTextureLayerEXT;
extern PFNGLGENFRAMEBUFFERSPROC glGenFramebuffers;
extern PFNGLBINDFRAMEBUFFERPROC glBindFramebuffer;
extern PFNGLFRAMEBUFFERTEXTURE2DPROC glFramebufferTexture2D;
extern PFNGLCHECKFRAMEBUFFERSTATUSPROC glCheckFramebufferStatus;
extern PFNGLDELETEFRAMEBUFFERSPROC glDeleteFramebuffers;
extern PFNGLBINDFRAGDATALOCATIONPROC glBindFragDataLocation;
// EXT_texture3D
extern PFNGLTEXIMAGE3DEXTPROC glTexImage3DEXT;
// draw buffers from OpenGL 2.0
extern PFNGLDRAWBUFFERSPROC glDrawBuffers;
// ATI_draw_buffers
extern PFNGLDRAWBUFFERSATIPROC glDrawBuffersATI;
//glProvokingVertex
extern PFNGLPROVOKINGVERTEXPROC glProvokingVertex;
//debug mode
extern PFNGLDEBUGMESSAGECONTROLARBPROC glDebugMessageControlARB;
extern PFNGLDEBUGMESSAGEINSERTARBPROC glDebugMessageInsertARB;
extern PFNGLDEBUGMESSAGECALLBACKARBPROC glDebugMessageCallbackARB;
extern PFNGLGETDEBUGMESSAGELOGARBPROC glGetDebugMessageLogARB;
//wgl
extern PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB;
extern PFNWGLCREATEPBUFFERARBPROC wglCreatePbufferARB;
extern PFNWGLGETPBUFFERDCARBPROC wglGetPbufferDCARB;
extern PFNWGLRELEASEPBUFFERDCARBPROC wglReleasePbufferDCARB;
extern PFNWGLDESTROYPBUFFERARBPROC wglDestroyPbufferARB;
extern PFNWGLQUERYPBUFFERARBPROC wglQueryPbufferARB;
extern PFNWGLBINDTEXIMAGEARBPROC wglBindTexImageARB;
extern PFNWGLRELEASETEXIMAGEARBPROC wglReleaseTexImageARB;
extern PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB;
extern PFNWGLSETPBUFFERATTRIBARBPROC wglSetPbufferAttribARB;
extern PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB;
bool isExtensionSupported ( const char * ext, const char * extList );
bool isExtensionSupported ( const char * ext );
void glext_init();
#endif /* __GLEXT_H__ */
<file_sep>#ifndef _CAMERA_H
#define _CAMERA_H
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gl\gl.h>
#include <gl\glu.h>
#include "..\math\mathlib.h"
// This is our camera class
class CCamera {
public:
CCamera();
// These are are data access functions for our camera's private data
vec3 Position() { return m_vPosition; }
vec3 View() { return m_vView; }
vec3 UpVector() { return m_vUpVector; }
vec3 Strafe() { return m_vStrafe; }
// This changes the position, view, and up vector of the camera.
// This is primarily used for initialization
void PositionCamera(float positionX, float positionY, float positionZ,
float viewX, float viewY, float viewZ,
float upVectorX, float upVectorY, float upVectorZ);
// This rotates the camera's view around the position depending on the values passed in.
void RotateView(float angle, float X, float Y, float Z);
// This moves the camera's view by the mouse movements (First person view)
void SetViewByMouse();
// This strafes the camera left or right depending on the speed (+/-)
void StrafeCamera(float speed);
// This will move the camera forward or backward depending on the speed
void MoveCamera(float speed);
// This checks for keyboard movement
void CheckForMovement();
// This updates the camera's view and other data (Should be called each frame)
void Update();
bool show_framerate;
private:
vec3 m_vPosition; // The camera's position
vec3 m_vView; // The camera's view
vec3 m_vUpVector; // The camera's up vector
vec3 m_vStrafe; // The camera's strafe vector
float kSpeed; // This is how fast our camera moves
};
#endif<file_sep>#pragma comment(lib, "winmm.lib")
#include "camera.h"
extern HWND g_hWnd;
// Our global float that stores the elapsed time between the current and last frame
double g_FrameInterval = 0.0f;
void CalculateFrameRate(bool show_framerate)
{
static float framesPerSecond = 0.0f; // This will store our fps
static double lastTime = 0.0f; // This will hold the time from the last frame
static char strFrameRate[50] = {0}; // We will store the string here for the window title
static double frameTime = 0.0f; // This stores the last frame's time
// Get the current time in seconds
double currentTime = timeGetTime() * 0.001f;
// Here we store the elapsed time between the current and last frame,
// then keep the current frame in our static variable for the next frame.
g_FrameInterval = currentTime - frameTime;
frameTime = currentTime;
// Increase the frame counter
++framesPerSecond;
// Now we want to subtract the current time by the last time that was stored
// to see if the time elapsed has been over a second, which means we found our FPS.
if( currentTime - lastTime > 1.0f )
{
// Here we set the lastTime to the currentTime
lastTime = currentTime;
// Copy the frames per second into a string to display in the window title bar
float time_in_ms = 1000.f / (float)framesPerSecond;
sprintf(strFrameRate, "FPS: %d (%.2f ms)", int(framesPerSecond), time_in_ms);
// Set the window title bar to our string
if (show_framerate)
SetWindowText(g_hWnd, strFrameRate);
// Reset the frames per second
framesPerSecond = 0;
}
}
CCamera::CCamera()
{
m_vPosition = vec3(0.0, 0.0, 0.0);
m_vView = vec3(0.0, 0.5, 1.0);
m_vUpVector = vec3(0.0, 1.0, 0.0);
kSpeed = 10.f;
show_framerate = true;
}
void CCamera::PositionCamera(float positionX, float positionY, float positionZ,
float viewX, float viewY, float viewZ,
float upVectorX, float upVectorY, float upVectorZ)
{
m_vPosition = vec3(positionX, positionY, positionZ);
m_vView = vec3(viewX, viewY, viewZ);
m_vUpVector = vec3(upVectorX, upVectorY, upVectorZ);
}
vec3 RotateAroundVector(const vec3 &B ,const vec3 &R, float delta)
{
vec3 dz = R * (B * R);
vec3 dx = B - dz;
vec3 dy = dx ^ R;
return dx*cosf(delta)+dy*sinf(delta)+dz;
}
void CCamera::SetViewByMouse()
{
//rotate camera only when we pressed right mouse button
static int mouseX = 0;
static int mouseY = 0;
static bool r_button_pressed = false;
if ((GetKeyState(VK_RBUTTON) & 0x80) && !r_button_pressed)
{
POINT mousePos;
GetCursorPos(&mousePos);
mouseX = mousePos.x;
mouseY = mousePos.y;
}
r_button_pressed = (GetKeyState(VK_RBUTTON) & 0x80);
if (!r_button_pressed)
return;
POINT mousePos;
float angleY = 0.0f; // for looking up or down
float angleZ = 0.0f; // to rotate around the Y axis (Left and Right)
static float currentRotX = 0.0f;
// get the mouse's current X,Y position
GetCursorPos(&mousePos);
if( (mousePos.x == mouseX) && (mousePos.y == mouseY) ) return;
// restore mouse position
SetCursorPos(mouseX, mouseY);
//roate camera view
angleY = (float)( (mousePos.x - mouseX) ) / 200.0f;
angleZ = (float)( (mousePos.y - mouseY) ) / 200.0f;
static float lastRotX = 0.0f;
lastRotX = currentRotX; // We store off the currentRotX and will use it in when the angle is capped
// Here we keep track of the current rotation (for up and down) so that
// we can restrict the camera from doing a full 360 loop.
currentRotX += angleZ;
vec3 vView = m_vView - m_vPosition;
vec3 new_dir = RotateAroundVector(vView, vec3(0,1,0), angleY);
vec3 vAxis = new_dir ^ m_vUpVector;
vAxis.y = 0;
vAxis.normalize();
vec3 new_dir2 = RotateAroundVector(new_dir, vAxis, angleZ);
m_vView = m_vPosition + new_dir2;
m_vUpVector = vAxis^new_dir2;
m_vUpVector.normalize();
}
void CCamera::RotateView(float angle, float x, float y, float z)
{
vec3 vNewView;
// Get the view vector (The direction we are facing)
vec3 vView = m_vView - m_vPosition;
// Calculate the sine and cosine of the angle once
float cosTheta = (float)cos(angle);
float sinTheta = (float)sin(angle);
// Find the new x position for the new rotated point
vNewView.x = (cosTheta + (1 - cosTheta) * x * x) * vView.x;
vNewView.x += ((1 - cosTheta) * x * y - z * sinTheta) * vView.y;
vNewView.x += ((1 - cosTheta) * x * z + y * sinTheta) * vView.z;
// Find the new y position for the new rotated point
vNewView.y = ((1 - cosTheta) * x * y + z * sinTheta) * vView.x;
vNewView.y += (cosTheta + (1 - cosTheta) * y * y) * vView.y;
vNewView.y += ((1 - cosTheta) * y * z - x * sinTheta) * vView.z;
// Find the new z position for the new rotated point
vNewView.z = ((1 - cosTheta) * x * z - y * sinTheta) * vView.x;
vNewView.z += ((1 - cosTheta) * y * z + x * sinTheta) * vView.y;
vNewView.z += (cosTheta + (1 - cosTheta) * z * z) * vView.z;
// Now we just add the newly rotated vector to our position to set
// our new rotated view of our camera.
m_vView = m_vPosition + vNewView;
}
void CCamera::StrafeCamera(float speed)
{
// Add the strafe vector to our position
m_vPosition.x += m_vStrafe.x * speed;
m_vPosition.z += m_vStrafe.z * speed;
// Add the strafe vector to our view
m_vView.x += m_vStrafe.x * speed;
m_vView.z += m_vStrafe.z * speed;
}
void CCamera::MoveCamera(float speed)
{
// Get the current view vector (the direction we are looking)
vec3 vVector = m_vView - m_vPosition;
vVector.normalize();
m_vPosition += vVector * speed;
m_vView += vVector * speed;
}
void CCamera::CheckForMovement()
{
// Once we have the frame interval, we find the current speed
float speed = kSpeed * g_FrameInterval;
if(GetKeyState('W') & 0x80) {
MoveCamera(speed);
}
if(GetKeyState('S') & 0x80) {
MoveCamera(-speed);
}
if(GetKeyState('A') & 0x80) {
StrafeCamera(-speed);
}
if(GetKeyState('D') & 0x80) {
StrafeCamera(speed);
}
}
void CCamera::Update()
{
// Calculate our frame rate and set our frame interval for time-based movement
CalculateFrameRate(show_framerate);
// Move the camera's view by the mouse
SetViewByMouse();
// This checks to see if the keyboard was pressed
CheckForMovement();
// Initialize a variable for the cross product result
vec3 vCross = (m_vView - m_vPosition) ^ m_vUpVector;
// Normalize the strafe vector
m_vStrafe = vCross;
m_vStrafe.normalize();
}<file_sep>#include <windows.h>
#include "glext.h"
PFNGLGETPROGRAMIVARBPROC glGetProgramivARB;
//min max
PFNGLMINMAXPROC glMinmax;
PFNGLGETMINMAXPROC glGetMinmax;
// stencil
PFNGLACTIVESTENCILFACEEXTPROC glActiveStencilFaceEXT;
//blend
PFNGLBLENDEQUATIONPROC glBlendEquation;
PFNGLBLENDFUNCSEPARATEEXTPROC glBlendFuncSeparateEXT;
//clear color
PFNGLCLEARCOLORIIEXTPROC glClearColorIiEXT;
PFNGLCLEARCOLORIUIEXTPROC glClearColorIuiEXT;
PFNGLCLEARBUFFERIVPROC glClearBufferiv;
PFNGLCLEARBUFFERUIVPROC glClearBufferuiv;
PFNGLCLEARBUFFERFVPROC glClearBufferfv;
PFNGLCLEARBUFFERFIPROC glClearBufferfi;
// textures
PFNGLACTIVETEXTUREARBPROC glActiveTextureARB;
PFNGLTEXIMAGE3DPROC glTexImage3D;
PFNGLCOPYTEXSUBIMAGE3DEXTPROC glCopyTexSubImage3DEXT;
PFNGLCOPYTEXSUBIMAGE3DPROC glCopyTexSubImage3D;
PFNGLMULTITEXCOORD3FARBPROC glMultiTexCoord3fARB;
PFNGLMULTITEXCOORD4FARBPROC glMultiTexCoord4fARB;
PFNGLMULTITEXCOORD4FVARBPROC glMultiTexCoord4fvARB;
PFNGLMULTITEXCOORD2FARBPROC glMultiTexCoord2fARB;
PFNGLMULTITEXCOORD2FVARBPROC glMultiTexCoord2fvARB;
PFNGLCLIENTACTIVETEXTUREARBPROC glClientActiveTextureARB;
PFNGLTEXSUBIMAGE3DPROC glTexSubImage3D;
PFNGLCOMPRESSEDTEXIMAGE2DPROC glCompressedTexImage2D;
PFNGLCOMPRESSEDTEXIMAGE2DARBPROC glCompressedTexImage2DARB;
PFNGLTEXPARAMETERIIVPROC glTexParameterIiv;
PFNGLGENERATEMIPMAPPROC glGenerateMipmap;
PFNGLMEMORYBARRIERPROC glMemoryBarrier;
PFNGLTEXTUREBARRIERPROC glTextureBarrier;
PFNGLTEXSTORAGE3DPROC glTexStorage3D;
PFNGLTEXSTORAGE2DPROC glTexStorage2D;
// arb programs
PFNGLGENPROGRAMSARBPROC glGenProgramsARB;
PFNGLBINDPROGRAMARBPROC glBindProgramARB;
PFNGLDELETEPROGRAMSARBPROC glDeleteProgramsARB;
PFNGLPROGRAMSTRINGARBPROC glProgramStringARB;
PFNGLPROGRAMENVPARAMETER4FARBPROC glProgramEnvParameter4fARB;
PFNGLPROGRAMENVPARAMETER4FVARBPROC glProgramEnvParameter4fvARB;
PFNGLPROGRAMLOCALPARAMETER4FARBPROC glProgramLocalParameter4fARB;
PFNGLPROGRAMLOCALPARAMETER4FVARBPROC glProgramLocalParameter4fvARB;
//shaders
PFNGLATTACHSHADERPROC glAttachShader;
PFNGLBINDATTRIBLOCATIONPROC glBindAttribLocation;
PFNGLCOMPILESHADERPROC glCompileShader;
PFNGLCREATEPROGRAMPROC glCreateProgram;
PFNGLCREATESHADERPROC glCreateShader;
PFNGLDELETEPROGRAMPROC glDeleteProgram;
PFNGLDELETESHADERPROC glDeleteShader;
PFNGLDETACHSHADERPROC glDetachShader;
PFNGLSHADERSOURCEPROC glShaderSource;
PFNGLLINKPROGRAMPROC glLinkProgram;
PFNGLUSEPROGRAMPROC glUseProgram;
PFNGLPROGRAMUNIFORM1IPROC glProgramUniform1i;
PFNGLVALIDATEPROGRAMPROC glValidateProgram;
PFNGLGETACTIVEATTRIBPROC glGetActiveAttrib;
PFNGLGETACTIVEUNIFORMPROC glGetActiveUniform;
//uniform buffer
PFNGLUNIFORMBUFFEREXTPROC glUniformBufferEXT;
//PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocationARB;
//texture buffer
PFNGLTEXBUFFERARBPROC glTexBufferARB;
//glPrimitiveRestartIndex
PFNGLPRIMITIVERESTARTINDEXPROC glPrimitiveRestartIndex;
PFNGLPRIMITIVERESTARTINDEXNVPROC glPrimitiveRestartIndexNV;
//instancing
PFNGLDRAWELEMENTSINSTANCEDEXTPROC glDrawElementsInstancedEXT;
PFNGLDRAWARRAYSINSTANCEDPROC glDrawArraysInstanced;
PFNGLDRAWELEMENTSINSTANCEDPROC glDrawElementsInstanced;
PFNGLMULTIDRAWELEMENTSINDIRECTPROC glMultiDrawElementsIndirect;
PFNGLDRAWARRAYSINDIRECTPROC glDrawArraysIndirect;
PFNGLTEXBUFFERPROC glTexBuffer;
//PFNGLPRIMITIVERESTARTINDEXPROC glPrimitiveRestartIndex;
PFNGLCOPYBUFFERSUBDATAPROC glCopyBufferSubData;
// nv programs
PFNGLGENPROGRAMSNVPROC glGenProgramsNV;
PFNGLBINDPROGRAMNVPROC glBindProgramNV;
PFNGLDELETEPROGRAMSNVPROC glDeleteProgramsNV;
PFNGLLOADPROGRAMNVPROC glLoadProgramNV;
PFNGLPROGRAMNAMEDPARAMETER4FNVPROC glProgramNamedParameter4fNV;
PFNGLPROGRAMNAMEDPARAMETER4FVNVPROC glProgramNamedParameter4fvNV;
// attrib arrays
PFNGLENABLEVERTEXATTRIBARRAYARBPROC glEnableVertexAttribArrayARB;
PFNGLVERTEXATTRIBPOINTERARBPROC glVertexAttribPointerARB;
PFNGLDISABLEVERTEXATTRIBARRAYARBPROC glDisableVertexAttribArrayARB;
PFNGLVERTEXATTRIB4FVARBPROC glVertexAttrib4fvARB;
PFNGLGETATTRIBLOCATIONARBPROC glGetAttribLocation;
PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer;
PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray;
PFNGLDISABLEVERTEXATTRIBARRAYPROC glDisableVertexAttribArray;
PFNGLVERTEXATTRIBDIVISORPROC glVertexAttribDivisor;
// vertex buffer object
PFNGLGENBUFFERSARBPROC glGenBuffersARB;
PFNGLBINDBUFFERARBPROC glBindBufferARB;
PFNGLBUFFERDATAARBPROC glBufferDataARB;
PFNGLDELETEBUFFERSARBPROC glDeleteBuffersARB;
PFNGLDRAWRANGEELEMENTSPROC glDrawRangeElements;
PFNGLMAPBUFFERARBPROC glMapBufferARB;
PFNGLUNMAPBUFFERARBPROC glUnmapBufferARB;
PFNGLBINDBUFFERRANGEPROC glBindBufferRange;
PFNGLBINDBUFFERBASEPROC glBindBufferBase;
PFNGLBINDIMAGETEXTUREPROC glBindImageTexture;
PFNGLBINDBUFFERPROC glBindBuffer;
PFNGLDELETEBUFFERSPROC glDeleteBuffers;
PFNGLGENBUFFERSPROC glGenBuffers;
PFNGLBUFFERDATAPROC glBufferData;
PFNGLMAPBUFFERPROC glMapBuffer;
PFNGLUNMAPBUFFERPROC glUnmapBuffer;
PFNGLMAPBUFFERRANGEPROC glMapBufferRange;
// vertex array
PFNGLBINDVERTEXARRAYPROC glBindVertexArray;
PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArray;
PFNGLGENVERTEXARRAYSPROC glGenVertexArrays;
//PFNGLISVERTEXARRAYPROC glIsVertexArray;
//transform feedback
PFNGLBINDTRANSFORMFEEDBACKPROC glBindTransformFeedback;
PFNGLDELETETRANSFORMFEEDBACKSPROC glDeleteTransformFeedback;
PFNGLGENTRANSFORMFEEDBACKSPROC glGenTransformFeedback;
PFNGLBEGINTRANSFORMFEEDBACKPROC glBeginTransformFeedback;
PFNGLENDTRANSFORMFEEDBACKPROC glEndTransformFeedback;
PFNGLTRANSFORMFEEDBACKVARYINGSPROC glTransformFeedbackVaryings;
PFNGLTRANSFORMFEEDBACKATTRIBSNVPROC glTransformFeedbackAttribsNV;
PFNGLBINDBUFFERBASENVPROC glBindBufferBaseNV;
PFNGLBEGINTRANSFORMFEEDBACKNVPROC glBeginTransformFeedbackNV;
PFNGLENDTRANSFORMFEEDBACKNVPROC glEndTransformFeedbackNV;
PFNGLBINDBUFFEROFFSETNVPROC glBindBufferOffsetNV;
PFNGLACTIVEVARYINGNVPROC glActiveVaryingNV;
PFNGLGETVARYINGLOCATIONNVPROC glGetVaryingLocationNV;
PFNGLTRANSFORMFEEDBACKVARYINGSNVPROC glTransformFeedbackVaryingsNV;
// occlision query
PFNGLGENQUERIESARBPROC glGenQueriesARB;
PFNGLDELETEQUERIESARBPROC glDeleteQueriesARB;
PFNGLBEGINQUERYARBPROC glBeginQueryARB;
PFNGLENDQUERYARBPROC glEndQueryARB;
PFNGLGETQUERYIVARBPROC glGetQueryivARB;
PFNGLGETQUERYOBJECTIVARBPROC glGetQueryObjectivARB;
PFNGLGETQUERYOBJECTUIVARBPROC glGetQueryObjectuivARB;
PFNGLGETQUERYOBJECTUI64VPROC glGetQueryObjectui64v;
PFNGLQUERYCOUNTERPROC glQueryCounter;
PFNGLBEGINQUERYINDEXEDPROC glBeginQueryIndexed;
PFNGLENDQUERYINDEXEDPROC glEndQueryIndexed;
PFNGLGETQUERYINDEXEDIVPROC glGetQueryIndexediv;
PFNGLGENQUERIESPROC glGenQueries;
PFNGLDELETEQUERIESPROC glDeleteQueries;
PFNGLBEGINQUERYPROC glBeginQuery;
PFNGLENDQUERYPROC glEndQuery;
PFNGLGETQUERYOBJECTIVPROC glGetQueryObjectiv;
// glsl
PFNGLCREATEPROGRAMOBJECTARBPROC glCreateProgramObjectARB;
PFNGLCREATESHADEROBJECTARBPROC glCreateShaderObjectARB;
PFNGLSHADERSOURCEARBPROC glShaderSourceARB;
PFNGLCOMPILESHADERARBPROC glCompileShaderARB;
PFNGLATTACHOBJECTARBPROC glAttachObjectARB;
PFNGLDETACHOBJECTARBPROC glDetachObjectARB;
PFNGLDELETEOBJECTARBPROC glDeleteObjectARB;
PFNGLBINDATTRIBLOCATIONARBPROC glBindAttribLocationARB;
PFNGLLINKPROGRAMARBPROC glLinkProgramARB;
PFNGLGETINFOLOGARBPROC glGetInfoLogARB;
PFNGLGETOBJECTPARAMETERIVARBPROC glGetObjectParameterivARB;
PFNGLVALIDATEPROGRAMARBPROC glValidateProgramARB;
PFNGLUSEPROGRAMOBJECTARBPROC glUseProgramObjectARB;
PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocationARB;
PFNGLUNIFORM1FARBPROC glUniform1fARB;
PFNGLUNIFORM1FVARBPROC glUniform1fvARB;
PFNGLUNIFORM2FARBPROC glUniform2fARB;
PFNGLUNIFORM2FVARBPROC glUniform2fvARB;
PFNGLUNIFORM3FARBPROC glUniform3fARB;
PFNGLUNIFORM3FVARBPROC glUniform3fvARB;
PFNGLUNIFORM4FARBPROC glUniform4fARB;
PFNGLUNIFORM4FVARBPROC glUniform4fvARB;
PFNGLUNIFORMMATRIX3FVARBPROC glUniformMatrix3fvARB;
PFNGLUNIFORMMATRIX4FVARBPROC glUniformMatrix4fvARB;
PFNGLUNIFORM3IVARBPROC glUniform3ivARB;
PFNGLUNIFORM4IVARBPROC glUniform4ivARB;
PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog;
PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog;
PFNGLGETSHADERIVPROC glGetShaderiv;
PFNGLGETPROGRAMIVPROC glGetProgramiv;
PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation;
PFNGLUNIFORM1IPROC glUniform1i;
PFNGLUNIFORM1FPROC glUniform1f;
PFNGLUNIFORM2FPROC glUniform2f;
PFNGLUNIFORM3FPROC glUniform3f;
PFNGLUNIFORM4FPROC glUniform4f;
PFNGLUNIFORM1FVPROC glUniform1fv;
PFNGLUNIFORM2FVPROC glUniform2fv;
PFNGLUNIFORM3FVPROC glUniform3fv;
PFNGLUNIFORM4FVPROC glUniform4fv;
PFNGLUNIFORM4IVPROC glUniform4iv;
PFNGLUNIFORM2IPROC glUniform2i;
PFNGLUNIFORMMATRIX2FVPROC glUniformMatrix2fv;
PFNGLUNIFORMMATRIX3FVPROC glUniformMatrix3fv;
PFNGLUNIFORMMATRIX4FVPROC glUniformMatrix4fv;
PFNGLACTIVETEXTUREPROC glActiveTexture;
//texture sampler
PFNGLGENSAMPLERSPROC glGenSamplers;
PFNGLDELETESAMPLERSPROC glDeleteSamplers;
PFNGLBINDSAMPLERPROC glBindSampler;
PFNGLSAMPLERPARAMETERIPROC glSamplerParameteri;
PFNGLSAMPLERPARAMETERFVPROC glSamplerParameterfv;
// EXT_depth_bounds_test
PFNGLDEPTHBOUNDSEXTPROC glDepthBoundsEXT;
// EXT_framebuffer_object
PFNGLISRENDERBUFFEREXTPROC glIsRenderbufferEXT;
PFNGLBINDRENDERBUFFEREXTPROC glBindRenderbufferEXT;
PFNGLDELETERENDERBUFFERSEXTPROC glDeleteRenderbuffersEXT;
PFNGLGENRENDERBUFFERSEXTPROC glGenRenderbuffersEXT;
PFNGLRENDERBUFFERSTORAGEEXTPROC glRenderbufferStorageEXT;
PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC glGetRenderbufferParameterivEXT;
PFNGLISFRAMEBUFFEREXTPROC glIsFramebufferEXT;
PFNGLDELETEFRAMEBUFFERSEXTPROC glDeleteFramebuffersEXT;
PFNGLFRAMEBUFFERTEXTURE1DEXTPROC glFramebufferTexture1DEXT;
PFNGLFRAMEBUFFERTEXTURE3DEXTPROC glFramebufferTexture3DEXT;
PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC glFramebufferRenderbufferEXT;
PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC glGetFramebufferAttachmentParameterivEXT;
PFNGLGENERATEMIPMAPEXTPROC glGenerateMipmapEXT;
PFNGLFRAMEBUFFERTEXTURELAYEREXTPROC glFramebufferTextureLayerEXT;
PFNGLGENFRAMEBUFFERSPROC glGenFramebuffers;
PFNGLBINDFRAMEBUFFERPROC glBindFramebuffer;
PFNGLFRAMEBUFFERTEXTURE2DPROC glFramebufferTexture2D;
PFNGLCHECKFRAMEBUFFERSTATUSPROC glCheckFramebufferStatus;
PFNGLDELETEFRAMEBUFFERSPROC glDeleteFramebuffers;
PFNGLBINDFRAGDATALOCATIONPROC glBindFragDataLocation;
// GL_EXT_texture3D
PFNGLTEXIMAGE3DEXTPROC glTexImage3DEXT;
// draw buffers from OpenGL 2.0
PFNGLDRAWBUFFERSPROC glDrawBuffers = NULL;
// ATI_draw_buffers
PFNGLDRAWBUFFERSATIPROC glDrawBuffersATI = NULL;
//glProvokingVertex
PFNGLPROVOKINGVERTEXPROC glProvokingVertex;
//debug mode
PFNGLDEBUGMESSAGECONTROLARBPROC glDebugMessageControlARB;
PFNGLDEBUGMESSAGEINSERTARBPROC glDebugMessageInsertARB;
PFNGLDEBUGMESSAGECALLBACKARBPROC glDebugMessageCallbackARB;
PFNGLGETDEBUGMESSAGELOGARBPROC glGetDebugMessageLogARB;
//wgl
PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = NULL;
PFNWGLCREATEPBUFFERARBPROC wglCreatePbufferARB = NULL;
PFNWGLGETPBUFFERDCARBPROC wglGetPbufferDCARB = NULL;
PFNWGLRELEASEPBUFFERDCARBPROC wglReleasePbufferDCARB = NULL;
PFNWGLDESTROYPBUFFERARBPROC wglDestroyPbufferARB = NULL;
PFNWGLQUERYPBUFFERARBPROC wglQueryPbufferARB = NULL;
PFNWGLBINDTEXIMAGEARBPROC wglBindTexImageARB = NULL;
PFNWGLRELEASETEXIMAGEARBPROC wglReleaseTexImageARB = NULL;
PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = NULL;
PFNWGLSETPBUFFERATTRIBARBPROC wglSetPbufferAttribARB = NULL;
PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = NULL;
//----------------------------------------------------------------------------------------------------------------
bool isExtensionSupported ( const char * ext, const char * extList )
{
const char * start = extList;
const char * ptr;
while ( ( ptr = strstr ( start, ext ) ) != NULL )
{
// we've found, ensure name is exactly ext
const char * end = ptr + strlen ( ext );
if ( isspace ( *end ) || *end == '\0' )
return true;
start = end;
}
return false;
}
bool isExtensionSupported ( const char * ext )
{
const char * extensions = (const char *) glGetString ( GL_EXTENSIONS );
if ( isExtensionSupported ( ext, extensions ) )
return true;
if ( wglGetExtensionsStringARB != NULL )
{
const char * wgl_extensions = (const char *) wglGetExtensionsStringARB ( wglGetCurrentDC () );
if ( isExtensionSupported ( ext, wgl_extensions ) )
return true;
}
return false;
}
//----------------------------------------------------------------------------------------------------------------
void glext_init() {
#ifdef _WIN32
#define GET_PROC_ADDRESS(a,b) b = (a)wglGetProcAddress(#b)
#else
#define GET_PROC_ADDRESS(a,b) b = (a)glXGetProcAddressARB((const GLubyte*)#b)
#endif
GET_PROC_ADDRESS(PFNGLGETPROGRAMIVARBPROC,glGetProgramivARB);
// min max
GET_PROC_ADDRESS(PFNGLMINMAXPROC,glMinmax);
GET_PROC_ADDRESS(PFNGLGETMINMAXPROC,glGetMinmax);
// stencil
GET_PROC_ADDRESS(PFNGLACTIVESTENCILFACEEXTPROC,glActiveStencilFaceEXT);
// blend
GET_PROC_ADDRESS(PFNGLBLENDEQUATIONPROC,glBlendEquation);
GET_PROC_ADDRESS(PFNGLBLENDFUNCSEPARATEEXTPROC,glBlendFuncSeparateEXT);
//clear color
GET_PROC_ADDRESS(PFNGLCLEARCOLORIIEXTPROC,glClearColorIiEXT);
GET_PROC_ADDRESS(PFNGLCLEARCOLORIUIEXTPROC,glClearColorIuiEXT);
GET_PROC_ADDRESS(PFNGLCLEARBUFFERIVPROC, glClearBufferiv);
GET_PROC_ADDRESS(PFNGLCLEARBUFFERUIVPROC, glClearBufferuiv);
GET_PROC_ADDRESS(PFNGLCLEARBUFFERFVPROC, glClearBufferfv);
GET_PROC_ADDRESS(PFNGLCLEARBUFFERFIPROC, glClearBufferfi);
// textures
GET_PROC_ADDRESS(PFNGLACTIVETEXTUREARBPROC, glActiveTextureARB);
GET_PROC_ADDRESS(PFNGLTEXIMAGE3DPROC,glTexImage3D);
GET_PROC_ADDRESS(PFNGLCOPYTEXSUBIMAGE3DEXTPROC,glCopyTexSubImage3DEXT);
GET_PROC_ADDRESS(PFNGLCOPYTEXSUBIMAGE3DPROC,glCopyTexSubImage3D);
GET_PROC_ADDRESS(PFNGLMULTITEXCOORD3FARBPROC,glMultiTexCoord3fARB);
GET_PROC_ADDRESS(PFNGLMULTITEXCOORD4FARBPROC,glMultiTexCoord4fARB);
GET_PROC_ADDRESS(PFNGLMULTITEXCOORD4FVARBPROC,glMultiTexCoord4fvARB);
GET_PROC_ADDRESS(PFNGLMULTITEXCOORD2FARBPROC,glMultiTexCoord2fARB);
GET_PROC_ADDRESS(PFNGLMULTITEXCOORD2FVARBPROC,glMultiTexCoord2fvARB);
GET_PROC_ADDRESS(PFNGLCLIENTACTIVETEXTUREARBPROC,glClientActiveTextureARB);
GET_PROC_ADDRESS(PFNGLTEXSUBIMAGE3DPROC,glTexSubImage3D);
GET_PROC_ADDRESS(PFNGLCOMPRESSEDTEXIMAGE2DPROC,glCompressedTexImage2D);
GET_PROC_ADDRESS(PFNGLCOMPRESSEDTEXIMAGE2DARBPROC,glCompressedTexImage2DARB);
GET_PROC_ADDRESS(PFNGLTEXPARAMETERIIVPROC, glTexParameterIiv);
GET_PROC_ADDRESS(PFNGLGENERATEMIPMAPPROC, glGenerateMipmap);
GET_PROC_ADDRESS(PFNGLMEMORYBARRIERPROC, glMemoryBarrier);
GET_PROC_ADDRESS(PFNGLTEXTUREBARRIERPROC, glTextureBarrier);
GET_PROC_ADDRESS(PFNGLTEXSTORAGE3DPROC, glTexStorage3D);
GET_PROC_ADDRESS(PFNGLTEXSTORAGE2DPROC, glTexStorage2D);
// arb programs
GET_PROC_ADDRESS(PFNGLGENPROGRAMSARBPROC,glGenProgramsARB);
GET_PROC_ADDRESS(PFNGLBINDPROGRAMARBPROC,glBindProgramARB);
GET_PROC_ADDRESS(PFNGLDELETEPROGRAMSARBPROC,glDeleteProgramsARB);
GET_PROC_ADDRESS(PFNGLPROGRAMSTRINGARBPROC,glProgramStringARB);
GET_PROC_ADDRESS(PFNGLPROGRAMENVPARAMETER4FARBPROC,glProgramEnvParameter4fARB);
GET_PROC_ADDRESS(PFNGLPROGRAMENVPARAMETER4FVARBPROC,glProgramEnvParameter4fvARB);
GET_PROC_ADDRESS(PFNGLPROGRAMLOCALPARAMETER4FARBPROC,glProgramLocalParameter4fARB);
GET_PROC_ADDRESS(PFNGLPROGRAMLOCALPARAMETER4FVARBPROC,glProgramLocalParameter4fvARB);
//shaders
GET_PROC_ADDRESS(PFNGLATTACHSHADERPROC, glAttachShader);
GET_PROC_ADDRESS(PFNGLBINDATTRIBLOCATIONPROC, glBindAttribLocation);
GET_PROC_ADDRESS(PFNGLCOMPILESHADERPROC, glCompileShader);
GET_PROC_ADDRESS(PFNGLCREATEPROGRAMPROC, glCreateProgram);
GET_PROC_ADDRESS(PFNGLCREATESHADERPROC, glCreateShader);
GET_PROC_ADDRESS(PFNGLDELETEPROGRAMPROC, glDeleteProgram);
GET_PROC_ADDRESS(PFNGLDELETESHADERPROC, glDeleteShader);
GET_PROC_ADDRESS(PFNGLDETACHSHADERPROC, glDetachShader);
GET_PROC_ADDRESS(PFNGLSHADERSOURCEPROC, glShaderSource);
GET_PROC_ADDRESS(PFNGLLINKPROGRAMPROC, glLinkProgram);
GET_PROC_ADDRESS(PFNGLUSEPROGRAMPROC, glUseProgram);
GET_PROC_ADDRESS(PFNGLPROGRAMUNIFORM1IPROC, glProgramUniform1i);
GET_PROC_ADDRESS(PFNGLVALIDATEPROGRAMPROC, glValidateProgram);
GET_PROC_ADDRESS(PFNGLGETACTIVEATTRIBPROC, glGetActiveAttrib);
GET_PROC_ADDRESS(PFNGLGETACTIVEUNIFORMPROC, glGetActiveUniform);
//uniform buffer
GET_PROC_ADDRESS(PFNGLUNIFORMBUFFEREXTPROC,glUniformBufferEXT);
//GET_PROC_ADDRESS(PFNGLGETUNIFORMLOCATIONARBPROC,glGetUniformLocationARB);
//texture buffer
GET_PROC_ADDRESS(PFNGLTEXBUFFERARBPROC,glTexBufferARB);
//glPrimitiveRestartIndex
GET_PROC_ADDRESS(PFNGLPRIMITIVERESTARTINDEXPROC,glPrimitiveRestartIndex);
GET_PROC_ADDRESS(PFNGLPRIMITIVERESTARTINDEXNVPROC,glPrimitiveRestartIndexNV);
//instancing
GET_PROC_ADDRESS(PFNGLDRAWELEMENTSINSTANCEDEXTPROC,glDrawElementsInstancedEXT);
GET_PROC_ADDRESS(PFNGLDRAWARRAYSINSTANCEDPROC, glDrawArraysInstanced);
GET_PROC_ADDRESS(PFNGLDRAWELEMENTSINSTANCEDPROC, glDrawElementsInstanced);
GET_PROC_ADDRESS(PFNGLMULTIDRAWELEMENTSINDIRECTPROC, glMultiDrawElementsIndirect);
GET_PROC_ADDRESS(PFNGLDRAWARRAYSINDIRECTPROC, glDrawArraysIndirect);
GET_PROC_ADDRESS(PFNGLTEXBUFFERPROC, glTexBuffer);
//GET_PROC_ADDRESS(PFNGLPRIMITIVERESTARTINDEXPROC, glPrimitiveRestartIndex);
GET_PROC_ADDRESS(PFNGLCOPYBUFFERSUBDATAPROC, glCopyBufferSubData);
// nv programs
GET_PROC_ADDRESS(PFNGLGENPROGRAMSNVPROC,glGenProgramsNV);
GET_PROC_ADDRESS(PFNGLBINDPROGRAMNVPROC,glBindProgramNV);
GET_PROC_ADDRESS(PFNGLDELETEPROGRAMSNVPROC,glDeleteProgramsNV);
GET_PROC_ADDRESS(PFNGLLOADPROGRAMNVPROC,glLoadProgramNV);
GET_PROC_ADDRESS(PFNGLPROGRAMNAMEDPARAMETER4FNVPROC,glProgramNamedParameter4fNV);
GET_PROC_ADDRESS(PFNGLPROGRAMNAMEDPARAMETER4FVNVPROC,glProgramNamedParameter4fvNV);
// attrib arrays
GET_PROC_ADDRESS(PFNGLENABLEVERTEXATTRIBARRAYARBPROC,glEnableVertexAttribArrayARB);
GET_PROC_ADDRESS(PFNGLVERTEXATTRIBPOINTERARBPROC,glVertexAttribPointerARB);
GET_PROC_ADDRESS(PFNGLDISABLEVERTEXATTRIBARRAYARBPROC,glDisableVertexAttribArrayARB);
GET_PROC_ADDRESS(PFNGLVERTEXATTRIB4FVARBPROC,glVertexAttrib4fvARB);
GET_PROC_ADDRESS(PFNGLGETATTRIBLOCATIONARBPROC,glGetAttribLocation);
GET_PROC_ADDRESS(PFNGLVERTEXATTRIBPOINTERPROC, glVertexAttribPointer);
GET_PROC_ADDRESS(PFNGLENABLEVERTEXATTRIBARRAYPROC, glEnableVertexAttribArray);
GET_PROC_ADDRESS(PFNGLDISABLEVERTEXATTRIBARRAYPROC, glDisableVertexAttribArray);
GET_PROC_ADDRESS(PFNGLVERTEXATTRIBDIVISORPROC, glVertexAttribDivisor);
// vertex buffer object
GET_PROC_ADDRESS(PFNGLGENBUFFERSARBPROC,glGenBuffersARB);
GET_PROC_ADDRESS(PFNGLBINDBUFFERARBPROC,glBindBufferARB);
GET_PROC_ADDRESS(PFNGLBUFFERDATAARBPROC,glBufferDataARB);
GET_PROC_ADDRESS(PFNGLDELETEBUFFERSARBPROC,glDeleteBuffersARB);
GET_PROC_ADDRESS(PFNGLDRAWRANGEELEMENTSPROC,glDrawRangeElements);
GET_PROC_ADDRESS(PFNGLMAPBUFFERARBPROC,glMapBufferARB);
GET_PROC_ADDRESS(PFNGLUNMAPBUFFERARBPROC,glUnmapBufferARB);
GET_PROC_ADDRESS(PFNGLBINDBUFFERRANGEPROC, glBindBufferRange);
GET_PROC_ADDRESS(PFNGLBINDBUFFERBASEPROC, glBindBufferBase);
GET_PROC_ADDRESS(PFNGLBINDIMAGETEXTUREPROC, glBindImageTexture);
GET_PROC_ADDRESS(PFNGLBINDBUFFERPROC, glBindBuffer);
GET_PROC_ADDRESS(PFNGLDELETEBUFFERSPROC, glDeleteBuffers);
GET_PROC_ADDRESS(PFNGLGENBUFFERSPROC, glGenBuffers);
GET_PROC_ADDRESS(PFNGLBUFFERDATAPROC, glBufferData);
GET_PROC_ADDRESS(PFNGLMAPBUFFERPROC, glMapBuffer);
GET_PROC_ADDRESS(PFNGLUNMAPBUFFERPROC, glUnmapBuffer);
GET_PROC_ADDRESS(PFNGLMAPBUFFERRANGEPROC, glMapBufferRange);
// vertex array
GET_PROC_ADDRESS(PFNGLBINDVERTEXARRAYPROC, glBindVertexArray);
GET_PROC_ADDRESS(PFNGLDELETEVERTEXARRAYSPROC, glDeleteVertexArray);
GET_PROC_ADDRESS(PFNGLGENVERTEXARRAYSPROC, glGenVertexArrays);
//transform feedback
GET_PROC_ADDRESS(PFNGLBINDTRANSFORMFEEDBACKPROC, glBindTransformFeedback);
GET_PROC_ADDRESS(PFNGLDELETETRANSFORMFEEDBACKSPROC, glDeleteTransformFeedback);
GET_PROC_ADDRESS(PFNGLGENTRANSFORMFEEDBACKSPROC, glGenTransformFeedback);
GET_PROC_ADDRESS(PFNGLBEGINTRANSFORMFEEDBACKPROC, glBeginTransformFeedback);
GET_PROC_ADDRESS(PFNGLENDTRANSFORMFEEDBACKPROC, glEndTransformFeedback);
GET_PROC_ADDRESS(PFNGLTRANSFORMFEEDBACKVARYINGSPROC, glTransformFeedbackVaryings);
GET_PROC_ADDRESS(PFNGLTRANSFORMFEEDBACKATTRIBSNVPROC, glTransformFeedbackAttribsNV);
GET_PROC_ADDRESS(PFNGLBINDBUFFERBASENVPROC, glBindBufferBaseNV);
GET_PROC_ADDRESS(PFNGLBEGINTRANSFORMFEEDBACKNVPROC, glBeginTransformFeedbackNV);
GET_PROC_ADDRESS(PFNGLENDTRANSFORMFEEDBACKNVPROC, glEndTransformFeedbackNV);
GET_PROC_ADDRESS(PFNGLBINDBUFFEROFFSETNVPROC, glBindBufferOffsetNV);
GET_PROC_ADDRESS(PFNGLACTIVEVARYINGNVPROC, glActiveVaryingNV);
GET_PROC_ADDRESS(PFNGLGETVARYINGLOCATIONNVPROC, glGetVaryingLocationNV);
GET_PROC_ADDRESS(PFNGLTRANSFORMFEEDBACKVARYINGSNVPROC, glTransformFeedbackVaryingsNV);
// occlision query
GET_PROC_ADDRESS(PFNGLGENQUERIESARBPROC, glGenQueriesARB);
GET_PROC_ADDRESS(PFNGLDELETEQUERIESARBPROC, glDeleteQueriesARB);
GET_PROC_ADDRESS(PFNGLBEGINQUERYARBPROC, glBeginQueryARB);
GET_PROC_ADDRESS(PFNGLENDQUERYARBPROC, glEndQueryARB);
GET_PROC_ADDRESS(PFNGLGETQUERYIVARBPROC, glGetQueryivARB);
GET_PROC_ADDRESS(PFNGLGETQUERYOBJECTIVARBPROC, glGetQueryObjectivARB);
GET_PROC_ADDRESS(PFNGLGETQUERYOBJECTUIVARBPROC, glGetQueryObjectuivARB);
GET_PROC_ADDRESS(PFNGLGETQUERYOBJECTUI64VPROC, glGetQueryObjectui64v);
GET_PROC_ADDRESS(PFNGLQUERYCOUNTERPROC, glQueryCounter);
GET_PROC_ADDRESS(PFNGLBEGINQUERYINDEXEDPROC, glBeginQueryIndexed);
GET_PROC_ADDRESS(PFNGLENDQUERYINDEXEDPROC, glEndQueryIndexed);
GET_PROC_ADDRESS(PFNGLGETQUERYINDEXEDIVPROC, glGetQueryIndexediv);
GET_PROC_ADDRESS(PFNGLGENQUERIESPROC, glGenQueries);
GET_PROC_ADDRESS(PFNGLDELETEQUERIESPROC, glDeleteQueries);
GET_PROC_ADDRESS(PFNGLBEGINQUERYPROC, glBeginQuery);
GET_PROC_ADDRESS(PFNGLENDQUERYPROC, glEndQuery);
GET_PROC_ADDRESS(PFNGLGETQUERYOBJECTIVPROC, glGetQueryObjectiv);
// glsl
GET_PROC_ADDRESS(PFNGLCREATEPROGRAMOBJECTARBPROC,glCreateProgramObjectARB);
GET_PROC_ADDRESS(PFNGLCREATESHADEROBJECTARBPROC,glCreateShaderObjectARB);
GET_PROC_ADDRESS(PFNGLSHADERSOURCEARBPROC,glShaderSourceARB);
GET_PROC_ADDRESS(PFNGLCOMPILESHADERARBPROC,glCompileShaderARB);
GET_PROC_ADDRESS(PFNGLATTACHOBJECTARBPROC,glAttachObjectARB);
GET_PROC_ADDRESS(PFNGLDETACHOBJECTARBPROC,glDetachObjectARB);
GET_PROC_ADDRESS(PFNGLDELETEOBJECTARBPROC,glDeleteObjectARB);
GET_PROC_ADDRESS(PFNGLBINDATTRIBLOCATIONARBPROC,glBindAttribLocationARB);
GET_PROC_ADDRESS(PFNGLLINKPROGRAMARBPROC,glLinkProgramARB);
GET_PROC_ADDRESS(PFNGLGETINFOLOGARBPROC,glGetInfoLogARB);
GET_PROC_ADDRESS(PFNGLGETOBJECTPARAMETERIVARBPROC,glGetObjectParameterivARB);
GET_PROC_ADDRESS(PFNGLVALIDATEPROGRAMARBPROC,glValidateProgramARB);
GET_PROC_ADDRESS(PFNGLUSEPROGRAMOBJECTARBPROC,glUseProgramObjectARB);
GET_PROC_ADDRESS(PFNGLGETUNIFORMLOCATIONARBPROC,glGetUniformLocationARB);
GET_PROC_ADDRESS(PFNGLUNIFORM1FARBPROC,glUniform1fARB);
GET_PROC_ADDRESS(PFNGLUNIFORM1FVARBPROC,glUniform1fvARB);
GET_PROC_ADDRESS(PFNGLUNIFORM2FARBPROC,glUniform2fARB);
GET_PROC_ADDRESS(PFNGLUNIFORM2FVARBPROC,glUniform2fvARB);
GET_PROC_ADDRESS(PFNGLUNIFORM3FARBPROC,glUniform3fARB);
GET_PROC_ADDRESS(PFNGLUNIFORM3FVARBPROC,glUniform3fvARB);
GET_PROC_ADDRESS(PFNGLUNIFORM4FARBPROC,glUniform4fARB);
GET_PROC_ADDRESS(PFNGLUNIFORM4FVARBPROC,glUniform4fvARB);
GET_PROC_ADDRESS(PFNGLUNIFORMMATRIX3FVARBPROC,glUniformMatrix3fvARB);
GET_PROC_ADDRESS(PFNGLUNIFORMMATRIX4FVARBPROC,glUniformMatrix4fvARB);
GET_PROC_ADDRESS(PFNGLUNIFORM3IVARBPROC,glUniform3ivARB);
GET_PROC_ADDRESS(PFNGLUNIFORM4IVARBPROC,glUniform4ivARB);
GET_PROC_ADDRESS(PFNGLUNIFORM2IPROC, glUniform2i);
GET_PROC_ADDRESS(PFNGLUNIFORMMATRIX2FVPROC, glUniformMatrix2fv);
GET_PROC_ADDRESS(PFNGLUNIFORMMATRIX3FVPROC, glUniformMatrix3fv);
GET_PROC_ADDRESS(PFNGLUNIFORMMATRIX4FVPROC, glUniformMatrix4fv);
GET_PROC_ADDRESS(PFNGLGETSHADERINFOLOGPROC,glGetShaderInfoLog);
GET_PROC_ADDRESS(PFNGLGETPROGRAMINFOLOGPROC,glGetProgramInfoLog);
GET_PROC_ADDRESS(PFNGLGETSHADERIVPROC,glGetShaderiv);
GET_PROC_ADDRESS(PFNGLGETPROGRAMIVPROC,glGetProgramiv);
GET_PROC_ADDRESS(PFNGLGETUNIFORMLOCATIONPROC, glGetUniformLocation);
GET_PROC_ADDRESS(PFNGLUNIFORM1IPROC, glUniform1i);
GET_PROC_ADDRESS(PFNGLUNIFORM1FPROC, glUniform1f);
GET_PROC_ADDRESS(PFNGLUNIFORM2FPROC, glUniform2f);
GET_PROC_ADDRESS(PFNGLUNIFORM3FPROC, glUniform3f);
GET_PROC_ADDRESS(PFNGLUNIFORM4FPROC, glUniform4f);
GET_PROC_ADDRESS(PFNGLUNIFORM1FVPROC, glUniform1fv);
GET_PROC_ADDRESS(PFNGLUNIFORM2FVPROC, glUniform2fv);
GET_PROC_ADDRESS(PFNGLUNIFORM3FVPROC, glUniform3fv);
GET_PROC_ADDRESS(PFNGLUNIFORM4FVPROC, glUniform4fv);
GET_PROC_ADDRESS(PFNGLUNIFORM4IVPROC, glUniform4iv);
GET_PROC_ADDRESS(PFNGLACTIVETEXTUREPROC, glActiveTexture);
//texture sampler
GET_PROC_ADDRESS(PFNGLGENSAMPLERSPROC, glGenSamplers);
GET_PROC_ADDRESS(PFNGLDELETESAMPLERSPROC, glDeleteSamplers);
GET_PROC_ADDRESS(PFNGLBINDSAMPLERPROC, glBindSampler);
GET_PROC_ADDRESS(PFNGLSAMPLERPARAMETERIPROC, glSamplerParameteri);
GET_PROC_ADDRESS(PFNGLSAMPLERPARAMETERFVPROC, glSamplerParameterfv);
// GL_EXT_texture3D
GET_PROC_ADDRESS(PFNGLTEXIMAGE3DEXTPROC, glTexImage3DEXT);
// EXT_depth_bounds_test
GET_PROC_ADDRESS(PFNGLDEPTHBOUNDSEXTPROC, glDepthBoundsEXT);
GET_PROC_ADDRESS(PFNGLISRENDERBUFFEREXTPROC, glIsRenderbufferEXT);
GET_PROC_ADDRESS(PFNGLBINDRENDERBUFFEREXTPROC, glBindRenderbufferEXT);
GET_PROC_ADDRESS(PFNGLDELETERENDERBUFFERSEXTPROC, glDeleteRenderbuffersEXT);
GET_PROC_ADDRESS(PFNGLGENRENDERBUFFERSEXTPROC, glGenRenderbuffersEXT);
GET_PROC_ADDRESS(PFNGLRENDERBUFFERSTORAGEEXTPROC, glRenderbufferStorageEXT);
GET_PROC_ADDRESS(PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC, glGetRenderbufferParameterivEXT);
GET_PROC_ADDRESS(PFNGLISFRAMEBUFFEREXTPROC, glIsFramebufferEXT);
GET_PROC_ADDRESS(PFNGLDELETEFRAMEBUFFERSEXTPROC, glDeleteFramebuffersEXT);
GET_PROC_ADDRESS(PFNGLFRAMEBUFFERTEXTURE1DEXTPROC, glFramebufferTexture1DEXT);
GET_PROC_ADDRESS(PFNGLFRAMEBUFFERTEXTURE3DEXTPROC, glFramebufferTexture3DEXT);
GET_PROC_ADDRESS(PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC, glFramebufferRenderbufferEXT);
GET_PROC_ADDRESS(PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC, glGetFramebufferAttachmentParameterivEXT);
GET_PROC_ADDRESS(PFNGLGENERATEMIPMAPEXTPROC, glGenerateMipmapEXT);
GET_PROC_ADDRESS(PFNGLFRAMEBUFFERTEXTURELAYEREXTPROC, glFramebufferTextureLayerEXT);
GET_PROC_ADDRESS(PFNGLDRAWBUFFERSPROC, glDrawBuffers);
GET_PROC_ADDRESS(PFNGLDRAWBUFFERSATIPROC, glDrawBuffersATI);
GET_PROC_ADDRESS(PFNGLPROVOKINGVERTEXPROC, glProvokingVertex);
GET_PROC_ADDRESS(PFNGLGENFRAMEBUFFERSPROC, glGenFramebuffers);
GET_PROC_ADDRESS(PFNGLBINDFRAMEBUFFERPROC, glBindFramebuffer);
GET_PROC_ADDRESS(PFNGLFRAMEBUFFERTEXTURE2DPROC, glFramebufferTexture2D);
GET_PROC_ADDRESS(PFNGLCHECKFRAMEBUFFERSTATUSPROC, glCheckFramebufferStatus);
GET_PROC_ADDRESS(PFNGLDELETEFRAMEBUFFERSPROC, glDeleteFramebuffers);
GET_PROC_ADDRESS(PFNGLBINDFRAGDATALOCATIONPROC, glBindFragDataLocation);
//debug mode
GET_PROC_ADDRESS(PFNGLDEBUGMESSAGECONTROLARBPROC, glDebugMessageControlARB);
GET_PROC_ADDRESS(PFNGLDEBUGMESSAGEINSERTARBPROC, glDebugMessageInsertARB);
GET_PROC_ADDRESS(PFNGLDEBUGMESSAGECALLBACKARBPROC, glDebugMessageCallbackARB);
GET_PROC_ADDRESS(PFNGLGETDEBUGMESSAGELOGARBPROC, glGetDebugMessageLogARB);
//wgl
GET_PROC_ADDRESS(PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB);
GET_PROC_ADDRESS(PFNWGLCREATEPBUFFERARBPROC, wglCreatePbufferARB);
GET_PROC_ADDRESS(PFNWGLGETPBUFFERDCARBPROC, wglGetPbufferDCARB);
GET_PROC_ADDRESS(PFNWGLRELEASEPBUFFERDCARBPROC, wglReleasePbufferDCARB);
GET_PROC_ADDRESS(PFNWGLDESTROYPBUFFERARBPROC, wglDestroyPbufferARB);
GET_PROC_ADDRESS(PFNWGLQUERYPBUFFERARBPROC, wglQueryPbufferARB);
GET_PROC_ADDRESS(PFNWGLBINDTEXIMAGEARBPROC, wglBindTexImageARB);
GET_PROC_ADDRESS(PFNWGLRELEASETEXIMAGEARBPROC, wglReleaseTexImageARB);
GET_PROC_ADDRESS(PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB);
GET_PROC_ADDRESS(PFNWGLSETPBUFFERATTRIBARBPROC, wglSetPbufferAttribARB);
GET_PROC_ADDRESS(PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB);
#undef GET_PROC_ADDRESS
}
|
0a42db724fddfabf01e2ff39d21781c76c4ef922
|
[
"C",
"Text",
"C++"
] | 18 |
C
|
jsjtxietian/CG_homework
|
cb96f9a283f1861048de8590dc76e4ff8a3e69f2
|
faee88ba4b6114a8007086294772cefce1d79ccb
|
refs/heads/master
|
<repo_name>EManual/EManual-CLI<file_sep>/emanual/cli.py
# -*- coding: utf-8 -*-
from emanual import make, __version__
import click
def print_version(ctx, param, value):
if not value or ctx.resilient_parsing:
return
click.echo(__version__)
ctx.exit()
@click.group()
@click.option('--version', is_flag=True, callback=print_version,
expose_value=False, is_eager=True, help='Show the version')
def main():
"""
Welecome to EManual CLI!
"""
pass
@main.command('create')
@click.argument('lang', )
def create_info(lang):
"""
Create the info.json File for Given Lang
"""
make.create_info(lang)
@main.command('server')
@click.option('--port', default=8000, help='port to listen')
def server(port):
"""
Server to preview the markdown files
"""
import os
os.system('python -m SimpleHTTPServer %s' % port)
@main.command('dist')
@click.argument('lang', )
def dist(lang):
"""
Distributing the markdown
"""
make.dist_zip(lang)
@main.command('newsfeeds')
@click.argument('update', default=True)
def newsfeeds(update):
"""
The cli for NewsFeeds module
"""
if update:
make.newsfeeds_update()
@main.command('filename')
@click.argument('operate', default='check')
@click.argument('path', default='.')
def filename_check(operate, path):
"""
The utils CLI for solve filename
$ emanual filename check [path=.]:check out if given path(defualt is current work path `.`) contains Chinese punctuation
$ emanual filename fix [path=.]: turn Chinese punctuation to English punctuation
"""
import filename
if operate == 'check':
filename.check(path)
if operate == 'fix':
filename.fix(path)
@main.command('init')
@click.argument('name')
def init_module(name):
"""
init a new module
"""
make.init_module(name)
<file_sep>/setup.py
#!/usr/bin/env python
# coding=utf-8
from setuptools import setup, find_packages
import emanual
with open('README.md') as f:
long_description = f.read()
setup(
name='emanual',
version=emanual.__version__,
description=emanual.__doc__.strip(),
long_description=long_description,
url='https://github.com/EManual/EManual-CLI',
author=emanual.__author__,
author_email='<EMAIL>',
license='MIT',
packages=find_packages(),
include_package_data=True,
install_requires=[
'click',
'path.py',
'pypinyin',
'mistune',
'beautifulsoup4'
],
entry_points={
'console_scripts' : [
'emanual=emanual.cli:main',
]
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
],
keywords='emanual cli',
)
<file_sep>/emanual/filename.py
# -*- coding: utf-8 -*-
__author__ = 'jayin'
from path import Path
import _
import os
import copy
import click
# 注意文件名不能用冒号`:`,干脆直接替换成空格!
_Chinese_Punction = [
u'!', u'“', u'”', u';', u'《', u'》', u'。', u'、', u',', u'【', u'】', u'(', u')', u'?', u':', u':'
]
_English_Punction = [
u'!', u'"', u'"', u';', u'<', u'>', u'.', u',', u',', u'[', u']', u'(', u')', u'?', u' ', u' '
]
# Chinese 2 English
C2E = dict(map(lambda x, y: [x, y], _Chinese_Punction, _English_Punction))
def check(path='.', _echo=True):
"""
检查路径目录(默认是当前)下的文件名是否存在中文字符的标点
:param path: 给定目录
:param _echo: 是否输出log
:return: dist
tpl = {
'src': '',
'dest': ''
}
"""
path = Path(path)
result = []
tpl = {
'src': '',
'dest': ''
}
def walk(p):
# 检查->改名
_name = p.name
for prounction in _Chinese_Punction:
if prounction in _name:
# 替换标点
_name = _name.replace(prounction, C2E[prounction])
if _name != p.name:
rename = copy.deepcopy(tpl)
rename['src'] = p.abspath()
rename['dest'] = os.path.join(os.path.dirname(p.abspath()), _name)
result.append(rename)
if p.isdir():
for f in p.listdir():
walk(f)
walk(path)
if _echo:
if len(result) == 0:
click.echo('Good! Not found!')
else:
for x in result:
click.echo(x['src'])
return result
def fix(path):
"""
修复存在中文标点的
:param path: 给定路径
"""
result = check(path, True)
for x in result:
click.echo('mv %s %s' % (x['src'], x['dest']))
Path.move(x['src'], x['dest'])
click.echo('Finish: fix all!')
<file_sep>/emanual/_.py
# -*- coding: utf-8 -*-
__author__ = 'jayin'
def is_markdown_file(filename=''):
"""
判断给定的文件名是否是markdown文件
"""
if filename.endswith('.md') or filename.endswith('.markdown'):
return True
return False
def read_file(file_path):
"""
读取文件
:param file_path: 文件路径
:return: string
"""
import codecs
with codecs.open(file_path, mode='r', encoding='utf-8') as f:
return f.read()
def get_markdown_p(content='', word=30):
"""
获得第一句<p>标签的内容
:param content: 未渲染,markdown格式内容
:param word: 若分段失败,则截取内容的长度
:return: string
"""
import mistune
from bs4 import BeautifulSoup
md = mistune.markdown(content)
soup = BeautifulSoup(md)
p = soup.find('p')
if len(p.text.split(u'。')) > 0:
return p.text.split(u'。')[0]
elif len(p.text.split(u'.')) > 0:
return p.text.split()
return p.text[0:word]
<file_sep>/requirements-dev.txt
click
path.py
pypinyin
mistune
beautifulsoup4<file_sep>/emanual/make.py
# -*- coding: utf-8 -*-
from path import Path
from pypinyin import lazy_pinyin
import copy
import json
import os
import _
MODE_TREE = 'tree'
MODE_FILE = 'file'
file_tpl = {
'mode': '',
'name': '',
'rname': '',
'path': ''
}
info_tpl = {
'files': [],
'mode': '',
'name': '',
'rname': '',
'path': ''
}
raw_md_root = Path('./markdown')
dist_root = Path('./dist')
info_dist_root = './dist/{lang}'
def check_path():
"""
检查是否存在'./markdown' './dist'
:return:
"""
if not raw_md_root.exists():
raise IOError('Not found : dir ./markdown ')
if not dist_root.exists():
dist_root.mkdir()
def gen_info(p):
"""
在`./markdown`下生成info.json
:param p: the path
"""
info = copy.deepcopy(info_tpl)
info['mode'] = MODE_TREE if p.isdir() else MODE_FILE
info['name'] = ''.join(lazy_pinyin(p.name))
info['rname'] = p.name
# p.rename(info['name'])# 路径也变为拼音
info['path'] = ''.join(lazy_pinyin(p.lstrip(dist_root)))
info['mtime'] = p.mtime
for f in p.listdir():
_file = copy.deepcopy(file_tpl)
_file['mode'] = MODE_TREE if f.isdir() else MODE_FILE
_file['name'] = ''.join(lazy_pinyin(f.name))
_file['rname'] = f.name
# _file['path'] = info['path'] + '/' + _file['name']
_file['path'] = os.path.join(info['path'], _file['name'])
_file['mtime'] = f.mtime
info['files'].append(_file)
with open(p + '/info.json', mode='w') as f:
f.write(json.dumps(info))
for f in p.dirs():
gen_info(f)
def clean_up(path='./markdown'):
"""
清除目录下:
1. `*.json文件`
2. `*.*~` linux下临时文件
3. `.DS_Store` OS X 下文件描述文件
:param path: 清除目录
"""
os.system("find {path} -name '*.json' | xargs rm -f ".format(path=path))
os.system("find {path} -name '*.*~' | xargs rm -f ".format(path=path))
os.system("find {path} -name '.DS_Store' | xargs rm -f ".format(path=path))
print('Finish: clean up !')
def dirs_pinyin(p):
"""
将指定的目录下得所有中文文件名转换拼音
:param p: 给定目录
"""
if p.isfile():
pinyin = ''.join(lazy_pinyin(p.name))
# 拼音先隔离dirname,因为父文件夹是最后才转换成拼音
Path.move(p.abspath(), os.path.join(p.dirname(), pinyin))
return
else:
for x in p.listdir():
dirs_pinyin(x)
if x.isdir():
pinyin = ''.join(lazy_pinyin(x.name))
Path.move(x.abspath(), os.path.join(x.dirname(), pinyin))
def create_info(lang):
"""
创建生成info.json文件以及把中文文件名变为拼音
:return:
"""
clean_up()
check_path()
lang_info_dist_root = info_dist_root.format(lang=lang)
p = Path(lang_info_dist_root)
if p.exists():
os.system('rm -fr %s' % lang_info_dist_root)
Path.copytree(raw_md_root, p)
gen_info(p)
dirs_pinyin(p)
print('Finish: generate info.json, please checkout `%s`' % p)
def dist_zip(lang):
"""
压缩create后在dist/{lang}下的文件夹到-> `{lang}.zip`
:param lang: 语言
"""
cwd = os.getcwd()
dest = os.path.join(cwd, 'dist')
if not os.path.exists(dest):
os.makedirs(dest)
# the zip
zip_file = os.path.join(dest, '%s.zip' % lang)
if os.path.exists(zip_file):
os.system('rm %s' % zip_file)
cmds = [
'cd %s' % dest,
'zip -q -r %s.zip %s/' % (lang, lang),
]
os.system(' && '.join(cmds))
print('Finish dist')
def newsfeeds_update():
"""
更新newsfeeds模块的信息
:return:
"""
# newsfeeds_root -> ./dist/newsfeeds
check_path()
newsfeeds_root = Path(os.path.join(dist_root, 'newsfeeds'))
if newsfeeds_root.exists():
os.system('rm -fr %s' % newsfeeds_root)
clean_up(dist_root)
Path.copytree(raw_md_root, newsfeeds_root)
files = []
def get_files(p):
for f in p.listdir():
if f.isfile() and _.is_markdown_file(f.name):
files.append(f)
elif f.isdir():
get_files(f)
def gen_page_info(files):
tpl = {
'name': '',
'rname': '',
'path': '',
'description': ''
}
sigle_page = 10 # 单页数量
files.reverse()
for page in range(1, len(files) / sigle_page + 2):
_data = []
for x in files[(page - 1) * sigle_page: page * sigle_page]:
_tmp = copy.deepcopy(tpl)
_tmp['name'] = ''.join(lazy_pinyin(x.name))
_tmp['rname'] = x.name
_tmp['path'] = ''.join(lazy_pinyin(x.lstrip(dist_root)))
_tmp['description'] = _.get_markdown_p(_.read_file(x.abspath()))
_data.append(_tmp)
with open(os.path.join(dist_root, '%d.json' % page), mode='w') as f:
f.write(json.dumps(_data))
get_files(newsfeeds_root)
gen_page_info(files)
dirs_pinyin(newsfeeds_root)
print('Finish newsfeeds update!\ntotal:%d' % len(files))
def init_module(module_name, path='.'):
"""
初始化一个模块
:param module_name: 模块名
:param path: 根目录 默认 .
:return:
"""
TYPE_FILE = 'file'
TYPE_DIRECTORY = 'directory'
mks = [
{'name': 'img', 'type': TYPE_DIRECTORY},
{'name': 'img/.gitkeep', 'type': TYPE_FILE},
{'name': 'dist', 'type': TYPE_DIRECTORY},
{'name': 'dist/.gitkeep', 'type': TYPE_FILE},
{'name': 'markdown', 'type': TYPE_DIRECTORY},
{'name': 'markdown/.gitkeep', 'type': TYPE_FILE},
{'name': 'README.md', 'type': TYPE_FILE},
]
module_name = u'md-' + module_name
os.system('mkdir %s' % module_name)
for x in mks:
if x['type'] == TYPE_FILE:
print('touch %s' % os.path.join(path, module_name, x['name']))
os.system('touch %s' % os.path.join(path, module_name, x['name']))
else:
print('mkdir %s' % os.path.join(path, module_name, x['name']))
os.system('mkdir %s' % os.path.join(path, module_name, x['name']))
<file_sep>/emanual/__init__.py
# -*- coding: utf-8 -*-
"""
EManual CLI - Command Line Interface for EManual
"""
__version__ = '0.4.4'
__author__ = '<NAME>'<file_sep>/README.md
EManual-CLI
-----------
[](http://badge.fury.io/py/emanual)
[](https://pypi.python.org/pypi/emanual/)
Command Line Interface for EManual
install
-------
```shell
$ pip install emanual
```
Usage
-----
## 语言资料模块
0. 初始化模块
```shell
$ emanual init {module name}
```
1. 创建`info.json` & 把中文文件名变为拼音
```shell
$ cd path/to/md-xxx
$ emanual create {lang}
// `./dist/{lang}`就是生成的内容
````
2. 生成lang.zip
```shell
$ emanual dist {lang} //lang为指定的语言,小写
```
## NewsFeeds模块
1. 更新
```shell
$ emanual newsfeeds update
```
## 文件名处理
```shell
cd path/to/md-xxx/markdown //通常修改这目录
emanual filename check [path=.] //检查路径目录(默认是当前)下的文件名是否存在中文字符的标点
emanual filename fix [path=.] //修复存在中文标点的
```
Development
-----------
#### 1. 使用virtualenv,未安装则`pip install virtualenv`
```shell
//创建虚拟的python开发环境
$ virtualenv env
//开启
$ source env/bin/activate
//退出
$ deactivate
```
#### 2. 安装依赖
```
$ pip install -r requirements-dev.txt
```
#### 3. 动态加载当前库
```shell
$ cd path/to/EManual-CLI
$ pip install --edit .
//or
$ pip install -e .
```
#### 4. 安装测试
```shell
$ python setup.py install
$ emanual --version
```
### 分发Python 包
参考[Python:打包和分发你的项目](http://www.jayinton.com/blog/index.html?tech/python/Packaging-and-Distributing-Projects.md)
dependency
--
- 命令行创建工具[click](https://github.com/mitsuhiko/click)
- 路径解释[path.py](https://github.com/jaraco/path.py)
- 中文转拼音[pypinyin](https://github.com/smallqiao/pypinyin)
- markdown渲染[mistune](https://github.com/lepture/mistune)
- DOM操作[beautifulsoup4](http://www.crummy.com/software/BeautifulSoup/)
License
-------
MIT
|
17bb7b60e9a186785036015e55c20209b8b7d684
|
[
"Markdown",
"Python",
"Text"
] | 8 |
Python
|
EManual/EManual-CLI
|
2ee9c9e167a8f13f2aa973653b390d724d5e3e6a
|
bd24ca3f612df1ff83ecc33582b9162532f84f71
|
refs/heads/master
|
<file_sep>#bar containing info about the machine in the local pane
pass
<file_sep>import json
import os
import sys
import time
import libtmux
from tmc_modules import tmc_session_manager
from tmc_tasks import tmc_ssh
from tmc_tasks import tmc_ansible_v1
import tmc_ui as tcui
import tmc_settings as tcs
example_file = 'tmc/configs/taskf_ssh.json'
class Config:
def __init__(self, name):
self.machines = {}
self.name = name
# Builds a new config via user-input, returns dict in desired format
def build(self):
machines, reading = {}, True
cfg_prompt = [
['enter your config-content!'],
['syntax: machine,info;machine,info [...]'],
['enter q to leave config-reading-mode.'],
[''],
['Press any key to enter reading mode']
]
while reading:
cmd = launch_ui(cfg_prompt, 'str')
if cmd == 'q':
reading = False
else:
try:
segments = cmd.split(';')
for x in segments:
print('parsing ' + x)
machine, info = self.parse(x)
machines[machine] = info
except:
err_msg = [
['Input-format must be key,val;key,val'],
['Input was:'],
['{0}'.format(cmd)]
]
launch_ui(err_msg, 'str')
return machines
# Returns a validated (by self.name_validator) name for the config
# (and creates the parameters for self.name_validator)
def create(self):
cmd, reading, self.raw_info = str, 1, []
info = 'creating config'
init_prompt = 'Is that name correct? (y/n)'
second_prompt = 'Enter a new name for the config please.'
target = launch_ui('Name the new config please!', 'str')
validation_prompt = [[target], [init_prompt], ['']]
name = self.name_validator(info, init_prompt, second_prompt, target, validation_prompt)
return name
def edit(self):
pass
# Loops through a validating-and-replacing-process until the user-input is 'y',
# returns the validated variable
def name_validator(self, info, init_prompt, second_prompt, target, validation_prompt):
validated = False
while not validated:
cmd = launch_ui(validation_prompt, 'chr')
if cmd == 'y':
result = target
validated = True
elif cmd == 'n':
target = launch_ui(second_prompt, 'chr')
else:
err_msg = 'not a valid command: {0}'.format(cmd)
launch_ui(err_msg, 'chr')
return result
def new(self):
self.name = self.create()
self.machines = self.build()
self.save()
# iterates through param, returns comma-split-iterations
def parse(self, data):
machine, info = data.split(',')
return machine, info
def save(self):
self.file = os.path.join(tcs.CONFIG_DIR, self.name + '.json')
with open(self.file, 'w') as f:
json.dump(self.machines, f)
def set_data(self, file, machines):
self.file = file
self.machines = machines
# called with a name (to be displayed in the menu) and a list of options for the menu-instance
class Menu:
def __init__(self, name, options):
self.menu_dict = {}
self.name = name
self.options = options
self.text = [[self.name]] + self.build_menu()
# Builds a dict from raw options with enum-results as keys,
# comprehends that dicts content as adequate, printable menu-options,
# returns the result as a string (n: option1 \n n+1: option2)
def build_menu(self):
for i, option in enumerate(self.options):
self.menu_dict[i] = option
self.menu_dict[i][0] = '{0}'.format(self.menu_dict[i][0])
text = []
for i, option in enumerate(self.menu_dict):
text.append(['{0}: {1}'.format(i+1, self.menu_dict[option][0])])
text.append('')
return text
# Launches the menu (prints the string)
# Loops the menu until a valid input has been made
# On valid input, returns the according value to the chosen option
def launch(self):
cmd = None
while not cmd in range(len(self.menu_dict)):
msg = self.text[:-1]
cmd = launch_ui(msg, 'chr')
if cmd.isdigit():
if int(cmd) - 1 in range(len(self.menu_dict)):
return(self.menu_dict[int(cmd)-1][1])
else:
err_msg = 'your answer was not in range!'
launch_ui(msg, 'chr')
return self.name
# Sets the global prompt by calling the prompt-function,
# prints the welcome-message, then calls the main-function
def app():
global prompt
prompt = build_prompt()
welcome_msg = 'Welcome to tmuxControl!'
launch_ui(welcome_msg, 'chr')
main()
# Casts 'whoami' and 'hostname' to os, builds and returns a prompt
def build_prompt():
prompt_info_file = tcs.FILE_DIR + '/prompt_info.txt'
if not os.path.isdir(tcs.FILE_DIR):
os.mkdir(tcs.FILE_DIR)
os.system('whoami > {0} && hostname >> {0}'.format(prompt_info_file))
with open(prompt_info_file, 'r') as f:
prompt_info = f.readlines()
current_user = prompt_info[0][:-1]
current_machine = prompt_info[1][:-1]
os.unlink(prompt_info_file)
return '\n{0}@{1}:'.format(current_user, current_machine)
# Says Goodbye and quits program
def exit_app():
bye_msg = 'Goodbye'
launch_ui(bye_msg, 'chr')
os.system('tmux kill-session -t tmc_ops')
os.system('tmux kill-session -t tmc_adm')
sys.exit(0)
# Reads jsons in tcs.configDir, calls menu (for picking an existing or creating a new config)
def get_config():
cfgs = [['Create new config', '']]
if not os.path.isdir(tcs.CONFIG_DIR):
os.mkdir(tcs.CONFIG_DIR)
for f in os.listdir(tcs.CONFIG_DIR):
if 'json' in f:
cfgs.append([f[:-5], f])
config_menu = Menu('Config Menu', cfgs)
chosen_config = config_menu.launch()
current_config = Config(chosen_config)
if chosen_config in os.listdir(tcs.CONFIG_DIR):
config_file = os.path.join(tcs.CONFIG_DIR, chosen_config)
with open(config_file, 'r') as f:
machines = json.load(f)
current_config.set_data(config_file, machines)
else:
current_config.new()
# Initializes the start_menu-options (returns list of lists)
def get_start():
start_menu = [
['Launch tmux-session with config', execute],
['Manage config', get_config],
['Stop the app', exit_app]
]
return start_menu
# Will launch the actual tmux-session - called with:
# a config (list of machines and respective info)
# and a task (for now: ssh-logins (with the included info))
def launch_ui(content, desired_return):
if type(content) == str:
content = [[content]]
cmd = tcui.launch(content, tcs.BLACK, tcs.BLACK, tcs.WHITE, tcs.BLACK, desired_return)
return cmd
# Instantiates the main_menu-object (of the Menu-class) with the initial menu-options
# (receives from get_start (which just returns a static dict)),
# then loops the main-menu-launch and calls the returned function
# (depending on the to-be-called-function, parameters may have to be called) (forever)
def main():
start_menu = get_start()
main_menu = Menu('Main Menu', start_menu)
run = True
while run:
cmd = main_menu.launch()
cmd()
cmd = ''
# The task thats gonna be executed (which this entire thing is about),
# going to be called with a parameter defining the targets,
# (e.g. ssh-connection=task, machines=targets (including login-information etc))
def execute():
init_ops()
launch_msg = 'launch successful!'
launch_ui(launch_msg, 'chr')
# gets the commands by the operations respective module (tmc_$OPERATION),
# launches one window per machine and issues the dicts cmd-value to that window
def init_ops(f=example_file, operation='ansible'):
server = libtmux.Server()
if operation == 'ssh':
# get dict with machine-info and ssh-commands (key = ssh)
target_dict = tmc_ssh.create_ssh_commands(f)
elif operation == 'ansible':
target_dict = tmc_ansible_v1.create_ansible_v1_commands('/home/dey25201/Projekte/Talanx/ansible')
elif operation == 'foo':
# target_dict = tmc_foo.create_foo_commands()
pass
# add window-names and -ids to target-dict (window_id, window_name)
# also actually creates ops-session and the windows
print >> sys.stderr, "%s" %(target_dict)
try:
target_dict = tmc_session_manager.create_windows(target_dict)
#session = server.find_where({ "session_name": "tmc_ops" })
#pane_id = 1
#for el in target_dict:
# window = session.find_where({ "window_name": el['window_name']})
# pane = window.select_pane('%{0}'.format(pane_id))
# pane = pane.select_pane()
# pane.send_keys(el['cmd'])
# pane_id += 1
except (Exception,),e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print >> sys.stderr, "### Unexpected exception: '%s' [%s] in file '%s' at line: %d" % (str(e), exc_type, fname, exc_tb.tb_lineno)
<file_sep>from setuptools import setup
setup(name='tmux-control',
version='0.2',
description='tmux session manager',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/2357mam/tmuxControl',
py_modules=['app', 'tmc_backend', 'tmc_settings', 'tmc_ui'],
install_requires=[
'libtmux'])
<file_sep>import curses
APP_NAME = 'tmuxControl'
APP_VERSION = 'v0.1'
APP_INFO = '{0} {1}'.format(APP_NAME, APP_VERSION)
GIT_LINK = 'https://github.com/2357mam/tmux-control'
FOOTER = 'source: {0}'.format(GIT_LINK)
# assigning colors
RED = curses.COLOR_RED
GREEN = curses.COLOR_GREEN
BLUE = curses.COLOR_BLUE
YELLOW = curses.COLOR_YELLOW
BLACK = curses.COLOR_BLACK
MAGENTA = curses.COLOR_MAGENTA
CYAN = curses.COLOR_CYAN
WHITE = curses.COLOR_WHITE
CONFIG_DIR = 'tmc/configs'
FILE_DIR = 'tmc/files'
<file_sep>import json
#reads taskf_ssh.json, returns dict
def get_targets(f):
with open(f, 'r') as f:
machines = f.read()
machines = json.loads(machines)
return machines
#returns dict {'machine':'ssh_command'}
def create_ssh_commands(f):
ssh_machines = get_targets(f)
ssh_dict = {}
for el in ssh_machines:
user = el['user']
system = el['machine']
el['cmd'] = 'neofetch && ssh {0}@{1}'.format(user, system)
return ssh_machines
<file_sep>import os
import libtmux
window_id = 1
#receives list of machine-dicts, creates one window per machine
def create_windows(targets):
global window_id
server = libtmux.Server()
os.system('tmux new -d -s tmc_ops')
session = server.find_where({ "session_name": "tmc_ops" })
#for el in targets:
# target = el['machine']
# window_name = target + '_w'
# session.new_window()
# session.windows[window_id].rename_window(window_name)
# el['window_name'] = window_name
# el['window_id'] = window_id
# window_id += 1
return(targets)
<file_sep>import os
REQUIREMENTS = [
'set-option -g allow-rename off',
]
TCF = os.getenv("HOME") + '/.tmux.conf'
def check():
with open(TCF, 'r') as f:
tmux_conf = f.read()
for x in REQUIREMENTS:
if not x in tmux_conf:
tmux_conf += '\n%s\n' %(x)
with open(TCF, 'w') as f:
f.write(tmux_conf)
<file_sep>import curses
import tmc_settings as tcs
def build_box(content_dict):
property_dict, box_height, box_width = get_box_properties(content_dict)
win = curses.newwin(box_height + 2, box_width, 5, 35)
win.bkgd(curses.color_pair(2))
win.refresh()
for section in property_dict:
if not section == 'content':
for line in property_dict[section]:
win.addstr(line[0] -2, 2, line[1])
else:
for line in property_dict[section]:
for entity in line:
if not type(entity) == list:
win.addstr(line[0] -2, 2, line[1])
else:
win.addstr(entity[0] -2, 2, entity[1])
win.box()
win.refresh()
def get_box_properties(content_dict):
property_dict = {}
box_height = 0
box_width = 0
line = 3
categories = ['header', 'content', 'footer']
for category in categories:
property_dict[category] = []
for row in content_dict[category]:
if not type(row) == list:
var = row
property_dict[category].append([line, row])
line, box_height = map(increment_vars,[line, box_height])
else:
for var in row:
property_dict[category].append([line, var])
line, box_height = map(increment_vars,[line, box_height])
if len(var) + 2 > box_width:
box_width = len(var) + 2
property_dict[category].append([line, ''])
line, box_height = map(increment_vars,[line, box_height])
box_width += 4
return property_dict, box_height, box_width
def increment_vars(x):
return x+1
def init_curses(inactive_color, window_bg, box_text, box_bg):
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(1)
curses.start_color()
curses.init_pair(1, inactive_color, window_bg)
curses.init_pair(2, box_text, box_bg)
stdscr.bkgd(curses.color_pair(1))
stdscr.refresh()
return stdscr
def kill_box(stdscr):
curses.nocbreak()
stdscr.keypad(False)
curses.echo()
curses.endwin()
def launch(menu, inactive_color, window_bg, box_text, box_bg, desired_return):
content = [x[0] for x in menu]
content_dict = {
'header' : [tcs.APP_INFO],
'content' : content,
'footer' : [tcs.FOOTER]
}
stdscr = init_curses(inactive_color, window_bg, box_text, box_bg)
build_box(content_dict)
cmd = get_command(desired_return, stdscr)
kill_box(stdscr)
return cmd
def get_command(desired_return, stdscr):
if desired_return == 'chr':
cmd = chr(stdscr.getch())
else:
cmd = stdscr.getstr()
return cmd
<file_sep># tmuxControl
Dynamic session-control:
most tmux-managers just initialize a static layout, where this will manage sessions on the fly.
The first intended use case is ssh-connecting to machine-lists found in a config-file, and management of
a) the active list of desired machines for the current session and
b) the session itself.
Usage: create a json-file containing a dict with infos about your machine, equivalent to tmc/configs/taskf_ssh.json,
pass your file as param1 to init_ops (or call app.py with your file as arg1 directly)
<file_sep>import sys
import os
# ansible v1 imports
from ansible.inventory import Inventory, InventoryParser, InventoryDirectory
def ansible_inventory(ansiblehosts,subset=None):
if os.path.isdir(ansiblehosts) or os.path.isfile(ansiblehosts):
inventory = Inventory(ansiblehosts)
if subset:
inventory.subset(subset)
else:
print >> sys.stderr, "### ERROR ansible-hosts %s not found" %(ansiblehosts)
return(inventory)
# import specific variables which are usefull to contact ansible-host
# TODO: it would be possible to get even more information about the ansible-host here
def ansible_variables(inventory,hosts):
result={}
group_vars={}
groups={}
# TODO: kommt man einfacher an die gruppen?
for g in inventory.get_groups():
if not g.name == 'all':
group_vars[g.name]=g.get_variables()
#print >> sys.stderr, "# group: %s" %(g.name)
for h in g.get_hosts():
#print >> sys.stderr, " %s" %(h.name)
if not groups.has_key(h.name):
groups[h.name]=[]
groups[h.name].append(g.name)
for h in inventory.list_hosts(hosts):
variables = inventory.get_variables(h)
#print >> sys.stderr, variables
#verbose = ''
#if variables.has_key('ansible_ssh_host'):
# verbose = "%s ansible_ssh_host: \"%s\"" %(verbose,variables['ansible_ssh_host'])
#if variables.has_key('comment'):
# verbose = "%s comment: \"%s\"" %(verbose,variables['comment'])
#print >> sys.stderr, "# %s%s" %(variables['inventory_hostname'],verbose)
#print >> sys.stderr, "# %s" %(variables)
if not result.has_key(h):
result[h]={}
result[h]['groups']=groups[h]
if variables.has_key('ansible_ssh_host'):
result[h]['ansible_ssh_host'] = variables['ansible_ssh_host']
if variables.has_key('ansible_ssh_user'):
result[h]['ansible_ssh_user'] = variables['ansible_ssh_user']
if variables.has_key('comment'):
result[h]['comment'] = variables['comment']
if variables.has_key('inventory_hostname'):
result[h]['inventory_hostname'] = variables['inventory_hostname']
return(result)
def create_ansible_v1_commands(myansibleprojectdir,myansiblehostlist=['all']):
hostsubset = ':'.join(myansiblehostlist)
inventory = ansible_inventory('%s/hosts' %(myansibleprojectdir),hostsubset)
variables = ansible_variables(inventory,hostsubset)
return variables
<file_sep>#!/usr/bin/python
# checks wether the app was called with an arg,
# arg can be:
# 1. a config-file to launch an ssh-session with
# 2. 'DIRECT_LAUNCH', launching the app without init_adm
# if no arg exists, init_adm is called,
# which then calls this script with 'DIRECT_LAUNCH' set as arg 1
# this seems kind of clunky, but makes sense:
# you just want to call one launching-app, and launch
# init_adm OR an ssh-session with a custom file/,
# after init_adm was called, you can launch the actual app -
# with a gui and in the correct tmux-environment.
import os
import sys
from tmc import tmc_backend as tcb
from tmc import tmc_init_adm
from tmc import tmc_tmux_conf_check as tcc
if __name__ == '__main__':
# ensures all requirements in tmux.conf are met
tcc.check()
try:
if len(sys.argv) == 1:
# launches 1. the session containing the tool,
# and 2. this script with arg1 'DIRECT_LAUNCH'
tmc_init_adm.launch()
else:
if sys.argv[1] == 'DIRECT_LAUNCH':
tcb.app()
else:
# initializes ops-session with arg-file
tcb.init_ops(sys.argv[1])
os.system('tmux attach-session -t tmc_ops')
except (Exception,),e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print >> sys.stderr, "### Unexpected exception: '%s' [%s] in file '%s' at line: %d" % (str(e), exc_type, fname, exc_tb.tb_lineno)
<file_sep># this module launches a tmux-session 'tmc_adm' and the tmc-app in window 0 of that session.
import os
import libtmux
LAUNCH_TOOL = os.getcwd() + '/app.py DIRECT_LAUNCH 2> .tmux-control-direct-launch.log'
def launch():
server = libtmux.Server()
res = os.system('tmux new -d -s tmc_adm -n program')
session = server.find_where({ "session_name": "tmc_adm" })
window = session.new_window()
session.windows[0].rename_window('TMC app-session')
pane = window.select_pane('%0')
pane = pane.select_pane()
pane.send_keys(LAUNCH_TOOL)
os.system('tmux attach-session -t tmc_adm')
|
d668bad5d357a3d0eb618c7fb373e795dafeb007
|
[
"Markdown",
"Python"
] | 12 |
Python
|
rostchri/tmux-control
|
c36d0efdbb38be3b2f710985fd25761f5095d0d5
|
b759f382240883a448689cb0c510e8a1457998e3
|
refs/heads/master
|
<file_sep>#ifndef ZOOKEEPER_C_H
#define ZOOKEEPER_C_H
#include <zookeeper.h>
#include <proto.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/time.h>
#include <time.h>
#include <errno.h>
#include <assert.h>
const char * errcode2str(int errcode);
int init(const char *);
int zoo_close();
int create(const char * node,char * value,char * buffer,int flags,int bufferlen);
int get(char * node,char * buffer,int *bufferlen);
int set(char * node,char * buffer);
int is_exist(const char * node);
#endif
<file_sep>#include "pth.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
#include <signal.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <errno.h>
/* the socket connection handler thread */
static void *handler(void *_arg)
{
int fd = (int)_arg;
time_t now;
char *ct;
now = time(NULL);
ct = ctime(&now);
char buf[4];
if(pth_read(fd,buf,4)!=4){
perror("read error");
close(fd);
return NULL;
}
if(memcmp(buf,"time",4)){
printf("not match\n");
close(fd);
return NULL;
}
pth_write(fd, ct, strlen(ct));
close(fd);
return NULL;
}
/* the stderr time ticker thread */
static void *ticker(void *_arg)
{
time_t now;
char *ct;
float load;
struct timeval tvTimeout;
tvTimeout.tv_sec = 1;
tvTimeout.tv_usec = 0;
long ready;
for (;;) {
pth_sleep(5);
pth_ctrl(PTH_CTRL_GETAVLOAD, &load);
ready = pth_ctrl(PTH_CTRL_GETTHREADS_READY);
printf("ticker: average load: %.2f new:%ld\n", load,ready);
}
}
/* the main thread/procedure */
int main(int argc, char *argv[])
{
pth_attr_t attr;
struct sockaddr_in sar;
struct protoent *pe;
struct sockaddr_in peer_addr;
int peer_len;
int sa, sw;
int port;
pth_init();
signal(SIGPIPE, SIG_IGN);
attr = pth_attr_new();
pth_attr_set(attr, PTH_ATTR_NAME, "ticker");
pth_attr_set(attr, PTH_ATTR_STACK_SIZE, 64*1024);
pth_attr_set(attr, PTH_ATTR_JOINABLE, FALSE);
pid_t pid = pth_spawn(attr, ticker, NULL);
pe = getprotobyname("tcp");
sa = socket(AF_INET, SOCK_STREAM, pe->p_proto);
sar.sin_family = AF_INET;
sar.sin_addr.s_addr = INADDR_ANY;
sar.sin_port = htons(9001);
int on=1;
if((setsockopt(sa,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on)))<0){
perror("setsockopt failed");
exit(1);
}
int ret = bind(sa, (struct sockaddr *)&sar, sizeof(struct sockaddr_in));
if(ret!=0){
perror("bind fail");
exit(1);
}
listen(sa, 50);
pth_attr_set(attr, PTH_ATTR_NAME, "handler");
for (;;) {
peer_len = sizeof(peer_addr);
sw = pth_accept(sa, (struct sockaddr *)&peer_addr, &peer_len);
//printf("sw:%d \n",sw);
pth_spawn(attr, handler, (void *)sw);
}
}
<file_sep>#include "zookeeper_c.h"
int main(int argc,char **argv){
char * host = "localhost:2111";
int rc = init(host);
if(rc) printf("init success!\n");
char * parent = "/test1";
char buffer[100];
char * childvalue = argv[1];
if(is_exist(parent)){
char * child;
sprintf(child,"%s/extra-%s",parent,childvalue);
int flag;
flag |= ZOO_EPHEMERAL;
flag |= ZOO_SEQUENCE;
if(create(child,childvalue,buffer,flag,sizeof(buffer))){
printf("create success!\n");
}
sprintf(child,"%s",buffer);
printf("fullpath:%s\n",child);
int len = sizeof(buffer);
memset(buffer,0,len);
if(get(child,buffer,&len)){
printf("value : %s",buffer);
}
}else{
int flag = 0;
if(create(parent,"",buffer,flag,sizeof(buffer))){
printf("create success!\n");
}
printf("not exist!\n");
}
}
<file_sep>#include "zookeeper_c.h"
static clientid_t myid;
static char * hostPort;
static zhandle_t *zh;
void watcher(zhandle_t *zzh, int type, int state, const char *path, void* context);
void output_zoo(int errcode,char * comment){
if(comment)
printf("%s errcode:%s\n",comment,errcode2str(errcode));
else
printf("errcode:%s\n",errcode2str(errcode));
}
const char * errcode2str(int errcode){
switch(errcode){
case 0:
return "ZOK";
case -1:
return "ZSYSTEMERROR";
case -2:
return "ZRUNTIMEINCONSISTENCY";
case -3:
return "ZDATAINCONSISTENCY";
case -4:
return "ZCONNECTIONLOSS";
case -5:
return "ZMARSHALLINGERROR";
case -6:
return "ZUNIMPLEMENTED";
case -7:
return "ZOPERATIONTIMEOUT";
case -8:
return "ZBADARGUMENTS";
case -9:
return "ZINVALIDSTATE";
case -100:
return "ZAPIERROR";
case -101:
return "ZNONODE";
case -102:
return "ZNOAUTH";
case -103:
return "ZBADVERSION";
case -108:
return "ZNOCHILDRENFOREPHEMERALS";
case -110:
return "ZNODEEXISTS";
case -111:
return "ZNOTEMPTY";
case -112:
return "ZSESSIONEXPIRED";
case -113:
return "ZINVALIDCALLBACK";
case -114:
return "ZINVALIDACL";
case -115:
return "ZAUTHFAILED";
case -116:
return "ZCLOSING";
case -117:
return "ZNOTHING";
case -118:
return "ZSESSIONMOVED";
}
}
int init(const char * hostport){
if(zh==NULL){
zoo_set_debug_level(ZOO_LOG_LEVEL_WARN);
zoo_deterministic_conn_order(1); // enable deterministic order
hostPort = (char *)malloc(strlen(hostport));
strcpy(hostPort,hostport);
zh = zookeeper_init(hostPort, watcher, 30000, &myid, 0, 0);
if (!zh) {
printf("errno:%d\n",errno);
return 0;
}
return 1;
}
return 0;
}
int zoo_close(){
int rc = zookeeper_close(zh);
if(hostPort) free(hostPort);
if(rc==ZOK) return 1;
else{
output_zoo(rc,"close ");
return 0;
}
}
int create(const char * node,char * value,char * buffer,int flags,int bufferlen){
int rc = zoo_create(zh, node, value==NULL?"":value, value==NULL?1:strlen(value), &ZOO_OPEN_ACL_UNSAFE, flags, buffer, bufferlen);
if (rc==ZOK)return 1;
else{
output_zoo(rc,"zoo_create ");
return 0;
}
}
int get(char * node,char * buffer,int * bufferlen){
struct Stat stat;
int rc = zoo_get(zh,node,1,buffer,bufferlen,&stat);
if(rc==ZOK){
return 1;
}else{
output_zoo(rc,"zoo_get ");
return 0;
}
}
int set(char * node,char * buffer){
int rc = zoo_set(zh,node,buffer,strlen(buffer),-1);
if(rc==ZOK){
return 1;
}else{
output_zoo(rc,"zoo_set ");
return 0;
}
}
int is_exist(const char * node){
struct Stat stat;
int is_exist = zoo_exists(zh,node,1,&stat);
if(is_exist==ZNONODE) return 0;
else if(is_exist==ZOK) return 1;
else{
output_zoo(is_exist,"is_exist");
return 0;
}
}
void watcher(zhandle_t *zzh, int type, int state, const char *path,
void* context)
{
/* Be careful using zh here rather than zzh - as this may be mt code
* the client lib may call the watcher before zookeeper_init returns */
fprintf(stderr, "Watcher %d state = %s", type, errcode2str(state));
if (path && strlen(path) > 0) {
fprintf(stderr, " for path %s", path);
}
fprintf(stderr, "\n");
if (type == ZOO_SESSION_EVENT) {
if (state == ZOO_CONNECTED_STATE) {
const clientid_t *id = zoo_client_id(zzh);
if (myid.client_id == 0 || myid.client_id != id->client_id) {
myid = *id;
fprintf(stderr, "Got a new session id: 0x%llx\n",
(long long) myid.client_id);
}
} else if (state == ZOO_AUTH_FAILED_STATE) {
fprintf(stderr, "Authentication failure. Shutting down...\n");
zookeeper_close(zzh);
zh=0;
} else if (state == ZOO_EXPIRED_SESSION_STATE) {
fprintf(stderr, "Session expired. Shutting down...\n");
zookeeper_close(zzh);
zh=0;
}
}
}
<file_sep>#include <sys/types.h>
#include <event.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <errno.h>
#define MAX_LINE 16384
typedef struct {
pthread_t thread_id; /* unique ID of this thread */
struct event_base *base; /* libevent handle this thread uses */
} LIBEVENT_DISPATCHER_THREAD;
typedef struct {
pthread_t thread_id; /* unique ID of this thread */
struct event_base *base; /* libevent handle this thread uses */
struct event notify_event; /* listen event for notify pipe */
int notify_receive_fd; /* receiving end of notify pipe */
int notify_send_fd; /* sending end of notify pipe */
} LIBEVENT_THREAD;
enum conn_state{
read_client,
write_client,
read_pipe,
con_close
};
typedef struct{
LIBEVENT_THREAD * thread;
enum conn_state state;
struct event notify_event;//conn event,the conn only have an event at one time
int client_fd;//accept fd
}conn;
static struct event_base *main_base;
static LIBEVENT_THREAD *threads;
static LIBEVENT_DISPATCHER_THREAD dispatcher_thread;
static pthread_mutex_t init_lock;
static pthread_cond_t init_cond;
static int init_count = 0;
static int nthreads = 4;
static int last_thread = -1;
static void thread_event_handler(int fd, short which, void *arg);
void add_conn_event(short flags,conn * c){
LIBEVENT_THREAD * thread = c->thread;
event_set(&c->notify_event, c->client_fd, flags, thread_event_handler,c);
event_base_set(thread->base, &c->notify_event);
if (event_add(&c->notify_event, 0) == -1) {
fprintf(stderr, "Can't monitor libevent notify pipe\n");
exit(1);
}
}
void main_event_handler(const int fd, const short which, void *arg) {
struct sockaddr_storage ss;
socklen_t slen = sizeof(ss);
int client_fd = accept(fd, (struct sockaddr*)&ss, &slen);
if (client_fd < 0) {
perror("accept error");
}
int flags;
if ((flags = fcntl(client_fd, F_GETFL, 0)) < 0 ||
fcntl(client_fd, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("setting O_NONBLOCK");
close(client_fd);
}
int tid = (last_thread + 1) % nthreads;
LIBEVENT_THREAD *thread = threads + tid;
if (write(thread->notify_send_fd,&client_fd,sizeof(int)) != sizeof(int)) {
perror("Writing to thread notify pipe");
}
last_thread++;
}
//create thread
static void create_worker(void *(*func)(void *), void *arg) {
pthread_t thread;
pthread_attr_t attr;
int ret;
pthread_attr_init(&attr);
if ((ret = pthread_create(&thread, &attr, func, arg)) != 0) {
fprintf(stderr, "Can't create thread: %s\n",
strerror(ret));
exit(1);
}
}
static void state_machine(conn * con_args);
static void thread_event_handler(int fd, short which, void *arg) {
//printf("%s\n",__FUNCTION__);
conn * con = (conn*)arg;
state_machine(con);
}
static void state_machine(conn * con_args){
int stop = 0;
while(!stop){
//printf("tid:%d con_state:%d\n",con_args->thread->thread_id,con_args->state);
switch (con_args->state){
case read_client:
con_args->state = write_client;
char buf[4];
if(read(con_args->client_fd,buf,4)!=4){
con_args->state = con_close;
break;
}
//match is 0
if(memcmp(buf,"time")){
printf("str not equals\n");
con_args->state = con_close;
break;
}
//printf("client receive value:%s\n",buf);
con_args->state = write_client;
event_del(&con_args->notify_event);
add_conn_event(EV_WRITE | EV_PERSIST,con_args);
stop =1;
break;
case write_client:
con_args->state = con_close;
time_t t1 = time(NULL);
char * ct = ctime(&t1);
write(con_args->client_fd,ct,strlen(ct));
break;
case con_close:
close(con_args->client_fd);
event_del(&con_args->notify_event);
free(con_args);
stop = 1;
break;
}
}
//printf("end while\n");
}
static void thread_libevent_process(int fd, short which, void *arg) {
LIBEVENT_THREAD * threads = (LIBEVENT_THREAD*)arg;
int accept_fd;
if (read(fd,&accept_fd, sizeof(int)) != sizeof(int)){
perror("read error!");
}
conn * con = (conn*)malloc(sizeof(conn));
if(con==NULL){
close(accept_fd);
return;
}
con->client_fd = accept_fd;
con->state = read_client;
con->thread = threads;
//printf("accept client fd:%d pid:%d\n",accept_fd,threads->thread_id);
add_conn_event(EV_READ | EV_PERSIST,con);
}
/*
* Worker thread: main event loop
*/
static void *worker_libevent(void *arg) {
LIBEVENT_THREAD *me = arg;
me->thread_id = pthread_self();
pthread_mutex_lock(&init_lock);
init_count++;
pthread_cond_signal(&init_cond);
pthread_mutex_unlock(&init_lock);
event_base_loop(me->base, 0);
return NULL;
}
static void thread_init() {
int i;
pthread_mutex_init(&init_lock, NULL);
pthread_cond_init(&init_cond, NULL);
threads = calloc(nthreads, sizeof(LIBEVENT_THREAD));
if (!threads) {
perror("Can't allocate thread descriptors");
exit(1);
}
for (i = 0; i < nthreads; i++) {
int fds[2];
if (pipe(fds)) {
perror("Can't create notify pipe");
exit(1);
}
threads[i].notify_receive_fd = fds[0];
threads[i].notify_send_fd = fds[1];
threads[i].base = event_init();
if (! threads[i].base) {
fprintf(stderr, "Can't allocate event base\n");
exit(1);
}
event_set(&threads[i].notify_event, threads[i].notify_receive_fd,
EV_READ | EV_PERSIST, thread_libevent_process,&threads[i]);
event_base_set(threads[i].base, &threads[i].notify_event);
if (event_add(&threads[i].notify_event, 0) == -1) {
fprintf(stderr, "Can't monitor libevent notify pipe\n");
exit(1);
}
}
for (i = 0; i < nthreads; i++) {
create_worker(worker_libevent, &threads[i]);
}
pthread_mutex_lock(&init_lock);
while (init_count < nthreads) {
pthread_cond_wait(&init_cond, &init_lock);
}
pthread_mutex_unlock(&init_lock);
}
/* the main thread/procedure */
int main(int argc, char *argv[]){
struct sockaddr_in sar;
struct protoent *pe;
struct sockaddr_in peer_addr;
int peer_len;
int sa;
int port;
signal(SIGPIPE, SIG_IGN);
pe = getprotobyname("tcp");
sa = socket(AF_INET, SOCK_STREAM, pe->p_proto);
int flags;
if ((flags = fcntl(sa, F_GETFL, 0)) < 0 ||
fcntl(sa, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("setting O_NONBLOCK");
close(sa);
return -1;
}
int one = 1;
setsockopt(sa, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
sar.sin_family = AF_INET;
sar.sin_addr.s_addr = INADDR_ANY;
sar.sin_port = htons(9001);
if(bind(sa, (struct sockaddr *)&sar, sizeof(struct sockaddr_in))){
perror("bind");
return;
}
listen(sa, 50);
main_base = event_init();
struct event main_event;
event_set(&main_event, sa, EV_READ | EV_PERSIST, main_event_handler, NULL);
event_base_set(main_base, &main_event);
if (event_add(&main_event, 0) == -1) {
fprintf(stderr, "Can't monitor main_event\n");
exit(1);
}
//init thread
thread_init();
event_base_loop(main_base, 0);
}
|
1b72303562250b62ab78c0e4f22569707a86a4a5
|
[
"C"
] | 5 |
C
|
ttyunix/interest
|
60d8fa7f23b26d04d7ff6691a7d040107a7f1585
|
3e8f9a6f376f53511650bf34364c640368c4fa26
|
refs/heads/master
|
<file_sep>from setuptools import setup
from setuptools.command.test import test as TestCommand
import sys
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errcode = pytest.main(self.test_args)
sys.exit(errcode)
setup(
name='hexagons',
version='0.1.1.0',
license='MIT License',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/diorge/hexagons',
packages=['hexagons'],
description='Hexagon grids for games',
tests_require=['pytest'],
cmdclass={'test': PyTest},
test_suite='hexagons.test',
extras_require={'testing': ['pytest']}
)
<file_sep>hexagons.test package
=====================
Submodules
----------
hexagons.test.test_coordinates module
-------------------------------------
.. automodule:: hexagons.test.test_coordinates
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: hexagons.test
:members:
:undoc-members:
:show-inheritance:
<file_sep>"""
.. module:: grid
:synopsis: Grids of hexagons and pixel conversions
.. moduleauthor:: <NAME> <<EMAIL>>
"""
from collections import namedtuple
from math import sqrt, floor, pi, cos, sin
from hexagons.coordinate import Axial
Hex = namedtuple('Hex', ['axiscoord', 'pixelcenter', 'pixelcorners'])
class HexagonGrid:
"""Hexagonal grid of hexagonal tiles
Note the grid itself will be the opposite of the hexes --
if the hexes are pointy, the hexagon-grid is flat, and vice-versa.
"""
@staticmethod
def determine_size(window_size, hex_size):
"""Calculates how many hexagons can be fit in the grid
Similar to each hexagon side, this side is the "radius"
of the hexagon grid
:param window_size: pixels in the window square
:type window_size: float
:param hex_size: size of the hexagon, in pixels
:type hex_size: float
:returns: int -- number of hexagons in the grid radius
"""
bigger = hex_size * 2
smaller = (bigger * sqrt(3)) / 2
total = floor(window_size / smaller)
if total % 2 == 0:
return (total - 2) // 2
return (total - 1) // 2
@staticmethod
def determine_hex_size(window_size, size):
"""Analogous to finding the grid size,
but in the opposite direction
:param window_size: pixes in the window square
:type window_size: float
:param size: number of hexagons in the grid radius
:type size: int
:returns: float -- size of the hexagon, in pixels
"""
total = size * 2 + 1
smaller = window_size / total
bigger = smaller / (sqrt(3) / 2)
return bigger / 2
@staticmethod
def _flat_corners(center, size):
"""Calculates the six corner pixels for flat hexagons
:param center: central pixel of the hexagon
:type center: iterable of float (size 2)
:param size: the size of the hexagon, or half the longest corner
:type size: float
:returns: iterable of float -- collection of corners
"""
for i in range(6):
angle_deg = 60 * i
angle_rad = pi / 180 * angle_deg
centerx, centery = center
yield (centerx + size * cos(angle_rad),
centery + size * sin(angle_rad))
@staticmethod
def _pointy_corners(center, size):
"""Calculates the six corner pixels for pointy hexagons
:param center: central pixel of the hexagon
:type center: iterable of float (size 2)
:param size: the size of the hexagon, or half the longest corner
:type size: float
:returns: iterable of float -- collection of corners
"""
for i in range(6):
angle_deg = 60 * i + 30
angle_rad = pi / 180 * angle_deg
centerx, centery = center
yield (centerx + size * cos(angle_rad),
centery + size * sin(angle_rad))
def __init__(self, window_size, center_hex, hex_format='pointy',
grid_size=0, hex_size=0):
"""Creates a new hexagonal grid
Prefers to use grid_size instead of hex_size if that variable is set.
One of these two variables must be set.
:param window_size: width/height pixels in the window (must be square)
:type window_size: float
:param center_hex: axial coordinate of the center hex
:type center_hex: Axial
:param hex_format: either 'flat' or 'pointy'
:type hex_format: str
:param grid_size: size of the grid, in hexagons
:type grid_size: int
:param hex_size: size of the hexagons, in pixels
:type hex_size: float
"""
if grid_size > 0:
self.size = grid_size
self.hex_size = HexagonGrid.determine_hex_size(window_size, grid_size)
else:
self.hex_size = hex_size
self.size = HexagonGrid.determine_size(window_size, hex_size)
self.window_size = window_size
self.hex_format = hex_format
self.topleft_corner = Axial(-self.size, -self.size)
self.move_center(center_hex)
def move_center(self, new_center):
"""Sets the hex in the center of the grid
:param new_center: coordinate of the center of the grid
:type new_center: Axial
"""
self.center_hex = new_center
window_x = window_y = self.window_size / 2
offset_center = new_center - self.topleft_corner
if self.hex_format == 'flat':
pixelx = self.hex_size * 3 / 2 * offset_center.q
pixely = self.hex_size * sqrt(3) * (offset_center.r + offset_center.q / 2)
else:
pixelx = self.hex_size * sqrt(3) * (offset_center.q + offset_center.r / 2)
pixely = self.hex_size * 3 / 2 * offset_center.r
self.xoffset = window_x - pixelx
self.yoffset = window_y - pixely
def inside_boundary(self, coord):
"""Checks if a given axial coordinate is inside the grid
:param coord: coordinate to be tested against the grid
:type coord: Axial
:returns: bool - True if inside, False otherwise
"""
coordx, coordy = coord - self.center_hex
return (abs(coordx + coordy) <= self.size and
abs(coordx) <= self.size and
abs(coordy) <= self.size)
def hexagon_list(self):
"""A sequence of hexagons
Hexagons are represented by triplets containing the axial coordinate,
the center pixel (a 2-tuple), and the corner pixels (a 6-tuple of 2-tuples)
"""
axial = tuple(p.to_axial()
for p in self.center_hex.to_cube().circle_around(self.size))
centers = tuple(self.get_center(coord) for coord in axial)
corners = tuple(tuple(self.center_to_corners(center))
for center in centers)
return list(map(Hex, axial, centers, corners))
def all_centers(self, axial_points):
"""Returns the pixel centers of the axial coordinates given
Each center is represented as a 2-tuple of floats (pixels)
"""
for point in axial_points:
yield self.get_center(point)
def get_center(self, axial):
"""Converts an axial coordinate to it's pixel center
:returns: 2-tuple of float
"""
offset_point = axial - self.topleft_corner
qcoord, rcoord = offset_point
if self.hex_format == 'flat':
centerx = self.hex_size * 3 / 2 * qcoord + self.xoffset
centery = self.hex_size * sqrt(3) * (rcoord + qcoord / 2) + self.yoffset
else:
centerx = self.hex_size * sqrt(3) * (qcoord + rcoord / 2) + self.xoffset
centery = self.hex_size * 3 / 2 * rcoord + self.yoffset
return (centerx, centery)
def center_to_corners(self, center):
"""Converts the pixel center of a hexagon to it's pixel corners
"""
corner_function = (HexagonGrid._flat_corners if self.hex_format == 'flat'
else HexagonGrid._pointy_corners)
return corner_function(center, self.hex_size)
def coord_to_corners(self, axial):
"""Converts an axial coordinate to it's pixel corners
"""
return self.center_to_corners(self.get_center(axial))
def clicked_hex(self, mousepos):
"""Gets the hexagon clicked
Calculates which hexagon is in a given window position,
returns None if no hexagon was clicked
:param mousepos: point clicked in the window
:type mousepos: tuple of float
:returns: Axial or None
"""
mousex, mousey = mousepos
mousex = mousex - self.xoffset
mousey = mousey - self.yoffset
size = self.hex_size
if self.hex_format == 'flat':
hexq = mousex * (2 / 3) / size
hexr = ((-mousex / 3) + (sqrt(3) / 3) * mousey) / size
else:
hexq = (mousex * (sqrt(3) / 3) - (mousey / 3)) / size
hexr = mousey * ((2 / 3) / size)
absolute_hex = Axial(hexq, hexr).to_cube().round().to_axial()
offset_hex = absolute_hex + self.topleft_corner
if self.inside_boundary(offset_hex):
return offset_hex
return None
<file_sep>Hexagons
========
Hexagonal grids for use in games.
Contains many utility functions like shapes and visibility.
<file_sep>"""
.. module:: coordinate
:synopsis: Axial and cube coordinates for hexagons
.. moduleauthor:: <NAME> <<EMAIL>>
Special thanks to Amit and his post: http://www.redblobgames.com/grids/hexagons
"""
import sys
from itertools import permutations
class Cube:
"""Cube coordinates for a hexagon
The coordinates (x, y, z) represent an unique hexagon
.. note:: x + y + z = 0 (or very close to it, there's some tolerance)
"""
TOLERANCE = 0.5
def __init__(self, x, y, z):
"""Creates a new immutable cube coordinate from points x, y, z
:param x: X coordinate
:type x: int or float
:param y: Y coordinate
:type y: int or float
:param z: Z coordinate
:type z: int or float
.. note:: Many operations assume the coordinates to be int,
you may wish to use :func:`Cube.round` before you apply
these operations.
"""
if abs(x + y + z) > Cube.TOLERANCE:
raise ValueError(f'Cube ({x}, {y}, {z}) does not slice the x+y+z=0 plane')
self._x = x
self._y = y
self._z = z
@property
def x(self):
"""Read-only X coordinate of the cube
:returns: int or float -- the X coordinate
"""
return self._x
@property
def y(self):
"""Read-only Y coordinate of the cube
:returns: int or float -- the Y coordinate
"""
return self._y
@property
def z(self):
"""Read-only Z coordinate of the cube
:returns: int or float -- the Z coordinate
"""
return self._z
def to_axial(self):
"""Converts the cube coordinate to an axial coordinate
:returns: Axial -- the unique corresponding axial coordinate
"""
return Axial(self.x, self.z)
def neighbors(self):
"""The neighbor cubes of the cube, assuming infinite grid
Always returns six neighbors in the same order (which is right border
first, then counterclock-wise).
:returns: iterable of Cube -- the neighbors
"""
return map(lambda d: self + d, Cube._neighbor_directions)
def diagonals(self):
"""The coordinates of the six diagonal hexagons
Diagonals are connected by a single edge, but no borders,
so the diagonals are distance 2 apart from the center
:returns: iterable of Cube -- the diagonals
"""
return map(lambda d: self + d, Cube._diagonal_directions)
def distance(self, other):
"""Calculates the distance between two hexagons
The distance is the number of hexes needed to traverse
to get from one point to the other
:returns: int or float
"""
return max(abs(self.x - other.x), abs(self.y - other.y),
abs(self.z - other.z))
def round(self):
"""Rounds a floating point to the nearest hexagon
This is not the same as rounding every coordinate,
because of the x+y+z=0 restriction.
Use this method when dealing with fractional cubes,
for example conversions to/from pixels.
:returns: Cube -- a new Cube coordinate with int values
"""
rx, ry, rz = map(round, self)
dx, dy, dz = [abs(d - o) for (d, o) in zip((rx, ry, rz), self)]
if dx > dy and dx > dz:
rx = -(ry + rz)
elif dy > dz:
ry = -(rx + rz)
else:
rz = -(rx + ry)
return Cube(rx, ry, rz)
def line_to(self, target):
"""Returns all hexes in a straight-line
The result is in order from self to target,
both extremes included.
:param target: end of the line
:type target: Cube
:returns: iterable of Cube -- points in the line
"""
def lerp(a, b, t):
return a + (b - a) * t
def cube_lerp(a, b, t):
return Cube(*(lerp(ax, bx, t) for (ax, bx) in zip(a, b)))
n = self.distance(target)
for i in range(n + 1):
yield (cube_lerp(self, target, i / n) + Cube._epsilon).round()
def circle_around(self, size, obstacles=None):
"""The collection of hexagons in a circle around this
:param size: the maximum distance, or radius of the circle
:type size: int
:param obstacles: function returning True for obstacle coordinates,
see :func:`Cube.floodfill`
:type obstacles: callable
:returns: iterable of Cube -- collection of hexagons in the circle
"""
if obstacles is not None:
yield from self.floodfill(size, obstacles)
else:
for x in range(-size, size + 1):
start = max(-size, -x - size)
end = min(size, -x + size)
for y in range(start, end + 1):
z = -(x + y)
yield self + Cube(x, y, z)
def floodfill(self, size, obstacle):
"""The collection of hexagons reachable in a finite amount of steps
Performs a flood-fill, collecting every reachable hexagon,
as long as no more than size steps are taken.
Will not walk through hexagons for which obstacle returns True.
:param size: the maximum number of steps from the origin
:type size: int
:param obstacle: function returning True for obstacle coordinates
:type obstacle: callable
:returns: iterable of Cube -- collection of reachable hexagons
"""
visited = set([self])
reachable = [[self]]
for k in range(1, size + 1):
reachable.append([])
for cube in reachable[k - 1]:
neighbors = cube.neighbors()
for neighbor in neighbors:
if neighbor not in visited and not obstacle(neighbor):
visited.add(neighbor)
reachable[k].append(neighbor)
return visited
def rotate_right(self, center=None, amount=1):
"""Returns the point after rotating to the right
Makes an amount of 60 degree rotations to the right,
centered in some other point (defaults to origin).
:param center: rotation center
:type center: Cube
:param amount: amount of 60 degree rotations
:type amount: int
:returns: Cube -- point after rotation
"""
if center is None:
center = Cube.origin
point = self - center
for i in range(amount):
x, y, z = point
point = Cube(-z, -x, -y)
return point + center
def rotate_left(self, center=None, amount=1):
"""Returns the point after rotating to the left
Makes an amount of 60 degree rotations to the left,
centered in some other point (defaults to origin).
:param center: rotation center
:type center: Cube
:param amount: amount of 60 degree rotations
:type amount: int
:returns: Cube -- point after rotation
"""
if center is None:
center = Cube.origin
point = self - center
for i in range(amount):
x, y, z = point
point = Cube(-y, -z, -x)
return point + center
def circumference(self, radius):
"""Returns the circumference around this point
:param radius: the fixed distance from the center
:type radius: int
:returns: iterable of Cube -- the ring
"""
current = set()
first = radius
for second in range(-radius, 1):
third = -(first + second)
for perm in permutations([first, second, third]):
current.add(self + Cube(*perm))
first = -radius
for second in range(0, radius + 1):
third = -(first + second)
for perm in permutations([first, second, third]):
current.add(self + Cube(*perm))
return current
def arc(self, direction, size):
"""Returns the arc within a 120 degree vision
:param direction: facing direction from self (a neighbor)
:type direction: Cube
:param size: size of the ring
:type size: int
:returns: iterable of Cube -- visible members of the arc
"""
horizon = (direction - self) * size
left_horizon = horizon.rotate_left(self)
right_horizon = horizon.rotate_right(self)
left_line = set(left_horizon.line_to(horizon))
right_line = set(right_horizon.line_to(horizon))
return left_line | right_line
def __add__(self, other):
"""Coordinate-wise addition
:param other: coordinate to be added
:type other: Cube
:returns: Cube -- the resulting addition
"""
return Cube(self.x + other.x, self.y + other.y, self.z + other.z)
def __neg__(self):
"""Negates all coordinates
:returns: Cube -- the opposing cube
"""
return Cube(-self.x, -self.y, -self.z)
def __sub__(self, other):
"""Coordinate-wise subtraction
:param other: coordinate to be subtracted from self
:type other: Cube
:returns: Cube -- the resulting subtraction
"""
return self + (-other)
def __mul__(self, scalar):
"""Scalar multiplication
:param scalar: the scalar value
:type scalar: int or float
:returns: Cube -- scaled coordinate
"""
return Cube(self.x * scalar, self.y * scalar, self.z * scalar)
def __eq__(self, other):
"""Determines equality
:param other: object to be compared
:type other: Cube
:returns: bool -- True if equal and False otherwise
"""
return (self.x, self.y, self.z) == (other.x, other.y, other.z)
def __hash__(self):
"""Hash value
:returns: int -- hash value
"""
return hash(tuple(self.__iter__()))
def __repr__(self):
"""Debugging representation
:returns: str -- readable representation
"""
return 'Cube({x}, {y}, {z})'.format(x=self.x, y=self.y, z=self.z)
def __iter__(self):
"""Iterable of the coordinates
:returns: iterable of int or float -- the coordinates
"""
yield self.x
yield self.y
yield self.z
Cube.origin = Cube(0, 0, 0)
Cube._neighbor_directions = (Cube(1, -1, 0), Cube(1, 0, -1), Cube(0, 1, -1),
Cube(-1, 1, 0), Cube(-1, 0, 1), Cube(0, -1, 1))
Cube._diagonal_directions = (Cube(2, -1, -1), Cube(1, 1, -2), Cube(-1, 2, -1),
Cube(-2, 1, 1), Cube(-1, -1, 2), Cube(1, -2, 1))
Cube._epsilon = Cube(sys.float_info.epsilon, sys.float_info.epsilon,
-2 * sys.float_info.epsilon)
class Axial:
"""Axial coordinates for a hexagon
Delegates most operations to :class:`Cube`,
convert when needed. Axial coordinates are better
for storage and pixel conversions
"""
def __init__(self, q, r):
self._q = q
self._r = r
@property
def q(self):
"""Column coordinate
"""
return self._q
@property
def r(self):
"""Row coordinate
"""
return self._r
def to_cube(self):
"""Converts the axial coordinate to a cube coordinate
:returns: Cube -- equivalent unique cube coordinate representation
"""
return Cube(self.q, -(self.q + self.r), self.r)
def neighbors(self):
"""The neighbor hexagons, assuming infinite grid
:returns: iterable of Axial -- the neighbors
"""
return(map(lambda d: Axial(self.q + d.q, self.r + d.r),
Axial._neighbor_directions))
def __eq__(self, other):
return (self.q, self.r) == (other.q, other.r)
def __add__(self, other):
return Axial(self.q + other.q, self.r + other.r)
def __neg__(self):
return Axial(-self.q, -self.r)
def __sub__(self, other):
return self + (-other)
def __repr__(self):
return 'Axial({q}, {r})'.format(q=self.q, r=self.r)
def __iter__(self):
yield self.q
yield self.r
def __hash__(self):
return hash(self.to_cube())
Axial._neighbor_directions = tuple(map(Cube.to_axial,
Cube._neighbor_directions))
<file_sep>"""
Test module for coordinate methods and conversions
"""
import hexagons.coordinate as coord
import pytest
import itertools
def test_cube_getters():
c = coord.Cube(1, 0, -1)
assert c.x == 1
assert c.y == 0
assert c.z == -1
def test_axial_getters():
c = coord.Axial(1, -1)
assert c.q == 1
assert c.r == -1
def test_cube_to_axis():
assert coord.Cube(1, 2, -3).to_axial() == coord.Axial(1, -3)
assert coord.Cube(-2, -3, 5).to_axial() == coord.Axial(-2, 5)
def test_axis_to_cube():
assert coord.Axial(1, -3).to_cube() == coord.Cube(1, 2, -3)
assert coord.Axial(-2, 5).to_cube() == coord.Cube(-2, -3, 5)
def test_invalid_cube():
""" Cubes are invalid if they don't slice the x+y+z=0 plane """
with pytest.raises(ValueError):
c = coord.Cube(1, 2, 3)
def test_iterable_cube():
c = coord.Cube(-2, 0, 2)
x, y, z = c
assert (c.x, c.y, c.z) == (x, y, z)
def test_iterable_axial():
c = coord.Axial(3, 5)
q, r = c
assert (c.q, c.r) == (q, r)
def test_cube_neighbors():
c = coord.Cube(0, 0, 0)
n = list(c.neighbors())
assert len(n) == 6
assert coord.Cube(1, -1, 0) in n
assert coord.Cube(1, 0, -1) in n
assert coord.Cube(0, 1, -1) in n
assert coord.Cube(-1, 1, 0) in n
assert coord.Cube(-1, 0, 1) in n
assert coord.Cube(0, -1, 1) in n
def test_axial_neighbors():
c = coord.Axial(5, 5)
n = list(c.neighbors())
assert len(n) == 6
assert coord.Axial(6, 5) in n
assert coord.Axial(6, 4) in n
assert coord.Axial(5, 4) in n
assert coord.Axial(4, 5) in n
assert coord.Axial(4, 6) in n
assert coord.Axial(5, 4) in n
def test_cube_diagonals():
c = coord.Cube(1, 0, -1)
n = list(c.diagonals())
assert len(n) == 6
assert coord.Cube(3, -1, -2) in n
assert coord.Cube(-1, 1, 0) in n
assert coord.Cube(0, 2, -2) in n
assert coord.Cube(2, -2, 0) in n
assert coord.Cube(0, -1, 1) in n
assert coord.Cube(2, 1, -3) in n
def test_cube_distance():
c = coord.Cube(0, 0, 0)
assert 0 == c.distance(c)
assert all(1 == c.distance(n) for n in c.neighbors())
assert 4 == c.distance(coord.Cube(-1, 4, -3))
def test_cube_round_simple():
c = coord.Cube(0.1, 1.8, -1.9)
assert c.round() == coord.Cube(0, 2, -2)
def test_cube_round_edge():
c = coord.Cube(0.4, 0.3, -0.7)
assert c.round() == coord.Cube(1, 0, -1)
def test_line():
origin = coord.Cube(0, 0, 0)
target = coord.Cube(2, -4, 2)
hexes_in_line = [origin, coord.Cube(1, -1, 0), coord.Cube(1, -2, 1),
coord.Cube(2, -3, 1), target]
line = origin.line_to(target)
assert set(hexes_in_line) == set(line)
def test_line_order():
""" The line must be draw in the order from origin to target """
origin = coord.Cube(0, 0, 0)
target = coord.Cube(-3, 1, 2)
hexes_in_line = [origin, coord.Cube(-1, 0, 1), coord.Cube(-2, 1, 1),
target]
line = list(origin.line_to(target))
assert hexes_in_line == line
def test_circle_around():
center = coord.Cube(0, 0, 0)
immediate = list(center.neighbors())
dist2 = [list(imm.neighbors()) for imm in immediate]
flat_dist2 = itertools.chain(*dist2)
everything = set([center]) | set(immediate) | set(flat_dist2)
assert everything == set(center.circle_around(2))
def test_circle_around_with_obstacles():
center = coord.Cube(0, 0, 0)
obstacles = [(1, 0, -1), (2, -1, -1), (2, -2, 0), (2, -3, 1), (1, -3, 2),
(0, -2, 2), (-1, -1, 2), (-1, 0, 1), (-2, 1, 1), (-3, 1, 2),
(-4, 1, 3), (-5, 1, 4), (1, 2, -3), (0, 2, -2), (-1, 2, -1)]
expected_within_3 = [center, (1, -1, 0), (1, -2, 1), (0, -1, 1),
(0, 1, -1), (1, 1, -2), (2, 1, -3), (2, 0, -2),
(-1, 1, 0), (-2, 2, 0), (-3, 3, 0), (-2, 3, -1),
(-3, 2, 1)]
obstacles = set(map((lambda d: coord.Cube(*d)), obstacles))
expected_within_3 = set(map((lambda d: coord.Cube(*d)), expected_within_3))
result = set(center.circle_around(3, lambda x: x in obstacles))
assert expected_within_3 == result
def test_rotate_right():
center = coord.Cube(2, 0, -2)
torotate = coord.Cube(4, -1, -3)
expected = [coord.Cube(3, -2, -1), coord.Cube(1, -1, 0),
coord.Cube(0, 1, -1), coord.Cube(1, 2, -3),
coord.Cube(3, 1, -4), coord.Cube(4, -1, -3)]
result = [torotate.rotate_right(center, i) for i in range(1, 7)]
assert expected == result
def test_rotate_left():
center = coord.Cube(2, 0, -2)
torotate = coord.Cube(4, -1, -3)
expected = [coord.Cube(3, 1, -4), coord.Cube(1, 2, -3),
coord.Cube(0, 1, -1), coord.Cube(1, -1, 0),
coord.Cube(3, -2, -1), coord.Cube(4, -1, -3)]
result = [torotate.rotate_left(center, i) for i in range(1, 7)]
assert expected == result
def test_circumference():
center = coord.Cube.origin
expected = set([coord.Cube(2, -2, 0), coord.Cube(2, -1, -1),
coord.Cube(2, 0, -2), coord.Cube(1, 1, -2),
coord.Cube(0, 2, -2), coord.Cube(-1, 2, -1),
coord.Cube(-2, 2, 0), coord.Cube(-2, 1, 1),
coord.Cube(-2, 0, 2), coord.Cube(-1, -1, 2),
coord.Cube(0, -2, 2), coord.Cube(1, -2, 1)])
result = set(center.circumference(2))
assert expected == result
def test_circumference_zero():
center = coord.Cube(1, 1, -2)
result = list(center.circumference(0))
assert [center] == result
def test_circumference_one():
center = coord.Cube(5, -6, 1)
assert set(center.neighbors()) == set(center.circumference(1))
def test_circumference_nonorigin():
center = coord.Cube(1, 0, -1)
expected = set([coord.Cube(3, -2, -1), coord.Cube(3, -1, -2),
coord.Cube(3, 0, -3), coord.Cube(2, 1, -3),
coord.Cube(1, 2, -3), coord.Cube(0, 2, -2),
coord.Cube(-1, 2, -1), coord.Cube(-1, 1, 0),
coord.Cube(-1, 0, 1), coord.Cube(0, -1, 1),
coord.Cube(1, -2, 1), coord.Cube(2, -2, 0)])
result = set(center.circumference(2))
assert expected == result
def test_arc():
center = coord.Cube.origin
facing_direction = coord.Cube(1, 0, -1)
expected = set([coord.Cube(3, -3, 0), coord.Cube(3, -2, -1),
coord.Cube(3, -1, -2), coord.Cube(3, 0, -3),
coord.Cube(2, 1, -3), coord.Cube(1, 2, -3),
coord.Cube(0, 3, -3)])
result = set(center.arc(facing_direction, 3))
assert expected == result
<file_sep>hexagons package
================
Subpackages
-----------
.. toctree::
hexagons.test
Submodules
----------
hexagons.coordinate module
--------------------------
.. automodule:: hexagons.coordinate
:members:
:undoc-members:
:show-inheritance:
hexagons.grid module
--------------------
.. automodule:: hexagons.grid
:members:
:undoc-members:
:show-inheritance:
hexagons.sample module
----------------------
.. automodule:: hexagons.sample
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: hexagons
:members:
:undoc-members:
:show-inheritance:
<file_sep>alabaster==0.7.9
Babel==2.3.4
docutils==0.13.1
imagesize==0.7.1
Jinja2==2.9.5
MarkupSafe==0.23
py==1.4.32
pygame==1.9.3
Pygments==2.2.0
pytest==3.0.6
pytz==2016.10
requests==2.13.0
six==1.10.0
snowballstemmer==1.2.1
Sphinx==1.5.2
<file_sep>#! /usr/bin/env python
import pygame
from hexagons.grid import HexagonGrid
from hexagons.coordinate import Axial
import random
def main():
def random_color():
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
return pygame.Color(r, g, b, 255)
hex_size = 50
grid_size = 4
window_size = 600
center_hex = Axial(0, 0)
hex_format = 'flat'
g = HexagonGrid(window_size, center_hex, hex_format=hex_format,
grid_size=grid_size)
pygame.init()
display = pygame.display.set_mode((window_size, window_size),
pygame.HWSURFACE)
running = True
colors = {}
for pt in center_hex.to_cube().circle_around(g.size):
colors[pt] = random_color()
def get_color(cubecoord):
if cubecoord not in colors:
colors[cubecoord] = random_color()
return colors[cubecoord]
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONUP:
pos = pygame.mouse.get_pos()
clicked = g.clicked_hex(pos)
if clicked is not None:
if clicked == g.center_hex:
colors[clicked.to_cube()] = random_color()
else:
g.move_center(clicked)
for ax, c, cn in g.hexagon_list():
pygame.draw.polygon(display, get_color(ax.to_cube()), cn)
pygame.display.flip()
pygame.quit()
if __name__ == '__main__':
main()
<file_sep>#! /usr/bin/env python
from collections import defaultdict
import random
import pygame
from hexagons.grid import HexagonGrid
from hexagons.coordinate import Axial
def main():
pygame.init()
letters = 'abcdefghijklmnopqrstuvxwyz '
white = pygame.Color(255, 255, 255, 255)
black = pygame.Color(0, 0, 0, 255)
font = pygame.font.SysFont('Arial', 30)
hex_size = 50
grid_size = 4
window_size = 600
center_hex = Axial(0, 0)
hex_format = 'pointy'
def next_letter(letter):
idx = letters.index(letter)
nextidx = (idx + 1) % len(letters)
return letters[nextidx]
letter_mapping = defaultdict(lambda: ' ')
g = HexagonGrid(window_size, center_hex, hex_format=hex_format,
grid_size=grid_size)
display = pygame.display.set_mode((window_size, window_size),
pygame.HWSURFACE)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONUP:
pos = pygame.mouse.get_pos()
clicked = g.clicked_hex(pos)
if clicked is not None:
#if clicked == g.center_hex:
letter_mapping[clicked] = next_letter(letter_mapping[clicked])
for ax, c, cn in g.hexagon_list():
pygame.draw.polygon(display, white, cn)
pygame.draw.polygon(display, black, cn, 1)
letter = letter_mapping[ax]
if letter != ' ':
letterdisplay = font.render(letter, True, black)
textwidth, textheight = font.size(letter)
x = c[0] - (textwidth / 2)
y = c[1] - (textheight / 2)
display.blit(letterdisplay, (x, y))
pygame.display.flip()
pygame.quit()
if __name__ == '__main__':
main()
|
d29f69d5da29a87600daf9e4253148f456cea6a0
|
[
"Markdown",
"Python",
"Text",
"reStructuredText"
] | 10 |
Python
|
diorge/hexagons
|
7516ff0faede0b470e6d415e17f5d22408f6b6d6
|
3eeb6db9019ed779311971e5d715b296d6e2c07d
|
refs/heads/master
|
<file_sep>var core_vm=require('./vm.0webcore.js');
var _reqlib=require('./vm.requirelib.js');
module.exports=function(vm,cb){
if(vm[core_vm.aprand].has_defined || vm[core_vm.aprand].has_started ||!vm.src){
return;
}
if(!core_vm.isfn(cb))cb=function(){}
if(vm.getcache().vmlib[vm.src]){
vm.getcache().add_ref('vm',vm.src,vm[core_vm.aprand].absrcid,'loadsub');
vm.__define(core_vm.tool.objClone(vm.getcache().vmlib[vm.src].exports));
vm.absrc=vm.src;
vm.__initdata_then_start(cb);
return;
}
var pvm=vm.pvm;
if(pvm)pvm[core_vm.aprand].loadingsub_count++;
var fresh=vm._is_fresh_ing ;
var opt={
app:vm.getapp(),
loadvm: pvm, pvmpath :pvm.absrc,
url: vm.absrc||vm.src,
type :'vm',
from: 'loadvm', fresh :fresh,
urlsid:vm[core_vm.aprand].absrcid,
refsid:pvm[core_vm.aprand].absrcid,
vm:vm,
};
_reqlib.cal_spec_path(opt);
core_vm.require.load(opt,function(err,mod,spec){
if(err){
core_vm.onerror(vm.getapp(),'load_vm_fail',spec.id || vm.src,err);
if(pvm){
pvm[core_vm.aprand].loadingsub_count--;
if(pvm[core_vm.aprand].loadingsub_count==0){
pvm.__onstart_a_zero_sub()
}
}
cb.call(vm,err);
}else{
vm.__define(mod);
vm.absrc=spec.id;
if(vm[core_vm.aprand].cbs_on_define){
for(var k in vm[core_vm.aprand].cbs_on_define)vm[core_vm.aprand].cbs_on_define[k]();
vm[core_vm.aprand].cbs_on_define=[];
}
vm.__initdata_then_start(cb);
}
});
}<file_sep>console.log("this is modbnotinlibpath ");
var mod2=require('./modbnotinlibpath2.js');
module.exports ={
str:"This text was required from modbnotinlibpath.js!",
str2:mod2.str
}<file_sep>var core_vm=require('./vm.0webcore.js');
var app_loaded=false;
var index_loaded=false;
module.exports.init=function(){
app_loaded=false;
index_loaded=false;
}
var start_index_vm=function(app,index_vm,mycb){
if(typeof (app.hookStart)!=='function')app.hookStart=function(cb){cb();}
app.hookStart(function(){
index_vm.__initdata_then_start(mycb);
})
}
var start_index_and_app=function(app,index_vm,cb){
start_index_vm(app,index_vm,cb);
}
var start_parse_index=function(app,file_indexvm,index_vm,cb,where){
if(app.indexvm_text==='' || !app_loaded){
return;
}
if(app.indexvm_text===true){
cb();
return;
}
index_vm[core_vm.aprand].absrcid=1;
core_vm.require.load({
app:app,
loadvm:null,pvmpath:'',
url:file_indexvm,
type:'vm',from:'file_indexvm',
text:app.indexvm_text,
urlsid:1,
refsid:1,
vm:index_vm
},function(err,mod,spec){
delete app.indexvm_text;
if(err){
core_vm.devalert(index_vm,'load file_indexvm fail');
if(typeof (cb)=='function')cb('error');
}else{
for(var k in mod){
index_vm[k]=mod[k];
}
}
index_vm.absrc=spec.id ;
index_loaded=true;
start_index_and_app(app,index_vm,cb);
});
}
var start_system=function(app,file_app,file_indexvm,index_vm,cb){
app.indexvm_text='';
if(file_indexvm){
app.loadfile('text',file_indexvm,function(err,text){
app.indexvm_text=text;
start_parse_index(app,file_indexvm,index_vm,cb,3);
});
}else{
app.indexvm_text=true;
start_parse_index(app,file_indexvm,index_vm,cb,4);
}
if(file_app){
core_vm.require.load({
app:app,
loadvm:null,pvmpath:'',
url:file_app,type:'lib',from:'file_app',
urlsid:2,
refsid:2,
vm:null,
},function(err,mod,spec){
if(err){
core_vm.devalert(index_vm,'load app fail ');
}
core_vm.rootvmset.checkappconfig(app,1);
core_vm.rootvmset.setstore(app);
app_loaded=true;
start_parse_index(app,file_indexvm,index_vm,cb,1);
});
}else{
core_vm.rootvmset.checkappconfig(app, {});
core_vm.rootvmset.setstore(app);
app_loaded=true;
start_parse_index(app,file_indexvm,index_vm,cb,2);
}
}
module.exports.start_system=start_system;
module.exports.start_index_vm=start_index_vm;
<file_sep>var core_vm=require('./vm.0webcore.js');
module.exports.setproto=function(proto){
proto.hasChild=function(id){
if(this[core_vm.aprand].vmchildren[id+''])return true;
else return false;
}
proto.getChild=function(id){
if(this[core_vm.aprand].vmchildren[id]){
return this.getcache().vmsbysid[this[core_vm.aprand].vmchildren[id]];
}else if(id.indexOf('.')>-1){
var tvm=this;
var parts = ~id.indexOf('.') ? id.split('.') : [id];
for (var i = 0; i < parts.length; i++){
tvm = tvm.getcache().vmsbysid[tvm[core_vm.aprand].vmchildren[parts[i]]]
if(tvm===undefined)break;
}
return tvm;
}
}
proto.getParent=function(){
return this.pvm;
}
proto.removeChild=function(id){
var cvm;
if(id instanceof core_vm.define.vmclass && this.sid===id.pvm.sid){
if (this[core_vm.aprand].vmchildren[id.id] && this[core_vm.aprand].vmchildren[id.id]==id.sid){
let realid=id.id;
cvm=id;
id=realid;
}
}
else if(core_vm.isstr(id))cvm=this.getChild(id);
if(cvm){
cvm.__vmclose(true);
cvm.getcache().removesid(cvm.sid);
delete this[core_vm.aprand].vmchildren[id];
}
}
proto.appendChild=function(opt,pnode,ifpnode){
if(!opt.id || this.hasChild(opt.id)){
core_vm.devalert(this,'loadsub 缺少id或者重复',opt.id)
return;
}
if(!opt.el)return;
if(!core_vm.isfn(opt.el.appendChild))return;
if(!opt.src ){
if(opt.path)opt.src=this.getapp().config.path.vm[opt.path];
else if(opt.tagname)opt.src=opt.tagname;
}
if(!opt.src){
}
var cvm=core_vm.define.define({pvm:this,el:opt.el,id:opt.id,src:opt.src});
if(ifpnode==1){
if(pnode && pnode.tag){
core_vm.inject.cal_inject_node(cvm,pnode);
cvm[core_vm.aprand].pvmevent=pnode.vmevent||{};
cvm[core_vm.aprand].pvmelevent=pnode.event||{};
cvm[core_vm.aprand].pvmnode=pnode;
if(pnode.attr.autostart!=false){
cvm._is_fresh_ing=this._is_fresh_ing;
core_vm.load(cvm);
}
}
}else if(opt){
var children=(cvm[core_vm.aprand].pvmnode)?cvm[core_vm.aprand].pvmnode.childNodes:[];
if(core_vm.isobj(opt.event)){
cvm[core_vm.aprand].pvmevent=opt.event
}
if(core_vm.isobj(opt.data)){
core_vm.tool.deepmerge(cvm[core_vm.aprand].append_data,opt.data);
for(var k in opt.data){
if(cvm[core_vm.aprand].datafrom_parent.indexOf(k)===-1){
cvm[core_vm.aprand].datafrom_parent.push(k);
}
}
for(var i=children.length-1;i>-1;i--){
if(children[i].tag=='data')children.splice(i,1)
}
}
if(core_vm.isobj(opt.option)){
core_vm.tool.deepmerge(cvm[core_vm.aprand].append_option,opt.option);
for(var i =children.length-1;i>-1;i--){
if(children[i].tag=='option')children.splice(i,1)
}
}
return cvm;
}
}
}<file_sep>var core_vm=require('./vm.0webcore.js');
module.exports.setproto=function(proto){
proto.__confirm_set_data_to_el=function(vm,p,v,oldv){
if(oldv==undefined) oldv=vm.__getData(p);
if(oldv===v)return;
vm.__setData(p,v);
var ps=p.split('.');
var len=ps.length;
if(ps[len-1]==parseInt(ps[len-1])){
var strp=p.substr(0,p.lastIndexOf('.'));
}
var __watching_data=vm[core_vm.aprand].watching_data[p]||vm[core_vm.aprand].watching_data['this.data.'+p];
if(Array.isArray(__watching_data)){
var ifcheck=false;
__watching_data.forEach(function(opt,w_sn){
if(opt.listid){
var ps=p.split('.');
var listpath='';
for(var i=0;i<len;i++){
if(i==0)listpath=ps[0];else listpath+='.'+ps[i];
if(Array.isArray(vm[core_vm.aprand].watching_list[listpath])){
break;
}
}
if(listpath==''){
return;
}
var array=vm.__getData(listpath);
if(!Array.isArray(array)){
return;
}
var index,sid,path;
for(var i=0;i<len;i++){
if(parseInt(ps[i])==ps[i]){
index=parseInt(ps[i]);
break;
}
}
if(index>-1){
ps.splice(0,i+1);
path=ps.join('.');
}
opt.el=vm.getel('@'+opt.listid);
if(opt.el){
opt.el=opt.el[index];
core_vm.watchcb.watch(opt,p,oldv,v);
}
}else{
core_vm.watchcb.watch(opt,p,oldv,v);
}
})
}
}
proto.__confirm_add_data_to_el=function(vm,p,index,v,cb){
var array=vm.__getData(p);
if(!Array.isArray(array))return cb(false);
index=parseInt(index);
if(index==-1)index=array.length;
array.splice(index,0,v);
var _listing=vm[core_vm.aprand].watching_list[p]||vm[core_vm.aprand].watching_list['this.data.'+p];
if(Array.isArray(_listing)){
_listing.forEach(function(opt){
core_vm.list.$add.call(array,opt,index,v);
})
}
cb(true)
}
proto.__confirm_del_data_to_el=function(vm,p,index,count,cb){
var array=vm.__getData(p);
if(!Array.isArray(array))return cb(false);
index=parseInt(index);
if(index==-1)index=array.length;
array.splice(index,count);
var _listing=vm[core_vm.aprand].watching_list[p]||vm[core_vm.aprand].watching_list['this.data.'+p];
if(Array.isArray(_listing)){
_listing.forEach(function(opt){
core_vm.list.$delat.call(array,opt,index);
})
}
cb(true);
}
}<file_sep>
var core_vm=require('./vm.0webcore.js');
var tapp;
var trim=function(str){
return str.replace(/^\s*|\s*$/g, '');
}
var all_isnot_seen=function (str){
for( var i=0,len=str.length; i<len; i++){
if(str.charCodeAt(i)>32) return false;
}
return true;
}
function issimple(str){
return (str.indexOf(':')>-1 || str.indexOf('|')>-1 || str.indexOf('?')>-1 || str.indexOf('(')>-1 || str.indexOf(')')>-1)?false:true;
}
function index_of(str,needle){
var r = str.match(new RegExp(needle, 'i' ));
return r==null?-1:r.index;
}
function stripquote(val) {
return val.replace(/^['"`]|['"`]$/g, '');
}
var reg_close =/^<\s*\/\s*([\w-_]+)\s*>/;
var reg_start=/^<\s*([\w]{1,})\s*/;
var reg_self_close=/^\s*\/\s*>/;
function add_watch(node,name,method){
node.watchs=node.watchs||[];
name=name.split('-watch-');
for(var i=0,len=name.length;i<len;i++)node.watchs.push([name[i].replace(/\-/g,'.'),method])
}
var DATA=0,OPTIONS=1,STATE=2;
var gsn=0;
var parse=function (xml,html_gsn,psn) {
xml = trim(xml);
xml = xml.replace(/\<\!--[\s\S]*?--\>/g, '');
xml="<_root_>"+xml+"</_root_>";
gsn=html_gsn || 0;
psn=psn||0;
var nodescache=[];
return gendoc();
function gendoc() {
return {
_root_: gentag(null,psn),
nodescache:nodescache,
}
}
function gentag(parentNode,psn) {
var m = nodematch(reg_start,'start');
if (!m){
return;
}
var node = {
sn:gsn++,
psn: (psn!=undefined?psn:(parentNode ? parentNode.sn:0)),
id:'',
tag:m[1],
utag:m[1].toLowerCase(),
attr:{},
dir:{},
childNodes:[],
parentNode:parentNode,
};
nodescache[node.sn]=node;
parse_attr(node);
if(node.attr && node.attr.class){
node.classList=node.attr.class.split(' ');
delete node.attr.class;
}else if(node.attrexp && node.attrexp.class){
node.classList=node.attrexp.class.split(' ');
delete node.attrexp.class;
}else{
node.classList=[];
}
if (nodematch(reg_self_close,'selfclose')) {
return node;
}
var index=xml.indexOf('>');
xml = xml.slice(index+1);
var nowtagLower=node.tag.toLowerCase();
if(nowtagLower=='br' || nowtagLower=='hr')return node;
child_or_content(node);
while(!nodematch(reg_close,'close',node.tag,node)){
if(xml)child_or_content(node);
else break;
}
return node;
}
function parse_attr(node){
var find_attr1=0,find_attr2=0;
while (!(eos() || is('>') || is('?>') || is('/>') )) {
find_attr1=1;
find_attr2=1;
var attr = attribute();
if(attr){
if(node.tag=='data'||(node.tag=='option' && node.parentNode.tag!=='select')){
node.attr[attr.name] = attr.value;
}else if(attr.name=='id') {
node.id=attr.value;
}
else if(attr.name=='el-filter'||attr.name=='el-hook'||attr.name=='el-list'){
node.dir[attr.name.substr(3)]=attr.value;
}else if(attr.name.substr(0,6)=='watch-'){
attr.name=attr.name.substr(6);
if(attr.name[0]=='[' && attr.name[attr.name.length-1]==']')attr.name=attr.name.substr(1,attr.name.length-2);
add_watch(node,attr.name,attr.value);
}else if(attr.name.substr(0,3)=='on-'){
node.event=node.event||{};
node.event[attr.name.substr(3)]=attr.value;
}else if(attr.name.substr(0,6)=='event-'){
node.vmevent=node.vmevent||{};
node.vmevent[attr.name.substr(6)]=attr.value;
}else{
var tmp = attr.value.match(/{([\S\s]*?)}/);
if(tmp==null){
node.attr[attr.name] = attr.value;
if(attr.value.toLowerCase()==='true')node.attr[attr.name]=true;
else if(attr.value.toLowerCase()==='false'){
node.attr[attr.name]=false;
}
}else{
node.attrexp=node.attrexp||{};
var last_indexOf_kuohao=attr.value.lastIndexOf('{');
if(last_indexOf_kuohao==0 && tmp.index==0 && tmp[0]==attr.value && issimple(tmp[1])){
var path=trim(tmp[1]);
var if_data_to_el=0,if_el_to_data=0;
if(path[0]=='!'){if_data_to_el=1;path=path.substr(1);}
if(path[path.length-1]=='!'){if_el_to_data=1;path=path.substr(0,path.length-1);}
var datatype=DATA;
if(path.indexOf('this.option.')==0){
datatype=OPTIONS;
if_data_to_el=1;
if_el_to_data=0;
}else if(path.indexOf('this.state.')==0){
datatype=STATE;
}
node.attrexp[attr.name]="{"+path+"}";
if(if_data_to_el){
add_watch(node,path,'toel-'+attr.name);
}
if(if_el_to_data){
node.event=node.event||{};
if(datatype==STATE)node.event['change']="tostate-"+path.replace('this.state.','');
else if(datatype==DATA)node.event['change']="todata-"+path;
}
}else{
node.attrexp[attr.name]=attr.value;
add_multi_watch(node,attr.value,'toel-'+attr.name);
}
}
}
}else{
find_attr1=0;
attr = attribute2();
if(attr){
if(!all_isnot_seen(attr.name)){
attr.name=attr.name.replace(/\W/g, '');
if(attr.name){
node.attr[attr.name]=true;
}
}
}else{
find_attr2=0;
}
}
if(find_attr1+find_attr2==0){
xml = xml.slice(xml.indexOf('>'));
}
}
}
function child_or_content(node){
var child,tcontent;
var find_child=0,find_content=0;
while (1) {
find_child=1;
find_content=1;
child = gentag(node);
if(child){
node.childNodes.push(child);
}else{
find_child=0;
}
tcontent = parse_content();
if(tcontent){
add_content_node(node,tcontent);
}else{
find_content=0;
}
if(find_child+find_content==0)break;
}
}
function new_node(type,pnode){
var node={tag:type,utag:type,
childNodes:[],dir:{},attr:{},psn:pnode.sn,sn:gsn++,parentNode:pnode};
nodescache[node.sn]=node;
pnode.childNodes.push(node);
return node;
}
function ifhave_operator (str) {
if(str.indexOf('|')>-1 ||(str.indexOf('?')>-1 && str.indexOf(':')>-1)
||(str.indexOf('(')>-1 && str.indexOf(')')>-1) ||str.indexOf('&&')>-1)return true;
}
function add_multi_watch(node,str,where) {
if(where!='toel-text' && ifhave_operator(str)){
return;
}
var needwatch=[];
str.replace(/([\S\s]*?)\{([\S\s]*?)\}/g,function(a,b,c,d,e,f,g){
c=trim(c);
if(!c)return;
if(c.indexOf('this.option.')==0){
if(c[0]!='!')c='!'+c;
}
if(c[c.length-1]=='!')c=c.substr(0,c.length-1);
if(c[0]==='!' && needwatch.indexOf(c)===-1){
needwatch.push(c.substr(1));
}
});
for(var i=0,len=needwatch.length;i<len;i++){
add_watch(node,needwatch[i],where);
}
}
function add_content_node(node,tcontent){
if(all_isnot_seen(tcontent))return;
if(tcontent.indexOf('\\u')>-1)tcontent=tcontent.replace(/\\u[a-fA-F0-9]{4}/g,function(a,b,c){return unescape(a.replace(/\\u/,'%u'))});
if(tcontent.indexOf('\\U')>-1)tcontent=tcontent.replace(/\\U[a-fA-F0-9]{4}/g,function(a,b,c){return unescape(a.replace(/\\U/,'%u'))});
var tag=node.tag.toLowerCase();
if(tapp.config.precode.indexOf(tag)>-1){
node.attr=node.attr||{};
node.attr.text=core_vm.tool.htmlunescape(tcontent);
return;
}
var tmp = tcontent.match(/{([\S\s]*?)}/g);
if(tmp==null){
if(tag=='text'){
node.text=tcontent;
}else{
var textnode=new_node('_text_',node);
textnode.text=tcontent;
}
return;
}else{
if(ifhave_operator(tcontent)){
var textnode=new_node('_exptext_',node);
textnode.text='';
textnode.exp_text=tcontent;
add_multi_watch(textnode,tcontent,'toel-text');
return;
}
tcontent.replace(/([\S\s]*?)\{([\S\s]*?)\}/g,function(a,b,c,d,e,f,g){
if(trim(b)){
var textnode=new_node('_text_',node);
textnode.text=trim(b);
}
c=trim(c);
if(c){
if(c[c.length-1]=='!')c=c.substr(0,c.length-1);
var textnode=new_node('_exptext_',node);
textnode.text='';
textnode.exp_text='{'+c+'}';
if(c.indexOf('this.option.')==0){
if(c[0]!='!')c='!'+c;
}
if(c[0]==='!'){
add_watch(textnode,c.substr(1),'toel-text');
}
}
});
var index=tcontent.lastIndexOf('}');
if(index!=tcontent.length-2){
var shengyu=tcontent.substr(index+2);
if(trim(shengyu)){
var textnode=new_node('_text_',node);
textnode.text=trim(shengyu);
}
}
}
}
function parse_content() {
var m = nodematch(/^([^<]*)/,'content');
return m?m[1]:'';
}
function attribute2(){
var m = nodematch(/^\s*([_-\w]+)\s*/ ,'attrstate');
if(m) return { name: m[1], value: (m[1]) }
}
function attribute() {
var m = nodematch(/([_-\w]+)\s*=\s*(\`[^`]*\`|"[^"]*"|'[^']*'|[ ]|[^<>\/\s]*)\s*/ ,'attr');
if(m){
return { name: trim(m[1]), value: trim(stripquote(m[2])) }
}
}
function nodematch(re,where,tag,node) {
var m = xml.match(re);
if(where=='attr' ){
if(m && ( m['index']>0 && !all_isnot_seen(m['input'].substr(0,m['index'])))){
return;
}
}else if(where=='close'){
if(m){
xml = xml.substr(m.index+m[0].length);
if(m[1]==tag || m[1].toLowerCase()==tag.toLowerCase()){
return true;
}else{
return tapp.config.strategy.force_close_not_match_close_tag?true: false;
}
}else{
xml = xml.slice(xml.indexOf('>')+1);
return tapp.config.strategy.force_close_error_close_tag?true: false;
}
}
if (!m)return;
xml = xml.slice(m.index+m[0].length);
return m;
}
function eos() {
return 0 == xml.length;
}
function is(prefix) {
return 0 == xml.indexOf(prefix);
}
}
function declaration() {
var m = nodematch(/^<\?xml\s*/,'declaration');
if (!m) return;
var node = {
attr: {}
};
while (!(eos() || is('?>'))) {
var attr = attribute();
if (!attr) return node;
node.attr[attr.tag] = attr.value;
}
nodematch(/\?>\s*/,'declaration 2');
return node;
}
function removeDOCTYPE(html) {
return html
.replace(/<\?xml.*\?>\n/, '')
.replace(/<!doctype.*\>\n/, '')
.replace(/<!DOCTYPE.*\>\n/, '');
}
module.exports=function(html,maxsn,psn,app,where){
tapp=app;
html=html
.replace(/<\?xml.*\?>\n/, '')
.replace(/<!doctype.*\>\n/, '')
.replace(/<!DOCTYPE.*\>\n/, '')
.replace(new RegExp('<script[^]*>[\\s\\S]*?</script>','gi'),'')
.replace(new RegExp('<style[^]*>[\\s\\S]*?</style>','gi'),'')
.replace(/\/\s*>/g, "/>")
.replace(/\/\>/g, " />")
.replace(/\<\>/g, "");
var all=parse(html,maxsn,psn,app);
return [all._root_,all.nodescache];
}
<file_sep>var abcd=require('./abcd.js');
module.exports={
name:'this is in abc.js',
abcd:abcd,
}<file_sep>
var core_vm=require('./vm.0webcore.js');
core_vm.onerror=function(app,type,where,error){
var cb=app.onerror;
if(core_vm.isfn(cb)){
cb.apply(app,arguments);
}
}
core_vm.onload=function(app,url,xhr,opt){
var cb=app.onload;
if(core_vm.isfn(cb)){
var res;
try{
res=cb.call(app,url,xhr,opt);
}catch(e){
console.error('onload',e)
}
return res;
}
}
core_vm.elget=function(el,n){return el?el.getAttribute(n):''}
core_vm.elset=function(el,n,v){return el?el.setAttribute(n,v):false;}
core_vm.getprefn=function(vm,type,name){
var fn;
if(name.substr(0,4)=='app.'){
name=name.substr(4);
fn=vm.getapp()[name];
}else{
if(vm[type] && typeof vm[type]==='object')fn=vm[type][name];
if(!core_vm.isfn(fn))fn=vm[name];
if(!core_vm.isfn(fn))fn=vm[type+'_js_'+name];
}
return fn;
}
core_vm.devalert=function(app_vm,title,e,err){
var msg=e?(e.message ||e.error ||e.toString()):'';
if(err)msg+="\n"+(err.message ||err.error ||err.toString());
console.error({
title:'dev alert:'+title.toString(),
message:msg,
})
}
core_vm.tryvmfn=function(vm,cvm,when){
if(!vm)return;
if(core_vm.isfn(vm[when])){
try{
vm[when].call(vm,cvm);
}catch(e){
core_vm.devalert(vm,'vm.'+when+':'+vm.id,e)
}
}else if(core_vm.isfn(vm.hook)){
try{
vm.hook.call(vm,when,cvm);
}catch(e){
core_vm.devalert(vm,'vm.hook.'+when+':'+vm.id,e)
}
}
}
core_vm.tryfn=function(_this,fn,args,message){
if(!core_vm.isfn(fn))return;
if(!Array.isArray(args))args=[args];
return fn.apply(_this,args);
var res;
res=fn.apply(_this,args);
return res;
}
const multilineComment = /^[\t\s]*\/\*\*?[^!][\s\S]*?\*\/[\r\n]/gm
const specialComments = /^[\t\s]*\/\*!\*?[^!][\s\S]*?\*\/[\r\n]/gm
const singleLineComment = /^[\t\s]*(\/\/)[^\n\r]*[\n\r]/gm
core_vm.delrem=function(str){
str=str+'';
return str
.replace(multilineComment, '')
.replace(specialComments, '')
.replace(/\/\*([\S\s]*?)\*\//g, '')
.replace(/\<\!\-\-[\s\S]*?\-\-\>/g, '')
.replace(singleLineComment, '\n')
.replace(/\;\s*\/\/.*(?:\r|\n|$)/g, ';\n')
.replace(/\,\s*\/\/.*(?:\r|\n|$)/g, ',\n')
.replace(/\{\s*\/\/.*(?:\r|\n|$)/g, '{\n')
.replace(/\)\s*\/\/.*(?:\r|\n|$)/g, ')\n')
}
core_vm.isfn=function(cb){ return typeof(cb)==='function'}
core_vm.isobj=function(obj){return typeof (obj)==='object'}
core_vm.isstr=function(obj){return typeof (obj)==='string'}
<file_sep>var core_vm=require('./vm.0webcore.js');
var cacheclass=function(appid){
this.appid=appid;
this.urlsid_seed=10;
this.urlsid={};
this.vmsbysid={};
this.vmparent={};
this.import_src_vm={};
this.import_src_block={};
this.import_src_lib={};
this.importblock={};
this.importstyle={};
this.vmbody={};
this.vmstyle={};
this.vmlib={};
this.jslib={};
this.use={
filter:{},method:{},operator:{},
domevent:{},dataevent:{},
block:{},
elhook:{},
};
}
var proto=cacheclass.prototype;
proto.destroy=function(){
for(var k in this)this[k]=null;
}
require("./vm.0cache.jslib.js").setproto(proto);
require("./vm.0cache.vm.js").setproto(proto);
require("./vm.0cache.import.js").setproto(proto);
require("./vm.0cache.clean.js").setproto(proto);
require("./vm.0cache.blockstyle.js").setproto(proto);
proto.getapp=function(){
return core_vm.wap;
}
proto.geturlsid=function(url){
if(!this.urlsid[url])this.urlsid[url]=this.urlsid_seed++;
return this.urlsid[url];
}
proto.add_ref=function(type,url,refsid,where){
var mod;
if(type=='lib'||type=='json')mod=this.jslib;
if(type=='vm') mod=this.vmlib;
if(type=='style')mod=this.importstyle;
if(type=='block')mod=this.importblock;
if(!mod){
return false;
}
mod=mod[url];
if(!mod)return false;
if(!mod.refsids)mod.refsids=[];
if(mod.refsids.indexOf(refsid)===-1){
mod.refsids.push(refsid);
}
return true;
}
proto.check_ifhas=function(type,id,refsid){
return this.add_ref(type,id,refsid,'check');
}
module.exports=cacheclass;<file_sep>var core_vm=require('./vm.0webcore.js');
module.exports.setproto=function(proto){
proto.cleanList=function(p){
if(Array.isArray(this[core_vm.aprand].watching_list[p])){
var listdata=this.__getData(p);
this[core_vm.aprand].watching_list[p].forEach(function(l_opt){
core_vm.list.$clean.call(listdata,l_opt);
});
}
}
proto.rebuildList=function(p){
if(Array.isArray(this[core_vm.aprand].watching_list[p])){
var listdata=this.__getData(p);
this[core_vm.aprand].watching_list[p].forEach(function(l_opt){
core_vm.list.$rebuild.call(listdata,l_opt);
});
}
}
proto.__blankfn=function(){}
proto.__getrandobj=function(){return this[core_vm.aprand]}
proto.__reset_list_index=function(wopt){
if(wopt.$index!==undefined && wopt.scope && wopt.scope.$index!==undefined) wopt.scope.$index= wopt.$index;
}
proto.getClassName=function(name){
return core_vm.web_private_style.get(this,name);
}
proto.hasSlot=function(name){
return this[core_vm.aprand].pvmslot[name]?true:false;
}
proto.__ensure_fn=function(){
}
}<file_sep>var core_vm=require('./vm.0webcore.js');
var global_rootvm={},index_vm={}
var check_body_when_not_file_indexvm=function(){
core_vm.wap.indexvm[core_vm.aprand].has_started=1;
var s=Object.keys(core_vm.wap.config.path.vm);
s.push(core_vm.wap.config.vmtag);
var el_src=document.body.querySelectorAll(s.join(',')) ;
var elsall=[];
[].forEach.call(el_src,function(el){ elsall.push(el)});
[].forEach.call(elsall,function(el){
if(el.hasAttribute('autostart') && el.getAttribute('autostart')==false)return;
var json={};
json.src=core_vm.wap.config.path.vm[el.localName]||el.getAttribute('src') || '';
json.id=el.getAttribute('id') || '';
var nodes=[];
el.childNodes.forEach(function(node){
el.removeChild(node);
});
var vm=core_vm.define.define({pvm:core_vm.wap.indexvm,el:el,id:json.id,src:json.src});
core_vm.load(vm,function(vm){
})
});
}
var start_system=function(){
var file_app,file_indexvm;
var scripts= document.getElementsByTagName('script');
for (var i = scripts.length - 1; i > -1; i -= 1) {
if(scripts[i].dataset['role']==='vmix'){
if(scripts[i].hasAttribute('app-file') || scripts[i].hasAttribute('index-file') ) {
file_indexvm=scripts[i].getAttribute('index-file');
file_app=scripts[i].getAttribute('app-file');
break;
}
}
}
module.exports.root=global_rootvm;
index_vm=core_vm.define.define({id:'__index__',pvm:null});
index_vm.__define({});
index_vm[core_vm.aprand].pvmevent={};
index_vm.pel=document.body;
module.exports.index=index_vm;
core_vm.wap.indexvm=index_vm;
index_vm.absrc=window.location.pathname;
var dirpath=window.location.pathname;
dirpath=dirpath.substr(0,dirpath.lastIndexOf('/'));
window.location.dirpath=dirpath;
var u = window.location.protocol + '//' + window.location.hostname;
if (window.location.port && window.location.port !== 80) {
u += ':' + window.location.port;
}
window.location.fullhost=u;
core_vm.rootvmstart.init();
core_vm.rootvmstart.start_system(core_vm.wap,file_app,file_indexvm,index_vm,function(){
if(!file_indexvm){
check_body_when_not_file_indexvm();
}
});
}
module.exports.start_system=start_system;
<file_sep>var core_vm=require('./vm.0webcore.js');
var check_array_repeat=function(s,listid,index){
var len=s.length;
for(var i=len-1;i>-1;i--){
if(s[i].listid && s[i].listid ==listid && s[i].$index==index){
s.splice(i,1);
}
}
}
var calnode_watch=function(vm,node,scope,where){
if(!node.watchs )return;
var watchs=node.watchs;
for (var j = 0,len=watchs.length; j<len; j++){
var dataname=watchs[j][0];
var elattr=watchs[j][1];
if(elattr.indexOf('js:')!==0 && elattr[0]=='{')elattr=core_vm.calexp.exp(vm,elattr,scope);
node.id=node.id||core_vm.cal.forece_calnodeid(vm,node,scope,'watch');
var wopt={
vm:vm,
node:node,
elid:node['id'],
scope:scope,
action:'prop',
$index:scope.$index
};
if(node.listid)wopt.listid=node.listid;
var func,para,toelattr
if(elattr.indexOf('js:')==0){
vm[core_vm.aprand].inline_watchjs.push(elattr.substr(3));
wopt.watchfunc='inlinejs_watch__'+(vm[core_vm.aprand].inline_watchjs.length-1);
wopt.watchpara=null;
}else if(elattr.indexOf('-toel-')>0){
var array=elattr.split('-toel-');
wopt.toelattr=array[1];
var tmp=core_vm.tool.parse_func_para(array[0]);
wopt.watchfunc= tmp[0];
wopt.watchpara= tmp[1];
}else if(elattr.substr(0,5)=='toel-'){
wopt.toelattr=elattr.substr(5);
}else{
var tmp=core_vm.tool.parse_func_para(elattr);
wopt.watchfunc= tmp[0];
wopt.watchpara= tmp[1];
}
var watch_path=core_vm.cal.now_path(scope,dataname,vm,'watch_path');
var key=watch_path.substr(watch_path.lastIndexOf('.')+1);
if(watch_path[0]=='[' && watch_path[watch_path.length-1]==']')watch_path=watch_path.substr(1,watch_path.length-2);
watch_path=watch_path.replace(/\[/g,'.').replace(/\]/g,'');
if(watch_path[0]=='.')watch_path=watch_path.substr(1);
if(where=='noel'){
wopt.elid=-2;
}
if(watch_path.indexOf('.-1')>-1){
alert("watch_path.indexOf('.-1')>-1");
continue;
}
var watch_obj=vm.data;
var if_is_state='data';
if(watch_path.indexOf('this.data.')==0){
watch_path=watch_path.substr(10);
watch_obj=vm.data||{};
if_is_state='data';
}else if(watch_path.indexOf('this.state.')==0){
watch_path=watch_path.substr(11);
watch_obj=vm.state||{};
if_is_state='state';
}else if(watch_path.indexOf('this.option.')==0){
watch_path=watch_path.substr(12);
watch_obj=vm.option||{};
if_is_state='option';
}
var value=core_vm.tool.objGetDeep(watch_obj,watch_path);
if(!wopt.watchfunc){
}else if(wopt.watchfunc){
if(wopt.node.tag!=='_exptext_'){
vm.__addto_onshow(function(){
core_vm.watchcb.watch(wopt,watch_path,'',value);
});
}
}
var watching=vm[core_vm.aprand]['watching_'+if_is_state];
if(watching){
watching[watch_path]=watching[watch_path]||[];
if(scope.$index!==undefined)check_array_repeat(watching[watch_path],wopt.listid,wopt.$index)
watching[watch_path].push(wopt);
}
}
}
exports=module.exports={
cal:calnode_watch,
}
<file_sep>var data={
version:'root.1',
name:'liyong1',
obj:{version:111,name:'root_liyong',age:123},
}
var vms={};
var datacenter={};
datacenter.get=function(vm,path,value,cb){
console.log("datacenter.get",'vmid='+vm.id,'path='+path);
return {vmid:vm.id,path:path}
};
datacenter.delete=function(vm,path,value,cb){
console.log("datacenter.delete",'vmid='+vm.id,path);
cb('datacenter.delete.ok')
};
datacenter.put=function(vm,path,value,cb){
console.log("datacenter.put",'vmid='+vm.id,path,value);
if(path=='name'){
console.log("修改.name",path,value,'原来='+data.name);
data.name=value;
if(vms['datarelevant'])vms['datarelevant'].ondatachange.call(vms['datarelevant'],path,value)
if(vms['datarel2'])vms['datarel2'].ondatachange.call(vms['datarel2'],path,value)
}else{
vm.objSetDeep(vm.data,path,value);
}
if(cb)cb('datacenter.put.ok')
};
datacenter.post=function(vm,path,value,cb){
console.log("datacenter.post",'vmid='+vm.id,path,value);
cb('datacenter.post.ok')
};
datacenter.start=function(vm,path,value,cb){
var obj={
version:data.version,
name:data.name,
obj:data.obj,
books:[{name:1},{name:2},{name:3}]
};
if(vm.id=='datarelevant'){
vms['datarelevant']=vm;
return obj;
}else if(vm.id=='datarel2'){
vms['datarel2']=vm;
return obj;
}if(vm.id=='hassub'){
return obj;
}else if(vm.id=='datacenter3'){//sample return bubble
return obj
}else if(vm.id=='datacenter'){
setTimeout(function(){
cb(obj);
},100);
return 'wait';
}
}
module.exports=function(type,vm,path,value,cb){
if (!datacenter[type])return null;
//console.log("datacenter,type="+type,'vm.id='+vm.id,path);
return datacenter[type](vm,path,value,cb)
}<file_sep>
<html>
<h4>multi node filter</h4>
<h4>this is calculate before htmltojson</h4>
<br/>
<div>
{% if {inta} > 99 %}<button>big than 99</button>
{% elseif {check()} %}<button>big than 90</button>
{% elseif {check2(10)}>101 %}<button>big than 70</button><button>big than 70</button>
{% elseif {inta} >=60 %}<button>big than 60</button>
{% elseif {inta} <60 %}<button>small than 60</button>
{% else %}<button>else </button>
{% endif %}
</div>
<pre>
{ % if {inta} > 99 %}<button>big than 99</button>
{ % elseif {check()} %}<button>big than 90</button>
{ % elseif {check2(10)}>101 %}<button>big than 70</button><button>big than 70</button>
{ % elseif {inta} >=60 %}<button>big than 60</button>
{ % elseif {inta} <60 %}<button>small than 60</button>
{ % else %}<button>else </button>
{ % endif %}
</pre>
<pre>
support "==" ">=" "<=" "<" ">"
this filter happens before htmltojson
</pre>
<h4>element filter sample</h4>
<h4>this is calculate after htmltojson</h4>
<button el-filter="if:{aaa}">if_a 1</button>
<button el-filter="elseif:{bbb}">if_b</button>
<button el-filter="elseif:{if_c({fff},1,2,3)}">if_c</button>
<button el-filter="else">if_d</button>
<button >no if will end this loop</button>
<button el-filter="if:{if_a(2)}">if_a 2</button>
<button el-filter="elseif:{if_b()}">if_b</button>
<button el-filter="elseif:{if_c()}">if_c</button>
<button el-filter="else">if_d</button>
<h4>source</h4>
<pre>
<button el-filter="if:{aaa}">if_a 1</button>
<button el-filter="elseif:{bbb}">if_b</button>
<button el-filter="elseif:{if_c({fff},1,2,3)}">if_c</button>
<button el-filter="else">if_d</button>
<button >no if will end this loop</button>
<button el-filter="if:{if_a(2)}">if_a 2</button>
<button el-filter="elseif:{if_b()}">if_b</button>
<button el-filter="elseif:{if_c()}">if_c</button>
<button el-filter="else">if_d</button>
</pre>
<h4>Explanation</h4>
<pre>
all children in same parent,you can use multi if-elseif-else.
not same as "show" or "display",if the computed result!==true,will not generate the element.
el-filter="{aaa}" ......... without (),will search under vm.data["aaa"],if undefined,then call vm.method["aaa"]()
el-filter="{if_a()}" ...... will call vm.method["if_a"]()
el-filter="{if_a(2)}" ..... not in a list,will call vm.method["if_a"](2)
el-filter="{if_a(2)}" ..... in a list,will call vm.method["if_a"](value,index,2)
if the target method not found,the result will be false.
</pre>
</html>
<script>
var mod={};
mod.data={
inta:51,
aaa:false,
bbb:true,
fff:true
}
mod.method={
check:function(){
console.error('check')
return false;
},
check2:function(a){
console.error('check2')
return parseInt(a)+100;
},
if_a:function(a ){ return (a==1) },
if_b:function(a,b,c){ return false; },
if_c:function(a,b,c){ return true; },
}
module.exports=mod;
</script><file_sep>
var core_vm=require('./vm.0webcore.js');
module.exports.setproto=function(proto){
proto.loadfilefresh_clear=function(id){
if(this.vmlib[id]){
delete this.vmlib[id];
delete this.vmbody[id];
delete this.vmstyle[id];
}
if(this.jslib[id]){
delete this.jslib[id];
}
}
proto.removesid=function(sid){
delete this.vmsbysid[sid];
delete this.vmparent[sid];
for(var csid in this.vmparent){
if(this.vmparent[csid]==sid){
delete this.vmparent[csid];
this.removesid(csid);
}
}
}
proto.keep=function(type,id){
if(type=='vm' && this.vmlib[id])this.vmlib[id].inpath=1;
if(type=='lib' && this.jslib[id])this.jslib[id].inpath=1;
}
proto.delete=function(mod,id){
if(mod && mod[id] &&mod[id].refsids.length==0 &&!mod[id].inpath)delete mod[id];
}
proto.clean_when_vm_clean=function(vm){
this.removesid(vm.sid);
var absrc=vm.absrc;
var absrcid=vm[core_vm.aprand].absrcid;
if(!this.vmlib[absrc]||this.vmlib[absrc].inpath==1){
return;
}
var sameurl=0;
for(var i in this.vmsbysid){
if(this.vmsbysid[i][core_vm.aprand].has_started==0)continue;
if(this.vmsbysid[i][core_vm.aprand].absrcid===vm[core_vm.aprand].absrcid)sameurl++;
}
if(sameurl>0){
return;
}
delete this.vmbody[absrc];
delete this.vmstyle[absrc];
delete this.vmlib[absrc];
this.clean_import(absrcid);
for(var k in this.vmlib){
var mod=this.vmlib[k];
if(mod && Array.isArray(mod.refsids)){
var index=mod.refsids.indexOf(absrcid);
if(index>-1){
mod.refsids.splice(index,1);
this.delete(this.vmlib,k);
}
}
}
for(var k in this.jslib){
var mod=this.jslib[k];
if(mod && Array.isArray(mod.refsids)){
var index=mod.refsids.indexOf(absrcid);
if(index>-1){
mod.refsids.splice(index,1);
this.delete(this.jslib,k);
}
}
}
}
}<file_sep>var core_vm=require('./vm.0webcore.js');
module.exports.setproto=function(proto){
proto.__addto_onstart=function(cb){
if(this[core_vm.aprand].has_started!==1){
this[core_vm.aprand].cbs_onstart.push(cb);
}else{
core_vm.tryfn(this,cb,[this],'vm.onstart')
}
}
proto.__addto_onshow=function(cb){
if(this[core_vm.aprand].has_started!==1){
this[core_vm.aprand].cbs_onshow.push(cb);
}else{
core_vm.tryfn(this,cb,[this],'vm.onshow.addto')
}
}
proto.__onshow=function(){
for(var k in this[core_vm.aprand].cbs_onshow){
core_vm.tryfn(this,this[core_vm.aprand].cbs_onshow[k],[this],'vm.onshow.exe')
}
this[core_vm.aprand].cbs_onshow=[];
for(var k in this[core_vm.aprand].cbs_onstart){
this[core_vm.aprand].cbs_onstart[k].call(this);
}
this[core_vm.aprand].cbs_onstart=[];
if(core_vm.isfn(this[core_vm.aprand].startcb_of_vmstart)){
core_vm.tryfn(this,this[core_vm.aprand].startcb_of_vmstart,[],'vm.start.cb,id='+this.id);
}else{
}
this.__clean_tmp_after_start();
}
var check_slot=function(vm,nodes){
for(var sn=0,len=nodes.length;sn<len;sn++){
if(nodes[sn].tag=='slot' && (!nodes[sn].attr || !nodes[sn].attr.name) ){
core_vm.inject.use_inject_nodes_when_create(vm,nodes[sn]);
}else{
check_slot(vm,nodes[sn].childNodes);
}
}
}
proto.__vmstart=function(startcb){
if(this[core_vm.aprand].has_started==1){
return;
}
var vm=this;
if(core_vm.isfn(startcb))vm[core_vm.aprand].startcb_of_vmstart=startcb;
if(core_vm.isfn(this.hookStart) && !this.__hookStart_has_called){
vm.getapp().hookstart_ing_vm=vm;
try{
this.hookStart.call(this,function(result){
vm.getapp().hookstart_ing_vm=null;
vm.__hookStart_has_called=1;
if(result!==false){
vm.__vmstart(startcb);
}else{
if(vm[core_vm.aprand].startcb_of_vmstart)vm[core_vm.aprand].startcb_of_vmstart(false);
vm.__init(true);
}
});
}catch(e){
core_vm.devalert(vm.getnap(),'hookStart error',vm.src,e)
vm.getapp().hookstart_ing_vm=null;
this.hookStart=null;
vm.__vmstart(startcb);
}
return;
}
core_vm.tryvmfn(vm.pvm,vm,'beforechildstart');
core_vm.tryvmfn(vm,null,'beforestart');
var bodytext=vm.getcache().get_body(vm);
if(core_vm.isfn(vm.hookTemplate)){
core_vm.cal.nodejson(vm,vm.hookTemplate(bodytext));
}else{
core_vm.cal.nodejson(vm,bodytext);
}
check_slot(vm,vm[core_vm.aprand].nodejson[0].childNodes);
var styletext=vm.getcache().get_vmstyle(vm);
if(styletext){
if(core_vm.isfn(vm.hookStyle)){
styletext=vm.hookStyle(styletext);
}
core_vm.web_private_style.add(vm,styletext);
}
core_vm.start.web(vm);
vm[core_vm.aprand].has_started_self=1;
if(vm.getapp().config.strategy.append_to_pel_wait_loading_child_vm==false){
vm.__append_bin_el();
}
if(vm[core_vm.aprand].loadingsub_count==0){
vm.__onstart_a_zero_sub()
}
}
proto.__onstart_a_zero_sub=function(){
var vm=this;
if(this.__top_fragment && this[core_vm.aprand].has_started_self==1
&& vm.getapp().config.strategy.append_to_pel_wait_loading_child_vm==true){
vm.__append_bin_el();
}
if(vm.pvm){
setTimeout(function(){
vm.pvm[core_vm.aprand].loadingsub_count--;
if(vm.pvm[core_vm.aprand].loadingsub_count==0){
vm.pvm.__onstart_a_zero_sub();
}
},0);
}else{
setTimeout(function(){
if(vm.getapp().hasstart==0){
vm.getapp().hasstart=1;
console.log('执行app.onstart1')
vm.getapp().onstart();
}
},10);
}
}
proto.__after_append_real=function(){
var vm=this;
vm[core_vm.aprand].has_started=1;
delete vm._is_fresh_ing;
vm.__onshow.call(vm);
core_vm.tryvmfn(vm,vm,'onstart');
core_vm.tryvmfn(vm.pvm,vm,'onchildstart');
}
proto.__after_append=function(){
var vm=this;
if(vm.getapp().config.strategy.append_to_pel_wait_loading_child_vm==true){
if(this.pvm){
this.pvm.__addto_onshow(function(){
vm.__after_append_real();
})
}else{
this.__after_append_real()
}
}else{
this.__after_append_real()
}
}
proto.__append_bin_el=function(){
var vm=this;
var fragment=vm.__top_fragment;
if(!fragment)return ;
var children=fragment.childNodes||[];
var len=children.length;
for(i=0;i<len;i++)vm[core_vm.aprand].els.push(children[i]);
var vmpel=vm.pel;
var i=0;
var __appento_ppel=false;
if(vm[core_vm.aprand].nodejson[0].childNodes.length==1 && len==1 &&
((core_vm.elget(vmpel,'appendto')=='ppel')||'ppel'==vm.config.appendto)){
vm.config.appendto='ppel';
core_vm.elset(vmpel,'_role_','placeholder');
var el=children[0];
var ppel=vmpel.parentNode;
ppel.appendChild(el);
vmpel.after(el);
ppel.removeChild(vmpel);
vm.__addto_onshow(function(){
vm.ppel=vm[core_vm.aprand].els[0].parentNode;
})
el.replaced_pel=vmpel;
var node=vm[core_vm.aprand].nodejson[0].childNodes[0];
node.event=node.event||{};
if(vm[core_vm.aprand].pvmelevent)for(var k in vm[core_vm.aprand].pvmelevent)node.event[k]=vm[core_vm.aprand].pvmelevent[k];
vm.__bind_as_top_view(node,el,'because.ppel');
__appento_ppel=true;
}else{
vmpel.appendChild(fragment);
}
delete vm.__top_fragment;
for(var k in vm[core_vm.aprand].pvmelevent){
vm[core_vm.aprand].domeventnames[k]=1;
}
if(!__appento_ppel){
vm.__bind_events();
}
setTimeout(function() {
vm.__after_append();
},0);
}
proto.restart=function(json,cb){
this.close();
if(core_vm.isfn(json)){
this.start(cb);
}else if(core_vm.isobj(json)){
if(json.src){
this.__setsrc(json.src);
}
this._is_fresh_ing=json.fresh===true ?true:false;
this.start(cb);
}else{
this.start(cb);
}
}
proto.start=function(cb){
if(!core_vm.isfn(cb))cb=function(){}
if(this[core_vm.aprand].has_defined){
this.__initdata_then_start(cb);
}else{
core_vm.load(this,cb);
}
}
proto.show=function(){
var els=this[core_vm.aprand].els;
for(var i=els.length-1;i>-1;i--){
els[i].style.display=core_vm.elget(els[i],'lastdisplay')||"";
}
}
proto.hide=function(){
var els=this[core_vm.aprand].els;
for(var i=els.length-1;i>-1;i--){
core_vm.elset(els[i],'lastdisplay',els[i].style.display||"");
els[i].style.display='none';
}
}
}<file_sep>
var readyList = [];
var readyFired = false;
var readyEventHandlersInstalled = false;
var ready=function () {
if (!readyFired) {
readyFired = true;
for (var i = 0; i < readyList.length; i++) {
readyList[i].fn.call(window, readyList[i].ctx);
}
readyList = [];
}
}
var readyStateChange=function () {
if ( document.readyState === "complete" ) {
ready();
}
}
module.exports.docReady = function(callback, context) {
if (readyFired) {
setTimeout(function() {callback(context);}, 1);
return;
} else {
readyList.push({fn: callback, ctx: context});
}
if (document.readyState === "complete" || (!document.attachEvent && document.readyState === "interactive")) {
setTimeout(ready, 1);
} else if (!readyEventHandlersInstalled) {
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", ready, false);
window.addEventListener("load", ready, false);
} else {
document.attachEvent("onreadystatechange", readyStateChange);
window.attachEvent("onload", ready);
}
readyEventHandlersInstalled = true;
}
}
//把web的 config文件 及其 配置系统 转到 mob<file_sep>var core_vm=require('./vm.0webcore.js');
var lopt_aid=0;
module.exports.gendata=function(vm,node,scope,pel){
var array=node.dir.list.split(' in ');
array[1]=core_vm.calexp.exp(vm,array[1],scope);
var abpath=core_vm.cal.now_path(scope,array[1],vm,'listgen');
abpath=abpath.replace(/^\s*|\s*$/g, '').replace(/\[([\s\S]*?)\]/g,function(a,b){
return "."+b+".";
}).replace(/^\.*|\.*$/g, '').replace(/\'|\"/g, '');
var listdata;
if(abpath.indexOf('this.')===0)listdata=core_vm.tool.objGetDeep(vm,abpath.substr(5));
else listdata=core_vm.tool.objGetDeep(vm.data,abpath);
return [array,abpath,listdata];
}
var g_classid=0;
var gen_watch_listclass=function(node){
if(node.watchs){
node.listid=++g_classid;
}
if(node.childNodes)node.childNodes.forEach(function(cnode){gen_watch_listclass(cnode)})
}
module.exports.gen=function(vm,node,scope,pel){
node.id='';
var tmp=module.exports.gendata(vm,node,scope,pel);
var array=tmp[0],abpath=tmp[1],listdata=tmp[2];
if(!Array.isArray(listdata)){
core_vm.onerror(vm.getapp(),'list_data_not_array',vm.absrc,{path:abpath},listdata);
return;
}else{
gen_watch_listclass(node);
var new_scope={
alias:array[0],
palias:array[1],
path:abpath,
pscope:scope,
};
new_scope.listdata=listdata;
new_scope.$index=0;
var lopt={
vm:vm,
node:node,
scope:new_scope,
};
var listing;
listing=vm[core_vm.aprand].watching_list;
listing[abpath]=listing[abpath]||[];
listing[abpath].push(lopt);
lopt.pel=pel;
vm.__addto_onstart(function(){
if(pel.nodeName=='#document-fragment' && pel.id==vm.id+'__tmp')lopt.pel=vm.pel;
});
lopt.sn_in_parent=pel.childNodes.length;
for(var k=0,len=listdata.length;k<len;k++){
core_vm.list.new_node(k,listdata[k],lopt,lopt.sn_in_parent+k,'init');
}
}
}
module.exports.$add=function(lopt,k,v){
var insert_pos=core_vm.list.get_fel_sn_in_parent(lopt,'add')+k;
core_vm.list.new_node(k,v,lopt,insert_pos,'add');
}
module.exports.$delat=function(lopt,index,oldv){
var sn_in_parent=core_vm.list.get_fel_sn_in_parent(lopt,'delat');
var childs=lopt.pel.childNodes;
lopt.vm.delel(childs[sn_in_parent+index]);
}
module.exports.$clean=function(lopt){
var sn_in_parent=core_vm.list.get_fel_sn_in_parent(lopt,'clean');
for(var i=this.length-1;i>-1;i--)lopt.vm.delel(lopt.pel.childNodes[sn_in_parent+i]);
}
module.exports.$rebuild=function(lopt){
var sn_in_parent=core_vm.list.get_fel_sn_in_parent(lopt,'rebuild');
for(var k=0,len=this.length;k<len;k++){
core_vm.list.new_node(k,this[k],lopt,sn_in_parent+k,'rebuild');
}
}
module.exports.new_node=function(k,v,lopt,insert_pos,where){
var scope_node=core_vm.tool.objClone(lopt.node);
delete scope_node.dir.list;
delete scope_node['id'];
lopt.scope.$index=k;
core_vm.cal.nodeid(lopt.vm,scope_node,lopt.scope);
core_vm.create.nodes(lopt.vm,scope_node,lopt.scope,lopt.pel,insert_pos,true);
}
module.exports.get_fel_sn_in_parent=function(lopt){
return lopt.sn_in_parent;
}
<file_sep>(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else {
var a = factory();
for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
}
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "./";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 31);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
var obj={};
if(typeof window!='undefined')obj.platform='web';
else obj.platform='mob';
//core_vm.aprand需要这个文件
module.exports=obj;
/***/ }),
/* 1 */
/***/ (function(module, exports) {
var _reqlib={};
module.exports=_reqlib;
var _htmlescapehash= {
'<': '<',
'>': '>',
'&': '&',
'"': '"',
"'": ''',
'/': '/'
};
var _htmlescapereplace= function(k){
return _htmlescapehash[k];
};
_reqlib.htmlescape=function(str){
return typeof(str) !== 'string' ? str : str.replace(/[&<>"]/igm, _htmlescapereplace);
}
// normalize an array of path components
function normalizeArray(v, keepBlanks) {
var L = v.length,
dst = new Array(L),
dsti = 0,
i = 0,
part, negatives = 0,
isRelative = (L && v[0] !== '');
for (; i < L; ++i) {
part = v[i];
if (part === '..') {
if (dsti > 1) {
--dsti;
} else if (isRelative) {
++negatives;
} else {
dst[0] = '';
}
} else if (part !== '.' && (dsti === 0 || keepBlanks || part !== '')) {
dst[dsti++] = part;
}
}
if (negatives) {
dst[--negatives] = dst[dsti - 1];
dsti = negatives + 1;
while (negatives--) {
dst[negatives] = '..';
}
}
dst.length = dsti;
return dst;
}
// normalize an id
_reqlib.normalizeId=function(id, parentId) {
id = id.replace(/\/+$/g, '');
return normalizeArray((parentId ? parentId + '/../' + id : id).split('/')).join('/');
}
// normalize a url
_reqlib.normalizeUrl=function(url, baseLocation) {
//console.log('normalizeUrl',url, baseLocation)
if (!(/^\w+:/).test(url)) {
var u=baseLocation.fullhost;
//console.error("---normalizeUrl",url, baseLocation.pathname);
//url从/开头 就从host根部开始 否则从pathname开始
var path = baseLocation.pathname;
if(url.charAt(0)!='/' && url.charAt(0)!='.'){
//不需要url='/'+url;
}
if (url.charAt(0) === '/') {
//不需要if(url.indexOf(baseLocation.dirpath)!==0)url=baseLocation.dirpath+url;
url = u + normalizeArray(url.split('/')).join('/');
} else {
path += ((path.charAt(path.length - 1) === '/') ? '' : '/../') + url;
url = u + normalizeArray(path.split('/')).join('/');
}
}
return url;
}
_reqlib.calUrl=function(href, pageurl) {
//console.error('calurl',href,pageurl)
//listview.event,mob_bind
var path = pageurl,url=href;
if (pageurl.charAt(0) !== '/')pageurl="/"+pageurl;
if (url.charAt(0) === '/') {
url = normalizeArray(url.split('/')).join('/');
} else {
path += ((path.charAt(path.length - 1) === '/') ? '' : '/../') + url;
url = normalizeArray(path.split('/')).join('/');
}
return url;
}
_reqlib.gen_path=function(app,url,from_path,needid,where){
//console.error("gen_path",where,url ,'from_path='+from_path);
var location=window.location;
//有from_path是loaddeps时
if(from_path){
if(from_path.indexOf(location.fullhost)==0)from_path=from_path.substr(location.fullhost.length);
}
from_path=from_path||location.pathname;
//console.log("cal_spec_path 2",url );
if(url.indexOf('://')==-1)url=_reqlib.normalizeId(url, url[0]=='.' ? from_path :'');//
//console.log("cal_spec_path 3",url );
if(url.indexOf('://')==-1)url = _reqlib.normalizeUrl(url, location);
if(!needid){
return url;
}else{
url=url.split("//")[1];
if(url)url=url.substr(url.indexOf('/'));
return url;
}
}
_reqlib.cal_spec_path=function(spec,from_path){
if(spec.from=='deps')return;
//spec.id 只对require有用
if(spec.url.indexOf('://')==-1)spec.url=_reqlib.gen_path(spec.app,spec.url,from_path || spec.pvmpath,false,6)
//console.log("cal_spec_path 4",spec.url,spec.id ,spec.knowpath);
if(!spec.knowpath || !spec.id ){
spec.id=spec.url.split("//")[1];
//console.log('计算',spec.url,spec.id)
if(spec.id)spec.id=spec.id.substr(spec.id.indexOf('/'));
}
//实际上只需要id load时加上location.origin就可以了 为了少出故障 先这样了
}
// define a constant (read-only) value property
//var defineConstant;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
var _reqlib=__webpack_require__(1);
// CommonJS compatible module loading.
// (Except from require.paths, it's compliant with spec 1.1.1.)
//https://github.com/rsms/browser-require/blob/master/require.js
var sub_inrequires={};
var ensurce_sub_inrequire=function(app){
if(!sub_inrequires[app.id]){
//console.log('没有subrequire',id, parentId)
sub_inrequires[app.id]=function (_subid) {
//都是绝对路径console.log('subrequire', _subid)
if(app.__cache.get_jslib(_subid)){
}else if(app.config.path.lib[_subid]) {
_subid=app.config.path.lib[_subid];
}
//console.log('内部_inrequire 计算后的id='+_subid, 'parent=');
return inrequire(app,null,_subid, '','lib','inreq');
};
Object.defineProperty(sub_inrequires,app.id,{configurable: false,enumerable:false,writable:false});
}
}
var inrequire=function(app,vm,id,parentId,type,where,urlsid) {
//where:check,有了就不下载
//type:vm,lib,json
//console.log("inrequire",id,parentId,'where='+where,'type='+type,'urlsid='+urlsid,vm?'vm.id='+vm.id:'');
var mod;
if(type=='lib'||type=='json')mod = app.__cache.get_jslib(id);
else mod = app.__cache.vmlib[id];
if(!mod){
//console.error("没有inrequire id="+id,parentId,'type='+type,where);
return null;
}else if(type=='vm' && mod.__extend_from && where=='check'){
return core_vm.extend.inmem(app,vm,id,mod.__extend_from);
}
if(mod.mode!=='lib' && typeof (mod.block)=='function') {// (type=='vm' ||mod.exports === undefined)
//console.error("没有 inrequire缓存",id );
//var block = mod.block;
mod.exports = {};
//js里面 可以 module.exports=xxx;可以exports.aa=xxx;不能exports=xx;因为改写了exports 与mod.exports没有关系了
ensurce_sub_inrequire(app);
try{
var sub_inrequire = sub_inrequires[app.id];
//console.error('==========require.app',app.id,gcache.sysnapid)
mod.block.call(vm||{},sub_inrequire, mod, mod.exports,app);
}catch(e){
console.error("inrequire_execute_error",id,e,'parentId='+parentId,'app.id='+app.id);
core_vm.onerror(app,"inrequire_execute_error",id,e);
//如果是开发 策略是 回调错误 则回调错误
mod.exports = {};//不会再次执行 应该让他可以再次执行 也许有些参数改变了 有些依赖改了
}
if(type=='lib'){
mod.mode='lib'; delete mod.block;
}else if(mod.mode!==undefined){
}else{
if(Object.keys(mod.exports).length==0){
mod.mode='vmfn';//保留block
}else{
if(mod.exports[core_vm.aprand]){
mod.exports={};//安全措施
}
mod.mode='lib';
delete mod.block;
}
}
}
//判断 是不是 string-number-date等基本对象 不是含有parent等的或者有el的对象
if(mod.mode=='vmfn')return {};
if(!mod.exports)return null;
if(where=='inreq')return core_vm.tool.objClone(mod.exports);
else return mod.exports;
}
var extendvm=function(app,id,extend_from){
var mod = app.__cache.vmlib[id];
if(mod){
mod.__extend_from=extend_from;
}
}
var define =function(spec,id, block,type,refsid) {
//console.error('req.cache.define',type,id)
var mod = {};
if(core_vm.isfn(block)){
mod.block=block;
}else{
mod.exports=block;
mod.mode='lib';//json
}
//console.log('define',id,mod)
if(type=='vm'){
spec.app.__cache.add_vmlib(id,mod,refsid);
}else{ //lib|json
spec.app.__cache.add_jslib(id,mod,refsid);
}
//mod.id=id;
return mod;
}
var loadfilefresh_clear = function(spec,id){
spec.app.__cache.loadfilefresh_clear(id);
}
module.exports={
define:define,
get:inrequire,
extendvm:extendvm,
loadfilefresh_clear:loadfilefresh_clear
};
//直接define 直接run如何
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
//module.exports=function(core){
var core_vm=__webpack_require__(0);
core_vm.onerror=function(app,type,where,error){
var cb=app.onerror;
if(core_vm.isfn(cb)){
cb.apply(app,arguments);
}
}
core_vm.onload=function(app,url,xhr,opt){
var cb=app.onload;
if(core_vm.isfn(cb)){
var res;
try{
res=cb.call(app,url,xhr,opt);
}catch(e){
console.error('onload',e)
}
return res;
}
//onload 就是app.js定义的 没有更早的了
}
core_vm.elget=function(el,n){return el?el.getAttribute(n):''}
core_vm.elset=function(el,n,v){return el?el.setAttribute(n,v):false;}
core_vm.getprefn=function(vm,type,name){
var fn;
//console.log('getprefn',type,name)
if(name.substr(0,4)=='app.'){
name=name.substr(4);
fn=vm.getapp()[name];
}else{
if(vm[type] && typeof vm[type]==='object')fn=vm[type][name];
if(!core_vm.isfn(fn))fn=vm[name];
if(!core_vm.isfn(fn))fn=vm[type+'_js_'+name];
}
return fn;
}
//todo tryfn对web来说要取消 2017-9-17
core_vm.devalert=function(app_vm,title,e,err){
var msg=e?(e.message ||e.error ||e.toString()):'';
if(err)msg+="\n"+(err.message ||err.error ||err.toString());
console.error({
title:'dev alert:'+title.toString(),
message:msg,
})
}
core_vm.tryvmfn=function(vm,cvm,when){
if(!vm)return;
if(core_vm.isfn(vm[when])){
try{
vm[when].call(vm,cvm);
}catch(e){
//console.error('tryvmfn.error:',e,e.toString(),e.stack)
core_vm.devalert(vm,'vm.'+when+':'+vm.id,e)
}
}else if(core_vm.isfn(vm.hook)){
try{
vm.hook.call(vm,when,cvm);
}catch(e){
core_vm.devalert(vm,'vm.hook.'+when+':'+vm.id,e)
}
}
}
core_vm.tryfn=function(_this,fn,args,message){
//app.beforestart,onstart,onclose
//vm.hookStart,.beforestart(urlhash),onstart,onchildstart,onchildclose,ondata,beforeclose,beforechildclose
//domevent即使try 如果有未定义对象 也会弹出runtime
if(!core_vm.isfn(fn))return;
if(!Array.isArray(args))args=[args];
//测试用
return fn.apply(_this,args);
//console.log('=====tryfn',message)
var res;
res=fn.apply(_this,args);
return res;
}
const multilineComment = /^[\t\s]*\/\*\*?[^!][\s\S]*?\*\/[\r\n]/gm
const specialComments = /^[\t\s]*\/\*!\*?[^!][\s\S]*?\*\/[\r\n]/gm
const singleLineComment = /^[\t\s]*(\/\/)[^\n\r]*[\n\r]/gm
core_vm.delrem=function(str){
//if(!str)return '';
//console.log(str)
str=str+'';
return str
.replace(multilineComment, '')//去除多行js注释
.replace(specialComments, '')//去除多行js注释
.replace(/\/\*([\S\s]*?)\*\//g, '')//去除多行js注释
.replace(/\<\!\-\-[\s\S]*?\-\-\>/g, '')//删除 <!-- -->
//.replace(/\s*[\n\r]/g, '\n') //单行空白 影响pre格式的表现
.replace(singleLineComment, '\n') //单行
.replace(/\;\s*\/\/.*(?:\r|\n|$)/g, ';\n') //单行 ,结尾的
.replace(/\,\s*\/\/.*(?:\r|\n|$)/g, ',\n') //单行 ;结尾的
.replace(/\{\s*\/\/.*(?:\r|\n|$)/g, '{\n') //单行 {结尾的
.replace(/\)\s*\/\/.*(?:\r|\n|$)/g, ')\n') //单行 )结尾的
//.replace(/([\n\r]\s*[\n\r]){1,}/g,"\n") //多个换行 之间多个空白 影响pre格式的表现
//.replace(/(\s){2,}/g," ");
//取消 //删除连续空白 空行 不能替代为'' 至少一个空格
//.replace(/([ \t]){2,}/g,' ')
}
core_vm.isfn=function(cb){ return typeof(cb)==='function'}
core_vm.isobj=function(obj){return typeof (obj)==='object'}
core_vm.isstr=function(obj){return typeof (obj)==='string'}
//el-hook=node:qqw 专门处理hook-node
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
var seed_of_appsid=0;
var appclass=function(){
this.sid=++seed_of_appsid;
this.config={};
core_vm.rootvmset.checkappconfig(this,0);
this.hasstart=0;
this.__events={}
Object.defineProperty(this,'__events',{enumerable:false});
}
var proto=appclass.prototype;
proto.sub=function(name,vm,cb){
this.__events[name]=this.__events[name]||[];
this.__events[name].push([vm,cb,0]);
}
proto.subonce=function(name,vm,cb){
this.__events[name]=this.__events[name]||[];
this.__events[name].push([vm,cb,1]);
}
proto.unsub=function(name,vm,cb){
var evs=this.__events[name];
if(!evs)return ;
//console.log('app.event.off',name)
for(var k=evs.length-1;k>-1;k--){
if(vm==evs[k][0] && cb==evs[k][1]){
//console.log('找到app.event.off',name,k)
evs.splice(k,1);
}
}
}
proto.pub=function(name,data,vm,cb){
if(typeof(cb)!=='function')cb=function(){}
var evs=this.__events[name];
if(!evs)return cb({error:'no.listener'})
core_vm.tool.each(evs,function(ev,sid){ if(ev[2]===-1)delete evs[sid]; })
core_vm.tool.each(evs,function(ev){
ev[1].call(ev[0],data,vm,function(data){
cb.call(vm,data,ev[0])
});
if(ev[2]==1)ev[2]=-1;
})
for(var k=evs.length-1;k>-1;k--){
if(-1==evs[k][2])evs.splice(k,1);
}
}
proto.loadfile=function(type,filename,cb){
var loadobj={url:filename};
if(type=='vm')loadobj.type='vm';
else if(type=='text')loadobj.type='text';
else loadobj.type='lib';
loadobj.urlsid=2;
loadobj.refsid=2;
loadobj.app=this;
core_vm.require.load(loadobj,function(err,module,spec){
if (core_vm.isfn(cb)) cb(err,module,spec);
})
}
proto.setData=function(vm,p,v,cb){
if(!(vm instanceof core_vm.define.vmclass))return;
if(!core_vm.isfn(cb))cb=this.blankvm.__blankfn;
if(vm[core_vm.aprand].datafrom_store.indexOf(p.split('.')[0])==-1)return cb(false);
var oldv=vm.__getData(p);
if(oldv===v){
cb(false);
return;
}
this.blankvm.__confirm_set_data_to_el(vm,p,v);cb(true);
var fn=vm.event['app.setdata'];
if(core_vm.isfn(fn))fn.call(vm,{path:p,oldv:oldv,newv:v})
}
proto.addData=function(vm,p,index,v,cb){
if(!(vm instanceof core_vm.define.vmclass))return;
if(!core_vm.isfn(cb))cb=this.blankvm.__blankfn;
if(vm[core_vm.aprand].datafrom_store.indexOf(p.split('.')[0])==-1)return cb(false);
this.blankvm.__confirm_add_data_to_el(vm,p,index,v,function(res){
cb(res);
});
var fn=vm.event['app.adddata'];
if(core_vm.isfn(fn))fn.call(vm,{path:p,index:index,value:v})
}
proto.delData=function(vm,p,index,count,cb){
if(!(vm instanceof core_vm.define.vmclass))return;
if(!core_vm.isfn(cb))cb=this.blankvm.__blankfn;
if(vm[core_vm.aprand].datafrom_store.indexOf(p.split('.')[0])==-1)return cb(false);
this.blankvm.__confirm_del_data_to_el(vm,p,index,count||1,function(res){
cb(res);
});
var fn=vm.event['app.deldata'];
if(core_vm.isfn(fn))fn.call(vm,{path:p,index:index,count:count});
}
proto.use=function(where,name,fn){
if(!core_vm.isstr(where) )return;
if(core_vm.isobj(name)){
for(var k in name)this.use(where,k,name[k]);
return;
}
if( !core_vm.isstr(name) )return;
if(where=='vm'){
if(!core_vm.isobj(fn) || (!fn.template&&!fn.body))return;
this.__cache.vmbody[name]=fn.template||fn.body;
this.__cache.vmstyle[name]=fn.style||'';
this.__cache.add_vmlib(name,{exports:fn.lib||{}});
this.__cache.keep('vm',name);
return;
}else if(where=='lib'){
this.__cache.add_jslib(name,{exports:fn});
this.__cache.keep('lib',name);
return;
}
if(where==='block' && !core_vm.isstr(fn))return;
if(where!=='block' && !core_vm.isfn(fn))return;
if(where=='vmprototype'){
core_vm.define.extend(name,fn,this);
}else if(this.__cache.use[where]){
//console.log('扩展',where,name);
this.__cache.use[where][name]=fn;
}
}
module.exports=appclass;
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
var cacheclass=function(appid){
this.appid=appid;
//console.error('cache.appid='+appid)
this.urlsid_seed=10;//每个urlsid累加
this.urlsid={};
this.vmsbysid={}; //sid->
this.vmparent={};//cvm.sid->pvm.sid 用来清理从root下面的 用处不大
this.import_src_vm={};//absrcid:+name =>absrc 仅仅用来确定是vm确定相对src
this.import_src_block={};//absrcid:+name =>absrc
this.import_src_lib={};//absrcid:+name =>absrc
this.importblock={};//absrc=>{text,refsids}
this.importstyle={};//absrc=>{text,refsids}
this.vmbody={};// absrc->vm.template
this.vmstyle={};//absrc->vm.style
this.vmlib={};//require.define 过来
this.jslib={};//require.define 过来 里面专门建个import
this.use={
filter:{},method:{},operator:{},
domevent:{},dataevent:{},
block:{}, //use 过来,path.block 下载后过来 不在path的到importblock
elhook:{},//use 过来,path.elhook 下载后过来 不在path的到jslib
};
//path的部分 vm->vmlib,lib->jslib,elhook->use.elhook,block->use.block, check_if_lib_inpath确保清理时不会被清理
//use.vm到vmbody-vmlib-vmstyle 不经过require 没有清理标志urlsid|vmabsrc
//vm引入的放在import里面
//全局block,elhook 放到 app.__extendfn 可以用app.use(扩展
//全局lib,vm 在这里 可以用 app.use
}
//use,path,路径的都到相同的 vmlib,jslib 清理时 判断是不是use或者path
//import的不复用 需要复用的写在app.use 或者 app.path
var proto=cacheclass.prototype;
proto.destroy=function(){
for(var k in this)this[k]=null;
}
__webpack_require__(35).setproto(proto);
__webpack_require__(36).setproto(proto);
__webpack_require__(34).setproto(proto);
__webpack_require__(33).setproto(proto);
__webpack_require__(32).setproto(proto);
//强制http更新时如何清理cache 分开qingli
//TODO
proto.getapp=function(){
return core_vm.wap;
}
proto.geturlsid=function(url){
if(!this.urlsid[url])this.urlsid[url]=this.urlsid_seed++;
return this.urlsid[url];
}
proto.add_ref=function(type,url,refsid,where){
//console.log('标记引用',where,type,url,refsid)
var mod;
if(type=='lib'||type=='json')mod=this.jslib;
if(type=='vm') mod=this.vmlib;
if(type=='style')mod=this.importstyle;
if(type=='block')mod=this.importblock;
if(!mod){
return false;
}
mod=mod[url];
if(!mod)return false;
if(!mod.refsids)mod.refsids=[];
if(mod.refsids.indexOf(refsid)===-1){
mod.refsids.push(refsid);
//console.log('lib vmabsrc 加进一个',libid,mod.refsids)
}
return true;
}
proto.check_ifhas=function(type,id,refsid){
return this.add_ref(type,id,refsid,'check');
}
module.exports=cacheclass;
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
var calnodejson=function(vm,tempalte_html){// 可以提前 但要等data与template
vm[core_vm.aprand].node_max_sn=1;
var html=vm.template || tempalte_html||'';
html=core_vm.calif.multi(vm,html);
//console.log("html",html);
var tmp=core_vm.calhtmltojson(html,vm[core_vm.aprand].node_max_sn,0,vm.getapp(),3);
//改成 parentNode 了 vm[core_vm.aprand].parent_of_nodes=tmp[1];//按sn排列的 方便查找parent 用于watch时查找是否parent已经watch某个属性
vm[core_vm.aprand].nodejson.push(tmp[0])//.childNodes;//_root_的child
//console.log(vm[core_vm.aprand].nodejson)
}
var forece_calnodeid=function(vm,node,scope,head){
vm[core_vm.aprand].seed_of_el_aid++;
//if(!scope || scope.$index==undefined)
return head+'_elid_'+vm.sid+'_'+vm[core_vm.aprand].seed_of_el_aid;
}
var calnodeid=function(vm,node,scope){
if(!node.id){//这里仅仅是list的第一个id vm.pel的根id watch的不在这里
vm[core_vm.aprand].seed_of_el_aid++;
//if(!scope || scope.$index==undefined)
node['id']='vm_elid_'+vm.sid+'_'+vm[core_vm.aprand].seed_of_el_aid;
//else node['id']='vmelid_'+vm.sid+'_aid_'+scope.aid+'_sid_'+scope.$index;
}
return node.id;
}
var cal_now_path=function(pscope,str,vm,where){
//list='book in books'
//inject.use_inject_nodes_when_create cal_now_path(scope,text,vm)
//当前path 得出 books.0.name.1.xx 0,1等数组index会根据sid计算出来
var abpath='';
var t_scope=pscope;
//console.log("计算路径,str="+str,'pscope.alias='+ (pscope ? pscope.alias :'没有'),where);
if(str==t_scope.alias){
//notdeep
abpath=t_scope.path;
if(t_scope.listdata!=undefined && t_scope.$index!==undefined){
abpath+="."+t_scope.$index;
//console.log('不同吗',t_scope.$index,t_scope.listdata.$sid.indexOf(t_scope.$sid))
}
}else {
while(1){
if(str.indexOf(t_scope.alias+'.')==0){
//console.log("与这个scope 别名相同",t_scope.alias,t_scope.$sid,t_scope.listdata.$sid);
abpath=t_scope.path;
if(t_scope.listdata!==undefined && t_scope.$index!==undefined){
abpath+='.'+t_scope.$index;
}
abpath+='.'+str.replace(t_scope.alias+'.','');
//console.log('abpath='+abpath,t_scope.$index,t_scope.listdata.$sid.indexOf(t_scope.$sid))
break;//找到一个别名相同的就结束了
}
t_scope=t_scope.pscope;
if(t_scope==null)break;
}
}
//console.log("最终路径->",abpath);
if(!abpath){
//console.log("没有找到 别名相同的 parent ,pscope.path="+pscope.path);
abpath=str;
}
if(abpath[0]=='.')abpath=abpath.substr(1);
//console.log("最终路径",abpath);
return abpath;
}
var merge_json_str=function(vm,where,str,skipmerge){
//就是直接执行
//<attr>{a:1,b:2}<attr>
//var obj=eval(' [ '+node.childNodes[0].text+' ] ');
//console.log('merge_json_str',str)
var fn=new Function("e",'return [ '+str+' ] ');
var obj;
try{
obj=fn.call({},null);
}catch(e){}
if(Array.isArray(obj) && obj[0]){
if(skipmerge)return obj[0];
else{
vm[where]=vm[where]||{};
if(typeof obj[0]=='object')core_vm.tool.deepmerge(vm[where],obj[0]);
//else vm[where]=obj[0];
}
}
}
exports=module.exports={
nodejson:calnodejson,
nodeid:calnodeid,
forece_calnodeid:forece_calnodeid,
//nodeid_notdeeplist:nodeid_notdeeplist,
now_path:cal_now_path,
//path_to_bubian:path_to_bubian,
merge_json_str:merge_json_str,//计算inject的jsonstring
}
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
var pscope_attr=function(scope,str){
//{pscope.$index}
//console.log('pscope_attr',scope,str)
var res;
var tmps=str.split('.');
var t_scope=scope;
for(var i=0,len=tmps.length;i<len;i++){
if(tmps[i]=='pscope'){t_scope=t_scope.pscope; if(!t_scope)break;}
else if(tmps[i]=='$index' && i==len-1){res=t_scope.$index;break;}
//else if(tmps[i]=='$sid' && i==len-1){res=t_scope.$sid;break;}
else if(tmps[i]=='$value'){res=t_scope.listdata[t_scope.$index];}
}
return res;
}
var trimquota=function(str){
return str.replace(/^\s*|\s*$/g, '').replace(/^[\'\"]*|[\'\"]*$/g, '');
}
var trim=function(str){
return str.replace(/^\s*|\s*$/g, '');
}
var method=function(funcname,para,vm,scope){
//console.log('计算函数',funcname,para,vm)
para=para||'';
//para=trimquota(para);
if(funcname[0]=='!')funcname=funcname.substr(1);
var func=core_vm.getprefn(vm,'method',funcname);
var paras=para.split(',');
if(!core_vm.isfn(func))func=vm.getcache().use.method[funcname];
if(core_vm.isfn(func )){
if(scope.$index!=undefined ){
for(var i=0,len=paras.length;i<len;i++){
paras[i]=core_vm.tool.trim(paras[i]);
if(paras[i]=='$index')paras[i]=scope.$index;
else if(paras[i]=='$value')paras[i]=scope.listdata[scope.$index];
else if(paras[i].indexOf('pscope.')>-1)paras[i]=pscope_attr(scope,paras[i]);
}
}
var res;
//console.log('准备计算',funcname)
try{
res=func.apply(vm,paras);
}catch(e){
core_vm.devalert(vm,'method.'+funcname,e)
}
return res===undefined?'':res;
}else if(funcname.indexOf('.')>-1){
var str=funcname.substr(0,funcname.lastIndexOf('.'));
var funcname2=funcname.substr(funcname.lastIndexOf('.')+1);
var v=val(str,vm,scope);
//console.log('尝试原声函数',v,'funcname2.'+funcname2)
if(v!==undefined && core_vm.isfn(v[funcname2])){
//console.log('尝试',str,v,funcname2,trimquota(para),v[funcname2](para))
return v[funcname2].apply(vm,paras)+'';
}else {
core_vm.onerror(vm.getapp(),"no_method_when_cal",vm.absrc,{funcname:funcname,para:para});
return '';
}
}else{
return ''
}
}
var val=function(str,vm,scope,where){
//console.log("计算val",str,where);
if(str===undefined || str==='')return str;
var res='';
str=core_vm.tool.trim(str);
var quotastr=str.replace(/^[\'\"]*|[\'\"]*$/g, '');
//判断是否两端引号
if(quotastr.length+2 ==str.length){
return quotastr;
}
if(str[0]=='!')str=str.substr(1);
var tmp=core_vm.tool.parse_func_para(str);
//console.log("计算是否是函数还是属性",str,tmp);
if(tmp[1]==undefined){
if(str.substr(0,5)=='this.'){
//console.log('计算this数据',str.substr(5),vm.state)
res=core_vm.tool.objGetDeep(vm,str.substr(5));
if(res==undefined){
core_vm.onerror(vm.getapp(),"data_path_error1",vm.absrc,{path:str});
res='';//不返回undefined
}
}else{
if(str=='$index')res=scope.$index;
//else if(str=='$sid')res=scope.$sid;
else if(str=='$value')res=scope.listdata[scope.$index];
else if(str.indexOf('pscope.')>-1){
res=pscope_attr(scope,str);
}else{
//console.log("准备计算路径",str,scope);
var abpath=core_vm.cal.now_path(scope,str,vm,'calval');
//多个scope可以直接调用pscope的alias
if(abpath.indexOf('this.')===0)res=core_vm.tool.objGetDeep(vm,abpath.substr(5));
else res=core_vm.tool.objGetDeep(vm.data,abpath);
//console.log("val 最终路径",abpath,res);//,vm.data
if(res===undefined){
if(str[str.length-1]=='!'){
return val(str.substr(0,str.length-1),vm,scope,where)
}else{
core_vm.onerror(vm.getapp(),"data_path_error2",vm.absrc,{path:str});
res='';
}
}
}
}
}else{
res=core_vm.calexp.method(tmp[0],tmp[1],vm,scope);
}
//console.log('计算val结果',str,res);
return res;//+'';
}
var gen_filter=function(exp,vm,scope){
//格式 {obj.name | filter | filter2}
var array=exp.split('|');
var res=array[0];
if(array.length>1 && res){
for(var i=1;i<array.length;i++){
array[i]=core_vm.tool.trim(array[i]);
//不要带参数了
//var tmp=core_vm.tool.parse_func_para(array[i]);
var func=core_vm.getprefn(vm,'filter',array[i]);
if(!core_vm.isfn(func))func=vm.getcache().use.filter[array[i]]||core_vm.getprefn(vm,'method',array[i]);
if(core_vm.isfn(func )){
try{
res=func.call(vm,res);
}catch(e){
res='';
core_vm.devalert(vm,'filter :'+array[i],e);
}
}
}
}
return res;
}
//运算符扩充 setel-attr 扩充
var exp_one=function(vm,attrexp,scope,k){
//if(vm.id=='vm_switch')console.log('exp_one 原',attrexp)
//这里不需要trim
var ops=vm.getcache().use.operator;
return (attrexp.replace(/{(.*?)}/g,function(item, str){
//if(vm.id=='vm_switch')console.error("exp_one 分离 str="+str,str[0],str.length);
//str 是去除括号的 如果有运算符 str是已经计算过的
//str=trim(str);
var result='';
if(k=='_exptext_' ){//标签间的{} 可能是{!xx}
if(str[0]=='!')str=str.substr(1);
if(str[str.length-1]=='!')str=str.substr(0,str.length-1);
}
//还有+-乘除
var find=0;
for(var k in ops){
if(str.indexOf(k)>-1){
result=ops[k](str);
find=1;
break;
}
}
if(find==1 && result!==undefined && result!==''){
return result;
}else{
if(str.indexOf(' | ')>-1){//过滤
result= gen_filter(str,vm,scope);
}else{
str=trim(str);
result= core_vm.calexp.val(str,vm,scope,'exp6')+'';
}
return result+'';
}
//console.log(str,"result="+result);
//return result;
}));
}
var exp=function(vm,str,scope,k){
if(str.indexOf('{')===-1)return str;
//if(vm.id=='vm_switch')
//console.error("计算exp",str);
//{}可以嵌套
if(typeof(str)!=='string')return '';
str=trim(str);
str=str.replace('{%','{').replace('%}','}');
if(str.split('{').length !==str.split('}').length){
//{}括号数目不等
return str;
}else if(str.indexOf('{')==str.lastIndexOf('{') && str.indexOf('}')==str.lastIndexOf('}') ){
//console.log('只有一对括号')
return exp_one(vm,str,scope,k);
}else{
while(str.indexOf('{')>-1 ){
var pos=str.lastIndexOf('{');
//最后一个
var pos2=str.indexOf('}',pos);
if(pos2==-1)break;
var nstr=str.substring(pos,pos2+1);
//console.log('找到内部表达式',nstr,exp_one(vm,nstr,scope,k))
//不能用replace
str=str.substr(0,pos)+exp_one(vm,nstr,scope,k)+str.substr(pos2+1);
//先计算内部的括号
}
if(str.indexOf('{')>-1){
//不交错的 从左边的{开始
while(str.indexOf('{')>-1 && str.indexOf('}')){
var pos=str.indexOf('{');
var pos2=str.indexOf('}',pos);
if(pos2==-1)break;
var nstr=str.substring(pos,pos2+1);
//console.log('剩余内部表达式nstr='+nstr)
str=str.substr(0,pos)+exp_one(vm,nstr,scope,k)+str.substr(pos2+1);
}
}
//console.log('结果str='+str)
return str
}
}
var nodeattrexp=function(vm,node,scope){
//if(vm.id=='vm_switch')console.log('cal_exp',vm.id,node,node.attrexp);
//如 class='zz {}'
if(node.attrexp){
for(var k in node.attrexp){
//console.log('计算',k)
//标签内的表达式 ttt="qq {xx}"都放到 exp了
var res=core_vm.calexp.exp(vm,node.attrexp[k],scope);
node.attr[k]=res;
}
}
}
module.exports={
nodeattrexp:nodeattrexp,//calcommon node的 attrexp
val:val,//基本函数 都要调用到这里来 一个{}里面的 可能有|过滤 三元 条件
exp:exp,//watchcb exp_text,attrexp,list数组 a in b b的计算,id计算,on-click=,classList,_exptext_,watch,inject,block
method:method,
}
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
var tapp;//在calhtml引入简单替换
var trim=function(str){
//去除字符串头尾空格与tab
//return str.replace(/^[\s\t ]+|[\s\t ]+$/g, '');
return str.replace(/^\s*|\s*$/g, '');//.replace(/[\r\t\n]/g, " ");
}
var all_isnot_seen=function (str){
for( var i=0,len=str.length; i<len; i++){
if(str.charCodeAt(i)>32) return false;
}
return true;//全部是不可见字符就忽略了
}
function issimple(str){
return (str.indexOf(':')>-1 || str.indexOf('|')>-1 || str.indexOf('?')>-1 || str.indexOf('(')>-1 || str.indexOf(')')>-1)?false:true;
}
function index_of(str,needle){
//忽略大小写
var r = str.match(new RegExp(needle, 'i' ));
return r==null?-1:r.index;
}
function stripquote(val) {
//去掉首尾的括号
return val.replace(/^['"`]|['"`]$/g, '');
}
// * 匹配前一项0次或多次,等价于{0, }
var reg_close =/^<\s*\/\s*([\w-_]+)\s*>/;//格式 < /aa-_bb > 单点冒号要吗 2017-10-1 todo 尽量宽松点 删去最后的 \s* 可以让>后面的空白起效
var reg_start=/^<\s*([\w]{1,})\s*/;//格式 < aa.:bb 单点冒号要吗 2017-10-1 todo
var reg_self_close=/^\s*\/\s*>/; //格式 空白符/> 删去最后的 \s*
function add_watch(node,name,method){
//firefox object有watch函数
//console.log("add_watch",name);
node.watchs=node.watchs||[];
name=name.split('-watch-');
for(var i=0,len=name.length;i<len;i++)node.watchs.push([name[i].replace(/\-/g,'.'),method])
}
var DATA=0,OPTIONS=1,STATE=2;
var gsn=0;
var parse=function (xml,html_gsn,psn) {
xml = trim(xml);
xml = xml.replace(/\<\!--[\s\S]*?--\>/g, '');
xml="<_root_>"+xml+"</_root_>";
gsn=html_gsn || 0;
psn=psn||0;
var nodescache=[];
return gendoc();
function gendoc() {
return {
//declaration: declaration(),
_root_: gentag(null,psn),//nownode
nodescache:nodescache,
}
}
function gentag(parentNode,psn) {
//console.log('gentag ', psn);
//console.log('--tag--');
var m = nodematch(reg_start,'start');//格式 < aa.:bb 前面可以有空格 ,'start',pnode.tag找出<div 空格 下面attribute
//console.log(m);
if (!m){
//0位是< 肯定是标签不对 也可能是要关闭 遇到了是<>空标签导致下面都进行不了了
return;//不能 返回 gentag(parentNode);
}
var node = {
sn:gsn++,
psn: (psn!=undefined?psn:(parentNode ? parentNode.sn:0)),
id:'',
tag:m[1],// (parentNode && parentNode.dir['vm'])? m[1] : m[1],//不能小写.toLowerCase() inject的不小写
utag:m[1].toLowerCase(),
attr:{},
dir:{},
childNodes:[],
parentNode:parentNode,
};
nodescache[node.sn]=node;
parse_attr(node);
if(node.attr && node.attr.class){
node.classList=node.attr.class.split(' ');
delete node.attr.class;
}else if(node.attrexp && node.attrexp.class){
node.classList=node.attrexp.class.split(' ');
delete node.attrexp.class;//已经添加监控了
//class可能在attrexp是因为需要监控 计算会专门进行
}else{
node.classList=[];
}
//console.log('属性结束,node.classList=',node.sn,node.classList)
if (nodematch(reg_self_close,'selfclose')) {
return node;
}
//nodematch(/\??>\s*/,'next>',node.tag);//找下一个 > 改为下面的
var index=xml.indexOf('>');
xml = xml.slice(index+1);
var nowtagLower=node.tag.toLowerCase();
if(nowtagLower=='br' || nowtagLower=='hr')return node;
//一定要提前寻找
child_or_content(node);
while(!nodematch(reg_close,'close',node.tag,node)){
//console.log("错误 关闭tag="+node.tag+",xml=",xml.length);
if(xml)child_or_content(node);
else break;
}
//console.log('准备关闭 2','tag='+node.tag,'xml='+xml)
//xml=trim(xml);
return node;
}
function parse_attr(node){
var find_attr1=0,find_attr2=0;
while (!(eos() || is('>') || is('?>') || is('/>') )) {
//|| is(' >')
find_attr1=1;
find_attr2=1;
var attr = attribute();
if(attr){
//console.log('attr 1 ,' , attr );
if(node.tag=='data'||(node.tag=='option' && node.parentNode.tag!=='select')){//两种 一种是注入一种是select-option
//inject的不监控
node.attr[attr.name] = attr.value;
}else if(attr.name=='id') {
node.id=attr.value;
}
else if(attr.name=='el-filter'||attr.name=='el-hook'||attr.name=='el-list'){
node.dir[attr.name.substr(3)]=attr.value;
}else if(attr.name.substr(0,6)=='watch-'){
attr.name=attr.name.substr(6);
if(attr.name[0]=='[' && attr.name[attr.name.length-1]==']')attr.name=attr.name.substr(1,attr.name.length-2);
add_watch(node,attr.name,attr.value);
}else if(attr.name.substr(0,3)=='on-'){
node.event=node.event||{};
node.event[attr.name.substr(3)]=attr.value;
}else if(attr.name.substr(0,6)=='event-'){
//不取消 原因是尽量在html里面定义
node.vmevent=node.vmevent||{};
node.vmevent[attr.name.substr(6)]=attr.value;
}else{
var tmp = attr.value.match(/{([\S\s]*?)}/);
if(tmp==null){
node.attr[attr.name] = attr.value;
if(attr.value.toLowerCase()==='true')node.attr[attr.name]=true;
else if(attr.value.toLowerCase()==='false'){
node.attr[attr.name]=false;
//console.error('禁用',attr.name)
}
}else{
//console.log('表达式',attr,tmp[0],tmp[1])
node.attrexp=node.attrexp||{};
// : 条件不监控 ()函数不监控 | 可以监控 简单属性可以监控 style="width:{aa}"不监控
//var tmpp=tmp[1].split('|')[0];
var last_indexOf_kuohao=attr.value.lastIndexOf('{');
if(last_indexOf_kuohao==0 && tmp.index==0 && tmp[0]==attr.value && issimple(tmp[1])){
//console.log('简单属性,没有:|?()',attr.value)
//简单属性是只有一个{},没有函数(),没有过滤器|,没有三元?:
var path=trim(tmp[1]);
var if_data_to_el=0,if_el_to_data=0;
if(path[0]=='!'){if_data_to_el=1;path=path.substr(1);}
if(path[path.length-1]=='!'){if_el_to_data=1;path=path.substr(0,path.length-1);}
var datatype=DATA;
if(path.indexOf('this.option.')==0){
datatype=OPTIONS;
if_data_to_el=1;
if_el_to_data=0;
}else if(path.indexOf('this.state.')==0){
datatype=STATE;
}
node.attrexp[attr.name]="{"+path+"}";
if(if_data_to_el){
add_watch(node,path,'toel-'+attr.name);
}
if(if_el_to_data){
//node.tag=='input'//data是inject-data 这里不要监控 在inject里面监控
//基本操作就是on-change 其他特殊的自己 设置 on-keyup
//console.log("绑定到 onchange");
node.event=node.event||{};
if(datatype==STATE)node.event['change']="tostate-"+path.replace('this.state.','');
else if(datatype==DATA)node.event['change']="todata-"+path;
}
}else{
//console.log('复杂监控 需要专门计算',attr.value,node)
node.attrexp[attr.name]=attr.value;
add_multi_watch(node,attr.value,'toel-'+attr.name);
}
//console.log(tmp,node.watchs);
}
}
}else{
find_attr1=0;
attr = attribute2();//独立的 类似 checked disabled
//console.log('没有 attr1','attr 2,', attr );
if(attr){
//console.error("发现独立属性",attr);
if(!all_isnot_seen(attr.name)){
attr.name=attr.name.replace(/\W/g, '');
if(attr.name){
node.attr[attr.name]=true;
}
}
}else{
find_attr2=0;
}
}
if(find_attr1+find_attr2==0){
//log('属性结束1',xml)
xml = xml.slice(xml.indexOf('>'));
}
}
}
function child_or_content(node){
var child,tcontent;
var find_child=0,find_content=0;
while (1) {
find_child=1;
find_content=1;
child = gentag(node);
if(child){
node.childNodes.push(child);
}else{
find_child=0;
}
//console.log("------------check child,node="+node.tag);
tcontent = parse_content();
if(tcontent){
add_content_node(node,tcontent);
}else{
find_content=0;
}
if(find_child+find_content==0)break;
}
}
function new_node(type,pnode){
var node={tag:type,utag:type,
childNodes:[],dir:{},attr:{},psn:pnode.sn,sn:gsn++,parentNode:pnode};//
nodescache[node.sn]=node;
pnode.childNodes.push(node);
return node;
}
function ifhave_operator (str) {
if(str.indexOf('|')>-1 ||(str.indexOf('?')>-1 && str.indexOf(':')>-1)
||(str.indexOf('(')>-1 && str.indexOf(')')>-1) ||str.indexOf('&&')>-1)return true;
}
function add_multi_watch(node,str,where) {
//不能有todata 最后一个冒号无效 被删除
//<btn text="{!x},{!y}" />
//<btn>{!x},{!y}</btn>
//有 三元操作?: 或者|| && 过滤|
if(where!='toel-text' && ifhave_operator(str)){
return;
}
var needwatch=[];
str.replace(/([\S\s]*?)\{([\S\s]*?)\}/g,function(a,b,c,d,e,f,g){
c=trim(c);
if(!c)return;
if(c.indexOf('this.option.')==0){
if(c[0]!='!')c='!'+c;//自动监控option
}
if(c[c.length-1]=='!')c=c.substr(0,c.length-1);
if(c[0]==='!' && needwatch.indexOf(c)===-1){
needwatch.push(c.substr(1));
}
});
//content 只能data-to-el.text
//console.log('add_multi_watch',needwatch,where,str)
for(var i=0,len=needwatch.length;i<len;i++){
add_watch(node,needwatch[i],where);
}
//标签之间的 每个watch 成为一个textnode
//console.log(str,node.vmwatch)
//如果有@node 专门分成一个节点
}
function add_content_node(node,tcontent){
//console.log("增加内容","|"+tcontent+"|");
if(all_isnot_seen(tcontent))return;
//tcontent=trim(tcontent);
if(tcontent.indexOf('\\u')>-1)tcontent=tcontent.replace(/\\u[a-fA-F0-9]{4}/g,function(a,b,c){return unescape(a.replace(/\\u/,'%u'))});
if(tcontent.indexOf('\\U')>-1)tcontent=tcontent.replace(/\\U[a-fA-F0-9]{4}/g,function(a,b,c){return unescape(a.replace(/\\U/,'%u'))});
// \u3000 代表空格 \u20ac 日元
var tag=node.tag.toLowerCase();
if(tapp.config.precode.indexOf(tag)>-1){
//tag=='pre' || tag=='code'
//console.error('发现code',tag)
node.attr=node.attr||{};
node.attr.text=core_vm.tool.htmlunescape(tcontent);
return;
}
var tmp = tcontent.match(/{([\S\s]*?)}/g);
if(tmp==null){//没有表达式
if(tag=='text'){// || (!isweb && text_biaoqian[node.tag]) 放到生成里去做 2016/11/4
node.text=tcontent;
}else{
var textnode=new_node('_text_',node);
textnode.text=tcontent;
}
return;
}else{
//console.log("发现标签间表达式",tcontent);
//分成多个节点的问题是移动 mob.button 里面没法容纳多个label
if(ifhave_operator(tcontent)){
//复杂的有操作符的 直接监控整体
var textnode=new_node('_exptext_',node);
textnode.text='';
textnode.exp_text=tcontent;
add_multi_watch(textnode,tcontent,'toel-text');
return;
}
tcontent.replace(/([\S\s]*?)\{([\S\s]*?)\}/g,function(a,b,c,d,e,f,g){
//console.log(tag,'匹配','a='+a,'b='+b,'c='+c,'d='+d,'e='+e,'f='+f,'g='+g);
if(trim(b)){
var textnode=new_node('_text_',node);//{之前的
textnode.text=trim(b);
}
c=trim(c);
if(c){
if(c[c.length-1]=='!')c=c.substr(0,c.length-1);
var textnode=new_node('_exptext_',node);
textnode.text='';
textnode.exp_text='{'+c+'}';
if(c.indexOf('this.option.')==0){
if(c[0]!='!')c='!'+c;//自动监控option
}
if(c[0]==='!'){
add_watch(textnode,c.substr(1),'toel-text');
}
}
});
var index=tcontent.lastIndexOf('}');
if(index!=tcontent.length-2){
var shengyu=tcontent.substr(index+2);
if(trim(shengyu)){
var textnode=new_node('_text_',node);
textnode.text=trim(shengyu);
}
}
}
}
function parse_content() {
var m = nodematch(/^([^<]*)/,'content');//到<停止
return m?m[1]:'';
}
function attribute2(){
//checked 没有等号
var m = nodematch(/^\s*([_-\w]+)\s*/ ,'attrstate'); //到>或空白停止 checked可以
if(m) return { name: m[1], value: (m[1]) }
}
function attribute() {
//width=50% 没有引号时出错
//log('1attribute %j', xml);
var m = nodematch(/([_-\w]+)\s*=\s*(\`[^`]*\`|"[^"]*"|'[^']*'|[ ]|[^<>\/\s]*)\s*/ ,'attr');
// .:#@$_- 顺序关键
//属性名去掉#@$
//$是数组方法 $state 取消了$
//属性名允许的 .:-_
//冒号:是listview 里面的 pic:image的数据绑定方法 冒号已经取消
//value是 '"` 三种引号开头到下一个引号,单引号开头到下一个单引号,或者是到一个空格结束,到一个不跨越 <的 /或者>结束
//aa='ds' || aa="ss" ||aa=sss
//name可以用连字符 a.b a:b a_b font-color='ss'
// src="http://ww.sss.ss/ss.img" ok
// src="http:///ww.sss.ss/ss.img" not ok 3/// noooo
if(m){
return { name: trim(m[1]), value: trim(stripquote(m[2])) }
}
}
function nodematch(re,where,tag,node) {
//start,selfclose,close,content,attr,attrstate
//console.log("----"+where+",tag="+tag,xml);
var m = xml.match(re);
//console.log('match.'+where,m)
if(where=='attr' ){
if(m && ( m['index']>0 && !all_isnot_seen(m['input'].substr(0,m['index'])))){
//比如 <div sss ddd='sss'> 先查找是=的attr 这时会发现 前面的sss不是全部为不可见字符
//console.log('滴滴滴滴滴滴',m)
return;
//接下去会去找attr2
}
}else if(where=='close'){
// console.log("close="+tag,m);
if(m){
xml = xml.substr(m.index+m[0].length);
if(m[1]==tag || m[1].toLowerCase()==tag.toLowerCase()){
return true;
}else{
return tapp.config.strategy.force_close_not_match_close_tag?true: false;
}
}else{
xml = xml.slice(xml.indexOf('>')+1);//删除 </222> 错误的部分 不删除会循环
return tapp.config.strategy.force_close_error_close_tag?true: false;
}
}
if (!m)return;
xml = xml.slice(m.index+m[0].length);
return m;
//清除开始的空白 不需要了 主要是 attr2 已经可以匹配 xml = xml.replace(/^\s*/g ,'');
//console.log(where+',m0='+m[0]+',结果xml= |'+xml.replace(/[\r\n]/g,'')+"\n");
//slice(start,end)和substring(start,end)
//他们两个的end都是原字符串的索引,意思为截取到end(不包括end)位置的字符
//二者的区别是:
//slice中的start如果为负数,会从尾部算起,-1表示倒数第一个,-2表示倒数第2个,此时end必须为负数,并且是大于start的负数,否则返回空字符串
//slice的end如果为负数,同样从尾部算起,如果其绝对值超过原字符串长度或者为0,返回空字符串
//substring会取start和end中较小的值为start,二者相等返回空字符串,任何一个参数为负数被替换为0(即该值会成为start参数)
//substr的end参数表示,要截取的长度,若该参数为负数或0,都将返回空字符串
}
function eos() {//End-of-source
return 0 == xml.length;
}
function is(prefix) {//prefix
return 0 == xml.indexOf(prefix);
}
}
function declaration() {
var m = nodematch(/^<\?xml\s*/,'declaration');
if (!m) return;
// tag
var node = {
attr: {}
};
// attr
while (!(eos() || is('?>'))) {
var attr = attribute();
if (!attr) return node;
node.attr[attr.tag] = attr.value;
}
nodematch(/\?>\s*/,'declaration 2');
return node;
}
function removeDOCTYPE(html) {
return html
.replace(/<\?xml.*\?>\n/, '')
.replace(/<!doctype.*\>\n/, '')
.replace(/<!DOCTYPE.*\>\n/, '');
}
module.exports=function(html,maxsn,psn,app,where){
//console.log('原始html',html,app.id);
tapp=app;
//var pre_regx=new RegExp('<pre([\\s\\S]*?)>([\\s\\S]*?)<\/pre>', 'gi');
//var code_regx=new RegExp('<code([\\s\\S]*?)>([\\s\\S]*?)<\/code>', 'gi');
//.replace(pre_regx,function(a,b,c,d){ return '<pre'+b+'>'+core_vm.tool.htmlescape(c)+'</pre>' })
//.replace(code_regx,function(a,b,c,d){ return '<code'+b+'>'+core_vm.tool.htmlescape(c)+'</code>'})
//需要requirecal提前做了工作
html=html
.replace(/<\?xml.*\?>\n/, '')
.replace(/<!doctype.*\>\n/, '')
.replace(/<!DOCTYPE.*\>\n/, '')
.replace(new RegExp('<script[^]*>[\\s\\S]*?</script>','gi'),'')
.replace(new RegExp('<style[^]*>[\\s\\S]*?</style>','gi'),'')
.replace(/\/\s*>/g, "/>") // /> 之间的空格
.replace(/\/\>/g, " />") // />前面空出来一个空格作为属性结束符号
.replace(/\<\>/g, "");
//var start=new Date().getTime();
var all=parse(html,maxsn,psn,app);
//console.log("时间",new Date().getTime()-start);
//__recursion_one_text_child_to_text_attr(xml._root_);//ti自己处理 web不需要
//console.log(all._root_.childNodes)
return [all._root_,all.nodescache];//.childNodes;
}
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
var cal_els_filter=function(vm,str,scope){
//console.log('\n\ncal_els_filter',str);
scope=scope||{};//提前计算的 scopr是root
var calstr=str;
var mustv;
var array,res,method;
if(str.indexOf('>=')>-1){ array=str.split('>=');method='>=';}
else if(str.indexOf('<=')>-1){ array=str.split('<=');method='<=';}
else if(str.indexOf('!==')>-1){ array=str.split('!==');method='!==';}
else if(str.indexOf('===')>-1){ array=str.split('===');method='==';}
else if(str.indexOf('==')>-1){ array=str.split('==');method='==';}
else if(str.indexOf('>')>-1){ array=str.split('>');method='>';}
else if(str.indexOf('<')>-1){ array=str.split('<');method='<';}
if(array && method){
calstr=core_vm.tool.trim(array[0]);
mustv=core_vm.calexp.exp(vm,core_vm.tool.trimquota(core_vm.tool.trim(array[1])),scope,'cal_els_filter');//期望值去除括号
res=core_vm.calexp.exp(vm,calstr,scope,'cal_els_filter');
var result=false;
if(method=='>='){if(1+Number(res)>=1+Number(mustv))result=true;}
else if(method=='>'){if(1+Number(res)>1+Number(mustv))result=true;}
else if(method=='<='){if(1+Number(res)<=1+Number(mustv))result=true;}
else if(method=='<'){if(1+Number(res)<1+Number(mustv))result=true;}
else if(method=='=='){if(res+''==mustv+'')result=true;}
else if(method=='!=='){if(res+''!==mustv+'')result=true;}
//console.log("cal_els_filter",'|'+method+'|','计算res=|'+res+'|','must=|'+mustv+'|,',result,typeof res,typeof mustv);
return result;
}else{
res=core_vm.calexp.exp(vm,str,scope,'cal_els_filter');
//console.log("cal_els_filter 计算",str,res,res?'对':'错',typeof (res));
if(res && res!=='null' && res!=='false'&& res!=='undefined')return true;
else return false;
}
}
var parse_if=function(name,vm,scope){
//console.log('paser_if',name,cal_els_filter(vm,name,scope))
return cal_els_filter(vm,name,scope);
}
var if_multi=function(vm,html){
//console.log('if_multi',html)
return html.replace(/{%[ ]{0,}if([\s\S]*?){%[ ]{0,}endif[ ]{0,}%}/g, function (item, qparam,param) {
//console.log("if_multi 发现 item="+ item+", qparam="+ qparam +", param="+ param);
//return qparam ? _eval_tmpl_func(qparam,vm): "";//函数
//var returnstr='';
var ifs=[];
var strs=[];
var starts=[];
var lens=[];
var result=[];
item.replace(/{%([\s\S]*?)%}([\s\S]*?)/gm,function(a,b,c,d){
//console.log('剩余', 'a='+a,'b='+b,'c='+c,'d='+d);
ifs.push(b);
starts.push(d);
lens.push(a.length);
});
for(var k=0,len=starts.length-1;k<len;k++){
strs.push(item.substr(starts[k]+lens[k],starts[k+1]-starts[k]-lens[k]))
}
//console.log(ifs,starts,lens,strs)
var return_sn=-1;
for(var i=0,len=ifs.length;i<len;i++){
ifs[i]=core_vm.tool.trim(ifs[i]);
var this_result=false;
if(ifs[i].indexOf('elseif ')==0 || ifs[i].indexOf('else if ')==0){
this_result=cal_els_filter(vm,core_vm.tool.trim(ifs[i].substr(7)));
}else if(ifs[i].indexOf('if ')==0){
this_result=cal_els_filter(vm,core_vm.tool.trim(ifs[i].substr(3)));
}else if(ifs[i]=='else'){
this_result=true;
}
if(this_result==true){
return_sn=i;
break;
}
//console.log(i,this_result,ifs[i],'return_sn='+return_sn);//,strs[return_sn]
}
if(return_sn>-1)return strs[return_sn];
else return '';
});
}
var single=function(vm,if_result,filter,sn,scope,start_index){
//filter=dir.filter
if(filter){
if(filter=='else'){
//console.log('如果',filter,sn,if_result)
var find_true=0;
for(var j=sn-1;j>start_index;j--){
if(if_result[j]==true){
find_true=1;
break;
}
}
if(find_true==0){
if_result[sn]=true;
}else{
if_result[sn]=false;
}
}else if(filter.substr(0,7) =='elseif:'){//可以用elseif-:空格等分割
var find_true=0;
for(var j=sn-1;j>start_index;j--){
if(if_result[j]==true){
find_true=1;
break;
}
}
if(find_true==1){
if_result[sn]=false;
}else if(if_result[sn-1]===false){
if_result[sn]=parse_if(filter.substr(7),vm,scope);
}
}else if(filter.substr(0,3) =='if:'){
if_result[sn]=parse_if(filter.substr(3),vm,scope);
}else{
if_result[sn]=parse_if(filter,vm,scope);
}
}else{// if(filter.substr(0,3) =='if:')
//根本过不来
if_result[sn]=true;
}
}
module.exports={
single:single,
multi:if_multi
}
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.create=function(vm,node,scope,pel,insert_pos){
//var html='';
//指令顺序: 表达式,bind,watch
//console.log('creat_web',node.tag,node.utag,node.attr.text);
if(node.tag=='_root_' ){
core_vm.create.nodes(vm,node,scope,pel);
return ;
}
if(!vm){
core_vm.delalert.error('create miss vm')
return;
}
if(node.utag=='slot'){
node=core_vm.inject.use_inject_nodes_when_create(vm,node,scope)||node;
}
var newvmopt=core_vm.createvm(vm,node,scope);
//这时没有el 应该是内部使用的
if(node.dir.hook && node.dir.hook.indexOf('node:')==0){
core_vm.elhook(vm,null,node.dir.hook.substr(5),'beforeCreated',node);
}
if(node.tag=='_text_' ||(node.tag=='_exptext_' && !node.watchs) ){
//不需要监控 直接写到html里面 需要监控 创建 text标签 mob里面不是这样处理 而是把id赋给pel
//console.log('文本',pel,pel.nodeName,node.text);
if(pel.nodeName=='#document-fragment' ||pel.id==vm.id+'__tmp'){
thisel= document.createTextNode(node.text);
pel.appendChild( thisel);
return;
}else{
pel.innerHTML=pel.innerHTML+node.text;//
return;
}
}
core_vm.createcommon.idclass(vm,node,scope);
var thisel;
if(node.tag=='_exptext_')thisel= document.createElement('span');//document.createTextNode(node.text);
else thisel=document.createElement(node.tag);
if(!thisel){
return null;
}
if(node.listid)thisel.listid=node.listid;
if(node.id ){
//if(node.id!==thisel.id)console.error('id不同2',node.id,thisel.id)
thisel.id=node.id;//mob的id必须在生成el前加到node.style
}
for(var k in node.attr){
if(k=='text' || k=='html')continue; // || k=='class'
thisel.setAttribute( k,node.attr[k])
}
if(node.classList.length>0){
//classList 与mob不同
core_vm.web_private_style.check(vm,node);
thisel.className=node.classList.join(' ');//直接classList赋值不行
}
if(newvmopt){
pel.appendChild( thisel);
newvmopt.el=thisel;
vm.appendChild(newvmopt,node,1);
}else if(thisel){
core_vm.createcommon.event(vm,node,scope,thisel);
if(node.tag=='text'){ thisel.textContent=node.text; node.childNodes=[];}
else if(node.attr.text){ thisel.textContent=node.attr.text; node.childNodes=[];}
else if(node.attr.html) {thisel.innerHTML=node.attr.html; node.childNodes=[];}
else if(node.text) {thisel.textContent=node.text; node.childNodes=[];}
if(insert_pos==undefined || insert_pos==pel.childNodes.length)pel.appendChild(thisel);
else pel.insertBefore(thisel,pel.childNodes[insert_pos]);
if(node.dir.hook)core_vm.elhook(vm,thisel,node.dir.hook,'selfCreated');
if(node.childNodes && node.childNodes.length>0 && !node.childskip_inject){
core_vm.create.nodes(vm,node,scope,thisel);
}
if(node.dir.hook)core_vm.elhook(vm,thisel,node.dir.hook,'childrenCreated');
}
return thisel;
}
module.exports.nodes=function(vm,node,scope,pel,insert_pos,iflist){
//原来传过来的参数是node.childNode,现在改为node,是因为可能要操作其下属
var nodes=iflist?[node]:(node.childNodes||[]);
if(!Array.isArray(nodes)) nodes=[nodes];
if(nodes.length==0)nodes=[];
var needif=0;
var if_result=[],start_index=-1;
core_vm.createblock.find_block(nodes,vm,scope,pel);
for(var sn=0,len=nodes.length;sn<len;sn++){
if(nodes[sn].dir && nodes[sn].dir.filter){
needif=1;
break;
}
}
//console.log('create.nodes',nodes[0].utag);//,nodes
for(var sn=0,len=nodes.length;sn<len;sn++){
var node=nodes[sn];
if(sn=='if_result'||!node.tag)continue;
if(node.$injectscope){
//强制转换
//第一次遇到 转换vm 下级的不需要
//console.error('注入的',vm.absrc)
if(node.$injectfromvm_sid){
var inject_vm=vm.getcache().vmsbysid[node.$injectfromvm_sid];
if(!inject_vm){
core_vm.devalert(vm,'no inject_vm')
continue;
}else{
vm=inject_vm;
}
}
//不能使用vm.pvm 因为多层标记 导致pvm一直累积
scope=node.$injectscope;
}
if(needif){
if(!node.dir || !node.dir.filter){
if_result[sn]=true;
start_index=sn;
}else{
core_vm.calif.single(vm,if_result,node.dir.filter,sn,scope,start_index);//需要在这里 因为 inject
if(node.dir.filter=='else')start_index=sn+1;
}
}
if(needif===0 || if_result[sn]===true){
if(!node.dir.list){
module.exports.create(vm,node,scope,pel,insert_pos);
}else{
core_vm.list.gen(vm,node,scope,pel);
}
}
}
//delete if_result;
}
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
var check_block_text=function(nodes,name,text){
//console.log('check_block_text',nodes.length)
nodes.forEach(function(node){
//console.log('check_block_text',node.tag,node.text,name)
var find=0;
if(node.event){
//console.log('node.event',node.event)
for(var k in node.event){
if(node.event[k]==name){
node.event[k]=text;
find=1;
}
}
}
if(find==1)return;
for(var k in node.attr){
//console.log('qqqq',k,node.attr[k])
if(typeof (node.attr[k])=='string' && node.attr[k].indexOf(name)>-1){
//console.error('找到1',node.tag,node.attr.text,text)
node.attr[k]=node.attr[k].replace(name,text);
//break;
}
}
if(node.text && node.text.indexOf(name)>-1){
//标签之间的
//console.error('找到2',node.tag,node.text,text)
node.text=node.text.replace(name,text);
//break;
}
if(node.childNodes && node.childNodes.length>0){
check_block_text(node.childNodes,name,text);
}
});
}
module.exports.find_block=function(nodes,vm,scope,pel){
nodes.forEach(function(node,sn){
var utag=node.utag;
if(vm.getcache().use.block[utag] || vm.getcache().check_if_import('block',vm[core_vm.aprand].absrcid,utag)){
//console.log('发现wrapper',core_vm.tool.objClone(node));
var oldparent=node.parentNode;
var oldid=node.id;
blocktext=vm.getcache().get_block_text(vm,utag);
if(!blocktext){
return;
}
//直接字符串替换
//var blocktext=blockobj;
//var obj=core_vm.tool.objClone(blockobj.childNodes);
var s=[];
for(var k in node.attr)if(s.indexOf(k)==-1)s.push(k);
for(var k in node.attrexp)if(s.indexOf(k)==-1)s.push(k);
s.forEach(function(name,i){
var text=node.attr[name];
if(!text && node.attrexp)text=node.attrexp[name];
if(i==0 && utag.indexOf('-')==-1){
if(!text && node.childNodes.length>0)text=node.childNodes[0].text;
}
if(text){
text=core_vm.calexp.exp(vm,text,scope);
//check_block_text(obj,'$'+name,text);
blocktext=blocktext.replace(new RegExp('\\$'+name, 'g'),text)
}
})
//nodes[sn]=obj[0];
//字符串
nodes[sn]=core_vm.calhtmltojson(blocktext,0,0,vm.getapp(),5)[0].childNodes[0];
nodes[sn].parentNode=oldparent;
if(oldid)nodes[sn].id=oldid;
if(node.attr.style)nodes[sn].attr.style=node.attr.style;
}
})
}
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.idclass=function(vm,node,scope){
//console.log('idclass',node.id)
//watch的早计算过了
if(node.id){
if(node.id.indexOf('{')>-1)node.id=core_vm.calexp.exp(vm,node.id,scope);
if(vm.getapp().config.strategy.not_document_getelbyid && node.id.indexOf('_elid_'+vm.sid)==-1){
var newid=core_vm.cal.forece_calnodeid(vm,node,scope,'doc');
node.oriid=node.id;
if(node.id)vm[core_vm.aprand].newid_2_oldid[newid]=node.id
node.id=newid;
}
vm.__regel('id', node.oriid||node.id, node.id);
}
if(node.attr.role){
node.id=node.id||core_vm.cal.forece_calnodeid(vm,node,scope,'role');
vm.__regel('role',node.attr.role,node.id,scope.$index);
}
node.classList=node.classList||[];
var str=node.classList.join(' ').replace(/ /g,' ').replace(/^\s*|\s*$/g, '');
if(str)node.classList=str.split(' ');
else node.classList=[];
if(node.classList.length>0 ){
for(var i=node.classList.length-1;i>-1;i--){if(node.classList[i]==='')node.classList.splice(i,1)}
}
if(node.classList.length>0){
node.id=node.id||core_vm.cal.forece_calnodeid(vm,node,scope,'class');
vm.__regel('classList',node.classList,node.id,scope.$index);
}
if(node.listid){
node.id=node.id||core_vm.cal.forece_calnodeid(vm,node,scope,'list');
vm.__regel('listel',node.listid,node.id,scope.$index);
}
}
function decapitalize(str) {
str = ""+str;
return str.charAt(0).toLowerCase() + str.slice(1);
};
module.exports.event=function(vm,node,scope,thisel){
if(!node.event)return;
core_vm.tool.each(node.event,function(funcname,event){
var event_name=decapitalize(event);
//console.log('这里绑定了el',event_name,vm.id,vm.sid,vm[core_vm.aprand].has_started)
vm[core_vm.aprand].domeventnames[event_name]=1;
if(funcname.indexOf('js:')==0){
vm[core_vm.aprand].inline_onjs.push(funcname.substr(3));//不计算 因为可能用到{}
funcname='inlinejs_on__'+(vm[core_vm.aprand].inline_onjs.length-1);
}else{
funcname=core_vm.calexp.exp(vm,funcname,scope)
}
core_vm.elset(thisel,'on-'+event_name,funcname,scope);
})
}
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports=function(vm,node,scope){
//计算表达式attrexp 条件 text
//计算bind watch
//计算vm到到bind 到 _sub_vm_tmp
var config=vm.getapp().config;
if(config.precode.indexOf(node.utag)>-1){
return;
}
var newvm;
core_vm.calexp.nodeattrexp(vm,node,scope);
if(node.id && node.id[0]=='{')node.id=core_vm.calexp.exp(vm,node.id,scope);
if(node.classList && node.classList.length>0 ){
node.classList.forEach(function(str,i){
if(node.classList[i][0]=='{')node.classList[i]=core_vm.calexp.exp(vm,str,scope);
})
node.classList=node.classList.join(' ').replace(/ /g,' ').split(' ');
}
//先计算数据 再计算style
if(node.tag=='_exptext_'){
node.text=core_vm.calexp.exp(vm,node.exp_text,scope,'_exptext_');
}
if(node.watchs){
if(node.id){
node.id=core_vm.calexp.exp(vm,node.id,scope);
}else {
node.id=core_vm.cal.forece_calnodeid(vm,node,scope,'watch');
}
//watch时 nodeid要确定因为要作为elid保存
core_vm.watchcal.cal(vm,node,scope,'common');
//text html 的初始值应该在标签之间
}
var utag=node.utag;
if(utag===config.vmtag || node.attr[config.vmtag+'-src'] || vm.getcache().vmlib[utag]||
config.path.vm[utag] || vm.getcache().check_if_import('vm',vm[core_vm.aprand].absrcid,utag)){
if(node.id=='parent'||node.id=='child')node.id='';
if(!node.id)node.id=core_vm.define.newvmid();
node.childNodes=node.childNodes||[];
node.attr=node.attr||{};
//console.error("在"+vm.id+" 发现 vm ",'utag='+utag, node.event,node);
if(node.childNodes.length>0)core_vm.inject.biaojiinject_in_calcommon(vm,scope,node.childNodes);
newvm={
src:vm.getcache().check_if_import('vm',vm[core_vm.aprand].absrcid,utag)||config.path.vm[utag]
||node.attr[config.vmtag+'-src']||node.attr.src||utag,
id:node.attr.id||node.id||core_vm.define.newvmid(),
};
if(vm.getcache().vmlib[utag]){
newvm.src=utag;
newvm.absrc=utag;
}
node.childskip_inject=1;
}
return newvm;
//接下来处理 _root_ text等标签
//接下来 处理 event bind state 各自处理
}
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
var global_vmid_seed=10;//不要为
var global_nodeid_seed=0;//不要为
var vmclass=function(id){
this.id=id;
this.__init();
//console.log('vmclass new ',this.sid,this.id)
//id用于查询 absrc用于是绝对路径 url不是绝对路径 用于 favor记录与下属href计算
//url 是引用时写的
//src 是格式化后的 mob.topvm.id=src
}
var vmproto=vmclass.prototype;
var cb=function(){}
var need_keep=['appsid','id','sid','src','absrc','pel','pvm',];
var need_keep_rand=['absrcid','pvmevent','pvmelevent','pvmnode'];
vmproto.__init=function(ifclose){
if(!ifclose){
this.sid=this.sid||(++global_vmid_seed);
this.id=this.id||('id_auto_'+String(this.sid));
}
if(ifclose){
this.__auto_unsub_app();
for(var k in this){
if(!this.hasOwnProperty(k))continue;
else if(need_keep.indexOf(k)>-1)continue;
else if(k===core_vm.aprand)continue;
else {
this[k]=null;
}
}
for(var k in this[core_vm.aprand])if(need_keep_rand.indexOf(k)==-1)delete this[core_vm.aprand][k];
//mob.views 如pop,dialog清理后才能删除
}
if(!ifclose){
this[core_vm.aprand]={};
Object.defineProperty(this,core_vm.aprand, {configurable: false,enumerable: false,writable:false});
}
let obj=this[core_vm.aprand];
//只需要来自 inject,append,start的参数
if(!ifclose){
obj.pvmevent={};//event-aa=xx cvm.pubup(aa)
obj.pvmelevent={};//on-click=ss eventdom发现不了函数时有用
obj.pvmnode=null;
}
obj.pvmslot={};//
obj.has_started=0;
obj.has_defined=0;
obj.append_data={};
obj.append_option={};
obj.datafrom_store=[];
obj.datafrom_parent=[];
obj.cbs_on_define=[];
obj.cbs_onstart=[];
obj.cbs_onclose=[];
obj.cbs_onshow=[];
}
vmproto.__clean_tmp_after_start=function(){
//来自__pvm的都没有clone
delete this[core_vm.aprand].pvmslot;
delete this[core_vm.aprand].append_data;
delete this[core_vm.aprand].append_option;
delete this[core_vm.aprand].has_started_self;
delete this[core_vm.aprand].has_defined;
delete this[core_vm.aprand].cbs_onstart;
delete this[core_vm.aprand].cbs_onshow;
delete this[core_vm.aprand].loadingsub_count;
delete this[core_vm.aprand].startcb_of_vmstart;
//根据配置 可能过早清理有问题
}
//node解析出一个 vm,就_init, start之前可能会修改其配置 setChildData ,src等 需要有基本属性
//流程是append(parse||pvm)->load(远程|cache|packed)-define->start
//close流程 最后需要新建一个vm 保持其id-src-pel-ppel-pelevnet-pelnode-,不包括pvmslot(来自pelnode)
//不包括appenddata-appendoption(只能来自手动append)
//属性类别:id-src-pel-pvm 调用时制定
//pelcb,peleveent,pelnode,pvmslot node里面指定
//append-data-option 应该与 pel部分是互斥的 类型不同
//start里面应该不包含src 只包含刷新 如果想换src 那就remove 再append
//aprand里面的是运行中需要的 不能清理的 define之前的可以清理
vmproto.__define=function(vmobj){
//style,template 保存到$cache了
//console.log('__define',this.id,this.sid)
var tvm=this;
if(typeof (vmobj)!=='object' ||vmobj===null)vmobj={};
if(vmobj.sid)delete vmobj.sid;
if(vmobj.id)delete vmobj.id;
if(vmobj.src)delete vmobj.src;
if(vmobj.pel)delete vmobj.pel;
if(vmobj.ppel)delete vmobj.ppel;
for(var k in vmobj){
if(vmproto[k]===undefined)tvm[k]=vmobj[k]; //else console.log('you can not override vm.prototype.fn',k)
}
tvm.data=tvm.data||{};
tvm.state=tvm.state||{};
tvm.option=tvm.option||{};
tvm.event=tvm.event||{};
tvm.config=tvm.config||{};
if(!Array.isArray(tvm.config.cacheClasses))tvm.config.cacheClasses=[];
//tvm.config.pelDisplayType=tvm.config.pelDisplayType||"block";
tvm.config.appendto= (tvm.config.appendto==='ppel')?'ppel':"pel";
tvm.__auto_sub_app();
//basic: sid,id,src,pel,pvm,absrc,
//interface: data,event,option,state
//config: appendto,cacheClasses,pelDisplayType
var obj=this[core_vm.aprand];
//基本的
obj.newid_2_oldid={}
obj.vmchildren={};
obj.rootscope={};
obj.nodejson=[];
//element需要的
obj.seed_of_el_aid=0;
obj.els_binded=[];//bind的 close时清除
obj.els=[];
obj.elsdom={'id':{},'class':{},'role':{},'listel':{}};
obj.private_style={};
//start中的
obj.domeventnames={};
obj.domeventnames_binded=[];
obj.cbs_onstart=[];
obj.cbs_onclose=[];
obj.cbs_onshow=[];
obj.loadingsub_count=0;
obj.has_defined=1;
obj.has_started=0;
//运行中的
obj.inline_onjs=[''];
obj.inline_watchjs=[''];
obj.watching_data={};
obj.watching_state={};
obj.watching_option={};
obj.watching_list={};
//console.error('看看define几次')
this.__ensure_fn();
return this;
}
__webpack_require__(39).setproto(vmproto);
__webpack_require__(38).setproto(vmproto);
__webpack_require__(51).setproto(vmproto);//store
__webpack_require__(42).setproto(vmproto);
__webpack_require__(43).setproto(vmproto);
__webpack_require__(44).setproto(vmproto);
__webpack_require__(41).setproto(vmproto);
__webpack_require__(45).setproto(vmproto);
__webpack_require__(48).setproto(vmproto);
__webpack_require__(46).setproto(vmproto);
__webpack_require__(47).setproto(vmproto);
__webpack_require__(50).setproto(vmproto);
__webpack_require__(40).setproto(vmproto);
__webpack_require__(49).setproto(vmproto);
//require("./vm.proto.event.js").setproto(vmproto);
//冒号放弃require("./vm.proto.pubsub.js").setproto(vmproto);
//require("./vm.proto.pubupdown.js").setproto(vmproto);
vmproto.__setsrc=function(src){
if(typeof (src)!=='string')src='';
this.src=src||'';
if(this.src){
this.absrc=_reqlib.gen_path(this.getapp(),this.src,this.pvm ?this.pvm.absrc:'',true,5);
this[core_vm.aprand].absrcid=this.getcache().geturlsid(this.absrc);
//if(this.absrc.indexOf('/webapp/')!==0)
//console.error('绝对地址',this.absrc,'相对地址',this[core_vm.aprand].absrcid)
}
}
var libbatchdom=__webpack_require__(37);
vmproto.batchdom=function(fn, ctx){
libbatchdom.set(fn, ctx)
};
vmproto.getapp=function(){
return core_vm.wap;
}
vmproto.getcache=function(){
//console.error('getcache',this.appsid,this.id,gcache.napsid[this.appsid])
return core_vm.wap.__cache;
}
for(var k in vmproto){
if(k[0]=='_')Object.defineProperty(vmproto,k,{configurable: false,enumerable:false,writable:false});
}
var _reqlib=__webpack_require__(1);
var define=function(opt,uap){
//opt是外部数据 id,src,pvm,el, | vmobj 是内部数据是vm本身
var tvm=new vmclass(opt.id);
if(opt.el)tvm.pel=opt.el;
tvm.getcache().vmsbysid[tvm.sid]=tvm;
if(opt.pvm){
tvm.getcache().vmparent[tvm.sid]=opt.pvm.sid;
tvm.pvm=opt.pvm;
tvm.pvm[core_vm.aprand].vmchildren= tvm.pvm[core_vm.aprand].vmchildren || {};
tvm.pvm[core_vm.aprand].vmchildren[tvm.id]=tvm.sid;
}
//console.log('define',tvm.id)
tvm.__setsrc(opt.src||opt.url);
return tvm;
}
module.exports={
vmclass:vmclass,
define:define,
newvmid:function(){
global_nodeid_seed++;//bindsidofvm使用
return 'id_auto_'+global_nodeid_seed;//web中不同的vm区分开来
},
protect:function(){
//console.log('保护vm')
//core.protect.protect(vmclass);
//core.protect.protect(vmproto);
//主要是不能删除 不能改写
}
}
//module.exports.protect(); //update core后 _又显示出来了
//vmproto.route=function(hash,cb){if(typeof (hash)=='string' && core_vm.isfn(cb))core_vm.route(hash).bind(cb,this);}
//vmproto.navigate=function(hash,title,force){core_vm.route.navigate(hash,title,force);}
module.exports.extend=function(name,fn){
if(core_vm.isfn(fn))vmproto[name]=fn;//可能会失败 因为configurable=false
}
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
var hook=function(name,vm,el,when,node,libid){
var fn=vm.getcache().use.elhook[name] || (vm.getcache().jslib[libid]?vm.getcache().jslib[libid].exports:null);
if(core_vm.isfn(fn)){
try{
fn.call({},vm,el,when,node);
}catch(e){
core_vm.devalert(vm,'el-hook.'+name+':'+when,e)
}
}
}
module.exports=function(vm,el,src,when,node){
var name=src; //value可以其他途径取得
//console.log('hook',name)
//when: selfCreated,childrenCreated,attached
if(name.indexOf('this.')==0){
var fn=core_vm.tool.objGetDeep(vm,name.substr(5));
if(core_vm.isfn(fn)){
try{
fn.call({},vm,el,when,node);
}catch(e){
core_vm.devalert(vm,'el-hook.'+name+':'+when,e)
}
}
if(when=='childrenCreated'){
vm.__addto_onshow(function(){
fn.call({},vm,el,'attached',node);
})
}
return;
}
if(vm.getcache().use.elhook[name]){
hook(name,vm,el,when,node);
if(when=='childrenCreated'){
vm.__addto_onshow(function(){
hook(name,vm,el,'attached',node);
})
}
return;
}
//return;
var opt={
app:vm.getapp(),
loadvm:vm,pvmpath:vm.absrc,
url:vm.getapp().config.path.elhook[name]||name,
type:'lib',
fresh:false,
from:'loadelhook',elhook_second_times:(when=='childrenCreated'?true:false),
refsid:vm[core_vm.aprand].absrcid
};
var fresh=vm._is_fresh_ing ;//只有mob.top可以设置
opt.fresh=fresh;
//console.log('需要elhook',when,el.childNodes.length)
core_vm.require.load(opt,function(err,mod,spec){
if(err){
core_vm.onerror(vm.getapp(),'load_elhook_fail',spec.id,vm.absrc,err);
return;
}else if(core_vm.isfn(mod)){
//console.log('hook下载',name,spec);
if(vm.getapp().config.path.elhook[name]){
vm.getcache().use.elhook[name]=mod;
delete vm.getcache().jslib[spec.id];
hook(name,vm,el,when,node);
}else{
hook(name,vm,el,when,node,spec.id);
}
if(when=='childrenCreated'){
//selfCreated
vm.__addto_onshow(function(){
hook(name,vm,el,'attached',node,spec.id);
})
}
}
//console.log("下载 elhook",mod);
});
}
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
var check_event_type=function(vm,e){
if(!vm || !vm[core_vm.aprand].domeventnames[e.type]){
//console.log('page not bind this event,: '+e.type)
return true;
}
}
module.exports.get_owner=function(e){
var el=e.target,owner;
while(1){
if(el.hasAttribute('owner')){owner=el.getAttribute('owner');break;}
if(el.hasAttribute('bindsidofvm')){break;}
el=el.parentNode;
if(!el ||!el.hasAttribute)break;
}
return owner;
}
module.exports.stopEvent=function(e){
e.stopPropagation();//阻止事件冒泡,但不阻击默认行为 可以避免其他所有DOM元素响应这个事件
//e.preventDefault(); //不阻击事件冒泡,但阻击默认行为 可以在触发默认操作之前终止事件 例如click <a>后的跳转
}
module.exports.get_funcname=function(e,vm){
//on-click-self表示不capture下级 就是下级 算了 可以在函数里面自己解决
var funcname='',str='on-'+e.type;
var el=e.target;
if(el.attributes[str+'-self']) funcname=el.attributes[str+'-self'].value;
else if(el.attributes[str]) funcname=el.attributes[str].value;
//else if(el.attributes[str+':capture']) funcname=el.attributes[str+':capture'].value;
else{
while(1){
if(el.attributes['isvmpel']){
break;
}else if(el.attributes[str]){
funcname=el.attributes[str].value;
break;
}else if(el.attributes['href']){
funcname='href:'+el.attributes['href'].value;
break;
}else if(el.hasAttribute('bindsidofvm')){
break;
}else{
el=el.parentNode;
if(!el || el==document || el==document.body)break;
}
}
}
return funcname+'';
}
var goto_pelevent=function(e,vm){
//return
//设计是用来找不到函数式由pvm定义在pel上的函数 实际上 vm定义在pel上就可以了
var funcname,pel=vm.pel,pvm=vm.pvm;
funcname=core_vm.elget(pel,'on-'+e.type);
module.exports.stopEvent(e);
if((!funcname ||funcname=='parent') && vm[core_vm.aprand].pvmelevent[e.type])funcname=vm[core_vm.aprand].pvmelevent[e.type];
//pel.on-click 传递给 vm[core_vm.aprand].pvmelevent
//console.error('pelevent 2',funcname,vm.id);//,pvm,pel,vm.id
if(!funcname){
//console.log('!funcname')
return;
}
var fn=core_vm.getprefn(pvm,'domevent',funcname);
if(!fn){
//console.log('!fn')
return;
}
core_vm.tryfn(pvm,fn,[e],'vm.domevent.pelevent');
}
module.exports.all=function(e,thisvm){
//e.type=click
//if(e.source.sn==undefined)return;//自动生成的如listview的item
//module.exports.stopEvent(e);//必须根据情况 处理
//if(check_event_type(this.vm,e))return;
//console.log('domevent',this,thisvm.id);
//this=事件的开始者;
var funcname=core_vm.eventdom.get_funcname(e,thisvm);
//console.log("dom 事件",e.type,'this.id='+this.id,funcname);//,'utag='+e.source.utag,e.source.id,
//list里面的 要得到index 可以从e.source向上 找placeholder 然后找顺序 太麻烦 现在是给函数加参数 xxx({$index})在计算时候得到index
//console.log("dom 事件",e.type,"funcname="+funcname,'this.id='+thisvm.id,e.target,'vm.id='+thisvm.id,thisvm.url);//thisvm.data,
//全部不冒泡
if(funcname=='auto'){
var elid=thisvm[core_vm.aprand].newid_2_oldid[e.target.id]||e.target.id;
funcname=elid+'.'+e.type;
}else if(!funcname||funcname=='parent'){
//取消 都停止向上冒泡if(true!==thisvm.domevent.bubbleParent)
module.exports.stopEvent(e);
//很多情况是跨越了el的边界 如touch定义在一个el上 手指移动超出边界时 找不到fn
//console.log('没有funcname',thisvm.id);
goto_pelevent(e,thisvm);
//pel.on-click不会被利用 只有找不到函数式 到pvm执行定义在pel上的相同事件
return ;//不管return 什么 都会继续冒泡
}else if(funcname.indexOf('href:')===0){
module.exports.stopEvent(e);
return;//route处理
}
var tvm=thisvm;//事件目标所在的vm
var funcpara;
if(funcname.substr(0,3)!='js:' && funcname.substr(0,3)!='to:' ){
var tmp=core_vm.tool.parse_func_para(funcname);
funcname=tmp[0];
funcpara=tmp[1];
}
var owner=module.exports.get_owner(e);
if(owner && owner!='self'){
if(owner=='parent'){
tvm=thisvm.pvm;
}else{
tvm=thisvm.getcache().vmsbysid[owner];//thisvm._getgvm(owner);
}
}
if(!tvm){
//console.error("找不到目标 vm");
module.exports.stopEvent(e);return;
}
//事件系统:目的是尽量隔离 bubbleParent=false 找不到函数不冒泡 找到执行后返回值为true才冒泡
//vm.domevent.bubbleParent 默认为false 如果为true 找不到 funcname会向上冒泡
//funcname为四种 on-click=xxx,xxx(a,b,c),to-dataname,js:xxx
//在vm内部找触发的funcname 优先级on-click:self,on-click,on-click:capture
//e.target自身没有,找parent的on-click:capture
//console.log("func_process_real",funcname);
var result;
funcpara=funcpara||'';
var fn;
//console.log(e.source)
//console.log("准备,funcname=",funcname);
var fn=core_vm.getprefn(tvm,'domevent',funcname);
if(!core_vm.isfn(fn))fn=tvm.getcache().use.domevent[funcname];
if(core_vm.isfn(fn)){//包含js函数funcname.indexOf('js:')==0 &&
//console.log("已有编译的函数",funcname);
var array=[e].concat(funcpara.split(','));
if(funcname.substr(0,4)=='app.'){
result=core_vm.tryfn(thisvm.getapp(),fn,array,'vm.domevent.app');
}else{
if(funcname.indexOf('inlinejs_on__')==0)array=[e,thisvm.getapp()];
result=core_vm.tryfn(tvm,fn,array,'vm.domevent.inline');
}
}else if(funcname.indexOf('inlinejs_on__')==0){
var jsid=parseInt(funcname.replace('inlinejs_on__',''));
if(jsid>0){
var str=tvm[core_vm.aprand].inline_onjs[jsid];
tvm[core_vm.aprand].inline_onjs[jsid]='';//提到这里 vm.close后可能找不到位置了
//console.log('inlinejs',jsid,str,thisvm.id,tvm.id)
var fn;
try{
fn=new Function("e,app",str);
result=fn.call(tvm,e,thisvm.getapp());
}catch(error){
error.funcname=str;
core_vm.onerror(tvm.getapp(),'inlinejs_fn_error',tvm.absrc,error);
result=false;
}
if(core_vm.isfn(fn))tvm[funcname]=fn;
else tvm[funcname]=function(){};
}
}else if(funcname.substr(0,7)=='todata-' ||funcname.substr(0,8)=='tostate-'){
//console.error('change',funcname);//,e
//on-change="todata-name" on-return,on-check,
var el=e.target;
var newvalue= e.type=='check'?el.checked:(e.type=='change'&&el.value!='on'?el.value:(el.checked!=undefined?el.checked:el.value));
//radio的value一直是on
if(funcname.substr(0,7)=='todata-'){
funcname=funcname.substr(7).replace('this.data.','');
var oldv=core_vm.tool.objGetDeep(tvm.data,funcname);
if(oldv!==newvalue)tvm.__autobind_setData(funcname,newvalue,oldv);
}else if(funcname.substr(0,8)=='tostate-'){
funcname=funcname.substr(8).replace('this.state.','');
var oldv=core_vm.tool.objGetDeep(tvm.state,funcname);
if(oldv!==newvalue)tvm.__autobind_setstate(funcname,newvalue,oldv);
}
result=false;
}else{
core_vm.tryfn(tvm,tvm.onerror,[e,'domevent'],'onerror.no.fn');
core_vm.devalert(tvm,"no function,tvm.id=",tvm.id,'funcname='+funcname );//,tvm,e.target
//module.exports.stopEvent(e);
}
//总是停止
module.exports.stopEvent(e);
//如果不停止 引发pvm.pel的事件 但是 e.souce还是一个 找到的funcname也是一样,thisvm不同 会找到错误的函数
//console.log('结果',result,funcname,tvm.id,fn)
//if(!result)
}
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
var _requirecache=__webpack_require__(2);
module.exports.onload=function(spec,cb,meta,template,style_str,extend_from,when){
//extend_from 有错误也无所谓
//console.log('准备扩展')
var mod_from=_requirecache.get(spec.app,spec.vm,extend_from,'','vm','genmod_2',spec.urlsid)||{};
var mod_me= _requirecache.get(spec.app,spec.vm,spec.id, '','vm','genmod_1',spec.urlsid)||{};
_requirecache.extendvm(spec.app,spec.id,extend_from);
//console.log('扩展onload',extend_from,'template='+template.length);
//此处复杂
spec.app.__cache.add_ref('vm',extend_from,spec.urlsid,'vmextend');
if(mod_from){
mod_from=core_vm.tool.objClone(mod_from);
for(var k in spec.vm){
delete mod_from[k];//避免原型的设定覆盖 this.data等直接写的 并且要求原型一定要export
}
core_vm.tool.deepmerge_notreplace(mod_me,mod_from);//target,src 顺序不能变 原则是 新的如果有 就不改变
}
var newbody,oldbody=spec.app.__cache.get_body_extend(extend_from);
var fn=mod_me.extendTemplate || spec.vm.extendTemplate
if(core_vm.isfn(fn)){
try{
newbody=fn.call(spec.vm,oldbody,template);
}catch(e){
core_vm.devalert(spec.app,'extendTemplate',e)
}
}else{
newbody=template||oldbody;
}
var newstyle='',oldstyle=spec.app.__cache.get_vmstyle_extend(extend_from);
var fn=mod_me.extendStyle || spec.vm.extendStyle;
if(core_vm.isfn(fn)){
try{
newstyle=fn.call(spec.vm,oldstyle,style_str);
}catch(e){
core_vm.devalert(spec.app,'extendStyle',e)
}
}else{
newstyle=style_str||oldstyle;
}
spec.app.__cache.add_vmbody(spec.id,newbody,1);
spec.app.__cache.add_vmstyle_inline(spec.id,newstyle);
//console.log('扩展onload 完成')
//todo meta没有保存 二次扩展时找不到 meta只有一个用途 title 2018-04-08
cb(null,mod_me);
};
module.exports.inmem=function(app,vm,id,extend_from){
//console.log('扩展 inmem')
var mod_from=_requirecache.get(app,vm,extend_from,'','vm','extendinmem')||{};
var mod_me= _requirecache.get(app,vm,id, '','vm','extendinmem')||{};
mod_from=core_vm.tool.objClone(mod_from);
for(var k in vm)delete mod_from[k];//保护
core_vm.tool.deepmerge_notreplace(mod_me,mod_from);//target,src 顺序不能变 原则是 新的如果有 就不改变
return mod_me;
}
/***/ }),
/* 18 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.biaojiinject_in_calcommon=function(vm,scope,nodes){
//console.log("inject 标记",vm.id,vm.id,scope.aid);
nodes.forEach(function(node,sn){
//这一层不能标记 多次证明了2017-9-19
core_vm.inject.biaojiinject_level_1(vm,scope,node.childNodes);
});
}
module.exports.biaojiinject_level_1=function(vm,scope,nodes){
nodes.forEach(function(node,sn){
node.$injectscope=scope;
node.$injectfromvm_sid=vm.sid;//node绝对不能直接关联vm 否则clone时max-size mem
node.attr=node.attr ||{};
node.attr.owner='parent';//多层传递 parent 是不是可以
//只需要标记第一级
});
}
module.exports.inject_one_string=function(pvm,vm,utag,text,where){
var type=typeof (vm[where][utag]);
var caninject=true;
//console.log("inject_one_string",utag,type,text);
if(type=='undefined')vm[where][utag]=text;
else if(type=='boolean')vm[where][utag]=Boolean(text);
else if(type=='number')vm[where][utag]=Number(text);
else if(type=='float')vm[where][utag]=parseFloat(text);
else if(type=='string')vm[where][utag]=String(text);
else if(type=='object'){
if(typeof (text)=='string'){
var fn=new Function("e",'return [ '+text+' ] ');
var obj;
try{
obj=fn.call({},null);
}catch(e){}
if(obj)text=obj[0];
}
if(typeof (text)=='object'){
if(Array.isArray(vm[where][utag]) && Array.isArray(text) )vm[where][utag]=text;
else if(!Array.isArray(vm[where][utag]) && !Array.isArray(text) )vm[where][utag]=text;
else caninject=false;
}else{
caninject=false;
}
}else{
vm[where][utag]=text;
}
//console.log('注入后',where,vm.id,vm[where])
if(caninject){
if(vm[core_vm.aprand].datafrom_parent.indexOf(utag)===-1)vm[core_vm.aprand].datafrom_parent.push(utag);
}
}
module.exports.cal_inject_node=function(vm,innode){
var new_data_node={tag:'data',utag:'data',attr:{},attrexp:{},childNodes:[]};
var new_attr_node={tag:'option',utag:'option',attr:{},attrexp:{},childNodes:[]}
var finddata=0,findattr=0;
if(innode.dataset){
//把dataset转移过来
for(let k in innode.dataset)innode.attr['data-'+k]=innode.dataset[k]
}
core_vm.tool.each(innode.attr,function(v,k){
if(k=='id' || k=='style' || k=='role' || k=='event'|| k==vm.getapp().config.vmtag+'-src')return;
if(k.indexOf('data-')===0){
k=k.substr(5);
finddata=1;
if(v.indexOf('{')==0)new_data_node.attrexp[k]=v;
else new_data_node.attr[k]=v;
}else if(k.indexOf('option-')===0){
k=k.substr(7);
findattr=1;
if(typeof (v)=='string' && v.indexOf('{')==0)new_attr_node.attrexp[k]=v;
else new_attr_node.attr[k]=v;
}
})
if(finddata==1)innode.childNodes.push(new_data_node);
if(findattr==1)innode.childNodes.push(new_attr_node);
}
module.exports.inject_from_pvm_before_start=function(vm){
//console.log("计算附加node,vm.id="+vm.id,vm[core_vm.aprand].pvmnode);
//<apple option-x=1><data a=1 b=2/><node name=1><btn /><node></apple>
if(!vm[core_vm.aprand].pvmnode ){
return;
}
var pvm=vm.pvm;
var innode=core_vm.tool.objClone(vm[core_vm.aprand].pvmnode);
//console.log('innode',innode,vm[core_vm.aprand].pvmnode)
//slot的都是clone过得
innode.childNodes.forEach(function(node,sn){
if(!core_vm.isobj(node))return;
node.attr=node.attr||{};
if(node.utag=='option' || node.utag=='data'){
vm[node.utag]=vm[node.utag]||{};
if(node.attrexp){
for(var k in node.attrexp)node.attr[k]=node.attrexp[k];
}
for(var k in node.attr){
//有可能是boold number if(typeof (node.attr[k])=='string')continue;
var text=node.attr[k];//不能去掉 {}因为可能是json
if(typeof (node.attr[k])!=='string' || text.indexOf('this.')==-1){
module.exports.inject_one_string(pvm,vm,k,text,node.utag);
continue;
}
var watch_path=text.replace(/^\{*|\}*$/g, '').replace('this.','');
var in_data=core_vm.tool.objGetDeep(pvm,watch_path);
if(in_data==undefined){
in_data=core_vm.calexp.exp(pvm,text,pvm[core_vm.aprand].rootscope,'_exptext_');//复杂表达式的注入
}
if(typeof (in_data)=='object'){
in_data=core_vm.tool.objClone(in_data);
}
module.exports.inject_one_string(pvm,vm,k,in_data,node.utag);
}
}else{
if(node.attr.slot){
//console.log('slot',node.attr.slot)
vm[core_vm.aprand].pvmslot[node.attr.slot]=node;
}else{
//console.log('没有插槽name')
vm[core_vm.aprand].pvmslot[core_vm.aprand]=vm[core_vm.aprand].pvmslot[core_vm.aprand]||[];
vm[core_vm.aprand].pvmslot[core_vm.aprand].push(node);
}
}
});
}
module.exports.use_inject_nodes_when_create=function(tvm,node,scope){
//检查child
//这个node 是cvm的node
node.attrexp=node.attrexp||{};
if(scope && node.attrexp && node.attrexp.name){
node.attrexp.name=core_vm.calexp.exp(tvm,node.attrexp.name,scope);
}
var pnode=node.parentNode;
var pc=node.parentNode.childNodes;
var index=pc.indexOf(node);
//console.log('node.',index);
var name=!scope ?'' :(node.attr.name||node.attrexp.name);
//main slot 先找 没有scope
//console.log("use_inject_nodes_when_create",node.attr.name,tvm[core_vm.aprand].pvmslot);
if(scope && name){
//注入<div slot=22></div> //引用<slot name=nodeaa>default</slot>
var res=tvm[core_vm.aprand].pvmslot[name];
if(res){
//index==-1是因为数组的原因 就不能插入到原parent下面只能替代
if(index===-1){
//是数组里面的 clone了node的
node.tag=res.tag;
node.utag=res.utag;
node.attr={};
for(var k in res.attr)node.attr[k]=res.attr[k];
//其他不要了
node.childNodes=res.childNodes;
//不能再加了 child已经加了node.attr.owner='parent';
}else{
pc.splice(index,1,res);
pc[index].parentNode=pnode;
return pc[index];
}
module.exports.bind_vm_pvm_when_inject_node(tvm,res);
}
}else if(!scope && tvm[core_vm.aprand].pvmslot[core_vm.aprand]){
var index=pc.indexOf(node);
//console.log('slot.main',index)
if(index==-1)index=0;
pc.splice(index,1);
var mainslots=tvm[core_vm.aprand].pvmslot[core_vm.aprand];
//console.log('mainslots',mainslots)
for(var k=0;k<mainslots.length;k++){
mainslots[k].attr.owner='parent';
module.exports.bind_vm_pvm_when_inject_node(tvm,mainslots[k]);
pc.splice(index+k,0,mainslots[k]);
mainslots[k].parentNode=pnode;
//彻底代替原来的<slot></slot>
}
//console.log('main',node.parentNode.childNodes)
}
//console.log("发现node 最终路径",abpath,res,node);
}
module.exports.bind_vm_pvm_when_inject_node=function(tvm,node){
//inject node创建时使用来源vm, childvm可能没有绑定事件 这里提前标记
//不是原生的节点 本vm如果要响应click需要附加绑定
//console.log("bind_vm_pvm_when_inject_node",node,pnode);
if(!node)return;
if(node.event){
for(var k in node.event){
//console.log('增加tvm事件',tvm.id,k)
tvm[core_vm.aprand].domeventnames[k]=1;
}
}
if(node.childNodes && node.childNodes.length>0){
for(var i=0,len=node.childNodes.length;i<len;i++)module.exports.bind_vm_pvm_when_inject_node(tvm,node.childNodes[i]);
}
}
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
var lopt_aid=0;
module.exports.gendata=function(vm,node,scope,pel){
//console.log('---gendata')
var array=node.dir.list.split(' in ');
array[1]=core_vm.calexp.exp(vm,array[1],scope);
var abpath=core_vm.cal.now_path(scope,array[1],vm,'listgen');
//if(abpath.indexOf('this.data.')!==0)abpath='this.data.'+abpath;//.substr(9);
//if(abpath.indexOf('this.')!==0)abpath='this.data.'+abpath;
//abpath=abpath.substr(5);
abpath=abpath.replace(/^\s*|\s*$/g, '').replace(/\[([\s\S]*?)\]/g,function(a,b){
return "."+b+".";//方括号转成点
}).replace(/^\.*|\.*$/g, '').replace(/\'|\"/g, '');
var listdata;
if(abpath.indexOf('this.')===0)listdata=core_vm.tool.objGetDeep(vm,abpath.substr(5));
else listdata=core_vm.tool.objGetDeep(vm.data,abpath);
//console.log('list.gendata.abpath',abpath,listdata);
return [array,abpath,listdata];
}
var g_classid=0;
var gen_watch_listclass=function(node){
//console.log(node.dir,node.watchs)
//数组里面需要watch的加入_list_id 比如删掉index=0的,index=1的自动提升,
//修改index=0,根据_list_id找出一个el数组 第一个就是要找的el 但是要根据page的情况 甚至page也应该由datastore控制
if(node.watchs){
//每个list需要watch的 根据 listid 重新生成 node.id 保证id不重复
//然后regel到listel 用getel('@'+id)可以找到
//watch时 watch.listid
//数据变化时 watching_data里面储存有path 根据listid 找出 els 根据path找出index 就找到具体的那个el了
node.listid=++g_classid;
}
if(node.childNodes)node.childNodes.forEach(function(cnode){gen_watch_listclass(cnode)})
}
module.exports.gen=function(vm,node,scope,pel){
node.id='';
//console.log("list.gen abpath="+abpath,'list='+node.dir.list,listdata);
var tmp=module.exports.gendata(vm,node,scope,pel);
var array=tmp[0],abpath=tmp[1],listdata=tmp[2];
if(!Array.isArray(listdata)){
core_vm.onerror(vm.getapp(),'list_data_not_array',vm.absrc,{path:abpath},listdata);
return;
}else{
//console.log("发现数组",listdata);
gen_watch_listclass(node);
var new_scope={
alias:array[0],
palias:array[1],
path:abpath,
pscope:scope,
};
new_scope.listdata=listdata;
new_scope.$index=0;
//console.log("找到 listdata,abpath=",abpath);
var lopt={
vm:vm,
node:node,
scope:new_scope,
//aid:lopt_aid++
};
var listing;
//暂时支持attr,state的数组add-del
//if(abpath.indexOf('this.option')==0)listing=vm.__listing_option;
//else if(abpath.indexOf('this.state')==0)listing=vm.__listing_state; else
listing=vm[core_vm.aprand].watching_list;
listing[abpath]=listing[abpath]||[];
listing[abpath].push(lopt);
lopt.pel=pel;
vm.__addto_onstart(function(){
if(pel.nodeName=='#document-fragment' && pel.id==vm.id+'__tmp')lopt.pel=vm.pel;
});
lopt.sn_in_parent=pel.childNodes.length;
for(var k=0,len=listdata.length;k<len;k++){
core_vm.list.new_node(k,listdata[k],lopt,lopt.sn_in_parent+k,'init');
}
}
//return false;
}
module.exports.$add=function(lopt,k,v){
//console.log('增加了回调', k,v,sid,this,lopt );
var insert_pos=core_vm.list.get_fel_sn_in_parent(lopt,'add')+k;
core_vm.list.new_node(k,v,lopt,insert_pos,'add');
}
module.exports.$delat=function(lopt,index,oldv){
var sn_in_parent=core_vm.list.get_fel_sn_in_parent(lopt,'delat');
var childs=lopt.pel.childNodes;
lopt.vm.delel(childs[sn_in_parent+index]);
}
module.exports.$clean=function(lopt){
//var listdata=this;
var sn_in_parent=core_vm.list.get_fel_sn_in_parent(lopt,'clean');
//console.log("sn_in_parent="+sn_in_parent,listdata.length);
for(var i=this.length-1;i>-1;i--)lopt.vm.delel(lopt.pel.childNodes[sn_in_parent+i]);
}
module.exports.$rebuild=function(lopt){
//放弃 改为sort后自动
//console.log('更新了',this,this.length);//this是listdata
var sn_in_parent=core_vm.list.get_fel_sn_in_parent(lopt,'rebuild');
for(var k=0,len=this.length;k<len;k++){
core_vm.list.new_node(k,this[k],lopt,sn_in_parent+k,'rebuild');
}
}
module.exports.new_node=function(k,v,lopt,insert_pos,where){
//console.log("--list new_node",where);
//lopt.node.parentNode=null;
var scope_node=core_vm.tool.objClone(lopt.node);
delete scope_node.dir.list;
delete scope_node['id'];
lopt.scope.$index=k;
core_vm.cal.nodeid(lopt.vm,scope_node,lopt.scope);
core_vm.create.nodes(lopt.vm,scope_node,lopt.scope,lopt.pel,insert_pos,true);
}
module.exports.get_fel_sn_in_parent=function(lopt){
return lopt.sn_in_parent;
}
/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
var _reqlib=__webpack_require__(1);
module.exports=function(vm,cb){
if(vm[core_vm.aprand].has_defined || vm[core_vm.aprand].has_started ||!vm.src){
//console.log('vm.can not load cause of has_start || has_defined',vm.id,vm[core_vm.aprand].has_started,vm.src)
return;
}
if(!core_vm.isfn(cb))cb=function(){}
if(vm.getcache().vmlib[vm.src]){
//path-use 已经有了
vm.getcache().add_ref('vm',vm.src,vm[core_vm.aprand].absrcid,'loadsub');
vm.__define(core_vm.tool.objClone(vm.getcache().vmlib[vm.src].exports));
vm.absrc=vm.src;
vm.__initdata_then_start(cb);
return;
}
//console.log("loadvm 开始,id=",vm.id,'vmsrc='+vm.src,vm.__load_fresh,vm.pvm[core_vm.aprand].absrcid);
var pvm=vm.pvm;
if(pvm)pvm[core_vm.aprand].loadingsub_count++;
var fresh=vm._is_fresh_ing ;
//fresh=false;//websocket更新
var opt={
app:vm.getapp(),
loadvm: pvm, pvmpath :pvm.absrc,
url: vm.absrc||vm.src,
type :'vm',
from: 'loadvm', fresh :fresh,
urlsid:vm[core_vm.aprand].absrcid,
refsid:pvm[core_vm.aprand].absrcid,
vm:vm,
};
_reqlib.cal_spec_path(opt);
core_vm.require.load(opt,function(err,mod,spec){
//下载错误 到这里
//js 执行错误不到这里 mod会是
if(err){
core_vm.onerror(vm.getapp(),'load_vm_fail',spec.id || vm.src,err);
if(pvm){
pvm[core_vm.aprand].loadingsub_count--;
if(pvm[core_vm.aprand].loadingsub_count==0){
pvm.__onstart_a_zero_sub()
}
}
cb.call(vm,err);
}else{
//console.log('动态加载vm成功',mod.__extend_from,spec.id);
vm.__define(mod);
vm.absrc=spec.id;
if(vm[core_vm.aprand].cbs_on_define){
for(var k in vm[core_vm.aprand].cbs_on_define)vm[core_vm.aprand].cbs_on_define[k]();//获得absrc
vm[core_vm.aprand].cbs_on_define=[];
}
vm.__initdata_then_start(cb);
}
});
}
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
var _reqlib=__webpack_require__(1);
var _libcal=__webpack_require__(52);
var _requirecache=__webpack_require__(2);
var load_pending={};
if(1){
// we make use of XHR
if(XMLHttpRequest===undefined || typeof XMLHttpRequest === "undefined")
XMLHttpRequest = function () {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
throw new Error("This browser does not support XMLHttpRequest.");
};
}
//3处都是clone
//1.load时找到并 克隆 require(id)
//2.load->download_ok->evalResponse->evalResponse_genmod 此处克隆->cb_mod_with_extend_from 此处克隆两个
//require execute error 错误可以在chrome下看到哪一行 js_SyntaxError 看不到
var setparaxhr=function(xhr,cacheexpire,cache_text){
if(gcache.user.logintoken)xhr.setRequestHeader('logintoken',gcache.user.logintoken);
else xhr.setRequestHeader('clientid',gcache.clientid||'');
xhr.setRequestHeader('client-time',new Date().toUTCString());
if(!cacheexpire ||!cache_text)return;
//console.log("cacheexpire",cacheexpire);
if(cacheexpire && cacheexpire.lastmodify)xhr.setRequestHeader('If-Modified-Since',cacheexpire.lastmodify);
if(cacheexpire && cacheexpire.etag)xhr.setRequestHeader('If-None-Match',cacheexpire.etag);
}
function load(spec,callback) {
//spec:url,type,app, loadvm,pvmpath,
//from,fresh,method,data
//console.log('要下载',spec.type,spec.url,spec.text?'已有text':'')
//console.error('===load===',spec.url,spec.fresh);//,spec.app.id
if(typeof callback!='function') callback=function(){};
if(typeof spec === 'string') spec = {url: spec};
if (!spec.url) {
//console.error("缺少 属性spec",spec);
callback({type:'missing both url and id'},null,spec);
return;
}
//vm load时加上refsid
if(!spec.refsid ){
console.log('没有refsid',spec.url)
callback({type:'missing spec.refsid'},null,spec);
return;
}
if(!spec.urlsid) spec.urlsid=spec.app.__cache.geturlsid(spec.url);
_reqlib.cal_spec_path(spec);
if(spec && spec.text){
spec.callback=callback;
//console.log('有了text',spec.text.length,typeof (callback))
//为index设计的 先loadfile('text' 先解析app.js 然后解析index.html 目的是为了同时下载 先解析app.js
download_act(xhr,'onload',spec,'',null,true);
return;
}
//console.log("load cal_spec_path 后",spec.url,spec.pvmpath,spec.id );
if(spec.url==spec.pvmpath ||(spec.pvm && spec.url==spec.pvm.absrc) ||
spec.id==spec.pvmpath ||(spec.pvm && spec.id==spec.pvm.absrc)){
//console.error("url 重复",spec.id,spec.url,spec.pvmpath);
if(!spec.istop){
callback(new Error("url duplicate"),null,spec);
return;
}
}
//console.log("load cal_spec_path 后",spec.url,spec.id,spec.from );
//url带http id不带http
if(spec.url.indexOf('http://www.localhost.com/')==0){
spec.fresh=true;
var cache_text=gcache.fileroot.get_text('mydevapps/'+spec.url.replace('http://www.localhost.com/',''));
find_cache_file_mob(spec,cache_text,callback);
return;
}
if(load_pending[spec.url]){
load_pending[spec.url].push([spec,callback]);
//console.log('有pending',spec.url)
return;
}
if (spec.elhook_second_times || (!spec.fresh )){
//elhook_second_times:elhook第二次就不再下载,
//jslib都是作为deps出现的
//jslib都在vm的require的缓存里面 都不需要再load
//jslib在一个页面出现后,再在另外一个页面出现 如果abspath相同 不需要再load 自动找到
//jslib的id也转成 /xxx/yyy的abs路径
//vm的id都是 /xxx/yyy/xxx.vm等 根目录与location的根目录是一样的
//lib的id 是 spec.app.config.path.lib 或者当前vm里面的 可以是 ./aaa.js
//console.log("检查require 缓存",spec.id,spec.url,spec);
var module=_requirecache.get(spec.app,spec.vm,spec.id,'',spec.type,'check',spec.urlsid);
if(module){
//console.log("==find_cachevm_inrequie",spec.id);
find_cachevm_inrequie(module,spec,callback);
return;
}else{
//console.log("没有找到 require 缓存",spec.url,spec);
}
}
//
//todo 此处的顺序要严格 有reqcache用reqcache 有filecache用,并且自动进入reqcache
var cache_text='';
//console.log('是否下载 ',spec.url ,load_pending[spec.url]);
//console.log('将要下载,fresh=',spec.fresh,spec.loadfilefresh,spec.url);
var xhr;
xhr=new XMLHttpRequest();
xhr.hascallbacked=0;
load_pending[spec.url]=[[spec,callback]];
xhr.onreadystatechange = function (e) {
//console.log("\n\n\nonreadystatechange",'readyState='+xhr.readyState,'status='+xhr.status,xhr.hascallbacked);
//autoRedirect
if (4 != xhr.readyState){
//console.log("转向",spec.url,xhr.location );
return;
}else if (0 == xhr.status) {
download_act(xhr,'download_timeout',spec,cache_text);
}else{
//console.log('onreadystatechange',xhr.readyState,xhr.location);//,xhr.getheaderobj()
download_act(xhr,'readystatechange',spec,cache_text);
}
};
xhr.onload = function () {
download_act(xhr,'onload',spec,cache_text);
};
xhr.onerror = function (error) {
core_vm.devalert(spec.app,'onerror.xhr',xhr.location,error)
download_act(xhr,'download_error',spec,cache_text,error);
};
try{
xhr.open('GET',spec.url, true);
if(spec.fresh){
//xhr.setRequestHeader("fresh","true"); //fresh时总会返回304
}
xhr.send(null);
}catch(e){
//console.log('http 错误 捕捉');//一般捕捉不到
xhr.onerror.call(xhr,'error-catched')
}
//devtools 打开时总是fresh 否则 总是取缓存
}
function download_act(xhr,type,spec,cache_text,error,withtext){
if(withtext){
//mob已经解过密了
_libcal.evalResponse(0,spec,spec.text,function(err,mod){download_ok_pendingcb(spec,err,mod);},loads);
return
}
if(xhr.hascallbacked==1){
//console.error('已经在处理了',spec.url)
return;//mob 有可能过来多次
}else{
//console.error('还没有处理',spec.url)
xhr.hascallbacked=1;
}
if(!load_pending[spec.url])return;
//console.log("下载完成",spec.url,xhr.location,xhr.getAllResponseHeaders() );//,xhr.getResponseHeader('encrypt'),xhr.getAllResponseHeaders()
//if(spec.url!=xhr.location){
//console.error("下载转向了",spec.url,xhr.location );
spec.url_goto=xhr.location;
//}
//console.log("xhr."+type,spec.url,'xhr.readyState='+xhr.readyState,'xhr.status='+xhr.status,'xhr.hascallbacked='+xhr.hascallbacked);
var sucess=0;
if(type=='onload'){
sucess=1;
}else if(type=='readystatechange'){
if ((xhr.status < 300 && xhr.status >= 200) || (xhr.status === 0 && !spec.url.match(/^(?:https?|ftp):\/\//i))){
sucess=1;
}else{
sucess=0;
type='download_error'
}
}
//console.log('下载完成',spec.id,sucess)
var xhr_responseText=sucess>0 ? xhr.responseText:'';
if(1){
var result=core_vm.onload(spec.app,spec.url,xhr,spec);
if(result)xhr_responseText=result;//解决less sass的问题
}
//url相同 type相同 赋予的使命不同
if(1){
if(sucess==0){
download_ok_pendingcb(spec,{type:type,url:spec.url,status:xhr.status,xhr:xhr} );//
}else if(sucess==1){
_libcal.evalResponse(3,spec,xhr_responseText,function(err,mod){download_ok_pendingcb(spec,err,mod);},loads);
}
}
}
function download_ok_pendingcb(spec,error,mod){
//console.log("pendingcb",spec.url,error);
var cbs=[];
var specs=[];
var first_type='';
if(!load_pending[spec.url]){//withtext
cbs[0]=spec.callback;
specs[0]=spec;
first_type=spec.type;
}else{
var len=load_pending[spec.url].length;
for(var k=0;k<len;k++){
cbs.push(load_pending[spec.url][k][1]);
specs.push(load_pending[spec.url][k][0]);
}
first_type=load_pending[spec.url][0][0].type;
delete load_pending[spec.url];
}
if(error){
cbs.forEach(function(cb,i){ cb(error,null,specs[i]); });
}else{
cbs.forEach(function(cb,i){
let spec=specs[i];
if(spec.type=='css'){
spec.app.__cache.loadok_style(spec,mod);
cb(null,mod,spec);
}else if(spec.type=='text'){
cb(null,mod,spec);
}else if(spec.type=='block'){
spec.app.__cache.loadok_block(spec,mod);
cb(null,mod,spec);
}else{//lib,vm
if(spec.urlsid){
//console.log('下载完了',spec.type);
//同时两个vm 第一个 运行了 函数 第二个 没有 只是等待 exports 不行
if(spec.type=='vm'){
spec.app.__cache.add_ref('vm',spec.id,spec.refsid,'loadok');
}
if(spec.type=='lib'||spec.type=='json'){
spec.app.__cache.add_ref('lib',spec.id,spec.refsid,'loadok');
}
}
if(first_type=='text' && spec.type=='lib'){
//console.log('第一个是text后面是lib',typeof (mod),'重新来过')
spec.text=mod;
core_vm.require.load(spec,cb);
}else if(spec.type=='vm'){
//genmod尝试过了 _requirecache.get(spec.app,spec.vm,spec.id,'','vm','pendingok',spec.urlsid);
//console.log('啊啊啊啊',spec.id)
cb(null,clone_mod(mod,spec),spec);
}else{
cb(null,clone_mod(mod,spec),spec);
}
}
});
}
}
//find in mem,file,http 都统一到 pending来
function clone_mod(mod,spec){
if('css'==spec.type)return null;
else if('lib'==spec.type)return mod;
else if('vm'==spec.type)return core_vm.tool.objClone(mod);//全部clone 因为有可能打开再关闭 需要在require.cache保存原始
else if('text'==spec.type)return mod;
else return null;
}
//clone 的时机 find_cachevm_inrequie,find_cache_file_mob,evalResponse->pendingcb//保证正确克隆 不浪费
function find_cache_file_mob(spec,cache_text,loadcb){
//console.log("发现mob filecache",cache_text);
_libcal.evalResponse(4,spec,cache_text,function(err,mod){
loadcb(err,clone_mod(mod,spec),spec);
//spec.callback=loadcb;
//download_ok_pendingcb(spec,err,mod);
},loads);
}
function find_cachevm_inrequie(mod,spec,loadcb){
console.log("find_cachevm_inrequie",spec.type,mod.__extend_from);
//这里是提前下载或者多个vm公用一个vm
//js lib模块不到这里来 直接 require('abc') 了
loadcb(null,clone_mod(mod,spec),spec);//一定要克隆 extend工作已经做好了
}
function loads(urls, callback) {
//console.error("loads");
if(!Array.isArray(urls))urls=[urls];
var len = urls.length;
var errs = [];
var mods = [];
var specs=[];
var errcount = 0;
urls.forEach(function (url, i) {
if(!url){
len--;
return;
}
load(url, function (err, mod,spec) {
if (err) errcount++;
errs[urls.indexOf(url)] = err;
specs[urls.indexOf(url)] = spec;
mods[urls.indexOf(url)] = mod||{};//错误给个默认的{}
len--;
if (len == 0) callback(errcount, errs, mods,specs);
})
});
}
module.exports={}
module.exports.load = load;
module.exports.loads = loads;
module.exports.normalizeUrl=_reqlib.normalizeUrl;
//load.opt={loadvm,pvmpath}
//loadobj={url,type,fresh,from} from=deps,loadelhook,loadvm,web-init,mob-appopenpage
/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {
//<wrapper html=''> </wrapper>
var core_vm=__webpack_require__(0);
module.exports.setstore=function(app){
if(!app.store||(typeof(app.store)!=='object' && typeof(app.store)!=='function')){
app.store={};
}
if(!core_vm.isfn(app.store.init))app.store.init=function(cb){cb()};
if(!core_vm.isfn(app.store.vminit))app.store.vminit=function(cvm,cb){cb()};
if(!core_vm.isfn(app.store.get))app.store.get=function(cvm,path,cb){cb()};
if(!core_vm.isfn(app.store.set))app.store.set=function(cvm,path,value,cb){cb()};
if(!core_vm.isfn(app.store.add))app.store.add=function(cvm,path,index,value,cb){cb()};
if(!core_vm.isfn(app.store.del))app.store.del=function(cvm,path,index,cb){cb()};
}
var defconf={
isdev:false
,precode:['pre','code']
,vmtag:'vm'
,strategy:{
not_document_getelbyid:false,
auto_deepclone_store_data:true,
force_close_error_close_tag:true,
force_close_not_match_close_tag:true,
append_to_pel_wait_loading_child_vm:true,
setChildState:true,
cacheClassesAll:true,
}
,path:{
lib:{},vm:{},block:{},elhook:{},
}
}
module.exports.checkappconfig=function(app,obj){
//3次 空白一次 app.js setconfig一次 最后检查一次
//console.error('checkappconfig',obj,'app.sid='+app.sid)
app.config=app.config||app.pageconfig||{};
var apconf=app.config;
if(obj==0){
for(var k in defconf){
if(Array.isArray(defconf[k])){
apconf[k]=[];
for(var m in defconf[k])apconf[k].push(defconf[k][m])
}else if(typeof (defconf[k])=='object'){
apconf[k]={};
for(var m in defconf[k]){
apconf[k][m]=defconf[k][m];
}
}else{
apconf[k]=defconf[k];
}
}
apconf.precode_regexp={};
for(var k in apconf.precode){
apconf.precode_regexp[apconf.precode[k]]=
new RegExp('<'+apconf.precode[k]+'([\\s\\S]*?)>([\\s\\S]*?)<\/'+apconf.precode[k]+'>', 'gi');
}
}else if(obj==1){
for(var k in apconf){
if(defconf[k]!==undefined && typeof(defconf[k])!==typeof(apconf[k])){
delete apconf[k];
}
}
for(var k in defconf){
if(apconf[k]==undefined)apconf[k]=core_vm.tool.objClone(defconf[k]);
}
for(var k in apconf.strategy){
if(typeof(defconf.strategy[k])!==typeof(apconf.strategy[k]))delete apconf.strategy[k];
}
for(var k in defconf.strategy){
if(apconf.strategy[k]==undefined)apconf.strategy[k]=defconf.strategy[k];
}
apconf.precode_regexp={};
for(var k in apconf.precode){
if(typeof(apconf.precode[k])!=='string')delete apconf.precode[k];
}
for(var k in apconf.precode){
apconf.precode_regexp[apconf.precode[k]]=
new RegExp('<'+apconf.precode[k]+'([\\s\\S]*?)>([\\s\\S]*?)<\/'+apconf.precode[k]+'>', 'gi');
}
apconf.blockpath_regexp={};
for(var k in apconf.path){
if(typeof(apconf.path[k])!=='object')delete apconf.path[k];
}
for(var k in apconf.path.block){
apconf.blockpath_regexp[k]=new RegExp('<'+k+' ', 'gi');
}
var _reqlib=__webpack_require__(1);
for(var k in defconf.path){
if(apconf.path[k]==undefined)apconf.path[k]={};
for(var m in apconf.path[k]){
if(typeof(apconf.path[k][m])!=='string')delete apconf.path[k][m];
apconf.path[k][m]=_reqlib.gen_path(app,apconf.path[k][m],'',true,4);
//提前计算
}
}
//console.log('apconf',apconf.path)
}
//console.log('最终', app.config)
}
/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
var app_loaded=false;
var index_loaded=false;
module.exports.init=function(){
app_loaded=false;
index_loaded=false;
}
var start_index_vm=function(app,index_vm,mycb){
//console.error('start_index_vm');
if(typeof (app.hookStart)!=='function')app.hookStart=function(cb){cb();}
app.hookStart(function(){
index_vm.__initdata_then_start(mycb);
})
}
var start_index_and_app=function(app,index_vm,cb){
//console.log('开始 index-app都下载完了',app_loaded,index_loaded)
start_index_vm(app,index_vm,cb);
}
var start_parse_index=function(app,file_indexvm,index_vm,cb,where){
//console.error('start_parse_index',where,app.indexvm_text.length)
if(app.indexvm_text==='' || !app_loaded){
//if(app.indexvm_text=='')console.error('app.indexvm_text 没有下载')
//if(!app_loaded)console.error('app.js 没有下载')
return;
}
//console.error('index app.js都下载完了')
if(app.indexvm_text===true){
//没有index文件
cb();
return;
}
index_vm[core_vm.aprand].absrcid=1;
//console.error('1开始start_parse_index',file_indexvm,app.indexvm_text.length)
core_vm.require.load({
app:app,
loadvm:null,pvmpath:'',
url:file_indexvm,
type:'vm',from:'file_indexvm',
text:app.indexvm_text,
//urlsid:index_vm.sid,
urlsid:1,
refsid:1,
vm:index_vm
},function(err,mod,spec){
//console.log("加载 完成 index 文件",err,where, typeof (cb));
delete app.indexvm_text;
if(err){
core_vm.devalert(index_vm,'load file_indexvm fail');
if(typeof (cb)=='function')cb('error');
}else{
for(var k in mod){
index_vm[k]=mod[k];
}
}
index_vm.absrc=spec.id ;
index_loaded=true;
start_index_and_app(app,index_vm,cb);
});
}
var start_system=function(app,file_app,file_indexvm,index_vm,cb){
//console.error('0开始start_system',file_app,file_indexvm,typeof (cb))
app.indexvm_text='';
if(file_indexvm){
app.loadfile('text',file_indexvm,function(err,text){
app.indexvm_text=text;
start_parse_index(app,file_indexvm,index_vm,cb,3);
});
}else{
app.indexvm_text=true;//web 没有indexvm文件
start_parse_index(app,file_indexvm,index_vm,cb,4);
}
//有index 先下载 等待 app.js 汇合
//无index 汇合等待app
//有app 下载解析 与index会和
//无app 汇合 等待index
if(file_app){
//app.loadfile('text',file_app,function(err,text){ })
core_vm.require.load({
app:app,
loadvm:null,pvmpath:'',
url:file_app,type:'lib',from:'file_app',
urlsid:2,
refsid:2,
vm:null,
},function(err,mod,spec){
//console.log("加载完成 app.js 文件",err);//,mod
if(err){
core_vm.devalert(index_vm,'load app fail ');
}
core_vm.rootvmset.checkappconfig(app,1);
core_vm.rootvmset.setstore(app);
app_loaded=true;
start_parse_index(app,file_indexvm,index_vm,cb,1);
});
}else{
core_vm.rootvmset.checkappconfig(app, {});
core_vm.rootvmset.setstore(app);
app_loaded=true;
start_parse_index(app,file_indexvm,index_vm,cb,2);
}
}
module.exports.start_system=start_system;
module.exports.start_index_vm=start_index_vm;
/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
var global_rootvm={},index_vm={}
var check_body_when_not_file_indexvm=function(){
core_vm.wap.indexvm[core_vm.aprand].has_started=1;
var s=Object.keys(core_vm.wap.config.path.vm);
s.push(core_vm.wap.config.vmtag);
//var el_src=document.body.querySelectorAll("[vm-src]") ;
var el_src=document.body.querySelectorAll(s.join(',')) ;//或者其他标签
//var el_name=vm.pel.querySelectorAll("[vm-name]") ;//name直接调用注册的vm
var elsall=[];
[].forEach.call(el_src,function(el){ elsall.push(el)});
[].forEach.call(elsall,function(el){
//console.log('checkbody',el)
if(el.hasAttribute('autostart') && el.getAttribute('autostart')==false)return;
var json={};
json.src=core_vm.wap.config.path.vm[el.localName]||el.getAttribute('src') || '';
json.id=el.getAttribute('id') || '';
var nodes=[];
el.childNodes.forEach(function(node){
//这里不处理了
el.removeChild(node);
});
//el.childNodes=[];
//此处需要对index.body下的元素解析
//event,injectnodes,data,attr style
//pvm,el,id,src,pelevent,node,cb
var vm=core_vm.define.define({pvm:core_vm.wap.indexvm,el:el,id:json.id,src:json.src});
core_vm.load(vm,function(vm){
//console.log('checkbody.top vm',vm)
})
});
}
var start_system=function(){
//core_vm.rootvmset.checkappconfig(core_vm.wap,'web');
var file_app,file_indexvm;
var scripts= document.getElementsByTagName('script');
//console.log(scripts)
for (var i = scripts.length - 1; i > -1; i -= 1) {
if(scripts[i].dataset['role']==='vmix'){
if(scripts[i].hasAttribute('app-file') || scripts[i].hasAttribute('index-file') ) {
file_indexvm=scripts[i].getAttribute('index-file');
file_app=scripts[i].getAttribute('app-file');
break;
}
}
}
module.exports.root=global_rootvm;
index_vm=core_vm.define.define({id:'__index__',pvm:null});
index_vm.__define({});
index_vm[core_vm.aprand].pvmevent={};
index_vm.pel=document.body;
module.exports.index=index_vm;
core_vm.wap.indexvm=index_vm;
index_vm.absrc=window.location.pathname;
var dirpath=window.location.pathname;
dirpath=dirpath.substr(0,dirpath.lastIndexOf('/'));
window.location.dirpath=dirpath;
var u = window.location.protocol + '//' + window.location.hostname;
if (window.location.port && window.location.port !== 80) {
u += ':' + window.location.port;
}
//u+=dirpath;
window.location.fullhost=u;
//console.log('web',file_app,file_indexvm)
core_vm.rootvmstart.init();
core_vm.rootvmstart.start_system(core_vm.wap,file_app,file_indexvm,index_vm,function(){
if(!file_indexvm){
check_body_when_not_file_indexvm();
}
//console.error('web.system.started')
});
}
module.exports.start_system=start_system;
//从外边启动,不需要docreay
/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.web=function(vm){
//console.log('开始startvm',vm.id,vm.pel);
//html附加模式不能实现 一个vm下的child一起启动 只能一个一个启动 靠id找下级的vm
if(!vm.pel.style.display && vm.config.pelDisplayType)vm.pel.style.display=vm.config.pelDisplayType;
var fragment = document.createDocumentFragment();
fragment.id=vm.id+'__tmp'
vm.__top_fragment=fragment;
core_vm.create.nodes(vm,vm[core_vm.aprand].nodejson[0],vm[core_vm.aprand].rootscope,fragment);
}
/***/ }),
/* 26 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
var vm_tool={}
vm_tool.objGetDeep=function(obj,name){
//todo 考虑实际 也许 attr['a.b.c']是一个属性而不是attr.a.b.c 多级的应该自己指定
//console.log('objGetDeep name='+name);
//log(obj)
if(obj==undefined)return obj;
if(!(typeof obj =='object') || !(typeof name =='string') ){
//error('1')
return undefined;
}
name=name.replace(/^\s*|\s*$/g, '').replace(/\[([\s\S]*?)\]/g,function(a,b){
//console.log('发现方括号',a,b)
//[1]也转为.2便于遍历
//error('2')
return "."+b+".";
}).replace(/^\.*|\.*$/g, '').replace(/\'|\"/g, '');
//console.log('2 objGetDeep name='+name);
var r_obj=obj;
var parts = ~name.indexOf('.') ? name.split('.') : [name];
//console.log("objGetDeep",parts,r_obj);
for (var i = 0; i < parts.length; i++){
r_obj = r_obj[parts[i]]
if(r_obj===undefined){
break;
}
}
return r_obj;
//对于该函数的参数obj修改obj本省在函数外是无效的 修改 obj的属性在函数外有效 所有可以返回obj的内部属性而不影响obj本身
};
vm_tool.objSetDeep=function(obj,name,value,ifnew){
if(!obj || !(typeof obj =='object') || !(typeof name =='string') )return false;
if(name.indexOf('.')==-1){
if(ifnew || obj[name]!=undefined)obj[name]= value;
}else{
var p = name.split('.') ;
var len=p.length;
var err=0;
var n=[];
n[0]=obj;
//console.log("objSetDeep",obj,name,value);
for(var i=1;i<len;i++){
//console.log("objSetDeep",typeof p[i-1],p[i-1] );
if(Array.isArray(n[i-1]) ){
//p[i-1]=n[i-1].$sid.indexOf( parseInt(p[i-1] ));//.substr(4)
//console.log("真的是",p[i-1],n[i-1]);
p[i-1]=parseInt(p[i-1]);
}
if(ifnew && n[i-1][p[i-1]]==undefined){
n[i-1][p[i-1]]={}
}
n[i]=n[i-1][p[i-1]];
if(typeof n[i]!='object' || n[i]===null){
//console.log("错误",i,n[i]);
err=1;
break;
}
}
if(!err){
n[len-1][p[len-1]]=value;
//console.log("没有错误",n);
}
}
//return obj;
}
vm_tool.deepmerge=function(target, src) {
if(typeof target!=='object' ||typeof src!=='object' )return;
if(!Array.isArray(src) && Array.isArray(target))return;//src=[src];
if(Array.isArray(src) && !Array.isArray(target))return;
//here not deepclone
for(var k in src){
if(target[k]===undefined){
if(!core_vm.isobj(src[k])){
target[k]=src[k];
}else{
target[k]=vm_tool.objClone(src[k]);
}
}else if(!core_vm.isobj(src[k])){
target[k]=src[k];
}else if(Array.isArray(src[k])){
target[k]=[];
src[k].forEach(function(e, i) {
if(typeof e === 'object'){
target[k][i]={};
vm_tool.deepmerge(target[k][i], e);
}else{
target[k][i]=e;
}
});
}else{
vm_tool.deepmerge(target[k], src[k]);
}
}
}
vm_tool.deepmerge_notreplace=function(target, src) {
if(typeof target!=='object' ||typeof src!=='object' )return;
for(var k in src){
if(target[k]==undefined){
if(!core_vm.isobj(src[k])){
target[k]=src[k];
}else{
target[k]=vm_tool.objClone(src[k]);
}
}else if(core_vm.isobj(target[k]) && core_vm.isobj(src[k])){
vm_tool.deepmerge_notreplace(target[k], src[k]);
}
//关键是不能覆盖
}
}
vm_tool.trim=function(str){
//去除字符串头尾空格与tab
//return str.replace(/^[\s\t ]+|[\s\t ]+$/g, '');
return str.replace(/^\s*|\s*$/g, '');//.replace(/[\r\t\n]/g, " ");
}
vm_tool.trimquota=function(str){
//去除字符串头尾 ' "
//return str.replace(/^[\s\t ]+|[\s\t ]+$/g, '');
return str.replace(/^[\'\"]*|[\'\"]*$/g, '');//.replace(/[\r\t\n]/g, " ");
}
vm_tool.parse_func_para=function(str){
var res=[str,undefined];
str.replace(/(.*?)\((.*?)\)(.*?)/g, function (all,a, b){
//没有括号 all也没有
res[0]=vm_tool.trim(a);//函数名
res[1]=vm_tool.trim(b);//.split(",");//函数参数
});
return res;
}
vm_tool.parse_kv_para=function(str){
var parames = {};
//允许az09AZ -.[]
var array=str.split(";");
if(array.length==1)array=str.split(",")
for(var i=0,len=array.length;i<len;i++){
array[i].replace( /(.+)=(.+)/g, function(a, b, c){
//console.log(a, b, c);
parames[b] = c;
});
}
return parames;
}
vm_tool.objClone=function (obj,ifproto){
if(!obj)return obj;
if(obj instanceof core_vm.define.vmclass)return obj;
if(typeof (obj)!=='object'){
var a=obj;
return a;
}
if(obj.nodeType!==undefined ||obj.nodeName!==undefined )return obj;
//typeof ==function 已验证
// 直接通过普通赋值的方式,就实现了函数的克隆,并且不会影响之前的对象。原因就是函数的克隆会在内存单独开辟一块空间,互不影响。
var newobj;
if(Array.isArray(obj)){
newobj=new Array(obj.length);
for(var i=0,len=obj.length;i<len;i++){
if(typeof obj[i]=='object')newobj[i]=vm_tool.objClone(obj[i],ifproto);
else newobj[i]=obj[i];
}
}else{
if (obj.constructor == Object){
newobj = new obj.constructor();
}else{
newobj = new obj.constructor(obj.valueOf());
}
for(var k in obj){
if(!obj.hasOwnProperty(k) ||newobj[k] === obj[k] )continue;//有时对象嵌套 HTML EVENT不能克隆
//console.log('clone',k,typeof(obj[k]))
if(!obj[k]){
newobj[k] = obj[k];
}else if(k=='parentNode' && obj[k].tag ){
newobj[k] = obj[k];
//此处是特殊处理的 有时候要clone node
}else if (typeof(obj[k]) === 'object' ){
if(obj[k].nodeType!==undefined ||obj[k].nodeName!==undefined )newobj[k]=obj[k];
else{
//console.log('clone',k,obj[k])
newobj[k] = vm_tool.objClone(obj[k]);
}
}else{
newobj[k] = obj[k];
}
}
}
if(ifproto){
newobj.toString = obj.toString;
newobj.valueOf = obj.valueOf;
}
return newobj;
};
vm_tool.multiline = function (fn){
if (typeof fn !== 'function'){
throw new TypeError('Expected a function.');
}
//var match = reCommentContents.exec(fn.toString());
var match = /\/\*!?(?:\@preserve)?[ \t]*(?:\r\n|\n)([\s\S]*?)(?:\r\n|\n)\s*\*\//.exec(fn.toString());
if (!match){
throw new TypeError('Multiline comment missing.');
return '';
}
match[1]=match[1].replace(/\/\/.*?[\r\n]/g,'');
return match[1].replace(/\/\/.*?[\r\n]/g,'').replace(/\/\/.*?$/g,'');//最后一行用rn不能表示
};
vm_tool.each = function (obj, fn, context) {
// Iterate over array-like objects numerically.
if (obj != null && obj.length === +obj.length) {
for (var i = 0; i < obj.length; i++) {
fn.call(context, obj[i], i, obj);
}
} else {
for (var key in obj) {
// Use the Object prototype directly in case the object we are iterating
// over does not inherit from `Object.prototype`.
if (Object.prototype.hasOwnProperty.call(obj, key)) {
fn.call(context, obj[key], key, obj);
}
}
}
};
var _htmlescapehash= {
'<': '<',
'>': '>',
'&': '&',
'"': '"',
"'": ''',
'/': '/'
};
var _htmlunescapehash= {
'<':'<',
'>':'>',
'&':'&',
'"':'"',
''':"'",
'/':'/'
};
var _htmlescapereplace= function(k){
return _htmlescapehash[k];
};
var _htmlunescapereplace= function(k){
return _htmlunescapehash[k];
};
vm_tool.htmlescape=function(str){
return typeof(str) !== 'string' ? str : str.replace(/[&<>"]/igm, _htmlescapereplace);
}
vm_tool.htmlunescape=function(str){
return typeof(str) !== 'string' ? str : str.replace(/(<|>|&|"|'|/)/igm, _htmlunescapereplace);
}
module.exports=vm_tool;
/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
var check_array_repeat=function(s,listid,index){
//数组都加在0位置 就重复了
var len=s.length;
for(var i=len-1;i>-1;i--){
if(s[i].listid && s[i].listid ==listid && s[i].$index==index){
s.splice(i,1);
}
}
}
var calnode_watch=function(vm,node,scope,where){
//thisel,pel,
if(!node.watchs )return;
//<input type=text bind=xxx />
//< watch-a-b='cc(12)-to-s'> 监控a.b数据变化 调用 cc函数 返回值 赋给 el.s
//< watch-a-b-watch-c-d='cc(12)-to-s'> 监控 a.b , c.d 数据变化
//<a>aa{bb},ss{ddd}</a> 作为一个表达式监控 到 to-text
//console.log('计算 监控对象=','scope.path='+scope.path,'scope.alias='+scope.alias,where,node.watchs,vm.id);
//node.id已经计算过了
var watchs=node.watchs;
for (var j = 0,len=watchs.length; j<len; j++){
var dataname=watchs[j][0];
var elattr=watchs[j][1];
if(elattr.indexOf('js:')!==0 && elattr[0]=='{')elattr=core_vm.calexp.exp(vm,elattr,scope);
//计算过了
node.id=node.id||core_vm.cal.forece_calnodeid(vm,node,scope,'watch');
var wopt={
vm:vm,
node:node,//node 可以不要 只要 exp_text
elid:node['id'],
scope:scope,
action:'prop',
$index:scope.$index
};
if(node.listid)wopt.listid=node.listid;
var func,para,toelattr
if(elattr.indexOf('js:')==0){
//wopt.watchfunc= elattr;
vm[core_vm.aprand].inline_watchjs.push(elattr.substr(3));
wopt.watchfunc='inlinejs_watch__'+(vm[core_vm.aprand].inline_watchjs.length-1);
wopt.watchpara=null;
}else if(elattr.indexOf('-toel-')>0){
var array=elattr.split('-toel-');
wopt.toelattr=array[1];
var tmp=core_vm.tool.parse_func_para(array[0]);
wopt.watchfunc= tmp[0];
wopt.watchpara= tmp[1];
}else if(elattr.substr(0,5)=='toel-'){
wopt.toelattr=elattr.substr(5);
}else{
var tmp=core_vm.tool.parse_func_para(elattr);
wopt.watchfunc= tmp[0];
wopt.watchpara= tmp[1];
}
var watch_path=core_vm.cal.now_path(scope,dataname,vm,'watch_path');
//console.log("dataname="+dataname,'watch_path='+watch_path);
var key=watch_path.substr(watch_path.lastIndexOf('.')+1);
if(watch_path[0]=='[' && watch_path[watch_path.length-1]==']')watch_path=watch_path.substr(1,watch_path.length-2);
watch_path=watch_path.replace(/\[/g,'.').replace(/\]/g,'');
if(watch_path[0]=='.')watch_path=watch_path.substr(1);
if(where=='noel'){
//console.log('noel',wopt,watch_path)
wopt.elid=-2;
}
//console.error('监控对象,str='+dataname,'elid='+wopt.elid,'watch_path='+watch_path);//'vmid='+vm.id,'path='+scope.path,'alias='+scope.alias,
if(watch_path.indexOf('.-1')>-1){
alert("watch_path.indexOf('.-1')>-1");
continue;
}
var watch_obj=vm.data;
var if_is_state='data';
if(watch_path.indexOf('this.data.')==0){
watch_path=watch_path.substr(10);
watch_obj=vm.data||{};
if_is_state='data';
}else if(watch_path.indexOf('this.state.')==0){
watch_path=watch_path.substr(11);
watch_obj=vm.state||{};
if_is_state='state';
}else if(watch_path.indexOf('this.option.')==0){
watch_path=watch_path.substr(12);
watch_obj=vm.option||{};
if_is_state='option';
}
var value=core_vm.tool.objGetDeep(watch_obj,watch_path);
if(!wopt.watchfunc){
//没有watchfunc 就有 toelattr 就已经被计算过了
// && wopt.toelattr && node.tag!=='_exptext_'
}else if(wopt.watchfunc){
if(wopt.node.tag!=='_exptext_'){
vm.__addto_onshow(function(){
//console.log('第一次watch.cb',wopt.watchfunc,watch_path,wopt.elid,document.getElementById(wopt.elid))
core_vm.watchcb.watch(wopt,watch_path,'',value);
});
}
}
//console.log('=================real watch',watch_path,scope.$index)
var watching=vm[core_vm.aprand]['watching_'+if_is_state];
if(watching){
watching[watch_path]=watching[watch_path]||[];
if(scope.$index!==undefined)check_array_repeat(watching[watch_path],wopt.listid,wopt.$index)
watching[watch_path].push(wopt);
}
}
}
exports=module.exports={
cal:calnode_watch,
}
//<button each="book in books" title="{book.name}" ></button>
//watch-sss-watch-xxx=funcname
//watch-sss='toel-style-width' 监控两个属性
//watch-sss='yyy-to-style-width' 监控两个属性到 dater.yyy返回值到style-width
//watch-sss=xxx(123) 到函数 sss(a,el) a=123
/***/ }),
/* 28 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.watch=function(wopt,path,oldv,newv){
//传递el还是el.id
//传递el 当el被删除时 需要递归到doc才能最终确定 因为el.parent也可能被删除
//mod 需要设计一个类似 document.getElementById(wopt.elid)
//vm。getel 需要倒推判断 el.getParent().children.indexOf(el)是否为-1 如果是说明被清理 需要设为null
//console.error("_watch_cb",this,'wopt.elid='+wopt.elid,'path='+path,'oldv=',oldv,'newv=',newv,'action='+wopt.action,'toelattr='+wopt.toelattr);//
if(typeof (wopt)!=='object'){
return;
}
//console.log('变了,path='+path,'oripath='+wopt.oripath,wopt.elid,oldv,newv,wopt.vm.id);
//'scope.aid='+wopt.scope.aid,'elid='+wopt.elid,document.getElementById(wopt.elid)
//'toelattr='+wopt.toelattr,oldv+' --> '+newv'wopt.$sid[0]='+wopt.$sid[0],wopt.$sid
//console.log('变了,vm.id='+wopt.vm.id,'wopt.scope.$sid='+wopt.scope.$sid);
var vm=wopt.vm;
var el;
if(wopt.el){
el=wopt.el;//listview计算的新的el
}else{
el=document.getElementById(wopt.elid);
if(!el && vm.getapp().config.strategy.not_document_getelbyid && wopt.elid.indexOf('_elid_')==-1){
el=vm.getel("#"+wopt.elid);
//没有el有时原因是注册watch时的node.id=test 后来被改成_elid_112 需要getel一下就可以了
}
}
if(!el){
core_vm.devalert(vm,'no el',wopt.elid,path);
vm.__delel_watchcb_notfind(wopt.elid);
return;
}else{
var result=newv,bindtype=wopt.toelattr;
//console.log('有el',el,'newv='+newv,'bindtype='+bindtype);
if(!wopt.watchfunc){
//console.log('是否需要计算呢?',path,wopt)
wopt.vm.__reset_list_index(wopt);
if(wopt.node.tag=='_exptext_' || wopt.node.utag=='_exptext_'){
//web下是tag 直接创建text mob是utag tag被改为label
result=core_vm.calexp.exp(wopt.vm,wopt.node.exp_text,wopt.scope,'_exptext_');
//console.log('修改了result',result)
}else if(wopt.node.attrexp && wopt.node.attrexp[bindtype]){
//console.log('复杂表达式 位于内部')
result=core_vm.calexp.exp(wopt.vm,wopt.node.attrexp[bindtype],wopt.scope,'_exptext_2');
}else{
result=newv;
}
}else{
var event;
event={el:el,path:path,oldv:oldv,newv:newv};
var result;
var funcname=wopt.watchfunc;
var fn=core_vm.getprefn(vm,'dataevent',funcname);
if(core_vm.isfn(fn)){
try{
if(funcname.indexOf('inlinejs_watch__')==0)result=fn.call(vm,event,wopt.watchpara,vm.getapp());
else result=fn.call(vm,event,wopt.watchpara);
}catch(e){
core_vm.devalert(vm,'dataevent error',e)
}
//console.log('计算返回',result)
}else if(funcname.indexOf('inlinejs_watch__')==0){
var jsid=parseInt(funcname.replace('inlinejs_watch__',''));
if(jsid>0){
var str=vm[core_vm.aprand].inline_watchjs[jsid];
try{
var fn=new Function("e,para,app",str);
result=fn.call(vm,event,wopt.watchpara,vm.getapp());
vm[funcname]=fn;
}catch(error){
vm[funcname]=function(){};
core_vm.devalert(vm,'dataevent error',e)
}
vm[core_vm.aprand].inline_watchjs[jsid]='';
}
}
}
//console.log('有el',el,'result='+result,'bindtype='+bindtype);
if(bindtype && result!==undefined){
//不需要 需要手动介入的直接到一个函数就可以了
//console.log('可以修改dom,newv=',result)
//if(vm.beforeElAutoUpdate.call(vm,{el:el,type:bindtype,newv:result,datapath:path})!==false)
vm.batchdom(function(){
//console.log('real')
core_vm.watchcb.setweb(el,bindtype,result,wopt,path);
});
}
}
}
module.exports.setweb=function(el,bindtype,newv,wopt,path){
//console.log('cb bind web', 'bindtype='+bindtype,newv);
if(bindtype=='html')bindtype='innerHTML';
else if(bindtype=='class')bindtype='className';
//console.error("数据变化引发 setweb",el,bindtype,newv,typeof (newv));
if(core_vm.isfn(core_vm.wap.__cache.use.dataevent[bindtype])){
core_vm.wap.__cache.use.dataevent[bindtype](el,newv,wopt,path);
}else if(bindtype=='innerHTML' || bindtype=='html'){
el.innerHTML=newv;
}else if(bindtype=='text'){
if(el.textContent !=undefined)el.textContent=newv;
else if(el.text !=undefined)el.text=newv;//mob
else if(el.innerText !=undefined)el.innerText=newv;
//console.log(el.textContent,el.text,el.innerText)
}else if(bindtype=='value' || bindtype=='className'){
el[bindtype]=newv;
}else if( bindtype=='checked' || bindtype=='disabled' ){
el[bindtype]= (newv+''==='true') ? true :false;
}else{
var array=bindtype.split('-');
if(array.length==1)array=bindtype.split('.');
if(array.length==1){
el[array[0]]=newv;
}else if(array.length==2 ){
if(array[0]=='attr')el.setAttribute(array[1],newv);
else if(array[0]=='data')el.dataset[array[1]]=newv;
else if(array[0]=='style')el.style[array[1]]=newv;
else core_vm.tool.objSetDeep(el,array.join('.'),newv,false);
}
}
//http://www.jianshu.com/p/rRssiL JavaScript中的property和attribute的区别
}
/***/ }),
/* 29 */
/***/ (function(module, exports) {
//https://github.com/jfriend00/docReady/blob/master/docready.js
var readyList = [];
var readyFired = false;
var readyEventHandlersInstalled = false;
var ready=function () {
if (!readyFired) {
readyFired = true;
for (var i = 0; i < readyList.length; i++) {
readyList[i].fn.call(window, readyList[i].ctx);
}
readyList = [];
}
}
var readyStateChange=function () {
if ( document.readyState === "complete" ) {
ready();
}
}
module.exports.docReady = function(callback, context) {
if (readyFired) {
setTimeout(function() {callback(context);}, 1);
return;
} else {
readyList.push({fn: callback, ctx: context});
}
if (document.readyState === "complete" || (!document.attachEvent && document.readyState === "interactive")) {
setTimeout(ready, 1);
} else if (!readyEventHandlersInstalled) {
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", ready, false);
window.addEventListener("load", ready, false);
} else {
document.attachEvent("onreadystatechange", readyStateChange);
window.attachEvent("onload", ready);
}
readyEventHandlersInstalled = true;
}
}
//把web的 config文件 及其 配置系统 转到 mob
/***/ }),
/* 30 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
var g_classid=1;//全局的 多个vm一起的
module.exports.add=function(vm,text){
//console.log("私有 add_private_style",vm.absrc,text);
var id=vm.sid;
//console.log("add_private_style id="+id);
var css=vm[core_vm.aprand].private_style;
text=text.replace(/\.\s{0,}([-\w]+){/g,function(a,b,c){
css[b]=css[b]||'priv_'+(g_classid++);
return '.'+css[b]+'{';
});
text=text.replace(/\.\s{0,}([-\w]+)\s{1,}/g,function(a,b,c){
css[b]=css[b]||'priv_'+(g_classid++);
return '.'+css[b]+' ';
});
//console.log('css.add',id,text)
//mob 不支持私有 style对每个页面起作用
var curStyle=document.getElementById("_privatestyle_"+id);
if(!curStyle){
var curStyle = document.createElement('style');
curStyle.type = 'text/css';
curStyle.id="_privatestyle_"+id;
curStyle.appendChild(document.createTextNode(text));
document.getElementsByTagName("head")[0].appendChild(curStyle);
}else{
curStyle.textContent+='\n'+text;
}
}
module.exports.get=function(vm,name){
var css=vm[core_vm.aprand].private_style;
//console.log('css.get',id,css,name,css[name])
if(!css)return '';
return css[name] || '';
}
module.exports.check=function(vm,node){
//console.log("use_private_style vm.absrc="+vm.absrc,node.attr);
var css=vm[core_vm.aprand].private_style;
if(!css)return;
node.classList.forEach(function(name,i){
if(css[name]){
node.classList[i]=css[name];
}
})
}
/***/ }),
/* 31 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
core_vm.aprand='vm'+(new Date()).getTime().toString();
core_vm.define=__webpack_require__(14);
//core_vm.hook=require('../corevm/vm.hook.js');
core_vm.load=__webpack_require__(20),
core_vm.extend=__webpack_require__(17);
core_vm.start=__webpack_require__(25);
core_vm.elhook=__webpack_require__(15);
core_vm.inject=__webpack_require__(18);
core_vm.calhtmltojson=__webpack_require__(8);
core_vm.cal = __webpack_require__(6);
core_vm.calexp=__webpack_require__(7);
core_vm.calif=__webpack_require__(9);
//core_vm.calblock=require('../corevm/vm.calblockwrapper.js');
//core_vm.watchlib=require('../corevm/vm.watchlib.js');
core_vm.watchcal=__webpack_require__(27);
core_vm.watchcb=__webpack_require__(28);
core_vm.create=__webpack_require__(10);
core_vm.createcommon=__webpack_require__(12);
core_vm.createvm=__webpack_require__(13);
core_vm.createblock=__webpack_require__(11);
core_vm.list=__webpack_require__(19);
//core_vm.listholder=require('../corevm/vm.listholder.js');
core_vm.eventdom=__webpack_require__(16);
core_vm.tool=__webpack_require__(26);
core_vm.require=__webpack_require__(21);
core_vm.rootvmset=__webpack_require__(22);
core_vm.rootvmstart=__webpack_require__(23);
core_vm.web=__webpack_require__(24);
core_vm.webdocready=__webpack_require__(29);
//core_vm.route=require('../corevm/mob/vm.web_route.js');
core_vm.web_private_style=__webpack_require__(30);
//core_vm.web_eventdom=require('../corevm/mob/vm.web_eventdom.js');
//core_vm.web_create=require('../corevm/mob/vm.web_create.js');
__webpack_require__(3);
core_vm.cacheclass=__webpack_require__(5);
core_vm.appclass=__webpack_require__(4);
core_vm.wap=new core_vm.appclass();
core_vm.wap.id='ly';
core_vm.wap.__cache=new core_vm.cacheclass();
core_vm.wap.blankvm=core_vm.define.define({id:'_blankforapp_'});
core_vm.wap.blankvm.__define({name:'_blank_'});
//core_vm.gcache=new core_vm.cacheclass();
Object.defineProperty(core_vm.wap,'blankvm',{enumerable:false});
module.exports={
//core_vm:core_vm,
vmix:{
email:'<EMAIL>',
//是不是暴露一个app
},
}
core_vm.webdocready.docReady(core_vm.web.start_system);
/***/ }),
/* 32 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.setproto=function(proto){
proto.loadok_block=function(spec,text){
if(spec.utag){//import的
this.importblock[spec.id]={text:text||''};
this.add_ref('block',spec.id,spec.refsid,'loadok_block');
}else if(spec.pathtag){//巡查的
if(!this.use.block[spec.pathtag])this.use.block[spec.pathtag]=text;
}
}
proto.get_block_text=function(vm,utag){
//console.log('get_block_text',utag)
if(this.use.block[utag])return this.use.block[utag];
var src=this.check_if_import('block',vm[core_vm.aprand].absrcid,utag);
if(!src)return '';
var mod=this.importblock[src];
if(!mod)return '';
if(mod.refsids.indexOf(vm[core_vm.aprand].absrcid)===-1)mod.refsids.push(vm[core_vm.aprand].absrcid);
return mod.text ||'';
}
proto.loadok_style=function(spec,text){
this.importstyle[spec.id]={text:text||''};
this.add_ref('style',spec.id,spec.refsid,'loadok_style');
}
proto.__get_importstyle=function(vm){
var text='';
for(var k in this.importstyle){
if(this.importstyle[k].refsids.indexOf(vm[core_vm.aprand].absrcid)>-1)
text+=this.importstyle[k].text;
}
return text;
}
}
/***/ }),
/* 33 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.setproto=function(proto){
proto.loadfilefresh_clear=function(id){
//这个id=absrc
if(this.vmlib[id]){
//console.log('loadfilefresh_clear 发现vmlib');
delete this.vmlib[id];
delete this.vmbody[id];
delete this.vmstyle[id];
}
if(this.jslib[id]){
//console.log('loadfilefresh_clear 发现jslib');
delete this.jslib[id];
}
}
//vm.cache的位置
//cache.vmsbysid,pvm.vmchildren[id]=tvm.sid,
//nap.nowpage,nap.topvm[method_url]=vm; nap.gvm[type]=vm;
//uap.hookstart_ing_vm
proto.removesid=function(sid){
//console.error('cache.removesid',sid)
delete this.vmsbysid[sid];
delete this.vmparent[sid];//todo 这个没什么用
for(var csid in this.vmparent){
if(this.vmparent[csid]==sid){
delete this.vmparent[csid];
this.removesid(csid);//清理下面的
}
}
}
proto.keep=function(type,id){
//加一个-1进去
if(type=='vm' && this.vmlib[id])this.vmlib[id].inpath=1;
if(type=='lib' && this.jslib[id])this.jslib[id].inpath=1;
}
proto.delete=function(mod,id){
if(mod && mod[id] &&mod[id].refsids.length==0 &&!mod[id].inpath)delete mod[id];
}
proto.clean_when_vm_clean=function(vm){
//console.error('clean_when_vm_clean',vm.absrc,vm.sid)
//console.error('vmlib', this.vmlib[vm.absrc].refsids);
//根据sid clean cache记录
//根据absrc清理 body,style,lib import
//主要是 web的removechild,close
//mob的 closepage, freshpage不过来
this.removesid(vm.sid);
//this.vmlib[id].refsids
//removechild时 清理掉了 todo
var absrc=vm.absrc;
var absrcid=vm[core_vm.aprand].absrcid;
if(!this.vmlib[absrc]||this.vmlib[absrc].inpath==1){
//console.log('close不清理 找不到vmlib',absrc)
return;
}
var sameurl=0;
for(var i in this.vmsbysid){
if(this.vmsbysid[i][core_vm.aprand].has_started==0)continue;
if(this.vmsbysid[i][core_vm.aprand].absrcid===vm[core_vm.aprand].absrcid)sameurl++;
}
if(sameurl>0){
//console.log('vm不清理 剩余的还有absrc相同',absrc,this.vmlib[absrc]);
return;
}
//console.error('相同url都close了',this.vmlib[absrc].refsids)
//remove或者更换src时清除
//判断 use的vm不清理,path.vm不清理
//import的都清理
delete this.vmbody[absrc];
delete this.vmstyle[absrc];
delete this.vmlib[absrc];
this.clean_import(absrcid);
//__extend_from 的没有清理 并且没有sid
//下面是全局清理
for(var k in this.vmlib){
var mod=this.vmlib[k];
if(mod && Array.isArray(mod.refsids)){
var index=mod.refsids.indexOf(absrcid);
if(index>-1){
mod.refsids.splice(index,1);
this.delete(this.vmlib,k);
}
}
}
for(var k in this.jslib){
var mod=this.jslib[k];
if(mod && Array.isArray(mod.refsids)){
var index=mod.refsids.indexOf(absrcid);
if(index>-1){
mod.refsids.splice(index,1);
this.delete(this.jslib,k);
}
}
}
}
}
/***/ }),
/* 34 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.setproto=function(proto){
proto.add_import_src_when_cal=function(type,urlsid,name,src){
var a=urlsid+':'+name;
if(type=='vm') this.import_src_vm[a]=src;
if(type=='block')this.import_src_block[a]=src;
if(type=='lib'||type=='json') this.import_src_lib[a]=src;
}
proto.check_if_import=function(type,urlsid,name){
var a=urlsid+':'+name;
if(type=='vm') return this.import_src_vm[a]||'';
if(type=='block')return this.import_src_block[a]||'';
if(type=='lib'||type=='json') return this.import_src_lib[a]||'';
}
proto.clean_import=function(absrcid){
// console.log('清除styletext',this.import_src_vm,this.vmlib)
//console.log('看看',absrcid,this.import_src_block,this.importblock)
for(var k in this.import_src_block){
if(k.indexOf(absrcid+':')==0){
var b_absrc=this.import_src_block[k];
var styleobj=this.importblock[b_absrc];
if(styleobj && styleobj.refsids){
var index=styleobj.refsids.indexOf(absrcid);
if(index>-1)styleobj.refsids.splice(index,1);
this.delete(this.importblock,b_absrc);
}
delete this.import_src_block[k];
}
}
for(var k in this.import_src_lib){
if(k.indexOf(absrcid+':')==0){
var b_absrc=this.import_src_lib[k];
var styleobj=this.jslib[b_absrc];
if(styleobj && styleobj.refsids){
var index=styleobj.refsids.indexOf(absrcid);
if(index>-1)styleobj.refsids.splice(index,1);
this.delete(this.jslib,b_absrc);
}
delete this.import_src_lib[k];
}
}
//console.log('清除styletext',this.import_src_vm)
for(var k in this.import_src_vm) {
if(k.indexOf(absrcid+':')==0){
for(var i in this.vmsbysid){
if(this.vmsbysid[i].absrc===this.import_src_vm[k]){
var vmod=this.vmlib[this.import_src_vm[k]];
if(vmod && vmod.refsids){
var index=vmod.refsids.indexOf(absrcid);
if(index>-1){
vmod.refsids.splice(index,1);
this.clean_when_vm_clean(this.vmsbysid[i]);
}
}
break;
}
}
this.delete(this.import_src_vm,k);
//vm自己会清理
}
}
for(var k in this.importstyle){
if(this.importstyle[k].refsids){
var index=this.importstyle[k].refsids.indexOf(absrcid);
if(index>-1)this.importstyle[k].refsids.splice(index,1);
this.delete(this.importstyle,k);
}
//todo 从document.style 删除
}
}
}
/***/ }),
/* 35 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.setproto=function(proto){
proto.add_jslib=function(id,mod,refsid){
//console.log('add_jslib',id,refsid)
//use define
this.jslib[id]=mod;
if(refsid)mod.refsids=[refsid];
var path=this.getapp().config.path;
for(var k in path.lib){
if(path.lib[k]===id)this.keep('lib',id);
}
}
proto.get_jslib=function(id){
return this.jslib[id];
}
}
/***/ }),
/* 36 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.setproto=function(proto){
proto.add_vmlib=function(id,mod,refsid){
//console.log('add_vmlib',id,refsid,this.vmlib[id]?'有':'没有')
mod.refsids=[refsid];
this.vmlib[id] = mod;
var path=this.getapp().config.path;
for(var k in path.vm){
if(path.vm[k]===id){
this.keep('vm',id);
}
}
}
proto.add_vmbody=function(id,body,when){
//console.log('newvmbody',absrc,when)
this.vmbody[id]=body+'';
}
proto.add_vmstyle_inline=function(id,style_str){
this.vmstyle[id]=core_vm.tool.trim(style_str);
}
proto.get_vmlib=function(id){
return this.vmlib[id];
}
proto.get_body_extend=function(absrc){
return this.vmbody[absrc]||'';
}
proto.get_body=function(vm){
return this.vmbody[vm.absrc]+'';
}
proto.get_vmstyle_extend=function(absrc){
return this.vmstyle[absrc]||'';
}
proto.get_vmstyle=function(vm){
var text=this.vmstyle[vm.absrc]||'';
text+=this.__get_importstyle(vm);
return text;
}
}
/***/ }),
/* 37 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
var debug = 1 ? console.log.bind(console, '[fastdom]') : function() {};
var win=window;
var raf = function(cb) {
//console.log('16毫秒')
return setTimeout(cb, 16);
};
var reads=[];
var writes=[];
var scheduled=false;
function runTasks(tasks) {
//debug('run tasks');
var task; while (task = tasks.shift()) task();
}
function flush() {
//debug('flush');
var error;
try {
//debug('flushing reads', reads.length);
runTasks(reads);
//debug('flushing writes', writes.length);
runTasks(writes);
} catch (e) { error = e; }
scheduled = false;
//不是等16ms 也不是16ms执行不完就停下来
// If the batch errored we may still have tasks queued
if (reads.length || writes.length) scheduleFlush();
if (error) {
debug('task errored', error.message);
//if (fastdom.catch) fastdom.catch(error);
//else throw error;
}
}
var measure=function(fn, ctx) {
//debug('measure');
var task = !ctx ? fn : fn.bind(ctx);
reads.push(task);
scheduleFlush();
return task;
}
var mutate =function(fn, ctx) {
//debug('mutate');
var task = !ctx ? fn : fn.bind(ctx);
writes.push(task);
scheduleFlush();
return task;
}
function scheduleFlush() {
if (!scheduled) {
scheduled = true;
raf(flush);//16ms后执行或者win调用
//debug('flush scheduled');
}
}
module.exports={
get:measure,
set:mutate,
}
/***/ }),
/* 38 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.setproto=function(proto){
proto.cleanList=function(p){
if(Array.isArray(this[core_vm.aprand].watching_list[p])){
var listdata=this.__getData(p);
this[core_vm.aprand].watching_list[p].forEach(function(l_opt){
core_vm.list.$clean.call(listdata,l_opt);
});
}
}
proto.rebuildList=function(p){
if(Array.isArray(this[core_vm.aprand].watching_list[p])){
var listdata=this.__getData(p);
this[core_vm.aprand].watching_list[p].forEach(function(l_opt){
core_vm.list.$rebuild.call(listdata,l_opt);
});
}
//Object.defineProperty(listdata,'$update', {writable:false, enumerable: false, configurable: true});
}
proto.__blankfn=function(){}
proto.__getrandobj=function(){return this[core_vm.aprand]}
proto.__reset_list_index=function(wopt){
//list.watchcb._exptext_ <a>{www}</a>用到 重要 暂时放到这里
//标签内的需要自己设计$index
//只有watchcb用到
if(wopt.$index!==undefined && wopt.scope && wopt.scope.$index!==undefined) wopt.scope.$index= wopt.$index;
}
proto.getClassName=function(name){
return core_vm.web_private_style.get(this,name);
}
proto.hasSlot=function(name){
return this[core_vm.aprand].pvmslot[name]?true:false;
}
proto.__ensure_fn=function(){
}
}
/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.setproto=function(proto){
proto.hasChild=function(id){
if(this[core_vm.aprand].vmchildren[id+''])return true;
else return false;
}
proto.getChild=function(id){
if(this[core_vm.aprand].vmchildren[id]){
return this.getcache().vmsbysid[this[core_vm.aprand].vmchildren[id]];
}else if(id.indexOf('.')>-1){
var tvm=this;
var parts = ~id.indexOf('.') ? id.split('.') : [id];
for (var i = 0; i < parts.length; i++){
tvm = tvm.getcache().vmsbysid[tvm[core_vm.aprand].vmchildren[parts[i]]]
if(tvm===undefined)break;
}
return tvm;
}
}
proto.getParent=function(){
return this.pvm;
}
proto.removeChild=function(id){
var cvm;
if(id instanceof core_vm.define.vmclass && this.sid===id.pvm.sid){
if (this[core_vm.aprand].vmchildren[id.id] && this[core_vm.aprand].vmchildren[id.id]==id.sid){
let realid=id.id;
cvm=id;
id=realid;
}
}
else if(core_vm.isstr(id))cvm=this.getChild(id);
if(cvm){
cvm.__vmclose(true);
cvm.getcache().removesid(cvm.sid);
delete this[core_vm.aprand].vmchildren[id];
}
}
proto.appendChild=function(opt,pnode,ifpnode){
//opt={id,el,src}
if(!opt.id || this.hasChild(opt.id)){
core_vm.devalert(this,'loadsub 缺少id或者重复',opt.id)
return;
}
if(!opt.el)return;
if(!core_vm.isfn(opt.el.appendChild))return;
if(!opt.src ){
if(opt.path)opt.src=this.getapp().config.path.vm[opt.path];
else if(opt.tagname)opt.src=opt.tagname;//use的
}
if(!opt.src){
//可能的 延迟加载的 console.error('没有src',opt)
}
var cvm=core_vm.define.define({pvm:this,el:opt.el,id:opt.id,src:opt.src});
if(ifpnode==1){
if(pnode && pnode.tag){
core_vm.inject.cal_inject_node(cvm,pnode);
cvm[core_vm.aprand].pvmevent=pnode.vmevent||{};
cvm[core_vm.aprand].pvmelevent=pnode.event||{};//ppel时有用
cvm[core_vm.aprand].pvmnode=pnode;//先有node 再解析 data-option
if(pnode.attr.autostart!=false){
//console.log('这里loadsub')
cvm._is_fresh_ing=this._is_fresh_ing;
core_vm.load(cvm);
}
}
}else if(opt){
//只有 append调用 解析node时直接存入__append_data了
//console.log('__inject_for_me',json)
//append start 时可以注入data-option
var children=(cvm[core_vm.aprand].pvmnode)?cvm[core_vm.aprand].pvmnode.childNodes:[];
//收到append 原来的data被清理
if(core_vm.isobj(opt.event)){
cvm[core_vm.aprand].pvmevent=opt.event
}
if(core_vm.isobj(opt.data)){
core_vm.tool.deepmerge(cvm[core_vm.aprand].append_data,opt.data);
for(var k in opt.data){
if(cvm[core_vm.aprand].datafrom_parent.indexOf(k)===-1){
//console.log('插入一个 奇怪',k)
cvm[core_vm.aprand].datafrom_parent.push(k);
}
}
for(var i=children.length-1;i>-1;i--){
if(children[i].tag=='data')children.splice(i,1)
}
}
if(core_vm.isobj(opt.option)){
core_vm.tool.deepmerge(cvm[core_vm.aprand].append_option,opt.option);
for(var i =children.length-1;i>-1;i--){
if(children[i].tag=='option')children.splice(i,1)
}
}
return cvm;
}
}
}
/***/ }),
/* 40 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.setproto=function(proto){
proto.__addto_onclose=function(cb){
this[core_vm.aprand].cbs_onclose.push(cb);
}
proto.__vmclose=function(ifclean,iffresh){
//isfresh 取消了 全部清除
//console.error("vm销毁,this.id=",this.id,'this.absrc='+this.absrc);
if(!this[core_vm.aprand].has_started){
return;
}
//ifclean时 要从 cache.vmbysid清理,pvm.chldren清理 资源清理
var vm=this;
this[core_vm.aprand].has_started=0;
for(var k in this[core_vm.aprand].cbs_onclose){
this[core_vm.aprand].cbs_onclose[k].call(this);//都是内部函数
}
var vmpel=vm.pel;vmpel.setAttribute('bindsidofvm',0);vmpel.setAttribute('isvmpel',false);
//后面可能还会再startvmpel.setAttribute(this.getapp().config.vmtag+'-src','');
//isvmpel 应该可以清理掉 2017-10-1 todo 不要清理 isvmpel
var mypvm=this.pvm;
if(mypvm){
core_vm.tryvmfn(mypvm,this,'beforechildclose');
if(ifclean)delete mypvm[core_vm.aprand].vmchildren[this.id];
}
core_vm.tryvmfn(vm,null,'beforeclose');
let vmchildren=vm[core_vm.aprand].vmchildren;
if(vmchildren){
for(var k in vmchildren){
vm.getcache().vmsbysid[vmchildren[k]].__vmclose(iffresh ?true:ifclean,iffresh);
//fresh是chlid要清理掉,因为loadsub要新建
delete vmchildren[k];
}
}
this.__unbindall();
if('ppel'!==vm.config.appendto){
//几个因素 下级有ppel,一个el下 append了多个vm vm.close时不能清除vm.pel
//console.log('close.无ppel',this.id);//,vm[core_vm.aprand].els,vm.pel.childNodes
//这时候 els中有的元素是下级vm=ppel时 替换的 ,所有ppel的topel只能一个 需要清除所有child
var els=vm[core_vm.aprand].els;
for(var i=els.length-1;i>-1;i--){
if(els[i].parentNode===vm.pel){
vm.pel.removeChild(els[i]);
}else {
if(els[i].replaced_pel && els[i].replaced_pel.parentNode){
els[i].replaced_pel.parentNode.removeChild(els[i].replaced_pel)
}
if(els[i].parentNode){
els[i].parentNode.removeChild(els[i]);
}
}
}
//console.error('close.无ppel,pel剩余',vm.pel.childNodes.length);
}else{
//web.ppel是vm[core_vm.aprand].els[0].parentNode 因为插入时可能是#document-fragment 需要 onshow才知道
//mob.ppel 插入时就知道是谁
//console.log('close.有ppel',this.id,vm[core_vm.aprand].els)
var ppel=vm.ppel;
var pel=vm.pel;
if(ppel && pel){
ppel.replaceChild(pel,vm[core_vm.aprand].els[0]);
}
}
vm.__top_fragment=null;
if(ifclean){
if(vm.pel)vm.pel=null;
vm.pel=null;
}
core_vm.tryvmfn(vm,null,'onclose');
if(mypvm)core_vm.tryvmfn(mypvm,this,'onchildclose');
var curStyle=document.getElementById("_privatestyle_"+vm.sid);
if(curStyle)document.getElementsByTagName("head")[0].removeChild(curStyle);
//更多的全局注销
//马上注销 还是延时 延时可以利用缓存 需要加一个 closetime 如果又打开了 但是延时clean 造成混乱 必须马上
vm.__init(true);
if(ifclean)vm.clean('vmclose'); //比如刷新时是下载了新文件再vmclose的这时候clean会clean掉新的内容
this[core_vm.aprand].has_started=0;
this[core_vm.aprand].has_defined=0;
}
//close 并没有 从全局清理 再start时 sid不变
//clean用于 mob 的 返回按钮时 page的清理 web需要自己控制是否清理
//用户可以自己清理内存占用 如 css
proto.clean=function(type){
//console.log('vm.clean',type)
if(this[core_vm.aprand].has_started==0 && this[core_vm.aprand].has_defined==0){
this.getcache().clean_when_vm_clean(this);
}
//还是应该用vm自己的app 用appnow 在多个app切换时出错 2018-03-22
}
//close时移除style 需要把 style加在一个vmsid
proto.close=proto.__vmclose;
}
/***/ }),
/* 41 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.setproto=function(proto){
proto.setChildData=function(cvmid,p,v,cb){
//console.log('setChildData',cvmid,p,v)
var vm=this;
if(!core_vm.isfn(cb))cb=this.__blankfn;
if(typeof (cvmid)=='object')cvmid=cvmid.id;
var cvm=this.getChild(cvmid);
if(!cvm){
cb(false);
return;
}
if(!cvm[core_vm.aprand].has_started){
core_vm.tool.objSetDeep(cvm[core_vm.aprand].append_data,p,v,true);
var path=p.split('.')[0];
if(cvm[core_vm.aprand].datafrom_parent.indexOf(path)===-1){
cvm[core_vm.aprand].datafrom_parent.push(path);
}
return;
}
var oldv=cvm.__getData(p);
if(oldv===v){
cb(false);
return;
}
var fp=p.split('.')[0];
if(cvm[core_vm.aprand].datafrom_parent.indexOf(fp)==-1){
cb(false,'datasource not match');
return;
}
cvm.__confirm_set_data_to_el(cvm,p,v,oldv);
cb(true,null);
var fn=cvm.event['pvm.setdata'];
if(core_vm.isfn(fn))fn.call(cvm,{path:p,oldv:oldv,newv:v})
}
proto.addChildData=function(cvmid,p,index,v,cb){
var vm=this;
if(!core_vm.isfn(cb))cb=this.__blankfn;
if(typeof (cvmid)=='object')cvmid=cvmid.id;
var cvm=this.getChild(cvmid);
if(!cvm){
cb(false);
return;
}
var fp=p.split('.')[0];
if(cvm[core_vm.aprand].datafrom_parent.indexOf(fp)==-1){
cb(false,'datasource not match');
return;
}
cvm.__confirm_add_data_to_el(cvm,p,index,v,function(res){
cb(res);
});
var fn=cvm.event['pvm.adddata'];
if(core_vm.isfn(fn))fn.call(cvm,{path:p,index:index,value:v});
}
proto.delChildData=function(cvmid,p,index,count,cb){
var vm=this;
if(!core_vm.isfn(cb))cb=this.__blankfn;
if(typeof (cvmid)=='object')cvmid=cvmid.id;
var cvm=this.getChild(cvmid);
if(!cvm){
cb(false);
return;
}
var fp=p.split('.')[0];
if(cvm[core_vm.aprand].datafrom_parent.indexOf(fp)==-1){
cb(false,'datasource not match');
return;
}
cvm.__confirm_del_data_to_el(cvm,p,index,count,function(res){
cb(res);
});
var fn=cvm.event['pvm.deldata'];
if(core_vm.isfn(fn))fn.call(cvm,{path:p,index:index,count:count});
}
}
/***/ }),
/* 42 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.setproto=function(proto){
proto.__setData=function(p,v){
core_vm.tool.objSetDeep(this.data,p,v)
}
proto.__getData=function(p){
return core_vm.tool.objGetDeep(this.data,p)
}
var blank=function(){}
var check_source=function(vm,p){
var fp=p.split('.')[0];
if(vm[core_vm.aprand].datafrom_parent.indexOf(fp)>-1)return 'parent';
if(vm[core_vm.aprand].datafrom_store.indexOf(fp)>-1)return 'store';
return 'self';
}
proto.__autobind_setData=function(p,v,oldv){
this.setData(p,v);
}
proto.getData=function(p,cb){
if(!p || !core_vm.isfn(cb))return;
var vm=this;
var source=check_source(vm,p);
if(source=='self'){
cb(null,null,source);
}else if(source=='store'){
vm.getapp().store.get.call(vm.getapp(),vm,p,function(data,opt){
cb(data,opt,source);
});
}else if(source=='parent'){
var pcb=vm.pvm.dataProxy;
if(pcb)pcb=pcb.get;
if(core_vm.isfn(pcb)){
pcb.call(vm.pvm,vm,p,function(data,opt){
cb(data,opt,source);
})
}else{
cb(null)
}
}
}
proto.setData=function(p,v,cb){
//console.log('setdata',p,v)
var vm=this;
if(!core_vm.isfn(cb))cb=vm.__blankfn;
if(!p||v==undefined)return cb(false);
var oldv=vm.__getData(p);
if(oldv===v)return cb(false);
var source=check_source(vm,p);
if(source=='self'){
vm.__confirm_set_data_to_el(vm,p,v,oldv,cb);
cb(true,null,source);
}else if(source=='store'){
vm.getapp().store.set.call(vm.getapp(),vm,p,v,function(res,opt){
if(res)vm.__confirm_set_data_to_el(vm,p,v,oldv,cb);
cb(res,opt,source);
});
}else if(source=='parent'){
var pcb=vm.pvm.dataProxy;
if(pcb)pcb=pcb.set;
if(core_vm.isfn(pcb)){
pcb.call(vm.pvm,vm,p,v,function(res,opt){
if(res)vm.__confirm_set_data_to_el(vm,p,v,oldv,cb);
cb(res,opt,source);
})
}else{
cb(false,null,source)
}
}else{
cb(false,'datasource not match',source)
}
}
proto.addData=function(p,index,v,cb){
var vm=this;
if(!core_vm.isfn(cb))cb=vm.__blankfn;
if(!p||v==undefined)return cb(false);
var source=check_source(vm,p);
//console.log('adddata',source,p,index,v)
if(source=='self'){
vm.__confirm_add_data_to_el(vm,p,index,v,cb);
}else if(source=='store'){
vm.getapp().store.add.call(vm.getapp(),vm,p,index,v,function(res,opt){
if(res)vm.__confirm_add_data_to_el(vm,p,index,v,cb);
else cb(res,opt,source);
});
}else if(source=='parent'){
var pcb=vm.pvm.dataProxy;
if(pcb)pcb=pcb.add;
if(core_vm.isfn(pcb)){
pcb.call(vm.pvm,vm,p,index,v,function(res,opt){
if(res)vm.__confirm_add_data_to_el(vm,p,index,v,cb);
else cb(res,opt,source);
})
}else{
cb(false,null,source)
}
}else{
cb(false,'datasource not match',source);
}
}
proto.delData=function(p,index,count,cb){
//console.log('delData',p,index,count)
var vm=this;
if(!core_vm.isfn(cb))cb=vm.__blankfn;
if(!p)return cb(false);
if(parseInt(index)!==index)return;
if(!count)count=1;
var source=check_source(vm,p);
if(source=='self'){
vm.__confirm_del_data_to_el(vm,p,index,count,cb);
}else if(source=='store'){
vm.getapp().store.del.call(vm.getapp(),vm,p,index,count,function(res,opt){
if(res)vm.__confirm_del_data_to_el(vm,p,index,count,cb)
else cb(res,opt,source);
});
}else if(source=='parent'){
var pcb=vm.pvm.dataProxy;
if(pcb)pcb=pcb.del;
if(core_vm.isfn(pcb)){
pcb.call(vm.pvm,vm,p,index,count,function(res,opt){
if(res)vm.__confirm_del_data_to_el(vm,p,index,count,cb);
else cb(res,opt,source);
})
}else{
cb(false,null,source)
}
}else{
cb(false,'datasource not match',source)
}
}
}
/***/ }),
/* 43 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.setproto=function(proto){
proto.setChildOption=function(cvmid,p,v,cb){
var vm=this;
if(!core_vm.isfn(cb))cb=this.__blankfn;
//console.log('setChildOption',cvmid,p,v)
var cvm=this.getChild(cvmid);
if(!cvm)return cb(false);
if(!cvm[core_vm.aprand].has_started){
core_vm.tool.objSetDeep(cvm[core_vm.aprand].append_option,p,v,true);
return;
}
//console.log('cvm[core_vm.aprand].watching_option',cvm[core_vm.aprand].watching_option)
var oldv=core_vm.tool.objGetDeep(cvm.option,p);
if(oldv===v)return cb(false);
var obj=cvm[core_vm.aprand].watching_option[p];
if(Array.isArray(obj)){
//console.log('多个属性',obj.length)
obj.forEach(function(opt){
//console.log('属性',v,opt)
core_vm.tool.objSetDeep(cvm.option,p,v);
core_vm.watchcb.watch(opt,p,oldv,v)
})
var fn=cvm.event['pvm.setoption'];
if(core_vm.isfn(fn))fn.call(cvm,{path:p,newv:v,oldv:oldv});
}else{
cb(false);
}
}
}
/***/ }),
/* 44 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.setproto=function(proto){
var __real_setState=function(vm,p,v,oldv){
core_vm.tool.objSetDeep(vm.state,p,v);
var s=vm[core_vm.aprand].watching_state[p];
if(Array.isArray(s)){
var len=s.length;
s.forEach(function(opt,i){
core_vm.watchcb.watch(opt,p,oldv,v);
})
}
}
proto.setState=function(p,v,cb){
//console.log('setState',p,v,this[core_vm.aprand].watching_state)
var vm=this;
var oldv=core_vm.tool.objGetDeep(this.state,p);
if(p===undefined)return;
if(oldv===v)return ;
__real_setState(this,p,v,oldv);
if(!core_vm.isfn(cb))cb=this.__blankfn;
this.pubup('state',{path:p,newv:v,oldv:oldv,},cb);
}
proto.__autobind_setstate=function(p,v,oldv){
this.setState(p,v);
}
//proto.setstate=proto.setState;
}
/***/ }),
/* 45 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.setproto=function(proto){
proto.__confirm_set_data_to_el=function(vm,p,v,oldv){
//console.log('__confirm_set_data_to_el',vm.id,p,v,oldv)
if(oldv==undefined) oldv=vm.__getData(p);
if(oldv===v)return;
vm.__setData(p,v);
var ps=p.split('.');
var len=ps.length;
if(ps[len-1]==parseInt(ps[len-1])){
//setData('books.1',{name:11}) 用于原生listview的item修改
var strp=p.substr(0,p.lastIndexOf('.'));
}
var __watching_data=vm[core_vm.aprand].watching_data[p]||vm[core_vm.aprand].watching_data['this.data.'+p];
//console.log(__watching_data.length,Array.isArray(__watching_data));
if(Array.isArray(__watching_data)){
//console.log('多个',vm[core_vm.aprand].watching_data.length);
var ifcheck=false;
__watching_data.forEach(function(opt,w_sn){
//console.log('数据改变',p,v,opt.listid);
if(opt.listid){
//必须检查 增删
//console.log('有listid,可能是数组',opt)
var ps=p.split('.');
var listpath='';
for(var i=0;i<len;i++){
if(i==0)listpath=ps[0];else listpath+='.'+ps[i];
//console.log('listpath',listpath)
if(Array.isArray(vm[core_vm.aprand].watching_list[listpath])){
break;
}
}
if(listpath==''){
return;
}
var array=vm.__getData(listpath);
if(!Array.isArray(array)){
return;
}
var index,sid,path;
for(var i=0;i<len;i++){
if(parseInt(ps[i])==ps[i]){
index=parseInt(ps[i]);
break;
}
}
if(index>-1){
ps.splice(0,i+1);
path=ps.join('.');
}
//console.log('发现数组,path='+path,'listpath='+listpath,'index='+index);//,'class=_list_'+opt.listid
opt.el=vm.getel('@'+opt.listid);//特殊设计的
//console.log('el全部',opt.el)
if(opt.el){
opt.el=opt.el[index];
//发现数组 可能已经删除 需要根据class再次寻找
//console.log('el',opt.el,opt.$index,index)
core_vm.watchcb.watch(opt,p,oldv,v);
}
}else{
core_vm.watchcb.watch(opt,p,oldv,v);
}
})
}
}
proto.__confirm_add_data_to_el=function(vm,p,index,v,cb){
//console.log('__confirm_add_data_to_el')
var array=vm.__getData(p);
if(!Array.isArray(array))return cb(false);
index=parseInt(index);
if(index==-1)index=array.length;
array.splice(index,0,v);
//console.log('confirm_add_data',vm[core_vm.aprand].watching_list,vm[core_vm.aprand].watching_nlist);
var _listing=vm[core_vm.aprand].watching_list[p]||vm[core_vm.aprand].watching_list['this.data.'+p];
if(Array.isArray(_listing)){
_listing.forEach(function(opt){
core_vm.list.$add.call(array,opt,index,v);
})
}
cb(true)
}
proto.__confirm_del_data_to_el=function(vm,p,index,count,cb){
var array=vm.__getData(p);
if(!Array.isArray(array))return cb(false);
index=parseInt(index);
if(index==-1)index=array.length;
array.splice(index,count);
var _listing=vm[core_vm.aprand].watching_list[p]||vm[core_vm.aprand].watching_list['this.data.'+p];
if(Array.isArray(_listing)){
_listing.forEach(function(opt){
core_vm.list.$delat.call(array,opt,index);
})
}
cb(true);
}
}
/***/ }),
/* 46 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.setproto=function(proto){
function decapitalize(str) {
str = ""+str;
return str.charAt(0).toLowerCase() + str.slice(1);
};
var get_child_events=function(node,events){
var events=events || [];
if(node.event)for(var k in node.event){
if(events.indexOf(k)===-1)events.push(decapitalize(k));
}
if(node.childNodes)for(var k in node.childNodes)events=get_child_events(node.childNodes[k],events);
return events;
}
proto.__bind_as_top_view=function(node,el){
//这里没有isvmpel
core_vm.elset(el,'bindsidofvm',this.sid);
el._hasbindastop=el._hasbindastop||[];
var events=get_child_events(node,[]);
//console.log('__bind_as_top_view',node.utag,events)
for(var k in events){
if(el._hasbindastop.indexOf(events[k])==-1){
el._hasbindastop.push(events[k]);
this.__bind(el,events[k],core_vm.eventdom.all);
}
}
}
proto.__unbindel=function(el){
var s=this[core_vm.aprand].els_binded;
var len=s.length;
for(i=len-1;i>-1;i--){
if(s[i][0]===el){
el.removeEventListener(s[i][1],s[i][2]);
s.splice(i,1);
break;
}
}
}
proto.__unbindall=function(event,el,fn){
this[core_vm.aprand].els_binded.forEach(function(e){e[0].removeEventListener(e[1],e[2]);});
this[core_vm.aprand].els_binded=[];
}
proto.__bind=function(el,event,fn,ifdirect){
if(!el || !core_vm.isfn(fn) ||typeof(event)!=='string' || !el.addEventListener)return;
if(ifdirect){
//console.log('直接绑定函数',event)
this[core_vm.aprand].els_binded.push([el,event,fn]);
el.addEventListener(event,fn);
return
}
var vm=this;
var velfn=function(e){
fn.call(e.target,e,vm);
}
this[core_vm.aprand].els_binded.push([el,event,velfn]);
el.addEventListener(event,velfn);
}
proto.__bind_events=function(el){
var domeventnames=this[core_vm.aprand].domeventnames;
var domeventnames_binded=this[core_vm.aprand].domeventnames_binded;
//console.log('__bind_events',el?el.id:'',this.id,domeventnames,Object.keys(domeventnames))
for(var name in domeventnames){
//console.log('name='+name)
if(name.indexOf(':')>-1)name=name.substr(0,name.indexOf(':'));//:capture或者:self
if(domeventnames_binded.indexOf(name)==-1){
domeventnames_binded.push(name);
//console.log("准备绑定",el||this.pel);
if(el){
this.__bind(el||this.pel,name,core_vm.eventdom.all);
}else{
for(var k in this[core_vm.aprand].els)
this.__bind(this[core_vm.aprand].els[k],name,core_vm.eventdom.all);
}
//this.__bind(el||this.pel,name,core_vm.eventdom.all);
}else{
//console.log('已经绑定')
}
}
}
}
//浏览器事件
//on(abort|blur|cancel|canplay|canplaythrough|change|click|close|contextmenu|cuechange|
//dblclick|drag|dragend|dragenter|dragleave|dragover|dragstart|drop|durationchange|emptied|ended|
//error|focus|input|invalid|keydown|keypress|keyup|
//load|loadeddata|loadedmetadata|loadstart|
//mousedown|mouseenter|mouseleave|mousemove|mouseout|mouseover|mouseup|mousewheel|
//pause|play|playing|progress|ratechange|reset|resize|scroll|seeked|seeking|select|show|
//stalled|submit|suspend|timeupdate|toggle|volumechange|waiting|autocomplete|autocompleteerror|
//beforecopy|beforecut|beforepaste|copy|cut|paste|search|selectstart|wheel|webkitfullscreenchange|webkitfullscreenerror|
//touchstart|touchmove|touchend|touchcancel|
//pointerdown|pointerup|pointercancel|pointermove|pointerover|pointerout|pointerenter|pointerleave)
/***/ }),
/* 47 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.setproto=function(proto){
function intersect(arr1, arr2) {
if(!Array.isArray(arr1)||!Array.isArray(arr2))return [];
var res = [];
for(var i = 0; i < arr1.length; i++){
for(var j = 0; j < arr2.length; j++){
if(arr1[i] == arr2[j]){
res.push(arr1[i]);
arr1.splice(i,1);
arr2.splice(j,1);
i--;
j--;
}
}
}
return res;
};
proto.__delel_watchcb_notfind=function(id){
for(var k in this[core_vm.aprand].elsdom.id){
if(this[core_vm.aprand].elsdom.id[k]==id){
delete this[core_vm.aprand].elsdom.id[k];
}
}
}
proto.getel=function(name){
//得不到modalview
if(!name)return this[core_vm.aprand].els;//top
//dialog等没有加到dom的找不到
if(name[0]!=='#' && name[0]!=='.'&& name[0]!=='$'&& name[0]!=='@')name='#'+name;
var elsdom=this[core_vm.aprand].elsdom;
if(name[0]=='#'){
//console.log('getel',name,elsdom.id);
var id=elsdom.id[name.substr(1)];
if(id==undefined){
return null;
}else if(id==null){
delete elsdom.id[name.substr(1)];
return null;
}else{
return document.getElementById(id);
//console.log('el呢',id,this.__getel_may_dialog(id))
}
//return document.getElementById(id);
}else{
var els=[],ids=[];
if(name[0]=='@'){
//listel
ids=elsdom['listel'][name.substr(1)];
}else if(name[0]=='$'){
ids=elsdom['role'][name.substr(1)];
}else if(name[0]=='.'){
name=name.substr(1);
if(name.indexOf('.')==-1){
ids=elsdom['class'][name];
}else{
name=name.split('.');
for(var k in name)name[k]=core_vm.tool.trim(name[k]);
var id_s=[];
for(var k in name){
id_s[k]=[];
if(Array.isArray(elsdom['class'][name[k]])){
elsdom['class'][name[k]].forEach(function(tid){
id_s[k].push(tid);
})
}
}
ids=intersect(id_s[0],id_s[1]);
if(id_s.length>2){
for(var i=2;i<id_s.length;i++)ids=intersect(ids,id_s[i]);
}
}
}
if(ids){
for(var i=0,len=ids.length;i<len;i++){
els.push(document.getElementById(ids[i])||null);
}
for(var i=ids.length-1;i>-1;i--){
if(els[i]==null){
els.splice(i,1);
ids.splice(i,1);
}
}
}
return els;
}
//多类选择器 tagp.x.y 就不实现了 mob上可以对元素style实现 选择器就算了
}
//getel-需要统一 web mob
proto.__regel=function(type,name,webelid_or_mob_el,index){
//可以用getviewbyid了
//console.error('regel',type,name,webelid_or_mob_el,index)
var elsdom=this[core_vm.aprand].elsdom;
if(type=='id'){
elsdom.id[name]=webelid_or_mob_el;
}else if(type=='listel'){
//console.log('reg.listel',name,webelid_or_mob_el,index)
elsdom.listel[name]=elsdom.listel[name] || [];
var obj=elsdom.listel[name];
if(obj.indexOf(webelid_or_mob_el)==-1){
if(index!=undefined)obj.splice(index,0,webelid_or_mob_el)
else obj.push(webelid_or_mob_el);
//数组的元素按照加进来的位置排序
}
}else if(type=='classList'){
var array=name;
for(var k in array){
if(this.getapp().config.strategy.cacheClassesAll!==true || this.config.cacheClasses.indexOf(array[k])===-1)continue;
elsdom.class[array[k]]=elsdom.class[array[k]] || [];
if(elsdom.class[array[k]].indexOf(webelid_or_mob_el)==-1){
if(index!=undefined)elsdom.class[array[k]].splice(index,0,webelid_or_mob_el)
else elsdom.class[array[k]].push(webelid_or_mob_el);
//数组的元素按照加进来的位置排序
}
}
}else if(type=='role'){
elsdom.role[name]=elsdom.role[name] || [];
if(elsdom.role[name].indexOf(webelid_or_mob_el)==-1){
if(index!=undefined)elsdom.role[name].splice(index,0,webelid_or_mob_el)
else elsdom.role[name].push(webelid_or_mob_el);
//数组的元素按照加进来的位置排序
}
}
}
proto.delel=function(thisel,ifchild,ifhas_remove_from_parent){
//还是需要delel 主要是清除缓存
var velid,vclass,role;
//if(thisel)thisel=thisel;
//console.log('delel',thisel.id,ifchild,ifhas_remove_from_parent)
if(!thisel)return;
var elsdom=this[core_vm.aprand].elsdom;
velid=thisel.getAttribute('id');vclass=thisel.getAttribute('classList');role=thisel.getAttribute('role');
if(velid){
for(var k in elsdom.id){
if(elsdom.id[k]===velid)delete elsdom.id[k];
}
if(elsdom.id[velid])delete elsdom.id[velid];
if(thisel.listid){
var ids=elsdom['listel'][thisel.listid];
if(Array.isArray(ids)){
var index=ids.indexOf(velid);
if(index>-1)ids.splice(index,1);
}
}
if(role){
if(elsdom.role[role]){
var index=elsdom.role[role].indexOf(velid);
if(index>-1)elsdom.role[role].splice(index,1);
}
}
if(vclass){
for(var k in vclass){
if(elsdom.class[vclass[k]]){
var index=elsdom.class[vclass[k]].indexOf(velid);
if(index>-1)elsdom.class[vclass[k]].splice(index,1);
}
}
}
}
if(thisel.childNodes){
for(var i=0,len=thisel.childNodes.length;i<len;i++){
if(thisel.childNodes[i].nodeType==1)this.delel.call(this,thisel.childNodes[i],true);
}
}
if(!ifchild)thisel.parentNode.removeChild(thisel);
}
}
/***/ }),
/* 48 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.setproto=function(proto){
proto.sethtml=function(el,html){
if(typeof (el)=='string')el=this.getel(el);
if(!el)return;
var els=el.childNodes;for(var i=els.length-1;i>-1;i--)el.removeChild(els[i]);
this.addhtml(el,html);
}
proto.addhtml=function(el,html){
if(typeof (el)=='string')el=this.getel(el);
if(!el)return;
var vm=this;//[core_vm.aprand];
//web下node_max_sn没有加 mob下是计算style时处理的,
//node.sn主要是记录node的parent-child关系
var json=core_vm.calhtmltojson(html,vm[core_vm.aprand].node_max_sn+1,0,vm.getapp(),2);//+1的node是_root_,psn=0 sn是最大sn+1
//console.log('addhtml',json[0]);
//json=json[0].childNodes;
vm[core_vm.aprand].nodejson.push(json[0]);
core_vm.create.nodes(vm,json[0],vm[core_vm.aprand].rootscope,el);
//console.log('addhtml',vm[core_vm.aprand].domeventnames)
//console.log('addhtml',vm[core_vm.aprand].domeventnames_binded)
//有的会无效this.__bind_events(el);
this.__bind_as_top_view(json[0],el);
//这时候应该绑定到el本身
}
}
/***/ }),
/* 49 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.setproto=function(proto){
proto.__auto_sub_app=function(){
for(var k in this.event){
if(k.substr(0,4)=='app.' && typeof (this.event[k]=='function'))this.getapp().sub(k.substr(4),this,this.event[k])
}
}
proto.__auto_unsub_app=function(){
for(var k in this.event){
if(k.substr(0,4)=='app.' && typeof (this.event[k]=='function'))this.getapp().unsub(k.substr(4),this,this.event[k])
}
}
proto.pubapp=function(name,data,cb){
this.getapp().pub(name,data,this,cb)
}
proto.pubup=function(name,data,cb){
if(!this.pvm){
return;
}
var fn=this[core_vm.aprand].pvmevent[name];
if(!fn)fn=this.pvm.event[this.id+'.'+name];
if(!fn)fn=this.pvm.event['child'+'.'+name];
if(!fn)return;
if(!core_vm.isfn(fn))fn=core_vm.tool.objGetDeep(this.pvm,fn);
if(!core_vm.isfn(fn))fn=core_vm.tool.objGetDeep(this.pvm.event,fn);
if(!core_vm.isfn(fn))return;
var vm=this;
var pvm=this.pvm;
fn.call(this.pvm,data,this,function(data){
if(core_vm.isfn(cb))cb.call(vm,data,pvm);
})
}
//pubdown==pubto
proto.pubdown=function(cvmid,name,data,cb){
var vm=this;
//console.log('pubdown',cvmid)
if(typeof (cvmid)=='object')cvmid=cvmid.id;
if(!cvmid)return false;
var s=[]
if(cvmid=='*'){
s=Object.keys(this[core_vm.aprand].vmchildren)
}else{
s=[cvmid];
}
s.forEach(function(cvmid){
var cvm=vm.getChild(cvmid);
if(!cvm){
if(core_vm.isfn(cb))cb({error:'no.such.'+cvmid});
return;
}
//console.log(cvm.event,cvmid+'.'+name)
var fn=cvm.event['pvm.'+name];
if(!core_vm.isfn(fn))return;
fn.call(cvm,data,vm,function(data){
if(core_vm.isfn(cb))cb.call(vm,data,cvm);
})
})
}
}
/***/ }),
/* 50 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.setproto=function(proto){
proto.__addto_onstart=function(cb){
//list-elhook.js调用
//console.log('加入开始回调 onstart',cb)
//内部watch list等用的 还没有rect等
if(this[core_vm.aprand].has_started!==1){
this[core_vm.aprand].cbs_onstart.push(cb);
}else{
core_vm.tryfn(this,cb,[this],'vm.onstart')
}
}
proto.__addto_onshow=function(cb){
//elhook.js调用 dragableview,gif
//console.log('加入开始回调onshow',this.id,this.src);
if(this[core_vm.aprand].has_started!==1){
this[core_vm.aprand].cbs_onshow.push(cb);
}else{
core_vm.tryfn(this,cb,[this],'vm.onshow.addto')
}
}
proto.__onshow=function(){
//console.log('__onshow----------------',this[core_vm.aprand].cbs_onshow.length,this[core_vm.aprand].cbs_onstart.length)
//addto pel后 主要是modaltopview用的 创建一个view 需要高宽等于pel.rect.w
for(var k in this[core_vm.aprand].cbs_onshow){
core_vm.tryfn(this,this[core_vm.aprand].cbs_onshow[k],[this],'vm.onshow.exe')
}
this[core_vm.aprand].cbs_onshow=[];
for(var k in this[core_vm.aprand].cbs_onstart){
this[core_vm.aprand].cbs_onstart[k].call(this);//都是内部函数
}
this[core_vm.aprand].cbs_onstart=[];
if(core_vm.isfn(this[core_vm.aprand].startcb_of_vmstart)){
//console.log('__startcb_of_vmstart 是函数')
core_vm.tryfn(this,this[core_vm.aprand].startcb_of_vmstart,[],'vm.start.cb,id='+this.id);
}else{
//console.error('__startcb_of_vmstart 不是函数',this.id)
}
//console.log('自动禁止')
//
this.__clean_tmp_after_start();
}
var check_slot=function(vm,nodes){
//return;
//先检查是想在parent里面去掉<slot 但是list里面调用slot不行 没有scope.index
for(var sn=0,len=nodes.length;sn<len;sn++){
if(nodes[sn].tag=='slot' && (!nodes[sn].attr || !nodes[sn].attr.name) ){
core_vm.inject.use_inject_nodes_when_create(vm,nodes[sn]);
}else{
check_slot(vm,nodes[sn].childNodes);
}
}
}
proto.__vmstart=function(startcb){
//app.demo首页老是显示不正常 object
//console.log("vm.start",this.id,this[core_vm.aprand].has_started,typeof (startcb));
if(this[core_vm.aprand].has_started==1){
return;
}
var vm=this;
if(core_vm.isfn(startcb))vm[core_vm.aprand].startcb_of_vmstart=startcb;
if(core_vm.isfn(this.hookStart) && !this.__hookStart_has_called){
vm.getapp().hookstart_ing_vm=vm;
//hookstart有可能错误 try后错误了自动朝下走
try{
this.hookStart.call(this,function(result){
vm.getapp().hookstart_ing_vm=null;
vm.__hookStart_has_called=1;
if(result!==false){
vm.__vmstart(startcb);
}else{
if(vm[core_vm.aprand].startcb_of_vmstart)vm[core_vm.aprand].startcb_of_vmstart(false);
vm.__init(true);//这样就清理了 pvm cache都不需要清理
}
});
}catch(e){
core_vm.devalert(vm.getnap(),'hookStart error',vm.src,e)
vm.getapp().hookstart_ing_vm=null;
this.hookStart=null;
vm.__vmstart(startcb);
}
return;
}
core_vm.tryvmfn(vm.pvm,vm,'beforechildstart');
core_vm.tryvmfn(vm,null,'beforestart');
var bodytext=vm.getcache().get_body(vm);
//console.error('bodytext',bodytext.length)
if(core_vm.isfn(vm.hookTemplate)){
core_vm.cal.nodejson(vm,vm.hookTemplate(bodytext));
}else{
core_vm.cal.nodejson(vm,bodytext);
}
check_slot(vm,vm[core_vm.aprand].nodejson[0].childNodes);
var styletext=vm.getcache().get_vmstyle(vm);
//一个page退出时,在require.cache保存有 再次打开时 先去那里找 保存有template ,各种用户写的函数 以及刚刚cache的css
if(styletext){
if(core_vm.isfn(vm.hookStyle)){
styletext=vm.hookStyle(styletext);
}
//console.log('styletext',styletext)
core_vm.web_private_style.add(vm,styletext);
}
core_vm.start.web(vm);
vm[core_vm.aprand].has_started_self=1;
if(vm.getapp().config.strategy.append_to_pel_wait_loading_child_vm==false){
vm.__append_bin_el();
}
if(vm[core_vm.aprand].loadingsub_count==0){
vm.__onstart_a_zero_sub()
}
}
//loadingsub_count -- 一共两处 load.err 与 __onstart_a_zero_sub
proto.__onstart_a_zero_sub=function(){
var vm=this;
//console.log('__onstart_a_zero_sub',this.id)
if(this.__top_fragment && this[core_vm.aprand].has_started_self==1
&& vm.getapp().config.strategy.append_to_pel_wait_loading_child_vm==true){
vm.__append_bin_el();
}
//append后为了保证dom准备好 用了settimeout
//onchildstartfinished 用户自己判断 如果设置了 wait_child child结束就是自己onstart
//这里必须延时
if(vm.pvm){
setTimeout(function(){
vm.pvm[core_vm.aprand].loadingsub_count--;
if(vm.pvm[core_vm.aprand].loadingsub_count==0){
//pvm是否已经start完成了呢 都可能 根据 设置 append_to_pel_wait_loading_child_vm
vm.pvm.__onstart_a_zero_sub();
}
},0);
}else{
setTimeout(function(){
if(vm.getapp().hasstart==0){
vm.getapp().hasstart=1;
console.log('执行app.onstart1')
vm.getapp().onstart();
}
},10);
}
}
proto.__after_append_real=function(){
//console.log('__after_append_real',this.id)
var vm=this;
vm[core_vm.aprand].has_started=1;
delete vm._is_fresh_ing;
vm.__onshow.call(vm);
core_vm.tryvmfn(vm,vm,'onstart');
core_vm.tryvmfn(vm.pvm,vm,'onchildstart');
}
proto.__after_append=function(){
//console.log('__after_append',this.id)
var vm=this;
if(vm.getapp().config.strategy.append_to_pel_wait_loading_child_vm==true){
if(this.pvm){
this.pvm.__addto_onshow(function(){
vm.__after_append_real();
})
}else{
this.__after_append_real()
}
}else{
this.__after_append_real()
}
}
proto.__append_bin_el=function(){
//console.log('append_bin_el',vm.id);
var vm=this;
var fragment=vm.__top_fragment;
if(!fragment)return ;
var children=fragment.childNodes||[];
var len=children.length;
for(i=0;i<len;i++)vm[core_vm.aprand].els.push(children[i]);
var vmpel=vm.pel;
var i=0;
var __appento_ppel=false;
if(vm[core_vm.aprand].nodejson[0].childNodes.length==1 && len==1 &&
((core_vm.elget(vmpel,'appendto')=='ppel')||'ppel'==vm.config.appendto)){
vm.config.appendto='ppel';
//ppel可能是 #document-fragment 不能保存
core_vm.elset(vmpel,'_role_','placeholder');
var el=children[0];
//console.log('vm.ppel',vm.ppel ?'有':'无')
//if(vm.ppel)console.log('id是否相同',vm.ppel.id,vmpel.parentNode.id)
var ppel=vmpel.parentNode;
ppel.appendChild(el);
vmpel.after(el);
ppel.removeChild(vmpel);
vm.__addto_onshow(function(){
vm.ppel=vm[core_vm.aprand].els[0].parentNode;
})
el.replaced_pel=vmpel;
var node=vm[core_vm.aprand].nodejson[0].childNodes[0];
node.event=node.event||{};
if(vm[core_vm.aprand].pvmelevent)for(var k in vm[core_vm.aprand].pvmelevent)node.event[k]=vm[core_vm.aprand].pvmelevent[k];
vm.__bind_as_top_view(node,el,'because.ppel');
__appento_ppel=true;
}else{
vmpel.appendChild(fragment);
}
delete vm.__top_fragment;
for(var k in vm[core_vm.aprand].pvmelevent){
vm[core_vm.aprand].domeventnames[k]=1;
}
if(!__appento_ppel){
//console.error('现在绑定vm事件')
vm.__bind_events();
}
//确保el added
setTimeout(function() {
vm.__after_append();
},0);
}
proto.restart=function(json,cb){
//console.log('restart',json);
this.close();
if(core_vm.isfn(json)){
this.start(cb);
}else if(core_vm.isobj(json)){
if(json.src){
this.__setsrc(json.src);
}
this._is_fresh_ing=json.fresh===true ?true:false;
this.start(cb);
}else{
//可能 重新设置了data-option
this.start(cb);
}
}
proto.start=function(cb){
if(!core_vm.isfn(cb))cb=function(){}
//console.log('自己start',this.pel,this.id,this.src)
if(this[core_vm.aprand].has_defined){
//console.log('已经load')
this.__initdata_then_start(cb);
}else{
//都是去load
//if(this.pvm)console.log('去load',this.absrc,this.pvm.absrc,this.pvm[core_vm.aprand].absrcid);
core_vm.load(this,cb);
}
}
proto.show=function(){
var els=this[core_vm.aprand].els;
for(var i=els.length-1;i>-1;i--){
els[i].style.display=core_vm.elget(els[i],'lastdisplay')||"";
}
}
proto.hide=function(){
var els=this[core_vm.aprand].els;
for(var i=els.length-1;i>-1;i--){
core_vm.elset(els[i],'lastdisplay',els[i].style.display||"");
els[i].style.display='none';
}
}
}
/***/ }),
/* 51 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
module.exports.setproto=function(proto){
proto.__initdata_then_start=function(cb){
var vm=this;
core_vm.elset(vm.pel,'bindsidofvm',this.sid);
core_vm.elset(vm.pel,'isvmpel',true);
vm[core_vm.aprand].rootscope={alias:'',path:'',pscope:null,aid:0};
core_vm.inject.inject_from_pvm_before_start(vm,vm[core_vm.aprand].rootscope);
core_vm.tool.deepmerge(vm.data,vm[core_vm.aprand].append_data);
core_vm.tool.deepmerge(vm.option,vm[core_vm.aprand].append_option);
//console.log('__initdata_then_start')
if(!vm.getapp().store || !vm.getapp().store.vminit){
vm.__vmstart(cb);
return;
}
vm.getapp().store.vminit.call(vm.getapp(),vm,function(data){
if(typeof(data)=='object' && !Array.isArray(data)){
for(var k in data)vm[core_vm.aprand].datafrom_store.push(k);
if(vm.getapp().config.strategy.auto_deepclone_store_data){
core_vm.tool.deepmerge(vm.data,core_vm.tool.objClone(data));
}else {
for(var k in data)vm.data[k]=data[k];
}
}
if(vm.pvm && vm.pvm.dataProxy && core_vm.isfn(vm.pvm.dataProxy.vminit)){
vm.pvm.dataProxy.vminit.call(vm.pvm,vm,function(data){
if(data && typeof(data)=='object' && !Array.isArray(data)){
for(var k in data)vm[core_vm.aprand].datafrom_parent.push(k);
if(vm.getapp().config.strategy.auto_deepclone_store_data){
core_vm.tool.deepmerge(vm.data,core_vm.tool.objClone(data));
}else {
for(var k in data)vm.data[k]=data[k];
}
}
//console.log('得到pvm数据')
vm.__vmstart(cb);
})
}else{
//console.log('得到store数据')
vm.__vmstart(cb);
}
});
//不能把data改成proxy的原因是
//data.a=b 可以拦截并询问许可,但是没法回调
}
}
/***/ }),
/* 52 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
var _reqlib=__webpack_require__(1);
var _requirecache=__webpack_require__(2);
var _req_caltext=__webpack_require__(53);
var _libcal={};
module.exports=_libcal;
_libcal.evalResponse_genmod=function(spec,cb,meta,template,style_str,extend_from,when){
//console.log('evalResponse_genmod',spec.id,spec.urlsid,'模板长度='+template.length,'extend_from='+extend_from,when);//
//有require缓存 不到这里来
//这里 extend 不应该这里处理应在loadsub那里处理
if(spec.type=='vm' && extend_from){
core_vm.extend.onload(spec,cb,meta,template,style_str,extend_from,when);
}else{
//没有原型 可能是lib 可能没有urlsid就是原型先下载 然后给真的用的
//原型里面不能有require的 import的 否则找不到
var mod = _requirecache.get(spec.app,spec.vm,spec.id,'',spec.type,'genmod_3',spec.urlsid);
if (spec.type=='vm'){
spec.app.__cache.add_vmbody(spec.id,template,2);
if(style_str){
spec.app.__cache.add_vmstyle_inline(spec.id,style_str);
}
}
cb(null,mod);
}
}
_libcal.evalResponse=function(when,spec,responseText,cb,loads) {
if (!spec.url || !spec.id){
cb({type:'para',error:'!spec.url'},null);
return;
}
if(spec.loadfilefresh){
_requirecache.loadfilefresh_clear(spec,spec.id);
}
//console.log("evalResponse",spec,responseText);
if(spec.type=='css'||spec.type=='block'||spec.type=='text'){
cb(null,responseText);
return;
}
if(spec.type=='json'){
var obj={};
try{
obj=JSON.parse(responseText)
}catch(e){
core_vm.devalert(spec.app,'json error')
}
_requirecache.define(spec,spec.id,obj,spec.type,spec.refsid);
cb(null,core_vm.tool.objClone(obj));
return;
}
//todo check extend-mod
//console.log("下载完成 evalResponse,when=",when,spec.id,spec.fresh);//.toString() =protocol+//+hostname:port+pathname
var array = _req_caltext(responseText, spec.id,spec.type,spec);
var funcpara="require,module,exports,";
funcpara+='app';
var func_str=array[0];
try{
var newfn=new Function(funcpara,(spec.app.config.isdev==true?"//# sourceURL="+spec.url+"\n":'')+array[0]);
}catch(err){
//console.error("evalResponse fail", err.lineno,spec.url,err,func_str);//
//如 a=>s错误
//这里得不到错误行数 文件级别的函数外的错误
core_vm.devalert(spec.app,'js_SyntaxError:',spec.url+"\n"+err.toString());
//newfn=new Function(funcpara,'');//假冒一个函数
cb(new Error('js_SyntaxError'),null);
return;
}
_requirecache.define(spec,spec.id,newfn,spec.type,spec.refsid);
if (array[4] || array[5].length>0){
var extend_from=array[4] ;
var deps=array[5];
var needs=[];
for(var k in deps){
var src=deps[k].src;
var type=deps[k].type;
if(type=='css'){
needs.push({url:src, type:'css'});
}else if(type=='vm'){
needs.push({url:src, type:'vm'});//重复加入在 load时也会自动加倒cb里面
}else if(type=='block'){
if(deps[k].src){
var depobj={url:deps[k].src,type:'block'}
if(deps[k].importname){
depobj.importname=deps[k].importname;
}else if(deps[k].pathtag){
depobj.pathtag=deps[k].pathtag;
}
needs.push(depobj);
}
}else if(type=='lib'||type=='json'){
needs.push({id:src,url:src,type:type,importname:deps[k].importname});
}
}
if(extend_from ){
needs.push({url:extend_from, type:'vm',ifextend:1});
}
//console.log(spec.id,"依赖",needs,deps);
for(var i=needs.length-1;i>-1;i--){
needs[i].fresh=spec.fresh;
needs[i].pvmpath=spec.id;
needs[i].loadvm=spec.loadvm;
needs[i].app=spec.app;
//这里不给vmneeds[i].vm=spec.vm;
if(needs[i].type=='vm' && spec.app.config.path.vm[needs[i].url]){
needs[i].url=spec.app.config.path.vm[needs[i].url];
needs[i].knowpath=true;
}else if((needs[i].type=='lib'||needs[i].type=='json') && spec.app.config.path.lib[needs[i].url]){
needs[i].url=spec.app.config.path.lib[needs[i].url];
needs[i].knowpath=true;
}
if(needs[i].type=='vm'){
//vmneeds[i].vm= 此处没有vm 只是先现在而已
//先建立vm的好处是写法简单 如果几个page使用一个组件
//extend_from 时 是?先建立vm吗?
//先建立主要是写起来方便
}
//needs[i].urlsid=spec.urlsid;后面会计算
}
for(var k in needs){
_reqlib.cal_spec_path(needs[k],spec.url);//先计算 主要是下面判断是否有缓存
if(needs[k].ifextend)extend_from=needs[k].id;
}
for(var i=needs.length-1;i>-1;i--){
needs[i].from='deps';//在cal_spec_path后设置为deps load时就不再计算了
needs[i].refsid=spec.app.__cache.geturlsid(spec.id);
if(!needs[i].refsid){
console.error('找不到refsid',needs[i].url)
}
if(!spec.fresh && spec.app.__cache.check_ifhas(needs[i].type,needs[i].id,needs[i].refsid)){
//console.error('找到缓存模块,不再下载',needs[i].id);
//check 时加了refsid
needs.splice(i,1);
}
}
//console.error('准备下载deps',needs.length,extend_from)
if(needs.length==0){
_libcal.evalResponse_genmod(spec,cb,array[1],array[2],array[3],extend_from,0);
}else{
//needs中出了extend外的 vm,block可以不用等待用空函数去cb 用时pending就可以了 暂时都loads
loads(needs,function(errcount, errs, mods){
if(!errcount){
_libcal.evalResponse_genmod(spec,cb,array[1],array[2],array[3],extend_from,1);
}else{
core_vm.devalert(spec.app,"needs error",spec.id,spec.url,errs);
for(var k in errs){
if(errs[k]){
core_vm.onerror(spec.app,errs[k].type,needs[k].id,errs[k].error);
}
}
_libcal.evalResponse_genmod(spec,cb,array[1],array[2],array[3],extend_from,2);
}
})
};
}else{
_libcal.evalResponse_genmod(spec,cb,array[1],array[2],array[3],array[4],3);
}
}
/***/ }),
/* 53 */
/***/ (function(module, exports, __webpack_require__) {
var core_vm=__webpack_require__(0);
var _reqlib=__webpack_require__(1);
var requirePattern = /(?:^|[^\w\$_.])require\s*\(\s*["']([^"']*)["']\s*\)/g;
//可以 import * as abc from './abc.js' 就不要考虑 require了
//可以 import {a,b} abc from './abc.js' 就不要考虑 require了
var reg_elhook=new RegExp(' el-hook=[\'\"](.*?)[\'\"]', 'ig');
var reg_vmsrc;
var reg_style=new RegExp("<style(.*?)>([^<]*)</style>", 'ig');//
var reg_body=new RegExp("<body(.*?)>([\\s\\S]*?)</body>", 'i');
var reg_template=new RegExp("<template(.*?)>([\\s\\S]*?)</template>", 'i');
var reg_script=new RegExp("<script(.*?)>([\\s\\S]*?)</script>", 'ig');
var reg_html=new RegExp("<html(.*?)>([\\s\\S]*?)</html>", 'i');
var reg_head=new RegExp("<head(.*?)>([\\s\\S]*?)</head>", 'i');
var reg_prototype=new RegExp("<prototype>([\\s\\S]*?)</prototype>", 'i');
var reg_import=new RegExp("<import([\\s\\S]*?)>[</import>]*?", 'ig');
var adddep=function(deps,obj){
if(obj.src=='')return;
var findsame=deps.length==0?0:1;
for(var k in deps){
var findsame=1;
for(var n in obj){
if(obj[n]!==deps[k][n])findsame=0;
}
if(findsame==1)break;
}
if(findsame==0)deps.push(obj);
}
var all_isnot_seen=function (str){
for( var i=0,len=str.length; i<len; i++){
if(str.charCodeAt(i)>32) return false;
}
return true;//全部是不可见字符就忽略了
}
module.exports=function(content,id,type,spec){
//if(spec.type=='vm')console.log("cal_vmtext 1",id,spec.type,spec.from,spec.urlsid,"长度="+content.length);
var all_str=core_vm.delrem(content);
var script_str= type=='vm' ? '':all_str;
var style_str='',body_str=null,meta_str='',html_str='',extend_from='';
var deps=[];
if(type=='vm'){
//console.error('vm.code',spec.app.config.precode,spec.app.config.precode_regexp)
for(var k in spec.app.config.precode_regexp){
all_str=all_str.replace(spec.app.config.precode_regexp[k],function(a,b,c,d){
return '<'+k+b+'>'+core_vm.tool.htmlescape(c.replace(/\n/,''))+'</'+k+'>';
//<pre>qq</pre> qq前的第一个换行需要去掉
})
}
all_str=all_str.replace(reg_style,function(a,b,c,d){
//console.log('发现css','a='+a,'b='+b,'c='+c,'d='+d)
var match;
if(b)match=b.match(/src=['"](.*?)['"]/);
if(match){
adddep(deps,{type:'css',src:match[1],urlsid:spec.urlsid});
}else if(c){
style_str+=c;
}
return '';
});
//import的目的是随潮流 相比在config里面设置一样,但是只能在当前页面使用
all_str=all_str.replace(reg_import,function(a,b){
//console.log('发现 import','b='+b,spec.urlsid);
//导入后提前下载
//导入后只能用<name></name> 省不了 <div vm-src 这里关键是想用这个div标签 因为有可能有的css框架限定了div
var type,src,name;
b.replace(/[\s]{1,}type=['"]([\S]*?)['"]([\s]{0,}|[\>\/])/i,function(a,b){type=b});
b.replace(/[\s]{1,}src=['"]([\S]*?)['"]([\s]{0,}|[\>\/])/i,function(a,b){src=b});
b.replace(/[\s]{1,}name=['"]([\S]*?)['"]([\s]{0,}|[\>\/])/i,function(a,b){name=b});
//不能import lib json 因为路径计算复杂 可以 require('../ss/abc.js') 会计算成绝对路径
//console.log('发现import type='+type,'src='+src,'name='+name)
//这时pvm还没有
var src=_reqlib.gen_path(spec.app,src,spec.id,true,1);
//todo 如果path里面有 use里面有不加金deps
if(type=='prototype'){
extend_from=src;
}
spec.app.__cache.add_import_src_when_cal(type,spec.urlsid,name,src);
if(spec.app.__cache.check_ifhas(type,src,spec.urlsid)){
//console.error("引入已经有了",type,src)
return "";
}
if(type=='vm' ){
//不加入deps load时自动load
}else if(type=='block' ){
adddep(deps,{type:type,from:'import',src:src,utag:(name||src)});
}else if(type=='css' ){
adddep(deps,{type:'css',src:src,urlsid:spec.urlsid});
}else if(type=='lib' ){
adddep(deps,{type:'lib',src:src,urlsid:spec.urlsid});
}else if(type=='json' ){
//console.log('有json')
adddep(deps,{type:'json',src:src,urlsid:spec.urlsid});
}
//
return "";//vm不提前下载 因为没有vmid
});
//deps.vm 只有 import vm
all_str=all_str.replace(reg_body,function(a,b,c){body_str=c; return '';});
all_str=all_str.replace(reg_script,function(a,b,c){script_str+=c; return '';});
all_str=all_str.replace(reg_html,function(a,b,c){html_str=c; return ''; });
if(html_str){
html_str=html_str.replace(reg_head,function(a,b,c){meta_str=c;return "";});
if(body_str==null) body_str=html_str;
}
if(body_str==null)all_str=all_str.replace(reg_template,function(a,b,c){body_str=c;return '';});
if(body_str==null || all_isnot_seen(body_str))body_str='';
body_str=body_str.replace(/\{app\.(.*?)}/g,function(a,b,c,d){
//console.log('遇到主题',a,b)
return core_vm.tool.objGetDeep(spec.app,b);
})
//不在这里处理 主要这里得不到是urlsid
//reg_vmsrc=reg_vmsrc||new RegExp(' '+spec.app.config.vmtag+'-src'+'=[\'\"](.*?)[\'\"]', 'ig');
//body_str.replace(reg_vmsrc,function(a,b,c,d){ adddep(deps,{type:'vm',src:b}); });
body_str=body_str.replace(reg_elhook,function(a,b,c,d){
if(!spec.app.__cache.use.elhook[b] && b.indexOf('this.')!==0){
if(spec.app.config.path.elhook[b]){
adddep(deps,{type:'lib',src:spec.app.config.path.elhook[b]});
return ' el-hook="'+b+'" ';
}else{
var abs_b=_reqlib.gen_path(spec.app,b,spec.id,true,2);
adddep(deps,{type:'lib',src:abs_b,importname:b});
return ' el-hook="'+abs_b+'" ';
}
}else{
return ' el-hook="'+b+'" ';
}
});
//console.log(body_str)
for(var k in spec.app.config.blockpath_regexp){
body_str.replace(spec.app.config.blockpath_regexp[k],function(a,b,c,d){
adddep(deps,{type:'block',src:spec.app.config.path.block[k],pathtag:k});
delete spec.app.config.blockpath_regexp[k];//下载后就不需要了
})
}
}
if(script_str){
script_str=script_str.replace(requirePattern,function(a,b,c,d){
//console.log('解析require',a,b,c)
var importname=spec.app.__cache.check_if_import('lib',spec.urlsid,b);
if(!importname) importname=spec.app.__cache.check_if_import('json',spec.urlsid,b);
if(importname){
//console.log('已经import了',b,importname)
return a.replace(b,importname);
}
var abs_b,str;
if(spec.app.config.path.lib[b]){
abs_b=spec.app.config.path.lib[b];
str=a;
}else{
abs_b=_reqlib.gen_path(spec.app,b,spec.id,true,3);
str=a.replace(b,abs_b);
}
if(spec.app.__cache.get_jslib(abs_b)){
//console.log('找到lib',abs_b)
return str;
}
var obj={from:'require',type:'lib',src:abs_b}
if(b.indexOf('.json')>0 && b.lastIndexOf('.json')===b.length-5)obj.type='json';
adddep(deps,obj);
return str;
});
//console.log(script_str)
}
if(!script_str && deps.length==0 && !extend_from){
if(body_str==null)script_str=all_str;
else script_str='';
}
//console.log('计算结果',deps,spec.id)
//console.log("计算 script_str",script_str);
return [script_str.replace(/cor\e\./g,'co.').replace(/gcach\e\./g,'o0.'),
meta_str,body_str,style_str,extend_from,deps ];
}
/***/ })
/******/ ]);
});<file_sep>var core_vm=require('./vm.0webcore.js');
var hook=function(name,vm,el,when,node,libid){
var fn=vm.getcache().use.elhook[name] || (vm.getcache().jslib[libid]?vm.getcache().jslib[libid].exports:null);
if(core_vm.isfn(fn)){
try{
fn.call({},vm,el,when,node);
}catch(e){
core_vm.devalert(vm,'el-hook.'+name+':'+when,e)
}
}
}
module.exports=function(vm,el,src,when,node){
var name=src;
if(name.indexOf('this.')==0){
var fn=core_vm.tool.objGetDeep(vm,name.substr(5));
if(core_vm.isfn(fn)){
try{
fn.call({},vm,el,when,node);
}catch(e){
core_vm.devalert(vm,'el-hook.'+name+':'+when,e)
}
}
if(when=='childrenCreated'){
vm.__addto_onshow(function(){
fn.call({},vm,el,'attached',node);
})
}
return;
}
if(vm.getcache().use.elhook[name]){
hook(name,vm,el,when,node);
if(when=='childrenCreated'){
vm.__addto_onshow(function(){
hook(name,vm,el,'attached',node);
})
}
return;
}
var opt={
app:vm.getapp(),
loadvm:vm,pvmpath:vm.absrc,
url:vm.getapp().config.path.elhook[name]||name,
type:'lib',
fresh:false,
from:'loadelhook',elhook_second_times:(when=='childrenCreated'?true:false),
refsid:vm[core_vm.aprand].absrcid
};
var fresh=vm._is_fresh_ing ;
opt.fresh=fresh;
core_vm.require.load(opt,function(err,mod,spec){
if(err){
core_vm.onerror(vm.getapp(),'load_elhook_fail',spec.id,vm.absrc,err);
return;
}else if(core_vm.isfn(mod)){
if(vm.getapp().config.path.elhook[name]){
vm.getcache().use.elhook[name]=mod;
delete vm.getcache().jslib[spec.id];
hook(name,vm,el,when,node);
}else{
hook(name,vm,el,when,node,spec.id);
}
if(when=='childrenCreated'){
vm.__addto_onshow(function(){
hook(name,vm,el,'attached',node,spec.id);
})
}
}
});
}<file_sep>var core_vm=require('./vm.0webcore.js');
var debug = 1 ? console.log.bind(console, '[fastdom]') : function() {};
var win=window;
var raf = function(cb) {
return setTimeout(cb, 16);
};
var reads=[];
var writes=[];
var scheduled=false;
function runTasks(tasks) {
var task; while (task = tasks.shift()) task();
}
function flush() {
var error;
try {
runTasks(reads);
runTasks(writes);
} catch (e) { error = e; }
scheduled = false;
if (reads.length || writes.length) scheduleFlush();
if (error) {
debug('task errored', error.message);
}
}
var measure=function(fn, ctx) {
var task = !ctx ? fn : fn.bind(ctx);
reads.push(task);
scheduleFlush();
return task;
}
var mutate =function(fn, ctx) {
var task = !ctx ? fn : fn.bind(ctx);
writes.push(task);
scheduleFlush();
return task;
}
function scheduleFlush() {
if (!scheduled) {
scheduled = true;
raf(flush);
}
}
module.exports={
get:measure,
set:mutate,
}<file_sep>var core_vm=require('./vm.0webcore.js');
module.exports.setproto=function(proto){
var __real_setState=function(vm,p,v,oldv){
core_vm.tool.objSetDeep(vm.state,p,v);
var s=vm[core_vm.aprand].watching_state[p];
if(Array.isArray(s)){
var len=s.length;
s.forEach(function(opt,i){
core_vm.watchcb.watch(opt,p,oldv,v);
})
}
}
proto.setState=function(p,v,cb){
var vm=this;
var oldv=core_vm.tool.objGetDeep(this.state,p);
if(p===undefined)return;
if(oldv===v)return ;
__real_setState(this,p,v,oldv);
if(!core_vm.isfn(cb))cb=this.__blankfn;
this.pubup('state',{path:p,newv:v,oldv:oldv,},cb);
}
proto.__autobind_setstate=function(p,v,oldv){
this.setState(p,v);
}
}<file_sep>var core_vm=require('./vm.0webcore.js');
module.exports=function(vm,node,scope){
var config=vm.getapp().config;
if(config.precode.indexOf(node.utag)>-1){
return;
}
var newvm;
core_vm.calexp.nodeattrexp(vm,node,scope);
if(node.id && node.id[0]=='{')node.id=core_vm.calexp.exp(vm,node.id,scope);
if(node.classList && node.classList.length>0 ){
node.classList.forEach(function(str,i){
if(node.classList[i][0]=='{')node.classList[i]=core_vm.calexp.exp(vm,str,scope);
})
node.classList=node.classList.join(' ').replace(/ /g,' ').split(' ');
}
if(node.tag=='_exptext_'){
node.text=core_vm.calexp.exp(vm,node.exp_text,scope,'_exptext_');
}
if(node.watchs){
if(node.id){
node.id=core_vm.calexp.exp(vm,node.id,scope);
}else {
node.id=core_vm.cal.forece_calnodeid(vm,node,scope,'watch');
}
core_vm.watchcal.cal(vm,node,scope,'common');
}
var utag=node.utag;
if(utag===config.vmtag || node.attr[config.vmtag+'-src'] || vm.getcache().vmlib[utag]||
config.path.vm[utag] || vm.getcache().check_if_import('vm',vm[core_vm.aprand].absrcid,utag)){
if(node.id=='parent'||node.id=='child')node.id='';
if(!node.id)node.id=core_vm.define.newvmid();
node.childNodes=node.childNodes||[];
node.attr=node.attr||{};
if(node.childNodes.length>0)core_vm.inject.biaojiinject_in_calcommon(vm,scope,node.childNodes);
newvm={
src:vm.getcache().check_if_import('vm',vm[core_vm.aprand].absrcid,utag)||config.path.vm[utag]
||node.attr[config.vmtag+'-src']||node.attr.src||utag,
id:node.attr.id||node.id||core_vm.define.newvmid(),
};
if(vm.getcache().vmlib[utag]){
newvm.src=utag;
newvm.absrc=utag;
}
node.childskip_inject=1;
}
return newvm;
}
<file_sep>var core_vm=require('./vm.0webcore.js');
var _requirecache=require('./vm.requirecache.js');
module.exports.onload=function(spec,cb,meta,template,style_str,extend_from,when){
var mod_from=_requirecache.get(spec.app,spec.vm,extend_from,'','vm','genmod_2',spec.urlsid)||{};
var mod_me= _requirecache.get(spec.app,spec.vm,spec.id, '','vm','genmod_1',spec.urlsid)||{};
_requirecache.extendvm(spec.app,spec.id,extend_from);
spec.app.__cache.add_ref('vm',extend_from,spec.urlsid,'vmextend');
if(mod_from){
mod_from=core_vm.tool.objClone(mod_from);
for(var k in spec.vm){
delete mod_from[k];
}
core_vm.tool.deepmerge_notreplace(mod_me,mod_from);
}
var newbody,oldbody=spec.app.__cache.get_body_extend(extend_from);
var fn=mod_me.extendTemplate || spec.vm.extendTemplate
if(core_vm.isfn(fn)){
try{
newbody=fn.call(spec.vm,oldbody,template);
}catch(e){
core_vm.devalert(spec.app,'extendTemplate',e)
}
}else{
newbody=template||oldbody;
}
var newstyle='',oldstyle=spec.app.__cache.get_vmstyle_extend(extend_from);
var fn=mod_me.extendStyle || spec.vm.extendStyle;
if(core_vm.isfn(fn)){
try{
newstyle=fn.call(spec.vm,oldstyle,style_str);
}catch(e){
core_vm.devalert(spec.app,'extendStyle',e)
}
}else{
newstyle=style_str||oldstyle;
}
spec.app.__cache.add_vmbody(spec.id,newbody,1);
spec.app.__cache.add_vmstyle_inline(spec.id,newstyle);
cb(null,mod_me);
};
module.exports.inmem=function(app,vm,id,extend_from){
var mod_from=_requirecache.get(app,vm,extend_from,'','vm','extendinmem')||{};
var mod_me= _requirecache.get(app,vm,id, '','vm','extendinmem')||{};
mod_from=core_vm.tool.objClone(mod_from);
for(var k in vm)delete mod_from[k];
core_vm.tool.deepmerge_notreplace(mod_me,mod_from);
return mod_me;
}
<file_sep>
var pubsub=require('./applibpubsub.js');
app.sub=pubsub.sub;
app.subonece=pubsub.subonece;
app.unsub=pubsub.unsub;
app.pub=pubsub.pub;
var cache={};
var pubsub={};
module.exports=pubsub;
pubsub.sub=function(name,vm,cb){
if(typeof (name)!=='string' || typeof (cb)!=='function')return;
cache[name]=cache[name]||{};
cache[name][vm.sid]=[vm,cb,0];
}
pubsub.subonce=function(name,vm,cb){
if(typeof (name)!=='string' || (typeof (cb)!=='function'))return;
cache[name]=cache[name]||{};
cache[name][vm.sid]=[vm,cb,1];
}
pubsub.unsub=function(name,vm,cb){
if(typeof (name)!=='string' || (cb &&typeof (cb)!=='function'))return;
cache[name]=cache[name]||{};
if(cache[name][vm.sid]){
if(!cb || cb==cache[name][vm.sid][1])
delete cache[name][vm.sid];
}
}
var each = function (obj, fn, context) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
fn.call(context, obj[key], key, obj);
}
}
}
pubsub.pub=function(name,data,cb,from){
//console.log('pub',vm.id,cache[name])
if(typeof (name)!=='string' )return;
if(typeof(cb)!=='function')cb=function(){}
cache[name]=cache[name]||{};
var evs=cache[name];
each(evs,function(ev,sid){
if(ev[2]===-1)delete evs[sid];
})
each(evs,function(ev,sid){
ev[1].call(ev[0],data,function(data){
cb(data,ev[0])
},from);
if(ev[2]==1)ev[2]=-1;
})
}
<file_sep>module.exports={
"allowall":true,
"modal":{
},
//'vm1_vm2':'yes1',
/*'vm2_vm1':{
sender:['messagesample.vm2'],
receiver:'*',
center:function(event,system_cb){
console.log("结果到中心来了 1",event.sender,event.message,event.receiver,event.result);
//event.sendercallback(event.receiver,'我修改的结果');
system_cb();
},
},*/
"qqq":{},
"sss":{
sender:['modtest2'],
receiver:'*',
center:function(event,system_cb){
console.log("结果到中心来了 2");
cb(res)
},
}
}
<file_sep>var core_vm=require('./vm.0webcore.js');
module.exports.setproto=function(proto){
function intersect(arr1, arr2) {
if(!Array.isArray(arr1)||!Array.isArray(arr2))return [];
var res = [];
for(var i = 0; i < arr1.length; i++){
for(var j = 0; j < arr2.length; j++){
if(arr1[i] == arr2[j]){
res.push(arr1[i]);
arr1.splice(i,1);
arr2.splice(j,1);
i--;
j--;
}
}
}
return res;
};
proto.__delel_watchcb_notfind=function(id){
for(var k in this[core_vm.aprand].elsdom.id){
if(this[core_vm.aprand].elsdom.id[k]==id){
delete this[core_vm.aprand].elsdom.id[k];
}
}
}
proto.getel=function(name){
if(!name)return this[core_vm.aprand].els;
if(name[0]!=='#' && name[0]!=='.'&& name[0]!=='$'&& name[0]!=='@')name='#'+name;
var elsdom=this[core_vm.aprand].elsdom;
if(name[0]=='#'){
var id=elsdom.id[name.substr(1)];
if(id==undefined){
return null;
}else if(id==null){
delete elsdom.id[name.substr(1)];
return null;
}else{
return document.getElementById(id);
}
}else{
var els=[],ids=[];
if(name[0]=='@'){
ids=elsdom['listel'][name.substr(1)];
}else if(name[0]=='$'){
ids=elsdom['role'][name.substr(1)];
}else if(name[0]=='.'){
name=name.substr(1);
if(name.indexOf('.')==-1){
ids=elsdom['class'][name];
}else{
name=name.split('.');
for(var k in name)name[k]=core_vm.tool.trim(name[k]);
var id_s=[];
for(var k in name){
id_s[k]=[];
if(Array.isArray(elsdom['class'][name[k]])){
elsdom['class'][name[k]].forEach(function(tid){
id_s[k].push(tid);
})
}
}
ids=intersect(id_s[0],id_s[1]);
if(id_s.length>2){
for(var i=2;i<id_s.length;i++)ids=intersect(ids,id_s[i]);
}
}
}
if(ids){
for(var i=0,len=ids.length;i<len;i++){
els.push(document.getElementById(ids[i])||null);
}
for(var i=ids.length-1;i>-1;i--){
if(els[i]==null){
els.splice(i,1);
ids.splice(i,1);
}
}
}
return els;
}
}
proto.__regel=function(type,name,webelid_or_mob_el,index){
var elsdom=this[core_vm.aprand].elsdom;
if(type=='id'){
elsdom.id[name]=webelid_or_mob_el;
}else if(type=='listel'){
elsdom.listel[name]=elsdom.listel[name] || [];
var obj=elsdom.listel[name];
if(obj.indexOf(webelid_or_mob_el)==-1){
if(index!=undefined)obj.splice(index,0,webelid_or_mob_el)
else obj.push(webelid_or_mob_el);
}
}else if(type=='classList'){
var array=name;
for(var k in array){
if(this.getapp().config.strategy.cacheClassesAll!==true || this.config.cacheClasses.indexOf(array[k])===-1)continue;
elsdom.class[array[k]]=elsdom.class[array[k]] || [];
if(elsdom.class[array[k]].indexOf(webelid_or_mob_el)==-1){
if(index!=undefined)elsdom.class[array[k]].splice(index,0,webelid_or_mob_el)
else elsdom.class[array[k]].push(webelid_or_mob_el);
}
}
}else if(type=='role'){
elsdom.role[name]=elsdom.role[name] || [];
if(elsdom.role[name].indexOf(webelid_or_mob_el)==-1){
if(index!=undefined)elsdom.role[name].splice(index,0,webelid_or_mob_el)
else elsdom.role[name].push(webelid_or_mob_el);
}
}
}
proto.delel=function(thisel,ifchild,ifhas_remove_from_parent){
var velid,vclass,role;
if(!thisel)return;
var elsdom=this[core_vm.aprand].elsdom;
velid=thisel.getAttribute('id');vclass=thisel.getAttribute('classList');role=thisel.getAttribute('role');
if(velid){
for(var k in elsdom.id){
if(elsdom.id[k]===velid)delete elsdom.id[k];
}
if(elsdom.id[velid])delete elsdom.id[velid];
if(thisel.listid){
var ids=elsdom['listel'][thisel.listid];
if(Array.isArray(ids)){
var index=ids.indexOf(velid);
if(index>-1)ids.splice(index,1);
}
}
if(role){
if(elsdom.role[role]){
var index=elsdom.role[role].indexOf(velid);
if(index>-1)elsdom.role[role].splice(index,1);
}
}
if(vclass){
for(var k in vclass){
if(elsdom.class[vclass[k]]){
var index=elsdom.class[vclass[k]].indexOf(velid);
if(index>-1)elsdom.class[vclass[k]].splice(index,1);
}
}
}
}
if(thisel.childNodes){
for(var i=0,len=thisel.childNodes.length;i<len;i++){
if(thisel.childNodes[i].nodeType==1)this.delel.call(this,thisel.childNodes[i],true);
}
}
if(!ifchild)thisel.parentNode.removeChild(thisel);
}
}
<file_sep>var core_vm=require('./vm.0webcore.js');
var _reqlib=require('./vm.requirelib.js');
var sub_inrequires={};
var ensurce_sub_inrequire=function(app){
if(!sub_inrequires[app.id]){
sub_inrequires[app.id]=function (_subid) {
if(app.__cache.get_jslib(_subid)){
}else if(app.config.path.lib[_subid]) {
_subid=app.config.path.lib[_subid];
}
return inrequire(app,null,_subid, '','lib','inreq');
};
Object.defineProperty(sub_inrequires,app.id,{configurable: false,enumerable:false,writable:false});
}
}
var inrequire=function(app,vm,id,parentId,type,where,urlsid) {
var mod;
if(type=='lib'||type=='json')mod = app.__cache.get_jslib(id);
else mod = app.__cache.vmlib[id];
if(!mod){
return null;
}else if(type=='vm' && mod.__extend_from && where=='check'){
return core_vm.extend.inmem(app,vm,id,mod.__extend_from);
}
if(mod.mode!=='lib' && typeof (mod.block)=='function') {
mod.exports = {};
ensurce_sub_inrequire(app);
try{
var sub_inrequire = sub_inrequires[app.id];
mod.block.call(vm||{},sub_inrequire, mod, mod.exports,app);
}catch(e){
console.error("inrequire_execute_error",id,e,'parentId='+parentId,'app.id='+app.id);
core_vm.onerror(app,"inrequire_execute_error",id,e);
mod.exports = {};
}
if(type=='lib'){
mod.mode='lib'; delete mod.block;
}else if(mod.mode!==undefined){
}else{
if(Object.keys(mod.exports).length==0){
mod.mode='vmfn';
}else{
if(mod.exports[core_vm.aprand]){
mod.exports={};
}
mod.mode='lib';
delete mod.block;
}
}
}
if(mod.mode=='vmfn')return {};
if(!mod.exports)return null;
if(where=='inreq')return core_vm.tool.objClone(mod.exports);
else return mod.exports;
}
var extendvm=function(app,id,extend_from){
var mod = app.__cache.vmlib[id];
if(mod){
mod.__extend_from=extend_from;
}
}
var define =function(spec,id, block,type,refsid) {
var mod = {};
if(core_vm.isfn(block)){
mod.block=block;
}else{
mod.exports=block;
mod.mode='lib';
}
if(type=='vm'){
spec.app.__cache.add_vmlib(id,mod,refsid);
}else{
spec.app.__cache.add_jslib(id,mod,refsid);
}
return mod;
}
var loadfilefresh_clear = function(spec,id){
spec.app.__cache.loadfilefresh_clear(id);
}
module.exports={
define:define,
get:inrequire,
extendvm:extendvm,
loadfilefresh_clear:loadfilefresh_clear
};
<file_sep>
module.exports=function(vm,el,when,node){
//selfCreated,childrenCreated,attached
//console.log('hook,inpath,when='+when)
if(el && el.dataset['x']!=123)return;
if(when=='childrenCreated'){
el.style.background='#eee';
el.childNodes[0].style.color='green';
}
}<file_sep>var core_vm=require('./vm.0webcore.js');
module.exports.setproto=function(proto){
proto.__setData=function(p,v){
core_vm.tool.objSetDeep(this.data,p,v)
}
proto.__getData=function(p){
return core_vm.tool.objGetDeep(this.data,p)
}
var blank=function(){}
var check_source=function(vm,p){
var fp=p.split('.')[0];
if(vm[core_vm.aprand].datafrom_parent.indexOf(fp)>-1)return 'parent';
if(vm[core_vm.aprand].datafrom_store.indexOf(fp)>-1)return 'store';
return 'self';
}
proto.__autobind_setData=function(p,v,oldv){
this.setData(p,v);
}
proto.getData=function(p,cb){
if(!p || !core_vm.isfn(cb))return;
var vm=this;
var source=check_source(vm,p);
if(source=='self'){
cb(null,null,source);
}else if(source=='store'){
vm.getapp().store.get.call(vm.getapp(),vm,p,function(data,opt){
cb(data,opt,source);
});
}else if(source=='parent'){
var pcb=vm.pvm.dataProxy;
if(pcb)pcb=pcb.get;
if(core_vm.isfn(pcb)){
pcb.call(vm.pvm,vm,p,function(data,opt){
cb(data,opt,source);
})
}else{
cb(null)
}
}
}
proto.setData=function(p,v,cb){
var vm=this;
if(!core_vm.isfn(cb))cb=vm.__blankfn;
if(!p||v==undefined)return cb(false);
var oldv=vm.__getData(p);
if(oldv===v)return cb(false);
var source=check_source(vm,p);
if(source=='self'){
vm.__confirm_set_data_to_el(vm,p,v,oldv,cb);
cb(true,null,source);
}else if(source=='store'){
vm.getapp().store.set.call(vm.getapp(),vm,p,v,function(res,opt){
if(res)vm.__confirm_set_data_to_el(vm,p,v,oldv,cb);
cb(res,opt,source);
});
}else if(source=='parent'){
var pcb=vm.pvm.dataProxy;
if(pcb)pcb=pcb.set;
if(core_vm.isfn(pcb)){
pcb.call(vm.pvm,vm,p,v,function(res,opt){
if(res)vm.__confirm_set_data_to_el(vm,p,v,oldv,cb);
cb(res,opt,source);
})
}else{
cb(false,null,source)
}
}else{
cb(false,'datasource not match',source)
}
}
proto.addData=function(p,index,v,cb){
var vm=this;
if(!core_vm.isfn(cb))cb=vm.__blankfn;
if(!p||v==undefined)return cb(false);
var source=check_source(vm,p);
if(source=='self'){
vm.__confirm_add_data_to_el(vm,p,index,v,cb);
}else if(source=='store'){
vm.getapp().store.add.call(vm.getapp(),vm,p,index,v,function(res,opt){
if(res)vm.__confirm_add_data_to_el(vm,p,index,v,cb);
else cb(res,opt,source);
});
}else if(source=='parent'){
var pcb=vm.pvm.dataProxy;
if(pcb)pcb=pcb.add;
if(core_vm.isfn(pcb)){
pcb.call(vm.pvm,vm,p,index,v,function(res,opt){
if(res)vm.__confirm_add_data_to_el(vm,p,index,v,cb);
else cb(res,opt,source);
})
}else{
cb(false,null,source)
}
}else{
cb(false,'datasource not match',source);
}
}
proto.delData=function(p,index,count,cb){
var vm=this;
if(!core_vm.isfn(cb))cb=vm.__blankfn;
if(!p)return cb(false);
if(parseInt(index)!==index)return;
if(!count)count=1;
var source=check_source(vm,p);
if(source=='self'){
vm.__confirm_del_data_to_el(vm,p,index,count,cb);
}else if(source=='store'){
vm.getapp().store.del.call(vm.getapp(),vm,p,index,count,function(res,opt){
if(res)vm.__confirm_del_data_to_el(vm,p,index,count,cb)
else cb(res,opt,source);
});
}else if(source=='parent'){
var pcb=vm.pvm.dataProxy;
if(pcb)pcb=pcb.del;
if(core_vm.isfn(pcb)){
pcb.call(vm.pvm,vm,p,index,count,function(res,opt){
if(res)vm.__confirm_del_data_to_el(vm,p,index,count,cb);
else cb(res,opt,source);
})
}else{
cb(false,null,source)
}
}else{
cb(false,'datasource not match',source)
}
}
}<file_sep>var core_vm=require('./vm.0webcore.js');
module.exports.setproto=function(proto){
proto.sethtml=function(el,html){
if(typeof (el)=='string')el=this.getel(el);
if(!el)return;
var els=el.childNodes;for(var i=els.length-1;i>-1;i--)el.removeChild(els[i]);
this.addhtml(el,html);
}
proto.addhtml=function(el,html){
if(typeof (el)=='string')el=this.getel(el);
if(!el)return;
var vm=this;
var json=core_vm.calhtmltojson(html,vm[core_vm.aprand].node_max_sn+1,0,vm.getapp(),2);
vm[core_vm.aprand].nodejson.push(json[0]);
core_vm.create.nodes(vm,json[0],vm[core_vm.aprand].rootscope,el);
this.__bind_as_top_view(json[0],el);
}
}<file_sep>var core_vm=require('./vm.0webcore.js');
var global_vmid_seed=10;
var global_nodeid_seed=0;
var vmclass=function(id){
this.id=id;
this.__init();
}
var vmproto=vmclass.prototype;
var cb=function(){}
var need_keep=['appsid','id','sid','src','absrc','pel','pvm',];
var need_keep_rand=['absrcid','pvmevent','pvmelevent','pvmnode'];
vmproto.__init=function(ifclose){
if(!ifclose){
this.sid=this.sid||(++global_vmid_seed);
this.id=this.id||('id_auto_'+String(this.sid));
}
if(ifclose){
this.__auto_unsub_app();
for(var k in this){
if(!this.hasOwnProperty(k))continue;
else if(need_keep.indexOf(k)>-1)continue;
else if(k===core_vm.aprand)continue;
else {
this[k]=null;
}
}
for(var k in this[core_vm.aprand])if(need_keep_rand.indexOf(k)==-1)delete this[core_vm.aprand][k];
}
if(!ifclose){
this[core_vm.aprand]={};
Object.defineProperty(this,core_vm.aprand, {configurable: false,enumerable: false,writable:false});
}
let obj=this[core_vm.aprand];
if(!ifclose){
obj.pvmevent={};
obj.pvmelevent={};
obj.pvmnode=null;
}
obj.pvmslot={};
obj.has_started=0;
obj.has_defined=0;
obj.append_data={};
obj.append_option={};
obj.datafrom_store=[];
obj.datafrom_parent=[];
obj.cbs_on_define=[];
obj.cbs_onstart=[];
obj.cbs_onclose=[];
obj.cbs_onshow=[];
}
vmproto.__clean_tmp_after_start=function(){
delete this[core_vm.aprand].pvmslot;
delete this[core_vm.aprand].append_data;
delete this[core_vm.aprand].append_option;
delete this[core_vm.aprand].has_started_self;
delete this[core_vm.aprand].has_defined;
delete this[core_vm.aprand].cbs_onstart;
delete this[core_vm.aprand].cbs_onshow;
delete this[core_vm.aprand].loadingsub_count;
delete this[core_vm.aprand].startcb_of_vmstart;
}
vmproto.__define=function(vmobj){
var tvm=this;
if(typeof (vmobj)!=='object' ||vmobj===null)vmobj={};
if(vmobj.sid)delete vmobj.sid;
if(vmobj.id)delete vmobj.id;
if(vmobj.src)delete vmobj.src;
if(vmobj.pel)delete vmobj.pel;
if(vmobj.ppel)delete vmobj.ppel;
for(var k in vmobj){
if(vmproto[k]===undefined)tvm[k]=vmobj[k];
}
tvm.data=tvm.data||{};
tvm.state=tvm.state||{};
tvm.option=tvm.option||{};
tvm.event=tvm.event||{};
tvm.config=tvm.config||{};
if(!Array.isArray(tvm.config.cacheClasses))tvm.config.cacheClasses=[];
tvm.config.appendto= (tvm.config.appendto==='ppel')?'ppel':"pel";
tvm.__auto_sub_app();
var obj=this[core_vm.aprand];
obj.newid_2_oldid={}
obj.vmchildren={};
obj.rootscope={};
obj.nodejson=[];
obj.seed_of_el_aid=0;
obj.els_binded=[];
obj.els=[];
obj.elsdom={'id':{},'class':{},'role':{},'listel':{}};
obj.private_style={};
obj.domeventnames={};
obj.domeventnames_binded=[];
obj.cbs_onstart=[];
obj.cbs_onclose=[];
obj.cbs_onshow=[];
obj.loadingsub_count=0;
obj.has_defined=1;
obj.has_started=0;
obj.inline_onjs=[''];
obj.inline_watchjs=[''];
obj.watching_data={};
obj.watching_state={};
obj.watching_option={};
obj.watching_list={};
this.__ensure_fn();
return this;
}
require("./vm.proto.child.js").setproto(vmproto);
require("./vm.proto.base.js").setproto(vmproto);
require("./vm.proto.store.js").setproto(vmproto);
require("./vm.proto.dataflow.data.js").setproto(vmproto);
require("./vm.proto.dataflow.option.js").setproto(vmproto);
require("./vm.proto.dataflow.state.js").setproto(vmproto);
require("./vm.proto.dataflow.child.js").setproto(vmproto);
require("./vm.proto.dataflow.toui.js").setproto(vmproto);
require("./vm.proto.elhtml.js").setproto(vmproto);
require("./vm.proto.elbind.js").setproto(vmproto);
require("./vm.proto.elgetter.js").setproto(vmproto);
require("./vm.proto.start.js").setproto(vmproto);
require("./vm.proto.close.js").setproto(vmproto);
require("./vm.proto.event.js").setproto(vmproto);
vmproto.__setsrc=function(src){
if(typeof (src)!=='string')src='';
this.src=src||'';
if(this.src){
this.absrc=_reqlib.gen_path(this.getapp(),this.src,this.pvm ?this.pvm.absrc:'',true,5);
this[core_vm.aprand].absrcid=this.getcache().geturlsid(this.absrc);
}
}
var libbatchdom=require("./vm.batchdom.js");
vmproto.batchdom=function(fn, ctx){
libbatchdom.set(fn, ctx)
};
vmproto.getapp=function(){
return core_vm.wap;
}
vmproto.getcache=function(){
return core_vm.wap.__cache;
}
for(var k in vmproto){
if(k[0]=='_')Object.defineProperty(vmproto,k,{configurable: false,enumerable:false,writable:false});
}
var _reqlib=require('./vm.requirelib.js');
var define=function(opt,uap){
var tvm=new vmclass(opt.id);
if(opt.el)tvm.pel=opt.el;
tvm.getcache().vmsbysid[tvm.sid]=tvm;
if(opt.pvm){
tvm.getcache().vmparent[tvm.sid]=opt.pvm.sid;
tvm.pvm=opt.pvm;
tvm.pvm[core_vm.aprand].vmchildren= tvm.pvm[core_vm.aprand].vmchildren || {};
tvm.pvm[core_vm.aprand].vmchildren[tvm.id]=tvm.sid;
}
tvm.__setsrc(opt.src||opt.url);
return tvm;
}
module.exports={
vmclass:vmclass,
define:define,
newvmid:function(){
global_nodeid_seed++;
return 'id_auto_'+global_nodeid_seed;
},
protect:function(){
}
}
module.exports.extend=function(name,fn){
if(core_vm.isfn(fn))vmproto[name]=fn;
}
<file_sep>
var core_vm=require('./vm.0webcore.js');
module.exports.setproto=function(proto){
proto.add_vmlib=function(id,mod,refsid){
mod.refsids=[refsid];
this.vmlib[id] = mod;
var path=this.getapp().config.path;
for(var k in path.vm){
if(path.vm[k]===id){
this.keep('vm',id);
}
}
}
proto.add_vmbody=function(id,body,when){
this.vmbody[id]=body+'';
}
proto.add_vmstyle_inline=function(id,style_str){
this.vmstyle[id]=core_vm.tool.trim(style_str);
}
proto.get_vmlib=function(id){
return this.vmlib[id];
}
proto.get_body_extend=function(absrc){
return this.vmbody[absrc]||'';
}
proto.get_body=function(vm){
return this.vmbody[vm.absrc]+'';
}
proto.get_vmstyle_extend=function(absrc){
return this.vmstyle[absrc]||'';
}
proto.get_vmstyle=function(vm){
var text=this.vmstyle[vm.absrc]||'';
text+=this.__get_importstyle(vm);
return text;
}
}<file_sep>
var core_vm=require('./vm.0webcore.js');
module.exports.setproto=function(proto){
proto.add_jslib=function(id,mod,refsid){
this.jslib[id]=mod;
if(refsid)mod.refsids=[refsid];
var path=this.getapp().config.path;
for(var k in path.lib){
if(path.lib[k]===id)this.keep('lib',id);
}
}
proto.get_jslib=function(id){
return this.jslib[id];
}
}<file_sep>var wrap={};
wrap['navbar']='<nav class="navbar navbar-default"><div class="container-fluid"><div class="collapse navbar-collapse"><ul class="nav navbar-nav">'
+'<content></content>'+'</ul></div></div></nav>';
module.exports=wrap;<file_sep>
var core_vm=require('./vm.0webcore.js');
module.exports.web=function(vm){
if(!vm.pel.style.display && vm.config.pelDisplayType)vm.pel.style.display=vm.config.pelDisplayType;
var fragment = document.createDocumentFragment();
fragment.id=vm.id+'__tmp'
vm.__top_fragment=fragment;
core_vm.create.nodes(vm,vm[core_vm.aprand].nodejson[0],vm[core_vm.aprand].rootscope,fragment);
}
<file_sep>var core_vm=require('./vm.0webcore.js');
module.exports.biaojiinject_in_calcommon=function(vm,scope,nodes){
nodes.forEach(function(node,sn){
core_vm.inject.biaojiinject_level_1(vm,scope,node.childNodes);
});
}
module.exports.biaojiinject_level_1=function(vm,scope,nodes){
nodes.forEach(function(node,sn){
node.$injectscope=scope;
node.$injectfromvm_sid=vm.sid;
node.attr=node.attr ||{};
node.attr.owner='parent';
});
}
module.exports.inject_one_string=function(pvm,vm,utag,text,where){
var type=typeof (vm[where][utag]);
var caninject=true;
if(type=='undefined')vm[where][utag]=text;
else if(type=='boolean')vm[where][utag]=Boolean(text);
else if(type=='number')vm[where][utag]=Number(text);
else if(type=='float')vm[where][utag]=parseFloat(text);
else if(type=='string')vm[where][utag]=String(text);
else if(type=='object'){
if(typeof (text)=='string'){
var fn=new Function("e",'return [ '+text+' ] ');
var obj;
try{
obj=fn.call({},null);
}catch(e){}
if(obj)text=obj[0];
}
if(typeof (text)=='object'){
if(Array.isArray(vm[where][utag]) && Array.isArray(text) )vm[where][utag]=text;
else if(!Array.isArray(vm[where][utag]) && !Array.isArray(text) )vm[where][utag]=text;
else caninject=false;
}else{
caninject=false;
}
}else{
vm[where][utag]=text;
}
if(caninject){
if(vm[core_vm.aprand].datafrom_parent.indexOf(utag)===-1)vm[core_vm.aprand].datafrom_parent.push(utag);
}
}
module.exports.cal_inject_node=function(vm,innode){
var new_data_node={tag:'data',utag:'data',attr:{},attrexp:{},childNodes:[]};
var new_attr_node={tag:'option',utag:'option',attr:{},attrexp:{},childNodes:[]}
var finddata=0,findattr=0;
if(innode.dataset){
for(let k in innode.dataset)innode.attr['data-'+k]=innode.dataset[k]
}
core_vm.tool.each(innode.attr,function(v,k){
if(k=='id' || k=='style' || k=='role' || k=='event'|| k==vm.getapp().config.vmtag+'-src')return;
if(k.indexOf('data-')===0){
k=k.substr(5);
finddata=1;
if(v.indexOf('{')==0)new_data_node.attrexp[k]=v;
else new_data_node.attr[k]=v;
}else if(k.indexOf('option-')===0){
k=k.substr(7);
findattr=1;
if(typeof (v)=='string' && v.indexOf('{')==0)new_attr_node.attrexp[k]=v;
else new_attr_node.attr[k]=v;
}
})
if(finddata==1)innode.childNodes.push(new_data_node);
if(findattr==1)innode.childNodes.push(new_attr_node);
}
module.exports.inject_from_pvm_before_start=function(vm){
if(!vm[core_vm.aprand].pvmnode ){
return;
}
var pvm=vm.pvm;
var innode=core_vm.tool.objClone(vm[core_vm.aprand].pvmnode);
innode.childNodes.forEach(function(node,sn){
if(!core_vm.isobj(node))return;
node.attr=node.attr||{};
if(node.utag=='option' || node.utag=='data'){
vm[node.utag]=vm[node.utag]||{};
if(node.attrexp){
for(var k in node.attrexp)node.attr[k]=node.attrexp[k];
}
for(var k in node.attr){
var text=node.attr[k];
if(typeof (node.attr[k])!=='string' || text.indexOf('this.')==-1){
module.exports.inject_one_string(pvm,vm,k,text,node.utag);
continue;
}
var watch_path=text.replace(/^\{*|\}*$/g, '').replace('this.','');
var in_data=core_vm.tool.objGetDeep(pvm,watch_path);
if(in_data==undefined){
in_data=core_vm.calexp.exp(pvm,text,pvm[core_vm.aprand].rootscope,'_exptext_');
}
if(typeof (in_data)=='object'){
in_data=core_vm.tool.objClone(in_data);
}
module.exports.inject_one_string(pvm,vm,k,in_data,node.utag);
}
}else{
if(node.attr.slot){
vm[core_vm.aprand].pvmslot[node.attr.slot]=node;
}else{
vm[core_vm.aprand].pvmslot[core_vm.aprand]=vm[core_vm.aprand].pvmslot[core_vm.aprand]||[];
vm[core_vm.aprand].pvmslot[core_vm.aprand].push(node);
}
}
});
}
module.exports.use_inject_nodes_when_create=function(tvm,node,scope){
node.attrexp=node.attrexp||{};
if(scope && node.attrexp && node.attrexp.name){
node.attrexp.name=core_vm.calexp.exp(tvm,node.attrexp.name,scope);
}
var pnode=node.parentNode;
var pc=node.parentNode.childNodes;
var index=pc.indexOf(node);
var name=!scope ?'' :(node.attr.name||node.attrexp.name);
if(scope && name){
var res=tvm[core_vm.aprand].pvmslot[name];
if(res){
if(index===-1){
node.tag=res.tag;
node.utag=res.utag;
node.attr={};
for(var k in res.attr)node.attr[k]=res.attr[k];
node.childNodes=res.childNodes;
}else{
pc.splice(index,1,res);
pc[index].parentNode=pnode;
return pc[index];
}
module.exports.bind_vm_pvm_when_inject_node(tvm,res);
}
}else if(!scope && tvm[core_vm.aprand].pvmslot[core_vm.aprand]){
var index=pc.indexOf(node);
if(index==-1)index=0;
pc.splice(index,1);
var mainslots=tvm[core_vm.aprand].pvmslot[core_vm.aprand];
for(var k=0;k<mainslots.length;k++){
mainslots[k].attr.owner='parent';
module.exports.bind_vm_pvm_when_inject_node(tvm,mainslots[k]);
pc.splice(index+k,0,mainslots[k]);
mainslots[k].parentNode=pnode;
}
}
}
module.exports.bind_vm_pvm_when_inject_node=function(tvm,node){
if(!node)return;
if(node.event){
for(var k in node.event){
tvm[core_vm.aprand].domeventnames[k]=1;
}
}
if(node.childNodes && node.childNodes.length>0){
for(var i=0,len=node.childNodes.length;i<len;i++)module.exports.bind_vm_pvm_when_inject_node(tvm,node.childNodes[i]);
}
}
<file_sep>var core_vm=require('./vm.0webcore.js');
var cal_els_filter=function(vm,str,scope){
scope=scope||{};
var calstr=str;
var mustv;
var array,res,method;
if(str.indexOf('>=')>-1){ array=str.split('>=');method='>=';}
else if(str.indexOf('<=')>-1){ array=str.split('<=');method='<=';}
else if(str.indexOf('!==')>-1){ array=str.split('!==');method='!==';}
else if(str.indexOf('===')>-1){ array=str.split('===');method='==';}
else if(str.indexOf('==')>-1){ array=str.split('==');method='==';}
else if(str.indexOf('>')>-1){ array=str.split('>');method='>';}
else if(str.indexOf('<')>-1){ array=str.split('<');method='<';}
if(array && method){
calstr=core_vm.tool.trim(array[0]);
mustv=core_vm.calexp.exp(vm,core_vm.tool.trimquota(core_vm.tool.trim(array[1])),scope,'cal_els_filter');
res=core_vm.calexp.exp(vm,calstr,scope,'cal_els_filter');
var result=false;
if(method=='>='){if(1+Number(res)>=1+Number(mustv))result=true;}
else if(method=='>'){if(1+Number(res)>1+Number(mustv))result=true;}
else if(method=='<='){if(1+Number(res)<=1+Number(mustv))result=true;}
else if(method=='<'){if(1+Number(res)<1+Number(mustv))result=true;}
else if(method=='=='){if(res+''==mustv+'')result=true;}
else if(method=='!=='){if(res+''!==mustv+'')result=true;}
return result;
}else{
res=core_vm.calexp.exp(vm,str,scope,'cal_els_filter');
if(res && res!=='null' && res!=='false'&& res!=='undefined')return true;
else return false;
}
}
var parse_if=function(name,vm,scope){
return cal_els_filter(vm,name,scope);
}
var if_multi=function(vm,html){
return html.replace(/{%[ ]{0,}if([\s\S]*?){%[ ]{0,}endif[ ]{0,}%}/g, function (item, qparam,param) {
var ifs=[];
var strs=[];
var starts=[];
var lens=[];
var result=[];
item.replace(/{%([\s\S]*?)%}([\s\S]*?)/gm,function(a,b,c,d){
ifs.push(b);
starts.push(d);
lens.push(a.length);
});
for(var k=0,len=starts.length-1;k<len;k++){
strs.push(item.substr(starts[k]+lens[k],starts[k+1]-starts[k]-lens[k]))
}
var return_sn=-1;
for(var i=0,len=ifs.length;i<len;i++){
ifs[i]=core_vm.tool.trim(ifs[i]);
var this_result=false;
if(ifs[i].indexOf('elseif ')==0 || ifs[i].indexOf('else if ')==0){
this_result=cal_els_filter(vm,core_vm.tool.trim(ifs[i].substr(7)));
}else if(ifs[i].indexOf('if ')==0){
this_result=cal_els_filter(vm,core_vm.tool.trim(ifs[i].substr(3)));
}else if(ifs[i]=='else'){
this_result=true;
}
if(this_result==true){
return_sn=i;
break;
}
}
if(return_sn>-1)return strs[return_sn];
else return '';
});
}
var single=function(vm,if_result,filter,sn,scope,start_index){
if(filter){
if(filter=='else'){
var find_true=0;
for(var j=sn-1;j>start_index;j--){
if(if_result[j]==true){
find_true=1;
break;
}
}
if(find_true==0){
if_result[sn]=true;
}else{
if_result[sn]=false;
}
}else if(filter.substr(0,7) =='elseif:'){
var find_true=0;
for(var j=sn-1;j>start_index;j--){
if(if_result[j]==true){
find_true=1;
break;
}
}
if(find_true==1){
if_result[sn]=false;
}else if(if_result[sn-1]===false){
if_result[sn]=parse_if(filter.substr(7),vm,scope);
}
}else if(filter.substr(0,3) =='if:'){
if_result[sn]=parse_if(filter.substr(3),vm,scope);
}else{
if_result[sn]=parse_if(filter,vm,scope);
}
}else{
if_result[sn]=true;
}
}
module.exports={
single:single,
multi:if_multi
}<file_sep>
<html >
<h4>apple is defined in config.vmpath,i will auto load and cache it</h4>
<h4>normaly, you need inject something to it</h4>
<pre>
<apple>
<data color=red size= 8cm bgcolor=#999/>
</apple>
<apple>
<data color=blue size= 9cm/>
<node id='cb'>
<button on-click='cback'>callback me</button>
</node>
</apple>
</pre>
<h4>sample</h4>
<div style='display:inline-block;'>
<div style='width:50%;float:left'>
<apple>
<data color=red size= 8cm bgcolor=#999/>
<cbbtn><button on-click='cback'>callback</button></cbbtn>
</apple>
</div>
<div style='width:50%;float:right'>
<apple>
<data color=blue size= 9cm/>
<node id='cb'>
<button on-click='cback'>callback me</button></node>
</apple>
</div>
</div>
</html>
<script>
module.exports={
domevent:{
cback:function(){console.log("this.id="+this.id)}
}
}
</script><file_sep>var core_vm=require('./vm.0webcore.js');
module.exports.setproto=function(proto){
proto.__initdata_then_start=function(cb){
var vm=this;
core_vm.elset(vm.pel,'bindsidofvm',this.sid);
core_vm.elset(vm.pel,'isvmpel',true);
vm[core_vm.aprand].rootscope={alias:'',path:'',pscope:null,aid:0};
core_vm.inject.inject_from_pvm_before_start(vm,vm[core_vm.aprand].rootscope);
core_vm.tool.deepmerge(vm.data,vm[core_vm.aprand].append_data);
core_vm.tool.deepmerge(vm.option,vm[core_vm.aprand].append_option);
if(!vm.getapp().store || !vm.getapp().store.vminit){
vm.__vmstart(cb);
return;
}
vm.getapp().store.vminit.call(vm.getapp(),vm,function(data){
if(typeof(data)=='object' && !Array.isArray(data)){
for(var k in data)vm[core_vm.aprand].datafrom_store.push(k);
if(vm.getapp().config.strategy.auto_deepclone_store_data){
core_vm.tool.deepmerge(vm.data,core_vm.tool.objClone(data));
}else {
for(var k in data)vm.data[k]=data[k];
}
}
if(vm.pvm && vm.pvm.dataProxy && core_vm.isfn(vm.pvm.dataProxy.vminit)){
vm.pvm.dataProxy.vminit.call(vm.pvm,vm,function(data){
if(data && typeof(data)=='object' && !Array.isArray(data)){
for(var k in data)vm[core_vm.aprand].datafrom_parent.push(k);
if(vm.getapp().config.strategy.auto_deepclone_store_data){
core_vm.tool.deepmerge(vm.data,core_vm.tool.objClone(data));
}else {
for(var k in data)vm.data[k]=data[k];
}
}
vm.__vmstart(cb);
})
}else{
vm.__vmstart(cb);
}
});
}
}<file_sep>var core_vm=require('./vm.0webcore.js');
var check_block_text=function(nodes,name,text){
nodes.forEach(function(node){
var find=0;
if(node.event){
for(var k in node.event){
if(node.event[k]==name){
node.event[k]=text;
find=1;
}
}
}
if(find==1)return;
for(var k in node.attr){
if(typeof (node.attr[k])=='string' && node.attr[k].indexOf(name)>-1){
node.attr[k]=node.attr[k].replace(name,text);
}
}
if(node.text && node.text.indexOf(name)>-1){
node.text=node.text.replace(name,text);
}
if(node.childNodes && node.childNodes.length>0){
check_block_text(node.childNodes,name,text);
}
});
}
module.exports.find_block=function(nodes,vm,scope,pel){
nodes.forEach(function(node,sn){
var utag=node.utag;
if(vm.getcache().use.block[utag] || vm.getcache().check_if_import('block',vm[core_vm.aprand].absrcid,utag)){
var oldparent=node.parentNode;
var oldid=node.id;
blocktext=vm.getcache().get_block_text(vm,utag);
if(!blocktext){
return;
}
var s=[];
for(var k in node.attr)if(s.indexOf(k)==-1)s.push(k);
for(var k in node.attrexp)if(s.indexOf(k)==-1)s.push(k);
s.forEach(function(name,i){
var text=node.attr[name];
if(!text && node.attrexp)text=node.attrexp[name];
if(i==0 && utag.indexOf('-')==-1){
if(!text && node.childNodes.length>0)text=node.childNodes[0].text;
}
if(text){
text=core_vm.calexp.exp(vm,text,scope);
blocktext=blocktext.replace(new RegExp('\\$'+name, 'g'),text)
}
})
nodes[sn]=core_vm.calhtmltojson(blocktext,0,0,vm.getapp(),5)[0].childNodes[0];
nodes[sn].parentNode=oldparent;
if(oldid)nodes[sn].id=oldid;
if(node.attr.style)nodes[sn].attr.style=node.attr.style;
}
})
}<file_sep>var core_vm=require('./vm.0webcore.js');
var g_classid=1;
module.exports.add=function(vm,text){
var id=vm.sid;
var css=vm[core_vm.aprand].private_style;
text=text.replace(/\.\s{0,}([-\w]+){/g,function(a,b,c){
css[b]=css[b]||'priv_'+(g_classid++);
return '.'+css[b]+'{';
});
text=text.replace(/\.\s{0,}([-\w]+)\s{1,}/g,function(a,b,c){
css[b]=css[b]||'priv_'+(g_classid++);
return '.'+css[b]+' ';
});
var curStyle=document.getElementById("_privatestyle_"+id);
if(!curStyle){
var curStyle = document.createElement('style');
curStyle.type = 'text/css';
curStyle.id="_privatestyle_"+id;
curStyle.appendChild(document.createTextNode(text));
document.getElementsByTagName("head")[0].appendChild(curStyle);
}else{
curStyle.textContent+='\n'+text;
}
}
module.exports.get=function(vm,name){
var css=vm[core_vm.aprand].private_style;
if(!css)return '';
return css[name] || '';
}
module.exports.check=function(vm,node){
var css=vm[core_vm.aprand].private_style;
if(!css)return;
node.classList.forEach(function(name,i){
if(css[name]){
node.classList[i]=css[name];
}
})
}<file_sep>console.log("this is modbnotinlibpath2 ");
module.exports ={
str:"This is modbnotinlibpath2.js!",
}<file_sep>var core_vm=require('./vm.0webcore.js');
var _reqlib=require('./vm.requirelib.js');
var requirePattern = /(?:^|[^\w\$_.])require\s*\(\s*["']([^"']*)["']\s*\)/g;
var reg_elhook=new RegExp(' el-hook=[\'\"](.*?)[\'\"]', 'ig');
var reg_vmsrc;
var reg_style=new RegExp("<style(.*?)>([^<]*)</style>", 'ig');
var reg_body=new RegExp("<body(.*?)>([\\s\\S]*?)</body>", 'i');
var reg_template=new RegExp("<template(.*?)>([\\s\\S]*?)</template>", 'i');
var reg_script=new RegExp("<script(.*?)>([\\s\\S]*?)</script>", 'ig');
var reg_html=new RegExp("<html(.*?)>([\\s\\S]*?)</html>", 'i');
var reg_head=new RegExp("<head(.*?)>([\\s\\S]*?)</head>", 'i');
var reg_prototype=new RegExp("<prototype>([\\s\\S]*?)</prototype>", 'i');
var reg_import=new RegExp("<import([\\s\\S]*?)>[</import>]*?", 'ig');
var adddep=function(deps,obj){
if(obj.src=='')return;
var findsame=deps.length==0?0:1;
for(var k in deps){
var findsame=1;
for(var n in obj){
if(obj[n]!==deps[k][n])findsame=0;
}
if(findsame==1)break;
}
if(findsame==0)deps.push(obj);
}
var all_isnot_seen=function (str){
for( var i=0,len=str.length; i<len; i++){
if(str.charCodeAt(i)>32) return false;
}
return true;
}
module.exports=function(content,id,type,spec){
var all_str=core_vm.delrem(content);
var script_str= type=='vm' ? '':all_str;
var style_str='',body_str=null,meta_str='',html_str='',extend_from='';
var deps=[];
if(type=='vm'){
for(var k in spec.app.config.precode_regexp){
all_str=all_str.replace(spec.app.config.precode_regexp[k],function(a,b,c,d){
return '<'+k+b+'>'+core_vm.tool.htmlescape(c.replace(/\n/,''))+'</'+k+'>';
})
}
all_str=all_str.replace(reg_style,function(a,b,c,d){
var match;
if(b)match=b.match(/src=['"](.*?)['"]/);
if(match){
adddep(deps,{type:'css',src:match[1],urlsid:spec.urlsid});
}else if(c){
style_str+=c;
}
return '';
});
all_str=all_str.replace(reg_import,function(a,b){
var type,src,name;
b.replace(/[\s]{1,}type=['"]([\S]*?)['"]([\s]{0,}|[\>\/])/i,function(a,b){type=b});
b.replace(/[\s]{1,}src=['"]([\S]*?)['"]([\s]{0,}|[\>\/])/i,function(a,b){src=b});
b.replace(/[\s]{1,}name=['"]([\S]*?)['"]([\s]{0,}|[\>\/])/i,function(a,b){name=b});
var src=_reqlib.gen_path(spec.app,src,spec.id,true,1);
if(type=='prototype'){
extend_from=src;
}
spec.app.__cache.add_import_src_when_cal(type,spec.urlsid,name,src);
if(spec.app.__cache.check_ifhas(type,src,spec.urlsid)){
return "";
}
if(type=='vm' ){
}else if(type=='block' ){
adddep(deps,{type:type,from:'import',src:src,utag:(name||src)});
}else if(type=='css' ){
adddep(deps,{type:'css',src:src,urlsid:spec.urlsid});
}else if(type=='lib' ){
adddep(deps,{type:'lib',src:src,urlsid:spec.urlsid});
}else if(type=='json' ){
adddep(deps,{type:'json',src:src,urlsid:spec.urlsid});
}
return "";
});
all_str=all_str.replace(reg_body,function(a,b,c){body_str=c; return '';});
all_str=all_str.replace(reg_script,function(a,b,c){script_str+=c; return '';});
all_str=all_str.replace(reg_html,function(a,b,c){html_str=c; return ''; });
if(html_str){
html_str=html_str.replace(reg_head,function(a,b,c){meta_str=c;return "";});
if(body_str==null) body_str=html_str;
}
if(body_str==null)all_str=all_str.replace(reg_template,function(a,b,c){body_str=c;return '';});
if(body_str==null || all_isnot_seen(body_str))body_str='';
body_str=body_str.replace(/\{app\.(.*?)}/g,function(a,b,c,d){
return core_vm.tool.objGetDeep(spec.app,b);
})
body_str=body_str.replace(reg_elhook,function(a,b,c,d){
if(!spec.app.__cache.use.elhook[b] && b.indexOf('this.')!==0){
if(spec.app.config.path.elhook[b]){
adddep(deps,{type:'lib',src:spec.app.config.path.elhook[b]});
return ' el-hook="'+b+'" ';
}else{
var abs_b=_reqlib.gen_path(spec.app,b,spec.id,true,2);
adddep(deps,{type:'lib',src:abs_b,importname:b});
return ' el-hook="'+abs_b+'" ';
}
}else{
return ' el-hook="'+b+'" ';
}
});
for(var k in spec.app.config.blockpath_regexp){
body_str.replace(spec.app.config.blockpath_regexp[k],function(a,b,c,d){
adddep(deps,{type:'block',src:spec.app.config.path.block[k],pathtag:k});
delete spec.app.config.blockpath_regexp[k];
})
}
}
if(script_str){
script_str=script_str.replace(requirePattern,function(a,b,c,d){
var importname=spec.app.__cache.check_if_import('lib',spec.urlsid,b);
if(!importname) importname=spec.app.__cache.check_if_import('json',spec.urlsid,b);
if(importname){
return a.replace(b,importname);
}
var abs_b,str;
if(spec.app.config.path.lib[b]){
abs_b=spec.app.config.path.lib[b];
str=a;
}else{
abs_b=_reqlib.gen_path(spec.app,b,spec.id,true,3);
str=a.replace(b,abs_b);
}
if(spec.app.__cache.get_jslib(abs_b)){
return str;
}
var obj={from:'require',type:'lib',src:abs_b}
if(b.indexOf('.json')>0 && b.lastIndexOf('.json')===b.length-5)obj.type='json';
adddep(deps,obj);
return str;
});
}
if(!script_str && deps.length==0 && !extend_from){
if(body_str==null)script_str=all_str;
else script_str='';
}
return [script_str.replace(/cor\e\./g,'co.').replace(/gcach\e\./g,'o0.'),
meta_str,body_str,style_str,extend_from,deps ];
}<file_sep>var core_vm=require('./vm.0webcore.js');
module.exports.watch=function(wopt,path,oldv,newv){
if(typeof (wopt)!=='object'){
return;
}
var vm=wopt.vm;
var el;
if(wopt.el){
el=wopt.el;
}else{
el=document.getElementById(wopt.elid);
if(!el && vm.getapp().config.strategy.not_document_getelbyid && wopt.elid.indexOf('_elid_')==-1){
el=vm.getel("#"+wopt.elid);
}
}
if(!el){
core_vm.devalert(vm,'no el',wopt.elid,path);
vm.__delel_watchcb_notfind(wopt.elid);
return;
}else{
var result=newv,bindtype=wopt.toelattr;
if(!wopt.watchfunc){
wopt.vm.__reset_list_index(wopt);
if(wopt.node.tag=='_exptext_' || wopt.node.utag=='_exptext_'){
result=core_vm.calexp.exp(wopt.vm,wopt.node.exp_text,wopt.scope,'_exptext_');
}else if(wopt.node.attrexp && wopt.node.attrexp[bindtype]){
result=core_vm.calexp.exp(wopt.vm,wopt.node.attrexp[bindtype],wopt.scope,'_exptext_2');
}else{
result=newv;
}
}else{
var event;
event={el:el,path:path,oldv:oldv,newv:newv};
var result;
var funcname=wopt.watchfunc;
var fn=core_vm.getprefn(vm,'dataevent',funcname);
if(core_vm.isfn(fn)){
try{
if(funcname.indexOf('inlinejs_watch__')==0)result=fn.call(vm,event,wopt.watchpara,vm.getapp());
else result=fn.call(vm,event,wopt.watchpara);
}catch(e){
core_vm.devalert(vm,'dataevent error',e)
}
}else if(funcname.indexOf('inlinejs_watch__')==0){
var jsid=parseInt(funcname.replace('inlinejs_watch__',''));
if(jsid>0){
var str=vm[core_vm.aprand].inline_watchjs[jsid];
try{
var fn=new Function("e,para,app",str);
result=fn.call(vm,event,wopt.watchpara,vm.getapp());
vm[funcname]=fn;
}catch(error){
vm[funcname]=function(){};
core_vm.devalert(vm,'dataevent error',e)
}
vm[core_vm.aprand].inline_watchjs[jsid]='';
}
}
}
if(bindtype && result!==undefined){
vm.batchdom(function(){
core_vm.watchcb.setweb(el,bindtype,result,wopt,path);
});
}
}
}
module.exports.setweb=function(el,bindtype,newv,wopt,path){
if(bindtype=='html')bindtype='innerHTML';
else if(bindtype=='class')bindtype='className';
if(core_vm.isfn(core_vm.wap.__cache.use.dataevent[bindtype])){
core_vm.wap.__cache.use.dataevent[bindtype](el,newv,wopt,path);
}else if(bindtype=='innerHTML' || bindtype=='html'){
el.innerHTML=newv;
}else if(bindtype=='text'){
if(el.textContent !=undefined)el.textContent=newv;
else if(el.text !=undefined)el.text=newv;
else if(el.innerText !=undefined)el.innerText=newv;
}else if(bindtype=='value' || bindtype=='className'){
el[bindtype]=newv;
}else if( bindtype=='checked' || bindtype=='disabled' ){
el[bindtype]= (newv+''==='true') ? true :false;
}else{
var array=bindtype.split('-');
if(array.length==1)array=bindtype.split('.');
if(array.length==1){
el[array[0]]=newv;
}else if(array.length==2 ){
if(array[0]=='attr')el.setAttribute(array[1],newv);
else if(array[0]=='data')el.dataset[array[1]]=newv;
else if(array[0]=='style')el.style[array[1]]=newv;
else core_vm.tool.objSetDeep(el,array.join('.'),newv,false);
}
}
}
<file_sep>var path = require("path");
var webpack = require('webpack')
//var UglifyJsPlugin = webpack.optimize.UglifyJsPlugin;
const UglifyJsPluginES6 = require('uglifyjs-webpack-plugin')
module.exports = {
entry: './webentry.js',
output: {
path: __dirname+'/../dist/',
filename: 'vmix.js',
publicPath: "./",
libraryTarget: "umd"
},
plugins: [
/* new UglifyJsPlugin({
output: {comments: false },
compress: {warnings: false },
sourceMap: true
}),*/
new UglifyJsPluginES6({
uglifyOptions:{
ecma: 6,
warnings: false,
compress: true,
mangle:false,
}})
],
module: {
loaders: [ ]
}
};<file_sep>var _reqlib={};
module.exports=_reqlib;
var _htmlescapehash= {
'<': '<',
'>': '>',
'&': '&',
'"': '"',
"'": ''',
'/': '/'
};
var _htmlescapereplace= function(k){
return _htmlescapehash[k];
};
_reqlib.htmlescape=function(str){
return typeof(str) !== 'string' ? str : str.replace(/[&<>"]/igm, _htmlescapereplace);
}
function normalizeArray(v, keepBlanks) {
var L = v.length,
dst = new Array(L),
dsti = 0,
i = 0,
part, negatives = 0,
isRelative = (L && v[0] !== '');
for (; i < L; ++i) {
part = v[i];
if (part === '..') {
if (dsti > 1) {
--dsti;
} else if (isRelative) {
++negatives;
} else {
dst[0] = '';
}
} else if (part !== '.' && (dsti === 0 || keepBlanks || part !== '')) {
dst[dsti++] = part;
}
}
if (negatives) {
dst[--negatives] = dst[dsti - 1];
dsti = negatives + 1;
while (negatives--) {
dst[negatives] = '..';
}
}
dst.length = dsti;
return dst;
}
_reqlib.normalizeId=function(id, parentId) {
id = id.replace(/\/+$/g, '');
return normalizeArray((parentId ? parentId + '/../' + id : id).split('/')).join('/');
}
_reqlib.normalizeUrl=function(url, baseLocation) {
if (!(/^\w+:/).test(url)) {
var u=baseLocation.fullhost;
var path = baseLocation.pathname;
if(url.charAt(0)!='/' && url.charAt(0)!='.'){
}
if (url.charAt(0) === '/') {
url = u + normalizeArray(url.split('/')).join('/');
} else {
path += ((path.charAt(path.length - 1) === '/') ? '' : '/../') + url;
url = u + normalizeArray(path.split('/')).join('/');
}
}
return url;
}
_reqlib.calUrl=function(href, pageurl) {
var path = pageurl,url=href;
if (pageurl.charAt(0) !== '/')pageurl="/"+pageurl;
if (url.charAt(0) === '/') {
url = normalizeArray(url.split('/')).join('/');
} else {
path += ((path.charAt(path.length - 1) === '/') ? '' : '/../') + url;
url = normalizeArray(path.split('/')).join('/');
}
return url;
}
_reqlib.gen_path=function(app,url,from_path,needid,where){
var location=window.location;
if(from_path){
if(from_path.indexOf(location.fullhost)==0)from_path=from_path.substr(location.fullhost.length);
}
from_path=from_path||location.pathname;
if(url.indexOf('://')==-1)url=_reqlib.normalizeId(url, url[0]=='.' ? from_path :'');
if(url.indexOf('://')==-1)url = _reqlib.normalizeUrl(url, location);
if(!needid){
return url;
}else{
url=url.split("//")[1];
if(url)url=url.substr(url.indexOf('/'));
return url;
}
}
_reqlib.cal_spec_path=function(spec,from_path){
if(spec.from=='deps')return;
if(spec.url.indexOf('://')==-1)spec.url=_reqlib.gen_path(spec.app,spec.url,from_path || spec.pvmpath,false,6)
if(!spec.knowpath || !spec.id ){
spec.id=spec.url.split("//")[1];
if(spec.id)spec.id=spec.id.substr(spec.id.indexOf('/'));
}
}
<file_sep>var core_vm=require('./vm.0webcore.js');
module.exports.setproto=function(proto){
proto.__auto_sub_app=function(){
for(var k in this.event){
if(k.substr(0,4)=='app.' && typeof (this.event[k]=='function'))this.getapp().sub(k.substr(4),this,this.event[k])
}
}
proto.__auto_unsub_app=function(){
for(var k in this.event){
if(k.substr(0,4)=='app.' && typeof (this.event[k]=='function'))this.getapp().unsub(k.substr(4),this,this.event[k])
}
}
proto.pubapp=function(name,data,cb){
this.getapp().pub(name,data,this,cb)
}
proto.pubup=function(name,data,cb){
if(!this.pvm){
return;
}
var fn=this[core_vm.aprand].pvmevent[name];
if(!fn)fn=this.pvm.event[this.id+'.'+name];
if(!fn)fn=this.pvm.event['child'+'.'+name];
if(!fn)return;
if(!core_vm.isfn(fn))fn=core_vm.tool.objGetDeep(this.pvm,fn);
if(!core_vm.isfn(fn))fn=core_vm.tool.objGetDeep(this.pvm.event,fn);
if(!core_vm.isfn(fn))return;
var vm=this;
var pvm=this.pvm;
fn.call(this.pvm,data,this,function(data){
if(core_vm.isfn(cb))cb.call(vm,data,pvm);
})
}
proto.pubdown=function(cvmid,name,data,cb){
var vm=this;
if(typeof (cvmid)=='object')cvmid=cvmid.id;
if(!cvmid)return false;
var s=[]
if(cvmid=='*'){
s=Object.keys(this[core_vm.aprand].vmchildren)
}else{
s=[cvmid];
}
s.forEach(function(cvmid){
var cvm=vm.getChild(cvmid);
if(!cvm){
if(core_vm.isfn(cb))cb({error:'no.such.'+cvmid});
return;
}
var fn=cvm.event['pvm.'+name];
if(!core_vm.isfn(fn))return;
fn.call(cvm,data,vm,function(data){
if(core_vm.isfn(cb))cb.call(vm,data,cvm);
})
})
}
}<file_sep>
var start_system=function(app,file_app,file_indexvm,index_vm){
core_vm.rootvmstart.init();
core_vm.rootvmstart.start_system(app,file_app,file_indexvm,index_vm);
}
module.exports.start_system=start_system;
<file_sep>
var config_duplicate=false;
var gmap={};
var global_before,global_after;
var _route= function(path,ifrun){
if(typeof path=='undefined')path='';
if(path[path.length-1]!=='/')path+="/";
this.path = path;
if(!ifrun && !gmap[path]){//不是run才加进 gmap
gmap[path]=gmap[path]||{};
var tobj=gmap[path];
tobj.events=[];
tobj.contexts=[];
tobj.argnames=[];//每个route只有一个与上面两个不同
tobj.xiegangs=this.path.split('/').length;
tobj.prefix=path.substr(0,path.indexOf('/:'));
tobj.regx=path.replace(tobj.prefix,'').replace(/\:([^/]*?)\//g,
function(a,b,c){
tobj.argnames.push(b);
return '/([^/]*?)/';
}).replace(/\/\//g,'/');
if(tobj.regx[tobj.regx.length-1]!='/')tobj.regx+='/';
//console.log('new 路由',path,tobj);
tobj.regx=new RegExp(tobj.regx);
}
};
_route.prototype.getall= function() {
//console.log('_route.prototype.get,this.path='+this.path);
//this.path是 location.hash
this.argarray = [];//每找到一个符合条件的bindfunc 把run的参数封装成符合route的格式
this.events=[];
this.contexts=[];
//最后都要有一个/表示结束已经自动处理
if(typeof gmap[this.path]=='object' && gmap[this.path].events.length>0){
for(var i=0; i<gmap[this.path].events.length; i++){
this.events.push(gmap[this.path].events[i]);
this.contexts.push(gmap[this.path].contexts[i]);
}
//console.log("find route with no para 没有参数");
return this;
}
this.xiegangs=this.path.split('/').length;
for(r in gmap){
//可能路径参数设计不同
//#!/view/action/:action/:para/ 与 #!/view/action/:qqq/:www/ 是两个 但是 regx应该是相同的
var found=false;
var argarray=[];
if(gmap[r].xiegangs!=this.xiegangs || this.path.indexOf(gmap[r].prefix)!==0)continue;//斜杠个数不等也不行
this.path.replace(gmap[r].prefix,'').replace(gmap[r].regx,function(a,b,c,d,e){
//core.error("匹配参数para=",a,'b='+b,'c='+c,'d='+d,'e='+e);
argarray=Array.prototype.slice.call(arguments, 1,arguments.length-2);
//console.log('argarray',argarray,arguments);
found=true;
});
if(found==true){
//console.log("这个符合",r);
for(var i=0; i<gmap[r].events.length; i++){
this.events.push(gmap[r].events[i]);
this.contexts.push(gmap[r].contexts[i]);
this.argarray.push(argarray);
}
}
}
//debug.log('route this.path=(\''+this.path+'\')\n');
return this;
};
_route.prototype.bind= function(fn,obj) {
//console.log('路由bind',obj)
if(this.path=='') return 'nothing to bind';
if(typeof fn != 'function') return 'fn is invalid and cannot bind to route';
if(config_duplicate===true || gmap[this.path].events.length==0){
gmap[this.path].events.push(fn);
gmap[this.path].contexts.push(obj);
}
};
_route.prototype.unbind= function(fn,obj) {
if(this.path=='') return 'nothing to bind';
if(typeof fn != 'function') return 'fn is invalid and cannot bind to route';
if(gmap[this.path]){
var index = gmap[this.path].events.indexOf(fn);
if(index>-1){
gmap[this.path].events.splice(index,1);
gmap[this.path].contexts.splice(index,1);
}
}
};
_route.prototype.run= function() {
//console.log("route run");
this.getall();
if(global_before){
try{
global_before(this.path,this.argarray);
}catch(e){
core.error('route before error',e)
}
}
var results=[];
if(this.events.length==0){
return false;
}
for(var i=0; i<this.events.length; i++){
this.events[i].apply(this.contexts[i] || null,this.argarray[i]);
}
if(global_after){
try{
global_after(this.path,this.argarray);
}catch(e){
core.error('route after error',e)
}
}
};
var route={};
route.bind=function(path,context,cb){
new _route(path).bind(cb,context)
}
route.run=function(path,){
new _route(path,true).run();
}
var pushStatefunc=function(e){
//点击href='#sss'会触发 或者 history.go back会触发
//console.log(e);
//console.log(window.location.hash);
//core.error("_popstate","hash="+location.hash,e.state, history );//"old="+window._hash_last,
if(location.hash ){
//if(window._hash_last==location.hash)return;window._hash_last=location.hash;
route.run(window.location.hash);
var str=location.hash;// "?/"+hash.substr(1)
//if(!e.state)window.history.pushState({ }, document.title,'?/'+str.substr(1));else
window.history.replaceState({hash:str}, document.title, '?'+str.substr(1));//第三个参数为将替换掉 location.hash 改变url
//如果 pushState 后window.history多出来一个 如果不 replaceState history.go()时得不到 e.state 只是 loc.hash改变
// window.location.assign(config_rooturl+"/"+hash.substr(1));会刷新浏览器
//window.location.hash='';
}else if(!location.hash){
//console.log("没有 location.hash",e.state);
if(e.state && e.state.hash)route.run(e.state.hash);
}
};
var hashchangefunc=function(){
//if(window._hash_last==location.hash)return;window._hash_last=location.hash;
route.run(location.hash);
};
var config_usepushState=0;
route.setup=function(rooturl,usepushState){
config_usepushState=usepushState;
config_rooturl=rooturl;
//window._hash_last='';
//window.location.hash='';
window.removeEventListener('popstate', pushStatefunc);
window.removeEventListener('hashchange',hashchangefunc);
if(config_usepushState && window.history && window.history.pushState){
window.addEventListener('popstate',pushStatefunc);
}else{
window.addEventListener('hashchange',hashchangefunc);
}
};
route.navigate= function(hash, title,force) {
if(!config_usepushState){
if(title)window.document.title=title;
if(force && location.hash===hash)route.run(location.hash);
else if(location.hash!==hash)location.hash= (hash[0]=='#')?hash :"#"+hash;
}else{
route.run(hash);
window.history.pushState({hash:hash}, title?title :document.title, hash);
}
};
route.setblankindex=function(){
window.location.hash="";
}
route.starthistory=function(){//为收藏夹启动的webapp
if(window.location.hash!='')route.run(window.location.hash);
}
route.set_global_before=function(func){ if(typeof func == 'function')global_before=func;}
route.set_global_after=function(func){ if(typeof func == 'function')global_after=func;}
module.exports=route;
/*
route.setupduplicate=function(type){
config_duplicate=Boolean(type);
}
*/<file_sep># vmix.js
view module web component system,with loader,parser,binder,watcher,dataflow-control,extend,private-style,custome-element,slot
## step.1 include vmix.js,it will take care everything
```<script src="vmix.js" data-role='vmix' app-file="app.js" index-file='index.vm.html'></script>```
## step.2 write a vm file abc.html,mix your html-style-data-event,
```
<style>...</style>
<template>
<tag attra={a} attrb={b(1,2,3)} attrc={!c!}/>
<tag on-click="a" />
<tag watch-a="b" />
<tag el-filter="a " el-hook="b" el-list="c"/>
<tag vm-src="abd.html">
</template>
<script>
this.data={};
this.abc=function(){};
or module.exports={
option,state,event,method,fn,
}
</script>
```
## step.3 import abc.html
```
<vm id='xyz' src='./abc.html' /> use default tag name,and define a src,
<div id='xyz' vm -src='./abc.html'/> use any tag name,and define a vm-src
<abc id='xyz'/> custom Element name
```
## specific
- [x] Declarative:no global object,no "new vm()",vmix.js do everrything,
- [x] node style: node style js module exports, or just this.abc=xyz,
- [x] viewModule: plain js define,no relation with html element,
- [x] file: auto load-parse-cache-clean file,js inline,js require,
- [x] data-el: one-way two-way data-bind,
- [x] dataflow: 3 data type(data,option,state),3 data source(store,parent,self),controllable dataflow,
- [x] interact: up-down through defined data-option-state-event
- [x] custom Element name,private style,dom slot,inline js,
#### [vm demo](https://peterli888.github.io/vmix/#!/document/vmdemo)
#### [vm api](https://peterli888.github.io/vmix/#!/document/vmapi)
#### [app config](https://peterli888.github.io/vmix/#!/document/app)
#### [file load](https://peterli888.github.io/vmix/#!/document/file)
#### [element](https://peterli888.github.io/vmix/#!/document/element)
#### [vm dataflow](https://peterli888.github.io/vmix/#!/document/dataflow)
#### [vm interact](https://peterli888.github.io/vmix/#!/document/interact)
<file_sep>var core_vm=require('./vm.0webcore.js');
module.exports.idclass=function(vm,node,scope){
if(node.id){
if(node.id.indexOf('{')>-1)node.id=core_vm.calexp.exp(vm,node.id,scope);
if(vm.getapp().config.strategy.not_document_getelbyid && node.id.indexOf('_elid_'+vm.sid)==-1){
var newid=core_vm.cal.forece_calnodeid(vm,node,scope,'doc');
node.oriid=node.id;
if(node.id)vm[core_vm.aprand].newid_2_oldid[newid]=node.id
node.id=newid;
}
vm.__regel('id', node.oriid||node.id, node.id);
}
if(node.attr.role){
node.id=node.id||core_vm.cal.forece_calnodeid(vm,node,scope,'role');
vm.__regel('role',node.attr.role,node.id,scope.$index);
}
node.classList=node.classList||[];
var str=node.classList.join(' ').replace(/ /g,' ').replace(/^\s*|\s*$/g, '');
if(str)node.classList=str.split(' ');
else node.classList=[];
if(node.classList.length>0 ){
for(var i=node.classList.length-1;i>-1;i--){if(node.classList[i]==='')node.classList.splice(i,1)}
}
if(node.classList.length>0){
node.id=node.id||core_vm.cal.forece_calnodeid(vm,node,scope,'class');
vm.__regel('classList',node.classList,node.id,scope.$index);
}
if(node.listid){
node.id=node.id||core_vm.cal.forece_calnodeid(vm,node,scope,'list');
vm.__regel('listel',node.listid,node.id,scope.$index);
}
}
function decapitalize(str) {
str = ""+str;
return str.charAt(0).toLowerCase() + str.slice(1);
};
module.exports.event=function(vm,node,scope,thisel){
if(!node.event)return;
core_vm.tool.each(node.event,function(funcname,event){
var event_name=decapitalize(event);
vm[core_vm.aprand].domeventnames[event_name]=1;
if(funcname.indexOf('js:')==0){
vm[core_vm.aprand].inline_onjs.push(funcname.substr(3));
funcname='inlinejs_on__'+(vm[core_vm.aprand].inline_onjs.length-1);
}else{
funcname=core_vm.calexp.exp(vm,funcname,scope)
}
core_vm.elset(thisel,'on-'+event_name,funcname,scope);
})
}<file_sep>
<html>
<h4>parent on-event,catch event of cvm in pvm</h4>
<pre>
<div vm-src='./parent.onevent.sub.html' id='sub2' on-click='sub2click' />
mod.sub2click=function(){console.log('sub2click')}
</pre>
<div vm-src='./parent.onevent.sub.html' id='sub2' on-click='sub2click'/>
<pre>
<div vm-src='./parent.onevent.sub.html' id='sub3' on-click='sub3click' appendto=ppel />
mod.sub3click=function(){console.log('sub3click,,appendto=ppel')}
</pre>
<div vm-src='./parent.onevent.sub.html' id='sub3' on-click='sub3click' appendto=ppel />
</html>
<script>
var mod={};
mod.sub2click=function(e){
console.log('sub2click')
}
mod.sub3click=function(e){
console.log('sub3click,appendto=ppel')
}
module.exports=mod;
</script><file_sep>var core_vm=require('../src/vm.0webcore.js');
core_vm.aprand='vm'+(new Date()).getTime().toString();
core_vm.rootvmset=require('../src/vm.rootvmset.js');
core_vm.rootvmstart=require('../src/vm.rootvmstart.js');
core_vm.web=require('../src/vm.rootvmstartweb.js');
core_vm.webdocready=require('../src/vm.web.docready.js');
core_vm.define=require('../src/vm.define.js');
core_vm.load=require('../src/vm.load.js'),
core_vm.start=require('../src/vm.start.js');
core_vm.elhook=require('../src/vm.elhook.js');
core_vm.inject=require('../src/vm.inject.js');
core_vm.cal = require('../src/vm.cal.js');
core_vm.calexp=require('../src/vm.calexp.js');
core_vm.calif=require('../src/vm.calif.js');
core_vm.calhtmltojson=require('../src/vm.calhtmltojson.js');
core_vm.watchcal=require('../src/vm.watchcal.js');
core_vm.watchcb=require('../src/vm.watchcb.js');
core_vm.create=require('../src/vm.create.js');
core_vm.createcommon=require('../src/vm.createcommon.js');
core_vm.createvm=require('../src/vm.createvm.js');
core_vm.createblock=require('../src/vm.createblock.js');
core_vm.list=require('../src/vm.list.js');
core_vm.eventdom=require('../src/vm.eventdom.js');
core_vm.tool=require('../src/vm.tool.js');
core_vm.require=require('../src/vm.require.js');
core_vm.web_private_style=require('../src/vm.web_private_style.js');
require('../src/vm.00.js');
core_vm.cacheclass=require('../src/vm.0cache.js');
core_vm.gcache=new core_vm.cacheclass();
core_vm.appclass=require('../src/vm.0app.js');
core_vm.wap=new core_vm.appclass();
core_vm.wap.id='ly';
core_vm.wap.__cache=new core_vm.cacheclass();
core_vm.wap.blankvm=core_vm.define.define({id:'_blankforapp_'});
core_vm.wap.blankvm.__define({name:'_blank_'});
Object.defineProperty(core_vm.wap,'blankvm',{enumerable:false});
//core_vm.gcache=new core_vm.cacheclass();
Object.defineProperty(core_vm.wap,'blankvm',{enumerable:false});
module.exports={
vmix:{
email:'<EMAIL>',
},
}
core_vm.webdocready.docReady(core_vm.web.start_system);
|
008533f2b03a1a9863f8fcdcc1eb0cae346fdc3d
|
[
"JavaScript",
"HTML",
"Markdown"
] | 54 |
JavaScript
|
peterli888/vmix
|
58693c6afe51a7d53765473c54ed944df657a95c
|
b353961da0cf6732545c602daf4d9999b63a691b
|
refs/heads/master
|
<file_sep># console-bank
This is a console-bank.
It performs withdrawals and deposits based on
certain parameters:
* Customer's starting balance is $1,000
* Deposits over $500, bank gives $25.
* $50 fee for every overdraft
* If customer's account exceeds a negative
balance of $750, customer's account will be closed.
<file_sep>var transType = query();
var currentBal = 1000;
while(!isQuit(transType)){
if(transType === 'd'){
var x = depAmount();
var y = currentBal;
if(x > 500){
currentBal = bonusDep(x, y);
alert('Thank you. Your new balance is ' + '$' + currentBal);
} else {
currentBal = regDep(x, y);
alert('Thank you. Your new balance is ' + '$' + currentBal);
}
} else if(transType === 'w') {
var x = drawAmount();
var y = currentBal;
if(regDraw(x,y) < 0 && regDraw(x,y) >= -750){
currentBal = negDraw(x, y);
alert('You have overdrawn your account. A $50 fee has been assessed. Your new balance is negative ' + '$' + currentBal * -1);
} else if(regDraw(x,y) < -750){
alert('You have overdrawn your account by over $750. Your account has been closed.');
} else {
currentBal = regDraw(x, y);
alert('Thank you. Your new balance is ' + '$' + currentBal);
}
} else {
alert('Please enter (d)eposit or (w)ithdrawal');
}
transType = query();
}
function regDraw(x,y){
return y - x;
}
function negDraw(x,y){
return y - x - 50;
}
function regDep(x,y){
return x + y;
}
function bonusDep(x,y){
return x + y + 25;
}
function depAmount(){
var transaction = prompt('Please enter deposit amount')
return transaction * 1;
}
function drawAmount(){
var transaction = prompt('Please enter withdrawal amount')
return transaction * 1;
}
function query(){
var transType = prompt('(d)eposit, (w)ithdrawal, (q)uit');
return transType.toLowerCase();
}
function isQuit(letter){
return letter === 'q';
}
function transConfirm(){
}
|
b9fabd38bb198e61d2e849929031b4df3288bbc5
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
nathanhood/console-bank
|
1904be588c49270afea858d778197b4ff92474a4
|
5ab2f7d2e780c9b6646f98e0bf99a67ecdf18c00
|
refs/heads/master
|
<file_sep>require_relative "../_plugins/joiner"
require_relative "site"
require "minitest/autorun"
module Hub
class JoinDataTest < ::Minitest::Test
def setup
@site = DummyTestSite.new
end
def test_join_team_data_from_private_source
@site.data['team'] = [
{'name' => 'mbland', 'full_name' => '<NAME>'},
]
@site.data['private']['team'] = [
{'name' => 'mbland', 'email' => '<EMAIL>'},
]
impl = JoinerImpl.new(@site)
impl.join_data 'team', 'name'
assert_equal(
[{'name' => 'mbland', 'full_name' => '<NAME>',
'email' => '<EMAIL>'}],
@site.data['team'])
end
end
end
<file_sep>require_relative "../_plugins/snippets_publisher"
require "minitest/autorun"
module Snippets
class PublisherRedactionTest < ::Minitest::Test
def publisher(public_mode: false)
Publisher.new(headline: '', public_mode: public_mode)
end
def test_empty_string
text = ''
publisher.redact! text
assert_empty text
publisher(public_mode: true).redact! text
assert_empty text
end
def test_unredacted_string
text = 'Hello, World!'
publisher.redact! text
assert_equal 'Hello, World!', text
publisher(public_mode: true).redact! text
assert_equal 'Hello, World!', text
end
def test_redacted_string_private_mode
text = 'H{{ell}}o, Wor{{l}}d!'
publisher.redact! text
assert_equal 'Hello, World!', text
end
def test_redacted_string_public_mode
text = 'H{{ell}}o, Wor{{l}}d!'
publisher(public_mode: true).redact! text
assert_equal 'Ho, Word!', text
end
def test_multiline_redacted_string_private_mode
text = [
'- Did stuff{{ including private details}}',
'{{- Did secret stuff}}',
'- Did more stuff',
'{{- Did more secret stuff',
'- Yet more secret stuff}}',
].join('\n')
expected = [
'- Did stuff including private details',
'- Did secret stuff',
'- Did more stuff',
'- Did more secret stuff',
'- Yet more secret stuff',
].join('\n')
publisher.redact! text
assert_equal expected, text
end
def test_multiline_redacted_string_public_mode
text = [
'- Did stuff{{ including private details}}',
'{{- Did secret stuff}}',
'- Did more stuff',
'{{- Did more secret stuff',
'- Yet more secret stuff}}',
].join("\n")
expected = [
'- Did stuff',
'- Did more stuff',
].join("\n")
publisher(public_mode: true).redact! text
assert_equal expected, text
end
end
end
<file_sep>#! /bin/bash
#
# This is temporary until we set up a proper hookshot+webhoook deployment just
# like 18f.gsa.gov.
# Hack per:
# http://stackoverflow.com/questions/4774054/reliable-way-for-a-bash-script-to-get-the-full-path-to-itself
pushd $(dirname $0) >/dev/null
HUB_ROOT=$(dirname $(pwd -P))
popd >/dev/null
REMOTE="ubuntu@18f-site:/home/site/production/hub"
rsync -e ssh -vaxp --delete --ignore-errors $HUB_ROOT/_site_public $REMOTE
<file_sep>require_relative "../_plugins/snippets_version"
require "minitest/autorun"
module Snippets
class VersionTest < ::Minitest::Test
def test_raises_if_required_field_mapping_missing
error = assert_raises Version::InitError do
Version.new(
version_name:'v1',
field_map:{'Username' => 'username', 'Timestamp' => 'timestamp'})
end
assert_equal(
'Snippet version "v1" missing mappings for fields: ' +
'["last-week", "this-week"]',
error.to_s)
end
def test_raises_if_public_field_is_set_but_public_value_is_not
error = assert_raises Version::InitError do
Version.new(
version_name:'v3',
field_map:{
'Timestamp' => 'timestamp',
'Public' => 'public',
'Username' => 'username',
'Last week' => 'last-week',
'This week' => 'this-week',
},
public_field: 'public'
)
end
assert_equal(
'Snippet version "v3" has public_field and public_value mismatched: ' +
'public_field == "public"; public_value == nil',
error.to_s)
end
def test_raises_if_public_field_is_not_set_but_public_value_is
error = assert_raises Snippets::Version::InitError do
Version.new(
version_name:'v3',
field_map:{
'Timestamp' => 'timestamp',
'Public' => 'public',
'Username' => 'username',
'Last week' => 'last-week',
'This week' => 'this-week',
},
public_value: 'Public'
)
end
assert_equal(
'Snippet version "v3" has public_field and public_value mismatched: ' +
'public_field == nil; public_value == "Public"',
error.to_s)
end
def test_raise_if_snippet_contains_unrecognized_fields_not_in_field_map
version = Version.new(
version_name:'v1',
field_map:{
'Username' => 'username',
'Timestamp' => 'timestamp',
'Name' => 'full_name',
'Snippets' => 'last-week',
'No This Week' => 'this-week',
}
)
error = assert_raises Version::UnknownFieldError do
version.standardize({'Public' => ''})
end
assert_equal('Snippet field not recognized by version "v1": Public',
error.to_s)
end
def test_standardize_private_snippet_no_markdown
version = Version.new(
version_name:'v1',
field_map:{
'Username' => 'username',
'Timestamp' => 'timestamp',
'Name' => 'full_name',
'Snippets' => 'last-week',
'No This Week' => 'this-week',
}
)
snippet = {
'Username' => 'mbland',
'Timestamp' => '2014-12-31',
'Name' => '<NAME>',
'Snippets' => '- Did stuff',
}
expected = {
'username' => 'mbland',
'timestamp' => '2014-12-31',
'full_name' => '<NAME>',
'last-week' => '- Did stuff',
'public' => false,
'markdown' => false
}
assert_equal expected, version.standardize(snippet)
end
def test_standardize_public_snippet_with_markdown
version = Version.new(
version_name:'v3',
field_map:{
'Timestamp' => 'timestamp',
'Public' => 'public',
'Username' => 'username',
'Last week' => 'last-week',
'This week' => 'this-week',
},
public_field: 'public',
public_value: 'Public',
markdown_supported: true,
)
snippet = {
'Timestamp' => '2014-12-31',
'Public' => 'Public',
'Username' => 'mbland',
'Last week' => '- Did stuff',
'This week' => '- Do more stuff',
}
expected = {
'timestamp' => '2014-12-31',
'public' => true,
'username' => 'mbland',
'last-week' => '- Did stuff',
'this-week' => '- Do more stuff',
'markdown' => true
}
assert_equal expected, version.standardize(snippet)
end
end
end
<file_sep>require_relative "../_plugins/joiner"
require_relative "site"
require "minitest/autorun"
module Hub
class JoinProjectDataTest < ::Minitest::Test
def setup
@site = DummyTestSite.new
@site.data['private']['team'] = {}
@site.data['private']['projects'] = [
{'name' => 'MSB-USA', 'status' => 'Hold'}
]
end
def test_join_project
@impl = JoinerImpl.new(@site)
@impl.join_project_data
assert_equal([{'name' => 'MSB-USA', 'status' => 'Hold'}],
@site.data['projects'])
end
def test_hide_hold_projects_in_public_mode
@site.config['public'] = true
@impl = JoinerImpl.new(@site)
@impl.join_project_data
assert_empty @site.data['projects']
end
end
end
<file_sep>require_relative "../_plugins/joiner"
require_relative "site"
require "minitest/autorun"
module Hub
class SetupJoinSourceTest < ::Minitest::Test
def setup
@site = DummyTestSite.new
@site.data['private']['team'] = [
{'name' => 'mbland', 'full_name' => '<NAME>',
'private' => {'email' => '<EMAIL>'}
},
{'private' => [
{'name' => 'foobar', 'full_name' => '<NAME>'},
],
},
]
end
def test_remove_private_data
@site.config['public'] = true
impl = JoinerImpl.new(@site)
impl.setup_join_source
assert_equal(
[{'name' => 'mbland', 'full_name' => '<NAME>'}],
@site.data['private']['team'])
end
def test_promote_private_data
impl = JoinerImpl.new(@site)
impl.setup_join_source
assert_equal(
[{'name' => 'mbland', 'full_name' => '<NAME>',
'email' => '<EMAIL>',
},
{'name' => 'foobar', 'full_name' => '<NAME>'},
],
@site.data['private']['team'])
end
end
end
<file_sep>require_relative "../_plugins/snippets_publisher"
require "minitest/autorun"
module Snippets
class PublisherPublishTest < ::Minitest::Test
def setup
@original = {}
@expected = {}
end
def publisher(public_mode: false)
Publisher.new(headline: "\n####", public_mode: public_mode)
end
def make_snippet(last_week, is_public: false)
{
'last-week' => last_week ? last_week.join("\n") : last_week,
'this-week' => nil,
'markdown' => true,
'public' => is_public,
}
end
def add_snippet(timestamp, snippet, expected: true)
@original[timestamp] = [] unless @original.member? timestamp
@original[timestamp] << snippet
if expected
@expected[timestamp] = [] unless @expected.member? timestamp
@expected[timestamp] << snippet
end
end
def test_empty_snippets
assert_equal @expected, publisher.publish(@original)
end
def test_publish_all_snippets
add_snippet('20141218', make_snippet(['- Did stuff']))
add_snippet('20141225', make_snippet(['- Did stuff']))
add_snippet('20141231', make_snippet(['- Did stuff']))
add_snippet('20150107', make_snippet(['- Did stuff'], is_public: true))
assert_equal @expected, publisher.publish(@original)
end
def test_publish_only_public_snippets_in_public_mode
add_snippet('20141218', make_snippet(['- Did stuff']), expected: false)
add_snippet('20141225', make_snippet(['- Did stuff']), expected: false)
add_snippet('20141231', make_snippet(['- Did stuff']), expected: false)
add_snippet('20150107', make_snippet(['- Did stuff'], is_public: true))
assert_equal @expected, publisher(public_mode: true).publish(@original)
end
end
end
<file_sep>require_relative "../_plugins/joiner"
require_relative "site"
require "minitest/autorun"
module Hub
class ImportGuestUsersTest < ::Minitest::Test
def setup
@site = DummyTestSite.new
@site.data.delete 'private'
end
def test_no_private_data
assert_nil JoinerImpl.new(@site).import_guest_users
end
def test_no_hub_data
assert_nil JoinerImpl.new(@site).import_guest_users
assert_nil @site.data['guest_users']
end
def test_no_guest_users
@site.data['private'] = {'hub' => {}}
assert_nil JoinerImpl.new(@site).import_guest_users
assert_nil @site.data['guest_users']
end
def test_guest_users_moved_to_top_level
guests = [
{'email' => '<EMAIL>',
'full_name' => '<NAME>'},
]
@site.data['private'] = {'hub' => {'guest_users' => guests}}
assert_equal guests, JoinerImpl.new(@site).import_guest_users
assert_equal guests, @site.data['guest_users']
assert_nil @site.data['private']['hub']['guest_users']
end
end
end
<file_sep>require_relative 'snippets_publisher'
module Hub
class Snippets
# Used to convert snippet headline markers to h4, since the layout uses
# h3.
HEADLINE = "\n####"
MARKDOWN_SNIPPET_MUNGER = Proc.new do |text|
text.gsub!(/^::: (.*) :::$/, "#{HEADLINE} \\1") # For jtag. ;-)
text.gsub!(/^\*\*\*/, HEADLINE) # For elaine. ;-)
end
def self.publish(site)
publisher = ::Snippets::Publisher.new(
headline: HEADLINE, public_mode: site.config['public'],
markdown_snippet_munger: MARKDOWN_SNIPPET_MUNGER)
site.data['snippets'] = publisher.publish site.data['snippets']
end
def self.generate_pages(site)
return unless site.data.member? 'snippets'
site.data['snippets'].each do |timestamp, snippets|
generate_snippets_page(site, timestamp, snippets)
end
end
def self.generate_snippets_page(site, timestamp, snippets)
page = Page.new(site, 'snippets', "#{timestamp}.html",
"snippets.html",
"Snippets for #{Canonicalizer.hyphenate_yyyymmdd(timestamp)}")
page.data['snippets'] = snippets
site.pages << page
end
end
end
<file_sep>require_relative "../_plugins/joiner"
require_relative "page"
require_relative "site"
require "minitest/autorun"
module Hub
class FilterPrivatePagesTest < ::Minitest::Test
def setup
@site = DummyTestSite.new
@all_page_names = []
@public_page_names = []
end
def add_public_page(filename)
@site.pages << DummyTestPage.new(@site, '/pages', filename)
@all_page_names << filename
@public_page_names << filename
end
def add_private_page(filename)
@site.pages << DummyTestPage.new(@site, '/pages/private', filename)
@all_page_names << filename
end
def filter_pages_in_internal_mode
@site.config.delete 'public'
JoinerImpl.new(@site).filter_private_pages
end
def filter_pages_in_public_mode
@site.config['public'] = true
JoinerImpl.new(@site).filter_private_pages
end
def page_names
@site.pages.map {|p| p.name}
end
def test_no_pages
filter_pages_in_internal_mode
assert_empty page_names
filter_pages_in_public_mode
assert_empty page_names
end
def test_single_public_page
add_public_page 'public.html'
filter_pages_in_internal_mode
assert_equal(@all_page_names, page_names)
filter_pages_in_public_mode
assert_equal(@public_page_names, page_names)
end
def test_single_private_page
add_private_page 'private.html'
filter_pages_in_internal_mode
assert_equal(@all_page_names, page_names)
filter_pages_in_public_mode
assert_empty page_names
end
def test_public_and_private_pages
add_private_page 'private-0.html'
add_public_page 'public-0.html'
add_private_page 'private-1.html'
add_public_page 'public-1.html'
add_private_page 'private-2.html'
filter_pages_in_internal_mode
assert_equal(@all_page_names, page_names)
filter_pages_in_public_mode
assert_equal(@public_page_names, page_names)
end
end
end
<file_sep>require_relative "../_plugins/joiner"
require_relative "site"
require "minitest/autorun"
module Hub
class CreateTeamByEmailIndexTest < ::Minitest::Test
def setup
@site = DummyTestSite.new
@team = []
@site.data['private'] = {'team' => @team}
end
def test_nonexistent_join_source
@site.data.delete 'private'
@site.data.delete 'public'
impl = JoinerImpl.new(@site)
assert_equal 'public', impl.source
assert_empty impl.team_by_email
end
def test_nonexistent_team
@site.data.delete 'private'
impl = JoinerImpl.new(@site)
assert_equal 'public', impl.source
assert_empty impl.team_by_email
end
def test_empty_team
impl = JoinerImpl.new(@site)
assert_equal 'private', impl.source
assert_empty impl.team_by_email
end
def test_single_user_index
@team << {'name' => 'mbland', 'email' => '<EMAIL>'}
impl = JoinerImpl.new(@site)
assert_equal({'<EMAIL>' => 'mbland'}, impl.team_by_email)
end
def test_single_user_with_private_email_index
@team << {
'name' => 'mbland', 'private' => {'email' => '<EMAIL>'},
}
impl = JoinerImpl.new(@site)
assert_equal({'<EMAIL>' => 'mbland'}, impl.team_by_email)
end
def test_single_private_user_index
@team << {
'private' => [
{'name' => 'mbland', 'email' => '<EMAIL>'},
],
}
impl = JoinerImpl.new(@site)
assert_equal({'<EMAIL>' => 'mbland'}, impl.team_by_email)
end
def test_multiple_user_index
@team << {'name' => 'mbland', 'email' => '<EMAIL>'}
@team << {
'name' => 'foobar', 'private' => {'email' => '<EMAIL>'},
}
@team << {
'private' => [
{'name' => 'bazquux', 'email' => '<EMAIL>'},
],
}
expected = {
'<EMAIL>' => 'mbland',
'<EMAIL>' => 'foobar',
'<EMAIL>' => 'bazquux',
}
impl = JoinerImpl.new(@site)
assert_equal expected, impl.team_by_email
end
def test_ignore_users_without_email
@team << {'name' => 'mbland'}
@team << {'name' => 'foobar', 'private' => {}}
@team << {'private' => [{'name' => 'bazquux'}]}
impl = JoinerImpl.new(@site)
assert_empty impl.team_by_email
end
end
end
<file_sep>## 18F Hub
[The 18F Hub](https://18f.gsa.gov/hub) is a [Jekyll](http://jekyllrb.com/)-based documentation platform that aims to help [18F](https://github.com/18F) and other development teams organize and easily share their information, and to enable easy exploration of the connections between team members, projects, and skill sets. It aims to serve as the go-to place for all of a team's working information, whether that information is integrated into the Hub directly or provided as links to other sources. It also serves as a lightweight tool that other teams can experiment with and deploy with a minimum of setup.
See the [18F blog post announcing the Hub](https://18f.gsa.gov/2014/12/23/hub/) for more details about the vision behind the Hub and the goals it aims to achieve.
The main Git repository is https://github.com/18F/hub and the primary maintainer (for now) is [@mbland](https://github.com/mbland). The goal is to eventually hand ownership over to the [Documentation Working Group](https://18f.gsa.gov/hub/wg/documentation), or to the 18F team as a whole.
### Generating the site/hosting locally
It takes less than a minute to set up a hands-on demo, which we hope will inspire other teams to develop their own Hubs, publish [snippets](https://18f.gsa.gov/2014/12/17/snippets/), and organize working groups/guilds/grouplets.
You will need [Ruby](https://www.ruby-lang.org) ( > version 2.0 is a good idea). You may also consider using a Ruby version manager such as [rbenv](https://github.com/sstephenson/rbenv) to help ensure that Ruby version upgrades don't mean all your [gems](https://rubygems.org/) will need to be rebuilt.
To run your own local instance:
```
$ git clone <EMAIL>:18F/hub.git
$ cd hub
$ gem install bundler
$ bundle
$ bundle exec jekyll serve
```
### Instructions for 18F team members
The internal 18F Hub is hosted at https://hub.18f.us/ and the public Hub staging area is hosted at https://hub.18f.us/hub.
18F team members will want to initialize the [18F/data-private](https://github.com/18F/data-private) and [18F/hub-pages-private](https://github.com/18F/hub-pages-private) submodules after cloning:
```
# Initialize the _data/private and pages/private submodules
$ git submodule init
$ git submodule update --remote
```
By default, `bundle exec jekyll serve` will build the site with data from [_data/private](_data/private) if it is available. Not all data in `_data/private` is actually private, but data that should not be shared outside the team is marked by nesting it within `private:` attributes. To build in "public mode" so that information marked as private doesn't appear in the generated site:
```
$ bundle exec jekyll serve --config _config.yml,_config_public.yml
```
See the [Data README](_data/README.md) for instructions on how to import data into [_data/public](_data/public) for deployment to the Public Hub.
### Documentation
In addition to this README, there is also:
* [Deployment README](deploy/README.md) - DevOps details: publishing the generated site; AWS; Nginx; SSL; Google Auth Proxy
* [Plugins README](_plugins/README.md) - Development details: data import and joining; canonicalization; cross-referencing; page generation
* [Data README](_data/README.md) - Details regarding the organization and processing of data.
### Contributing
Just fork [18F/hub](https://github.com/18F/hub) and start sending pull requests! Feel free to ping [@mbland](https://github.com/mbland) with any questions you may have, especially if the current documentation should've addressed your needs, but didn't.
### Public domain
This project is in the worldwide [public domain](LICENSE.md). As stated in [CONTRIBUTING](CONTRIBUTING.md):
> This project is in the public domain within the United States, and copyright and related rights in the work worldwide are waived through the [CC0 1.0 Universal public domain dedication](https://creativecommons.org/publicdomain/zero/1.0/).
>
> All contributions to this project will be released under the CC0 dedication. By submitting a pull request, you are agreeing to comply with this waiver of copyright interest.
<file_sep>require_relative "../_plugins/joiner"
require_relative "site"
require "minitest/autorun"
module Hub
class SelectJoinSourceTest < ::Minitest::Test
def setup
@site = DummyTestSite.new
end
def test_select_private_source
@site.data['private'] = 'has private data'
impl = JoinerImpl.new @site
assert_equal 'private', impl.source
end
def test_select_public_source
@site.data.delete 'private'
impl = JoinerImpl.new @site
assert_equal 'public', impl.source
end
end
end
|
fd0b66fa2d64cb61961a5805b69d4f5b0460a4b6
|
[
"Markdown",
"Ruby",
"Shell"
] | 13 |
Ruby
|
jasonlally/hub
|
22adcc84ba887ed3d46743271f30e382782add43
|
baad42d37267d587490d5672a189e1c5e6ffcbb0
|
refs/heads/master
|
<repo_name>yudoufu/CoreMLInseptionSample<file_sep>/CoreMLInseptionSample/CameraCapture.swift
//
// CameraCapture.swift
// CoreMLInseptionSample
//
// Created by yudoufu on 2017/07/22.
// Copyright © 2017年 Personal. All rights reserved.
//
import Foundation
import AVFoundation
class CameraCapture: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate {
typealias ImageBufferHandler = ((CVImageBuffer) -> Void)
private let session = AVCaptureSession()
private let fps: CMTimeScale
private let parentLayer: CALayer?
private let imageBufferHandler: ImageBufferHandler?
private var camera: AVCaptureDevice!
private var previewLayer: AVCaptureVideoPreviewLayer?
init(parentLayer: CALayer?, fps: CMTimeScale = 20, completionHandler: ImageBufferHandler?) {
self.parentLayer = parentLayer
self.imageBufferHandler = completionHandler
self.fps = fps
super.init()
setupCamera()
}
private func setupCamera() {
guard let camera = AVCaptureDevice.default(for: .video) else {
print("no camera")
return
}
self.camera = camera
let status = AVCaptureDevice.authorizationStatus(for: .video)
switch status {
case .authorized:
connectSession()
case .notDetermined:
AVCaptureDevice.requestAccess(for: .video) { [weak self] authorized in
if authorized {
self?.connectSession()
}
}
case .restricted, .denied:
print("camera not autherized")
}
}
private func connectSession() {
do {
try setVideoInput()
setVideoOutput()
setupPreviewLayer()
} catch let error as NSError {
print(error)
}
}
private func setVideoInput() throws {
let videoInput = try AVCaptureDeviceInput(device: camera)
if session.canAddInput(videoInput) {
session.addInput(videoInput)
}
do {
try camera.lockForConfiguration()
camera.activeVideoMinFrameDuration = CMTime(value: 1, timescale: fps)
camera.activeVideoMaxFrameDuration = CMTime(value: 1, timescale: fps)
camera.unlockForConfiguration()
} catch {
fatalError()
}
}
private func setVideoOutput() {
let videoOutput = AVCaptureVideoDataOutput()
// ここはBGRAに変換しておかないといけない(画像認識のinput interfaceの関係)
videoOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as AnyHashable as! String: NSNumber(value: kCVPixelFormatType_32BGRA)]
videoOutput.alwaysDiscardsLateVideoFrames = true
videoOutput.setSampleBufferDelegate(self, queue: DispatchQueue.main)
if session.canAddOutput(videoOutput) {
session.addOutput(videoOutput)
}
}
private func setupPreviewLayer() {
guard previewLayer == nil else {
print("preview layer already exist")
return
}
guard let parentLayer = parentLayer else {
print("parent layer doesn't exist")
return
}
let layer = AVCaptureVideoPreviewLayer(session: session)
layer.frame = parentLayer.bounds
layer.contentsGravity = kCAGravityResizeAspectFill
layer.videoGravity = .resizeAspectFill
parentLayer.addSublayer(layer)
previewLayer = layer
}
func startSession() {
if !session.isRunning {
session.startRunning()
}
}
func stopSession() {
if session.isRunning {
session.stopRunning()
}
}
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
if let imageBufferHandler = imageBufferHandler, let buffer = CMSampleBufferGetImageBuffer(sampleBuffer) {
imageBufferHandler(buffer)
}
}
}
<file_sep>/CoreMLInseptionSample/ViewController.swift
//
// ViewController.swift
// CoreMLInseptionSample
//
// Created by yudoufu on 2017/07/22.
// Copyright © 2017年 Personal. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var mainView: UIView!
@IBOutlet weak var classLabel: UILabel!
private let network = Inceptionv3()
private var cameraCapture: CameraCapture!
override func viewDidLoad() {
super.viewDidLoad()
cameraCapture = CameraCapture(parentLayer: mainView.layer, fps: 3) { [weak self] imageBuffer in
self?.predictImageBuffer(imageBuffer)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
cameraCapture.startSession()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
cameraCapture.stopSession()
}
private func predictImageBuffer(_ imageBuffer: CVPixelBuffer) {
guard let resizedBuffer = resize(pixelBuffer: imageBuffer, newSize: CGSize(width: 299, height: 299)) else {
fatalError("Resize error")
}
guard let output = try? network.prediction(image: resizedBuffer) else {
fatalError("Prediction error")
}
classLabel.text = output.classLabel
print(output.classLabel)
}
private func resize(pixelBuffer: CVPixelBuffer, newSize: CGSize) -> CVPixelBuffer? {
let beforeImage = CIImage(cvPixelBuffer: pixelBuffer, options: nil)
let transform = CGAffineTransform(
scaleX: CGFloat(newSize.width) / CGFloat(CVPixelBufferGetWidth(pixelBuffer)),
y: CGFloat(newSize.height) / CGFloat(CVPixelBufferGetHeight(pixelBuffer))
)
let ciImage = beforeImage
.transformed(by: transform)
.cropped(to: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
var resizeBuffer: CVPixelBuffer?
CVPixelBufferCreate(kCFAllocatorDefault, Int(newSize.width), Int(newSize.height), CVPixelBufferGetPixelFormatType(pixelBuffer), nil, &resizeBuffer)
CIContext().render(ciImage, to: resizeBuffer!)
return resizeBuffer
}
}
|
ff6c88c341502b1c7588013492bffcd1da982d0b
|
[
"Swift"
] | 2 |
Swift
|
yudoufu/CoreMLInseptionSample
|
9780b13a9d1b7b54426e1c61ef505e1887d64947
|
319dbb123b888aefcc63c085b3561f95b062dcc4
|
refs/heads/master
|
<repo_name>BossDing/Litemall-Android<file_sep>/common/src/main/java/com/hubertyoung/common/base/BaseActivity.java
package com.hubertyoung.common.base;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.ColorInt;
import android.support.annotation.FloatRange;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import com.acty.litemall.BuildConfig;
import com.acty.litemall.R;
import com.facebook.stetho.common.LogUtil;
import com.hubertyoung.common.baserx.RxManager;
import com.hubertyoung.common.utils.AppManager;
import com.hubertyoung.common.utils.BarUtils;
import com.hubertyoung.common.utils.CommonLog;
import com.hubertyoung.common.utils.StatusBarCompat;
import com.hubertyoung.common.utils.TUtil;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import butterknife.ButterKnife;
import butterknife.Unbinder;
/**
* 基类
*/
/***************使用例子*********************/
//1.mvp模式
//public class SampleActivity extends BaseActivity<NewsChanelPresenter, NewsChannelModel>implements NewsChannelContract.View {
// @Override
// public int getLayoutId() {
// return R.layout.activity_news_channel;
// }
//
// @Override
// public void initPresenter() {
// mPresenter.setVM(this, mModel);
// }
//
// @Override
// public void initView() {
// }
//}
//2.普通模式
//public class SampleActivity extends BaseActivity {
// @Override
// public int getLayoutId() {
// return R.layout.activity_news_channel;
// }
//
// @Override
// public void initPresenter() {
// }
//
// @Override
// public void initView() {
// }
//}
public abstract class BaseActivity< T extends BasePresenter, E extends BaseModel > extends RxAppCompatActivity {
public String TAG = this.getClass()
.getSimpleName();
public T mPresenter;
public E mModel;
public Context mContext;
public RxManager mRxManager;
private boolean isConfigChange = false;
private Unbinder bind;
@Override
public void onCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
isConfigChange = false;
mRxManager = new RxManager();
if ( isRegisterEvent() ) {
mRxManager.mRxBus.register( this );
}
//设置昼夜主题
initTheme();
// 把actvity放到application栈中管理
AppManager.getAppManager()
.addActivity( this );
// 无标题
requestWindowFeature( Window.FEATURE_NO_TITLE );
// 设置竖屏
setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT );
doBeforeSetContentView();
if ( getLayoutId() != 0 ) {
setContentView( getLayoutId() );
//初始化黄油刀控件绑定框架
bind = ButterKnife.bind( this );
mContext = this;
mPresenter = TUtil.getT( this, 0 );
mModel = TUtil.getT( this, 1 );
if ( mPresenter != null ) {
mPresenter.mContext = this;
}
//初始化ToolBar
initToolBar();
this.initPresenter();
this.initView( savedInstanceState );
loadData();
} else {
LogUtil.e( "--->bindLayout() return 0" );
}
}
/**
* 设置layout前配置
*/
public void doBeforeSetContentView() {
// 默认着色状态栏
setStatusBarColor();
}
/*********************子类实现*****************************/
//获取布局文件
public abstract int getLayoutId();
//简单页面无需mvp就不用管此方法即可,完美兼容各种实际场景的变通
public abstract void initPresenter();
//初始化view
public abstract void initView( Bundle savedInstanceState );
protected abstract void loadData();
//初始化toolBar
public abstract void initToolBar();
/**
* 是否开启事件订阅
*
* @return
*/
protected boolean isRegisterEvent() {
return false;
}
/**
* 设置主题
*/
private void initTheme() {
// ChangeModeController.setTheme(this, R.style.DayTheme, R.style.NightTheme);
}
/**
* 着色状态栏(4.4以上系统有效)
*/
protected void setStatusBarColor() {
StatusBarCompat.setStatusBarColor( this, ContextCompat.getColor( this, R.color.colorPrimary ) );
// StatusBarCompat.translucentStatusBar(this);
}
/**
* 着色状态栏(4.4以上系统有效)
*/
protected void setStatusBarColor( @ColorInt int color ) {
StatusBarCompat.setStatusBarColor( this, color );
}
/**
* 沉浸状态栏(4.4以上系统有效)
*/
public void setTranslanteBar() {
// StatusBarCompat.translucentStatusBar(this);
BarUtils.setStatusBar4Bg( this );
}
/**
* 沉浸状态栏(4.4以上系统有效)
*/
protected void setTranslanteBar( @FloatRange( from = 0.0, to = 1.0 ) float alpha ) {
// StatusBarCompat.translucentStatusBar(this);
BarUtils.setStatusBar4Bg( this, alpha );
}
/**
* 为头部ImageView设置状态栏透明度
*
* @param view
*/
public void setHeightAndPadding( View view ) {
// StatusBarCompat.translucentStatusBar(this);
BarUtils.setStatusBar4ImageView( this, view );
}
/**
* 通过Class跳转界面
**/
public void startActivity( Class< ? > cls ) {
startActivity( cls, null );
}
/**
* 通过Class跳转界面
**/
public void startActivityForResult( Class< ? > cls, int requestCode ) {
startActivityForResult( cls, null, requestCode );
}
/**
* 含有Bundle通过Class跳转界面
**/
public void startActivityForResult( Class< ? > cls, Bundle bundle, int requestCode ) {
Intent intent = new Intent();
intent.setClass( this, cls );
if ( bundle != null ) {
intent.putExtras( bundle );
}
startActivityForResult( intent, requestCode );
}
/**
* 含有Bundle通过Class跳转界面
**/
public void startActivity( Class< ? > cls, Bundle bundle ) {
Intent intent = new Intent();
intent.setClass( this, cls );
if ( bundle != null ) {
intent.putExtras( bundle );
}
startActivity( intent );
}
/**
* 显示fragment 可返回
*
* @param fragment
* @param framlayoutID
*/
public void addViewFrame( BaseFragment fragment, int framlayoutID ) {
FragmentTransaction fragmentTransaction = getFragmentTransaction();
fragmentTransaction.replace( framlayoutID, fragment );
fragmentTransaction.addToBackStack( fragment.TAG );
fragmentTransaction.commitAllowingStateLoss();
}
/**
* 获取fragment beginTransaction
*
* @return
*/
public FragmentTransaction getFragmentTransaction() {
return this.getSupportFragmentManager()
.beginTransaction();
}
@Override
protected void onResume() {
super.onResume();
//debug版本不统计crash
if ( !BuildConfig.DEBUG ) {
//友盟统计
// MobclickAgent.onResume(this);
}
}
@Override
protected void onPause() {
super.onPause();
//debug版本不统计crash
if ( !BuildConfig.DEBUG ) {
//友盟统计
// MobclickAgent.onPause(this);
}
}
@Override
public void onConfigurationChanged( Configuration newConfig ) {
super.onConfigurationChanged( newConfig );
isConfigChange = true;
}
@Override
protected void onDestroy() {
super.onDestroy();
CommonLog.loge( "activity: " + getClass().getSimpleName() + " onDestroy()" );
destroyed = true;
if ( mPresenter != null ) mPresenter.onDestroy();
if ( mRxManager != null ) {
if ( isRegisterEvent() ) mRxManager.mRxBus.unregister( this );
mRxManager.clear();
}
if ( !isConfigChange ) {
AppManager.getAppManager()
.finishActivity( this );
}
if ( bind != null ) bind.unbind();
}
//im的基类activity
private boolean destroyed = false;
@Override
public void onBackPressed() {
super.onBackPressed();
}
@Override
public boolean onOptionsItemSelected( MenuItem item ) {
switch ( item.getItemId() ) {
case android.R.id.home:
onNavigateUpClicked();
return true;
}
return onOptionsItemSelectedDispose( item );
}
public boolean onOptionsItemSelectedDispose( MenuItem item ) {
return super.onOptionsItemSelected( item );
}
public void onNavigateUpClicked() {
onBackPressed();
}
protected void showKeyboard( boolean isShow ) {
InputMethodManager imm = ( InputMethodManager ) getSystemService( Context.INPUT_METHOD_SERVICE );
if ( isShow ) {
if ( getCurrentFocus() == null ) {
imm.toggleSoftInput( InputMethodManager.SHOW_FORCED, 0 );
} else {
imm.showSoftInput( getCurrentFocus(), 0 );
}
} else {
if ( getCurrentFocus() != null ) {
imm.hideSoftInputFromWindow( getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS );
}
}
}
// /**
// * 延时弹出键盘
// *
// * @param focus 键盘的焦点项
// */
// protected void showKeyboardDelayed( View focus ) {
// final View viewToFocus = focus;
// if ( focus != null ) {
// focus.requestFocus();
// }
//
// getHandler().postDelayed( new Runnable() {
// @Override
// public void run() {
// if ( viewToFocus == null || viewToFocus.isFocused() ) {
// showKeyboard( true );
// }
// }
// }, 200 );
// }
public boolean isDestroyedCompatible() {
if ( Build.VERSION.SDK_INT >= 17 ) {
return isDestroyedCompatible17();
} else {
return destroyed || super.isFinishing();
}
}
@TargetApi( 17 )
private boolean isDestroyedCompatible17() {
return super.isDestroyed();
}
protected boolean displayHomeAsUpEnabled() {
return true;
}
@Override
public boolean onKeyDown( int keyCode, KeyEvent event ) {
switch ( keyCode ) {
case KeyEvent.KEYCODE_MENU:
return onMenuKeyDown();
default:
return super.onKeyDown( keyCode, event );
}
}
protected boolean onMenuKeyDown() {
return false;
}
public void finishAndTransition() {
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ) {
finishAfterTransition();
} else {
finish();
}
}
}
<file_sep>/common/src/main/java/com/hubertyoung/common/os/OSUtil.java
/*
* Copyright (C) 2013 <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hubertyoung.common.os;
import android.os.Build;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.regex.Pattern;
/**
* Android系统工具箱
*/
public class OSUtil {
/**
* 根据/system/bin/或/system/xbin目录下是否存在su文件判断是否已ROOT
*
* @return true:已ROOT
*/
public static boolean isRoot() {
try {
return new File( "/system/bin/su" ).exists() || new File( "/system/xbin/su" ).exists();
} catch ( Exception e ) {
return false;
}
}
private static final String KEY_MIUI_VERSION_CODE = "ro.miui.ui.version.code";
private static final String KEY_MIUI_VERSION_NAME = "ro.miui.ui.version.name";
private static final String KEY_MIUI_INTERNAL_STORAGE = "ro.miui.internal.storage";
private static final String KEY_EMUI_VERSION_CODE = "ro.build.hw_emui_api_level";
public static boolean isMIUI() {
try {
final BuildProperties prop = BuildProperties.newInstance();
return prop.getProperty( KEY_MIUI_VERSION_CODE, null ) != null || prop.getProperty( KEY_MIUI_VERSION_NAME, null ) != null || prop.getProperty( KEY_MIUI_INTERNAL_STORAGE, null ) != null;
} catch ( final IOException e ) {
return false;
}
}
/**
* 判断是否为MIUI6以上
*/
public static boolean isMIUI6Later() {
try {
Class< ? > clz = Class.forName( "android.os.SystemProperties" );
Method mtd = clz.getMethod( "get", String.class );
String val = ( String ) mtd.invoke( null, "ro.miui.ui.version.name" );
val = val.replaceAll( "[vV]", "" );
int version = Integer.parseInt( val );
return version >= 6;
} catch ( Exception e ) {
return false;
}
}
public static boolean isEMUI() {
try {
final BuildProperties prop = BuildProperties.newInstance();
return prop.getProperty( KEY_EMUI_VERSION_CODE, null ) != null;
} catch ( final IOException e ) {
return false;
}
}
public static boolean isFlyme() {
try {
// Invoke Build.hasSmartBar()
Method method = Build.class.getMethod( "hasSmartBar" );
return ( method != null );
} catch ( final Exception e ) {
return false;
}
}
/**
* 判断是否Flyme4以上
*/
public static boolean isFlyme4Later() {
return Build.FINGERPRINT.contains( "Flyme_OS_4" ) || Build.VERSION.INCREMENTAL.contains( "Flyme_OS_4" ) || Pattern.compile( "Flyme OS [4|5]", Pattern.CASE_INSENSITIVE )
.matcher( Build.DISPLAY )
.find();
}
/**
* 判断当前系统是否是Android4.0
*
* @return 0:是;小于0:小于4.0;大于0:大于4.0
*/
public static int isAPI14() {
return Build.VERSION.SDK_INT - 14;
}
}<file_sep>/README.md
# Litemall-Android
Litemall-Android
Please edit local.properties and add the following
```properties
app=true
#component_basic=false
component_banner=false
component_dynamicsoreview=false
component_bankcard=false
component_filter=false
component_skeleton=false
component_jsbridge=true
component_multiimageview=false
component_gridpasswordview=false
component_pickerview=false
component_home=true
```
## 相关项目
[一个小商城。litemall = Spring Boot后端 + Vue管理员前端 + 微信小程序用户前端](https://github.com/linlinjava/litemall)
|
67188ac2e90ce7f5651d3f0d4bbf57228a9a9858
|
[
"Markdown",
"Java"
] | 3 |
Java
|
BossDing/Litemall-Android
|
e9229ef83d6c4b45a88e866aa2fe525ac8dc473d
|
c14bc6adeb53ddc100243925254053e234043734
|
refs/heads/master
|
<file_sep>var express = require('express');
var app = express();
var hbs = require('express-handlebars');
app.engine('hbs', hbs({extname: 'hbs'}));
app.set('views', './views');
app.set('view engine', 'hbs');
app.route('/').get(function (req, res) {
console.log('Запрос на страницу');
res.render('index', {title: 'Главная страница'});
});
app.route('/cart/:id').get(function (req, res) {
console.log('Запрос карточки пациента ' + req.params.id);
});
// Сервер на порту
app.listen(8888, function () {
console.log('Запущен на порту 8888');
});
|
1c8cbe78c0c1df09e1eb70242ca2fbd1ea357dbd
|
[
"JavaScript"
] | 1 |
JavaScript
|
Vian142/dental-clinic
|
85ff5e84f95dd8301e1340e1c79fd1ffa5130bb0
|
cd9f6857fede3e8ae9f20e6a36c98880d1ff0af6
|
refs/heads/master
|
<file_sep>//Supertest is a library to help test endpoints
const supertest = require('supertest');
//remember our server won't actually start
//due to the if statement in index.js
const server = require('./api/server');
const Auth = require('./auth/auth-model');
// test("Welcome Route", async () => {
// //Passing our server gives us an
// //instance of our server to we
// //can make http requests
// const result = await supertest(server).get("/")
// //does it return the expected status code?
// expect(result.status).toBe(200)
// // //does it return the expected data format?
// expect(result.type).toBe("application/json")
// // //does it return the expected data?
// expect(result.body.message).toBe("Welcome")
// })
//First Test
test("Login Route", async () => {
const data = {
"username":"charlie",
"password":"<PASSWORD>"
}
const result = await supertest(server).post("/api/auth/login").send(data);
expect(result.body.message).toBe("Welcome charlie, have a token...!")
token = result.body.token
expect(result.status).toBe(200)
console.log(token)
})
//Second Test
test("Jokes Route", async () => {
const result = await supertest(server).get("/api/jokes").set('authorization',token);
expect(result.status).toBe(200)
expect(result.body[0].id).toBe('0189hNRf2g')
// console.log(result)
})
//Third Test
// test("Register Route", async () => {
// const data = {
// "username":"charlito",
// "password":"<PASSWORD>"
// }
// const result = await supertest(server).post("/api/auth/register").send(data);
// expect(result.body.username).toBe(data.username)
// expect(result.status).toBe(201)
// })
|
ca386afb6e25e44f332d22cb96dc70f32c617cc4
|
[
"JavaScript"
] | 1 |
JavaScript
|
cleph01/Sprint-Challenge-Authentication
|
3779ae41a35f631bdfff4f1886dcc52f4cdc684d
|
3bd477cf69ad6fe2d2256c67c0830e318af01cc3
|
refs/heads/master
|
<file_sep># RoomSample
[](https://travis-ci.org/isaacizey/RoomSample)
[](https://coveralls.io/github/isaacizey/RoomSample?branch=master)
This project is a sample implementation of room database in android for a tutorial medium post.
### Application Structure
This application is created with android studio
### Installation
Clone this git repository `git clone https://github.com/isaacizey/RoomSample.git`
- open android studio
- Select open project from the file menu
- Run the project and test with an emulator or an android device
###Instructions
<file_sep>package com.kyalo.isaac.roomsample;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import android.support.annotation.NonNull;
@Entity(tableName = "word_table")
public class Word {
@PrimaryKey
@NonNull
@ColumnInfo(name = "word")
private String mWord;
@ColumnInfo(name = "location")
private String mLocation;
public Word(@NonNull String word, String location) {
this.mWord = word;
this.mLocation = location;
}
public String getWord() {
return this.mWord;
}
public String getLocation()
{
return this.mLocation;
}
//its basically a normal class with constructors, getters and setters(methods) and variables
}
|
2171ef143500b0ef9cb96c0349d23011ea76bd9b
|
[
"Markdown",
"Java"
] | 2 |
Markdown
|
isaacizey/RoomSample
|
245c811b032f0776ef9287f51d25b455519ced04
|
9980de9fb4a9c90c847c2fd3d90508df099aca0a
|
refs/heads/master
|
<repo_name>JustinHMKim/Databases_MasterOwl_Comics<file_sep>/README.md
# Databases_MasterOwl_Comics
Final Project for COEN 178, Introduction to Database Systems
Allows for item orders, computing totals, displaying order information. Takes into account item stock and customer membership status.
Includes a GUI for placing orders and setting shipping dates.
<file_sep>/scripts.sql
start cleanup.sql
set serveroutput on
spool projectoutput.txt
start tables.sql
start projecttrigger.sql
start inserts.sql
start projectfunction.sql
start projectqueries.sql
execute orderDetails (0,date '2017-10-01');
execute orderDetails (0,date '2017-10-08');
update ComicCustomer set custtype = 'gold', dateJoined = date '2019-06-07' where custid = 0;
execute orderDetails (0,date '2017-10-01');
execute setShipDate (10, date '2019-06-07');
execute orderDetails (0,date '2017-10-01');
select computetotal(10) from dual;
Select noCopies from StoreItem;
execute additemorder(26,3,5, date '2017-10-28', 20, NULL)
Select * from ItemOrders;
Select noCopies from StoreItem;
execute additemorder(26,3,5, date '2017-10-28', 2, NULL)
Select * from ItemOrders;
Select noCopies from StoreItem;
start orderReport.sql
spool off<file_sep>/projecttrigger.sql
Create Or Replace Trigger goldupdate --sets shipping fee to 0 for any outstanding orders, but not orders that have already gone through--
After UPDATE ON ComicCustomer
For each row
BEGIN
if updating ('custtype') then
if :NEW.custtype = 'gold' then
update ItemOrders
set shippingFee = 0
where custId = :NEW.custId and shippedDate is NULL;
END if;
End if;
END;
/
show errors;
Create Or Replace Trigger checkstock --Other constraint against adding too many comics to an order where there is not enough supply--
BEFORE INSERT OR UPDATE ON ItemOrders
For each row
DECLARE
avail integer;
BEGIN
Select noCopies into avail
from StoreItem
WHERE StoreItem.itemId =:NEW.itemId;
if :NEW.noitems > avail THEN
DBMS_OUTPUT.PUT_LINE ('Order too large');
RAISE_APPLICATION_ERROR(-20010,'Not enough stock for order');
End if;
END ;
/
show errors;
<file_sep>/inserts.sql
--Inserts values into the 3 tables--
Insert into StoreItem values (0,20.00, NULL, NULL,NULL,NULL,'L');
Insert into ComicCustomer values (0,'Jill','<EMAIL>','San Jose',NULL, 'regular');
Insert into ItemOrders values (0,0,0, date '2017-10-10', 1, date '2017-10-30',10);
Insert into StoreItem values (1,22.00, NULL, NULL,NULL,NULL,'XS');
Insert into ComicCustomer values (1,'Bill','<EMAIL>','Santa Clara',NULL, 'regular');
Insert into ItemOrders values (1,1,1, date '2017-10-11', 2, date '2017-10-20',10);
Insert into StoreItem values (2,100.00,129381, 5,'M dash', date '2013-9-10', NULL);
Insert into ComicCustomer values (2,'Will','<EMAIL>','San Francisco',date '2017-10-10', 'gold');
Insert into ItemOrders values (2,2,2, date '2017-10-8', 5, date '2017-10-29',0);
Insert into StoreItem values (3,10.00,129382, 19,'N dash', date '2013-9-11', NULL);
Insert into ItemOrders values (3,3,2, date '2017-10-8', 4, date '2017-10-28',0);
Insert into ComicCustomer values (3,'Mill','<EMAIL>','San Jose',date '2017-11-10', 'gold');
Insert into ItemOrders values (4,3,3, date '2017-10-8', 4, NULL,0);
Insert into ComicCustomer values (4,'Nill','<EMAIL>','San Jose',date '2017-11-10', 'gold');
Insert into ItemOrders values (5,3,4, date '2017-10-8', 4, NULL,0);
Insert into ItemOrders values (6,3,4, date '2017-10-8', 1, NULL,0);
Insert into ItemOrders values (7,3,4, date '2017-10-8', 100, NULL,0);
Insert into StoreItem values (4,40.00, NULL, NULL,NULL,NULL,'L');
Insert into ComicCustomer values (5,'Till','<EMAIL>','Santa Monica',NULL, 'regular');
Insert into ItemOrders values (8,4,4, date '2017-10-24', 1, date '2017-10-30',0);
Insert into StoreItem values (5,32.00, NULL, NULL,NULL,NULL,'XS');
Insert into ComicCustomer values (6,'Jill','<EMAIL>','Sahara',NULL, 'regular');
Insert into ItemOrders values (9,4,4, date '2017-10-09', 2, date '2017-11-23',0);
Insert into StoreItem values (6,40.00,129382, 5,'O dash', date '2013-11-10', NULL);
Insert into ItemOrders values (10,4,0, date '2017-10-07', 2,NULL,10);
<file_sep>/projectqueries.sql
Create or Replace Procedure addItemOrder (oid int, iid int, cid int, orddate DATE, noordered int, shipdate DATE)
AS
quant int;
memstatus varchar(255);
no_more_books EXCEPTION; --One of the constraints against adding too many books to an order--
BEGIN
Select noCopies into quant
from StoreItem
where StoreItem.itemid = iid;
Select custtype into memstatus
from ComicCustomer
where ComicCustomer.custId = cid;
IF quant is not NULL THEN
IF noordered > quant THEN
RAISE no_more_books;
ELSE
update StoreItem
set noCopies = (quant - noordered)
where StoreItem.itemId = iid;
END IF;
END IF;
IF memstatus = 'regular' THEN
INSERT INTO ItemOrders
(orderId, itemId, custId, orderDate, noItems, shippedDate, shippingFee)
VALUES
(oid,iid,cid,orddate,noordered,NULL,10.00);
ELSE
INSERT INTO ItemOrders
(orderId, itemId, custId, orderDate, noItems, shippedDate, shippingFee)
VALUES
(oid,iid,cid,orddate,noordered,NULL,0.00);
END IF;
EXCEPTION
WHEN no_more_books THEN
dbms_output.put_line('Insufficient stock for this order');
commit;
END;
/
Show errors;
Create or Replace Procedure setShipDate (oid int, shippingDate DATE)
IS
BEGIN
update ItemOrders
set shippedDate = shippingDate
where orderId = oid;
COMMIT;
END;
/
Show errors;
Create or Replace Procedure orderDetails (cid int, adate DATE)
As
selectedcust int;
thedate date;
o_cid ComicCustomer.custId%type;
o_name ComicCustomer.name%type;
o_phone_email ComicCustomer.phone_email%type;
o_address ComicCustomer.address%type;
o_iid StoreItem.itemId%type;
o_price StoreItem.price%type;
o_orderDate ItemOrders.orderDate%type;
o_shippedDate ItemOrders.shippedDate%type;
o_shipFee ItemOrders.shippingFee%type;
o_custtype ComicCustomer.custtype%type;
o_oid ItemOrders.orderId%type;
o_title StoreItem.title%type;
Cursor Cust IS
Select ComicCustomer.custid, name, phone_email, address, StoreItem.itemId, price,orderDate,shippedDate, shippingFee, custtype, orderId, title from ComicCustomer full outer join (ItemOrders full outer join StoreItem on ItemOrders.itemId = StoreItem.itemid) on ComicCustomer.custId = ItemOrders.custid where ComicCustomer.custid = cid AND ItemOrders.orderDate > adate order by ComicCustomer.custId;
--joins all the tables by itemid, then by custid so as to easily get all the relevant information to print--
BEGIN
open Cust;
Fetch Cust into o_cid, o_name, o_phone_email, o_address, o_iid, o_price, o_orderDate, o_shippedDate, o_shipFee, o_custtype, o_oid, o_title;
DBMS_OUTPUT.put_line('Customer Details: '||o_cid||', '||o_name||', '||o_phone_email||', '||o_address);
--Only need customer's details once, versus each of their orders, which necessitates the loop--
LOOP
IF o_title is not NULL THEN
DBMS_OUTPUT.put_line('Item Details: Order ID: '||o_oid||', Item ID: '||o_iid||', Title: ' ||o_title||', Price: '||o_price||', Date Ordered '||o_orderDate||', Date Shipped: '||o_shippedDate);
ELSE
DBMS_OUTPUT.put_line('Item Details: Order ID: '||o_oid||',Item ID: '||o_iid||', Price: $'||o_price||', Date Ordered '||o_orderDate||', Date Shipped: '||o_shippedDate);
END IF;
DBMS_OUTPUT.put_line('Subtotal: $'||computesubTotal(o_oid)||', Tax: $'||0.05*computesubTotal(o_oid)||', Shipping Fee: $'||o_shipFee||', Discount: $'||computediscount(o_oid)||', Total: $'||computeTotal(o_oid));
Fetch Cust into o_cid, o_name, o_phone_email, o_address, o_iid, o_price, o_orderDate, o_shippedDate, o_shipFee, o_custtype, o_oid, o_title;
--used the added functions to compute the nonattribute details--
EXIT WHEN CUST%notfound;
END LOOP;
close Cust;
END;
/
Show errors;
<file_sep>/projectfunction.sql
Create Or Replace Function computeTotal(oid int) --function computes total for a particular item order--
Return Number IS
totalSum DECIMAL(19, 4);
quantity int;
membership varchar(255);
sfee DECIMAL(19, 4);
BEGIN
Select price
into totalSum
from StoreItem
where StoreItem.itemId =
(Select itemId
from ItemOrders
where orderId = oid);
Select custtype
into membership
from ComicCustomer
where ComicCustomer.custid = (Select custid
from ItemOrders
where orderId = oid);
Select shippingFee, noItems
into sfee, quantity
from ItemOrders
where orderId = oid;
IF membership = 'gold' AND totalSum >= 100.00 THEN --applies 10% discount if purchase is at least $100 for gold members--
totalSum := 1.05 *((totalSum * quantity) * 0.9);
ELSIF membership = 'gold' AND totalSum < 100.00 THEN --otherwise just removes the shipping fee--
totalSum := 1.05 *(totalSum*quantity);
ELSE
totalSum := 1.05 *(totalSum*quantity) + sfee;
END IF;
RETURN totalSum;
END;
/
show errors;
Create Or Replace Function computesubTotal(oid int) --computes subtotal for use in report--
Return Number IS
subtotalSum DECIMAL(19, 4);
quantity int;
BEGIN
Select price
into subtotalSum
from StoreItem
where StoreItem.itemId =
(Select itemId
from ItemOrders
where orderId = oid);
Select noItems
into quantity
from ItemOrders
where orderId = oid;
IF quantity is not NULL THEN
subtotalSum := subtotalSum*quantity;
END IF;
RETURN subtotalSum;
END;
/
show errors;
Create Or Replace Function computediscount(oid int) --computes gold member discount for use in report--
Return Number IS
discount DECIMAL(19, 4);
totalSum DECIMAL(19, 4);
quantity int;
membership varchar(255);
BEGIN
Select price
into totalSum
from StoreItem
where StoreItem.itemId =
(Select itemId
from ItemOrders
where orderId = oid);
Select noItems
into quantity
from ItemOrders
where orderId = oid;
Select custtype
into membership
from ComicCustomer
where ComicCustomer.custid = (Select custid
from ItemOrders
where orderId = oid);
IF membership = 'gold' AND totalSum >= 100.00 THEN
discount := 0.1 *(totalSum * quantity) ;
ELSE
discount := 0;
END IF;
RETURN discount;
END;
/
show errors;<file_sep>/GUI Screenshots and Link/projectweb.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect input data from the form
// Get the orderid
$customerid = $_POST['customerid'];
/// Need to enter in form: 02-OCT-18
$somedate = date('d-M-y', strtotime($_POST['somedate']));
if (!empty($customerid)){
$customerid = prepareInput($customerid);
}
// Call the function with customerid and starting date for viewing orders
ViewOrderDB($customerid,$somedate);
}
function prepareInput($inputData){
$inputData = trim($inputData);
$inputData = htmlspecialchars($inputData);
return $inputData;
}
function ViewOrderDB($customerid,$somedate){
//connect to your database. Type in sd username, password and the DB path
$conn = oci_connect('hkim', '000012689111', '//dbserver.engr.scu.edu/db11g');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
if(!$conn) {
print "<br> connection failed:";
exit;
}
// Calling the PLSQL procedure, orderDetails
$sql = "CALL orderDetails(:customerid,:somedate)";
$foo = oci_parse($conn,$sql);
oci_bind_by_name($foo, ':customerid', $customerid);
oci_bind_by_name($foo, ':somedate', $somedate);
// Execute the query
$res = oci_execute($foo);
echo "$res";
oci_free_statement($foo);
OCILogoff($conn);
}
?>
<file_sep>/GUI Screenshots and Link/shipDate.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect input data from the form
// Get the orderid
$orderid = $_POST['orderid'];
/// Need to enter in form: 02-OCT-18
$shippeddate = date('d-M-y', strtotime($_POST['shippeddate']));
if (!empty($orderid)){
$orderid = prepareInput($orderid);
}
// Call the function to insert orderid and shippeddate
// into ItemOrders table
insertShipDateIntoDB($orderid,$shippeddate);
}
function prepareInput($inputData){
$inputData = trim($inputData);
$inputData = htmlspecialchars($inputData);
return $inputData;
}
function insertShipDateIntoDB($orderid,$shippeddate){
//connect to your database. Type in sd username, password and the DB path
$conn = oci_connect('hkim', '000012689111', '//dbserver.engr.scu.edu/db11g');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
if(!$conn) {
print "<br> connection failed:";
exit;
}
// Calling the PLSQL procedure, setShipDate
$sql = oci_parse($conn, 'begin setShipDate(:orderid,:shippeddate); end;');
oci_bind_by_name($sql, ':orderid', $orderid);
oci_bind_by_name($sql, ':shippeddate', $shippeddate);
// Execute the query
$res = oci_execute($sql);
if ($res){
echo '<br><br> <p style="color:green;font-size:20px">';
echo "Date Updated </p>";
}
else{
$e = oci_error();
echo $e['message'];
}
oci_free_statement($sql);
OCILogoff($conn);
}
?>
<file_sep>/tables.sql
CREATE TABLE ComicCustomer (
custId int PRIMARY KEY,
name varchar(255) NOT NULL,
phone_email varchar(255) NOT NULL UNIQUE,
address varchar(255),
dateJoined DATE,
custtype varchar(255),
CONSTRAINT customer_type CHECK (custtype = 'gold' OR custtype = 'regular')
);--Applied Null table approach for gold vs regular customers
CREATE TABLE StoreItem (
itemId int PRIMARY KEY,
price DECIMAL(19, 4),
ISBN int,
noCopies int CHECK (noCopies >= 0),
title varchar(255),
pubDate DATE,
shirtsize varchar(3),
CONSTRAINT ISBN_uni UNIQUE(ISBN),
CONSTRAINT item_type CHECK (ISBN is NULL OR shirtsize is NULL)
);/*Applied Null table approach for shirts vs comic books. ISBN and shirtsize indicate which type the item is; Constraint for one to
be NULL so no item can be both a shirt and a comicbook. */
CREATE TABLE ItemOrders (
orderId int NOT NULL,
itemId int NOT NULL,
custId int NOT NULL,
orderDate DATE,
noItems int,
shippedDate DATE,
CONSTRAINT chk_date CHECK (shippedDate > orderDate),
shippingFee DECIMAL(19, 4),
FOREIGN KEY (itemId) REFERENCES StoreItem(itemId),
FOREIGN KEY (custId) REFERENCES ComicCustomer(custId),
CONSTRAINT PK_ItemOrders PRIMARY KEY (orderId)
);
<file_sep>/orderReport.sql
-- the size of one page
SET PAGESIZE 20
SET LINESIZE 200
BREAK ON TODAY
COLUMN TODAY NEW_VALUE report_date
SELECT TO_CHAR(SYSDATE, 'fmMonth DD, YYYY') TODAY
FROM DUAL;
set termout off
ttitle center "MasterOwl Orders: Accessed " report_date skip 2
btitle center "MasterOwl Comics Inc."
spool orderReport.txt
column ComicCustomer.custid format a10 heading "Customer Id"
column name format a20 heading "Customer Name"
column phone_email format a20 heading "Phone/Email"
column address format a20 heading "Address"
column orderId heading "Order Id"
column title format a10 heading "Title"
column price format $9,999.99 heading "Item Price"
column orderDate format a20 heading "Date Ordered"
column shippedDate format a20 heading "Date Shipped"
column computesubTotal(orderId) format $9,999.99 heading "Subtotal"
column 0.05*computesubTotal(orderId) format $9,999.99 heading "Tax"
column shippingFee format $9,999.99 heading "Shipping Fee"
column computediscount(orderId) format $9,999.99 heading "Discount"
column computeTotal(orderId) format $9,999.99 heading "Grand Total"
--used functions to compute the nonattribute columns
BREAK ON orderId ON ROW SKIP 1
Select ComicCustomer.custid, name, phone_email, address, orderId, title, price,orderDate,shippedDate, computesubTotal(orderId), 0.05*computesubTotal(orderId), shippingFee, computediscount(orderId),computeTotal(orderId) from
ComicCustomer full outer join (ItemOrders full outer join StoreItem on ItemOrders.itemId = StoreItem.itemid) on ComicCustomer.custId = ItemOrders.custid where ComicCustomer.custid = &custid and ItemOrders.orderDate > &orderDate order by ItemOrders.orderId;
--gets the info based on the inputted custid and specified date, from &custid and &orderDate--
--joined all tables for simplicity--
spool off;
--clear all formatting commands ...
/*
CLEAR COLUMNS
CLEAR BREAK
TTITLE OFF
BTITLE OFF
SET VERIFY OFF
SET FEEDBACK OFF
SET RECSEP OFF
SET ECHO OFF
*/
|
4305c88f0da13bbdcf029e0091b7ab14f1a9bc95
|
[
"Markdown",
"SQL",
"PHP"
] | 10 |
Markdown
|
JustinHMKim/Databases_MasterOwl_Comics
|
601a9d71b924a187e8d5ee08fc2db773d25dc962
|
20160325defb802457cdbd109b26dedd1a05f61c
|
refs/heads/master
|
<repo_name>bettse/Janus<file_sep>/objc_dep/Makefile
PROJECT=Janus
EXCLUDE=(\-Prefix|main|FM|Tests|PK|ParseKit)
DOT=dot
circo: DOT=circo
twopi: DOT=twopi
default:
objc_dep.py -x "$(EXCLUDE)" ../ > $(PROJECT).dot
$(DOT) -Tpng $(PROJECT).dot -O
open $(PROJECT).dot.png
circo:
objc_dep.py -x "$(EXCLUDE)" ../ > $(PROJECT).dot
$(DOT) -Tpng $(PROJECT).dot -O
open $(PROJECT).dot.png
twopi:
objc_dep.py -x "$(EXCLUDE)" ../ > $(PROJECT).dot
$(DOT) -Tpng $(PROJECT).dot -O
open $(PROJECT).dot.png
<file_sep>/Janus/IOHIDBlockAdapter.c
//
// IOHIDBlockAdapter.c
// Janus
//
// Created by <NAME> on 9/1/15.
// Copyright © 2015 <NAME>. All rights reserved.
//
#include "IOHIDBlockAdapter.h"
void device_callback_helper(void *inBlock, IOReturn inResult, void *inSender, IOHIDDeviceRef inIOHIDDeviceRef) {
IOHIDDeviceBlock block = (IOHIDDeviceBlock)inBlock;
block(inResult, inSender, inIOHIDDeviceRef);
}
void input_callback_helper(void *inBlock, IOReturn result, void *sender, IOHIDReportType type, uint32_t reportID, uint8_t *report, CFIndex reportLength) {
IOHIDReportBlock block = (IOHIDReportBlock)inBlock;
block(result, sender, type, reportID, report, reportLength);
}
<file_sep>/Readme.md
# Release
See https://github.com/bettse/Janus/releases/0.5
Icon from http://findicons.com/icon/69400/circle_grey?id=332952
New UI design by [<NAME>](http://basvanderploeg.nl)
# Script Ideas:
* current stock price
* Play Next/Prev
* Volume up/down/certain level
* open google earth location
* open iphoto album
* open facetime to someone using facetime://
* control hue lights (movie mode?)
* Print App icon to cardboard and tag, link to open app
* Combination/Chain scripts (set lights + start music + open slideshow)
* Delegate launching/scripting to something like Alfred?
# Stateful scripts
* Last used
* How long tag has been on reader
* Number of scans per day
# Ideas from plannete domotique
* http://www.planete-domotique.com/confort/nabaztag-karotz/mir-ror/mir-ror-bulk-sans-nanoz.html
* Launch files on your computer
* Viewing websites
* Display videos, photos, music
* Voice reading info from your web site (RSS)
* Launches Podcasts from the internet
* Launch Webradios
* Sending emails containing variable parts
* Sending voice messages
* Diffusion Weather, Stocks, Air Quality
* Counting, recording and recalling past uses of an object
* Lock PC, launch the screen saver
* Send Twitter messages with variable parts
* Receiving emails and message subject
* Sending sensor data to external sites through URL
* Reading books (sold separately)
* Launching and piloting iTunes
* And launch Skype call
# sites
* http://www.journaldulapin.com/2013/03/01/reutiliser-facilement-un-mirror-sous-mac-os-x/
* http://www.journaldulapin.com/2013/02/12/reutiliser-un-mirror-sous-mac-os-x/
* http://labo.lcprod.net/2013/02/application-mac-os-x-gestion-du-mirror-de-violet-le-lecteur-rfid-associe-au-nabaztags/
* http://nabaztag.forumactif.fr/f70-mirror-mon-beau-mirror
#todo
* gourse and git-playback
* Janus as arbitrary event -> action framework.
* Right now Mirror causes tagEvents, why not a clock that causes clockEvents or timer that causes Timer events.
<file_sep>/stopBackup
#!/bin/bash
if [[ $2 = "IN" ]]
then
tmutil stopbackup
fi
<file_sep>/location.py
#!/usr/bin/python
import sys
import json
from os import system
from os import path
import ConfigParser
if(len(sys.argv) < 5):
sys.exit()
lat = sys.argv[1]
lon = sys.argv[2]
tagid = sys.argv[3]
friendlyname = sys.argv[3]
if(dir == 'OUT'):
sys.exit()
configfile = tagid + '.cfg'
kml = """<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2">
<Document id="feat_1">
<Placemark id="feat_2">
<name>""" + friendlyname + """</name>
<Point id="geom_0">
<coordinates>""" + lon + """,""" + lat + """</coordinates>
</Point>
</Placemark>
</Document>
</kml>
"""
f = open('%s.kml' % tagid, 'w')
f.write(kml)
f.close()
system("open %s.kml" % tagid)
|
0049149bd41fd5f2e17b910f8ae99825e386eb9b
|
[
"Markdown",
"Makefile",
"Python",
"C",
"Shell"
] | 5 |
Makefile
|
bettse/Janus
|
9f3cd794fc80a438879688621c7b2d5124ee511e
|
4c89398122043c140edc2ec12c317c3bb99c8d89
|
refs/heads/master
|
<file_sep>1.// function ChristmasTree(n){
// for ( i = 0; i <=n; i++) {
// let tree = ' ';
// for ( j = 1; j <= n-i; j++) {
// tree+= " ";
// };
// for ( k = 0; k <= i; k++) {
// tree += " *"
// };
// console.log(tree);
// };
// };
// ChristmasTree(6);
2.// function GetSequence(a,b) {
// let NewArray = []
// for (let i = a; i <= b; i++) {
// NewArray.push(i);
// };
// console.log(NewArray);
// };
// GetSequence(1,5);
3.//let NewArray = [32,25,85,89,45,76,7,41,2,12]
//a//console.log(NewArray);
//b //alert(Math.max(...NewArray));
//c //NewArray.push(15);
//console.log(NewArray);
//d //NewArray.shift(0);
//console.log(NewArray);
//e //NewArray.sort();
//NewArray.pop();
//console.log(NewArray);
//f //NewArray.splice(3,0,43);
//console.log(NewArray);
//g //console.log(NewArray.slice(3));
//h //NewArray.forEach(number => console.log(number));
//i //let SecondArray = []
// for ( i = 0; i < NewArray.length; i++) {
// if(NewArray[i] > 40){
// SecondArray.push(NewArray[i]);
// };
// };
// console.log(SecondArray);
4.// function Sum(a,b) {
// if(a==b){
// console.log((a+b)*3);
// }
// else{
// console.log(a+b);
// }
// }
// Sum(5,5);
|
288118cf942a17e3bb884813c057f6c124469288
|
[
"JavaScript"
] | 1 |
JavaScript
|
iftikharbg/tree-consecutive-methods-sum-iftixar
|
ccf68f813751061423f81606fb7ff0dacab29473
|
be4ae79b55f2bbe9254339f18cf0a19ba3ad9fc6
|
refs/heads/master
|
<repo_name>PnS2018/wgw<file_sep>/train_model.py
import numpy as np
from data.DataProcessor import DataProcessor
from model.ModelManager import ModelManager
from utils.config import config
np.random.seed(config.VERSION)
dp = DataProcessor()
print("Starting model training.")
# load data
train_x, train_y, test_x, test_y = dp.load_grayscale()
train_X, train_Y, test_X, test_Y, datagen = dp.preprocess_data(train_x, train_y, test_x, test_y)
model = ModelManager().get_model_v3()
# fits the model on batches with real-time data augmentation:
model.fit_generator(datagen.flow(train_x, train_Y, batch_size=64),
epochs=config.NUM_EPOCHS,
callbacks=[],
validation_data=(test_X, test_Y))
# save the trained model
model.save("version{}_epochs{}_model{}.h5".format(config.VERSION, config.NUM_EPOCHS, config.MODEL_VERSION))
print("Finishing model training.")
<file_sep>/requirements.txt
absl-py==0.2.0
astor==0.6.2
backports.functools-lru-cache==1.5
backports.weakref==1.0.post1
bleach==1.5.0
cycler==0.10.0
dotmap==1.2.20
enum34==1.1.6
funcsigs==1.0.2
futures==3.2.0
gast==0.2.0
grpcio==1.11.0
h5py==2.7.1
html5lib==0.9999999
Keras==2.1.5
kiwisolver==1.0.1
Markdown==2.6.11
matplotlib==2.2.2
mock==2.0.0
numpy==1.14.2
opencv-contrib-python==3.4.0.12
opencv-python==3.4.0.12
pbr==4.0.2
Pillow==5.1.0
protobuf==3.5.2.post1
pyparsing==2.2.0
python-dateutil==2.7.2
pytz==2018.4
PyYAML==3.12
scipy==1.0.1
six==1.11.0
subprocess32==3.2.7
tensorboard==1.7.0
tensorflow==1.7.0
termcolor==1.1.0
Werkzeug==0.14.1
<file_sep>/check_precision.py
import numpy as np
from keras.models import load_model
from data.DataProcessor import DataProcessor
from utils.config import config
dp = DataProcessor()
print("Starting precision check.")
# load and preprocess testing data
train_x, train_y, test_x, test_y = dp.load_grayscale()
_, _, test_X, test_Y, _ = dp.preprocess_data(train_x, train_y, test_x, test_y)
model = load_model('version{}_epochs{}_model{}.h5'.format(config.VERSION, config.NUM_EPOCHS, config.MODEL_VERSION))
preds_org = model.predict(test_X)
preds = np.round(preds_org - config.THRESHOLD + 0.5)
false_pos = 0
false_neg = 0
total_pos = 0
total_neg = 0
for i in range(0, len(preds)):
if test_Y[i][1] == 1:
total_neg += 1
if test_Y[i][0] == 1:
total_pos += 1
if preds[i][0] != test_Y[i][0] or preds[i][1] != test_Y[i][1]:
if test_Y[i][1] == 1:
false_pos += 1
if test_Y[i][0] == 1:
false_neg += 1
print("Above threshold {} we have:".format(config.THRESHOLD))
print('Total positives: {}, Total negatives: {}, False negatives: {}, False positives: {}'.format(total_pos, total_neg,
false_neg, false_pos))
print("Finished precision check.")
<file_sep>/model/ModelManager.py
import keras.backend as K
from keras.layers import Conv2D, Dense, Flatten, Input, MaxPooling2D
from keras.models import Model
from utils.config import config
class ModelManager:
"""
Wrapper for our models
"""
def __init__(self):
self.image_x_axis = config.IMAGE_SIZE
self.image_y_axis = config.IMAGE_SIZE
def get_model_v1(self):
"""
Our model MVP
:return: model instance
"""
x = Input((self.image_x_axis, self.image_y_axis, 1))
c1 = Conv2D(filters=20,
kernel_size=(7, 7),
padding='same',
activation='relu')(x)
p1 = MaxPooling2D((2, 2))(c1)
c2 = Conv2D(filters=25,
kernel_size=(5, 5),
padding='same',
activation='relu')(p1)
p2 = MaxPooling2D((2, 2))(c2)
f = Flatten()(p2)
d = Dense(200, activation='relu')(f)
y = Dense(2, activation='softmax')(d)
model = Model(x, y)
# print model summary
model.summary()
# compile the model against the categorical cross entropy loss
# loss: cost function, should be cross validation, categorical_crossentropy also possible
# optimizer: schedule learning rate troughout the training
# metric: performance measure categroical_crossentropy, AUC for binaryclassf, or accuracy
model.compile(loss='binary_crossentropy',
optimizer='sgd',
metrics=['accuracy'])
return model
def get_model_v2(self):
"""
Model that uses f1
:return: model instance
"""
x = Input((self.image_x_axis, self.image_y_axis, 1))
c1 = Conv2D(filters=20,
kernel_size=(7, 7),
padding='same',
activation='relu')(x)
p1 = MaxPooling2D((2, 2))(c1)
c2 = Conv2D(filters=25,
kernel_size=(5, 5),
padding='same',
activation='relu')(p1)
p2 = MaxPooling2D((2, 2))(c2)
f = Flatten()(p2)
d = Dense(20, activation='relu')(f)
y = Dense(2, activation='softmax')(d)
model = Model(x, y)
# print model summary
model.summary()
# compile the model against the categorical cross entropy loss
# loss: cost function, should be cross validation, categorical_crossentropy also possible
# optimizer: schedule learning rate troughout the training
# metric: performance measure categroical_crossentropy, AUC for binaryclassf, or accuracy
model.compile(loss='binary_crossentropy',
optimizer='sgd',
metrics=['accuracy', _f1, _precision, _recall])
return model
def get_model_v3(self):
"""
A bit more refined model
:return: model instance
"""
x = Input((self.image_x_axis, self.image_y_axis, 1))
c1 = Conv2D(filters=20,
kernel_size=(7, 7),
strides=(2, 2),
padding='same',
activation='relu')(x)
p1 = MaxPooling2D((2, 2))(c1)
c2 = Conv2D(filters=25,
kernel_size=(7, 7),
strides=(2, 2),
padding='same',
activation='relu')(p1)
p2 = MaxPooling2D((2, 2))(c2)
f = Flatten()(p2)
d = Dense(20, activation='relu')(f)
y = Dense(2, activation='softmax')(d)
model = Model(x, y)
# print model summary
model.summary()
# compile the model against the categorical cross entropy loss
# loss: cost function, should be cross validation, categorical_crossentropy also possible
# optimizer: schedule learning rate troughout the training
# metric: performance measure categroical_crossentropy, AUC for binaryclassf, or accuracy
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
return model
def get_model_v4(self):
"""
A bit more refined model
:return: model instance
"""
x = Input((self.image_x_axis, self.image_y_axis, 1))
c1 = Conv2D(filters=20,
kernel_size=(7, 7),
strides=(2, 2),
padding='same',
activation='relu')(x)
p1 = MaxPooling2D((2, 2))(c1)
c2 = Conv2D(filters=25,
kernel_size=(7, 7),
strides=(2, 2),
padding='same',
activation='relu')(p1)
p2 = MaxPooling2D((2, 2))(c2)
c3 = Conv2D(filters=15,
kernel_size=(7, 7),
strides=(2, 2),
padding='same',
activation='relu')(p2)
p3 = MaxPooling2D((2, 2))(c3)
f = Flatten()(p3)
d = Dense(20, activation='relu')(f)
y = Dense(2, activation='softmax')(d)
model = Model(x, y)
# print model summary
model.summary()
# compile the model against the categorical cross entropy loss
# loss: cost function, should be cross validation, categorical_crossentropy also possible
# optimizer: schedule learning rate troughout the training
# metric: performance measure categroical_crossentropy, AUC for binaryclassf, or accuracy
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
return model
def _recall(y_true, y_pred):
"""Recall metric.
Only computes a batch-wise average of recall.
Computes the recall, a metric for multi-label classification of
how many relevant items are selected.
"""
y_true = K.cast(K.argmax(y_true, axis=1), 'float32')
y_pred = K.cast(K.argmax(y_pred, axis=1), 'float32')
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
recall = true_positives / (possible_positives + K.epsilon())
return recall
def _precision(y_true, y_pred):
"""Precision metric.
Only computes a batch-wise average of precision.
Computes the precision, a metric for multi-label classification of
how many selected items are relevant.
"""
y_true = K.cast(K.argmax(y_true, axis=1), 'float32')
y_pred = K.cast(K.argmax(y_pred, axis=1), 'float32')
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
precision = true_positives / (predicted_positives + K.epsilon())
return precision
def _f1(y_true, y_pred):
prec = _precision(y_true, y_pred)
rec = _recall(y_true, y_pred)
return 2 * ((prec * rec) / (prec + rec + K.epsilon()))
<file_sep>/utils/config.py
import os
import yaml
from dotmap import DotMap
CONFIG_FILE = '{}/config.yml'.format(os.getcwd())
def get_config():
"""
This function creates a DotMap configuration object from the config.yml file.
:return: DotMap object of the configuration
"""
with open(CONFIG_FILE) as config_file:
config_yaml = yaml.load(config_file)
return DotMap(config_yaml, _dynamic=False)
config = get_config()
<file_sep>/data/DataProcessor.py
import os
import cv2
import numpy as np
from keras.preprocessing.image import (ImageDataGenerator, img_to_array,
load_img)
from keras.utils import to_categorical
from utils.config import config
class DataProcessor:
"""
Wrapper used for all data manipulation actions
"""
def __init__(self):
self.image_size = config.IMAGE_SIZE
self.train_waldo = config.TRAIN_WALDO
self.train_notwaldo = config.TRAIN_NOTWALDO
self.test_waldo = config.TEST_WALDO
self.test_notwaldo = config.TEST_NOTWALDO
self.augmented_train_waldo = config.AUGMENTED_TRAIN_WALDO
def load_grayscale(self):
"""
Load the train and test images as grayscale vectors from the data directory
:return: numpy arrays of the respective train and test images
"""
# a truth value of 0 corresponds to waldo and 1 to notwaldo
train_waldo_x, train_waldo_y = self._load_from_path_grayscale(self.train_waldo, 0)
train_notwaldo_x, train_notwaldo_y = self._load_from_path_grayscale(self.train_notwaldo, 1)
test_waldo_x, test_waldo_y = self._load_from_path_grayscale(self.test_waldo, 0)
test_notwaldo_x, test_notwaldo_y = self._load_from_path_grayscale(self.test_notwaldo, 1)
train_x = np.concatenate((train_waldo_x, train_notwaldo_x))
train_y = np.concatenate((train_waldo_y, train_notwaldo_y))
test_x = np.concatenate((test_waldo_x, test_notwaldo_x))
test_y = np.concatenate((test_waldo_y, test_notwaldo_y))
train_x = train_x.astype("float32")
test_x = test_x.astype("float32")
return train_x, train_y, test_x, test_y
def preprocess_data(self, train_x, train_y, test_x, test_y):
"""
Preprocess and augment the data to be used in the model
:return: numpy arrays with the augmented train and test vectors
"""
# augment training dataset
datagen = ImageDataGenerator(
featurewise_center=True,
featurewise_std_normalization=True,
rotation_range=5,
width_shift_range=0.1,
height_shift_range=0.1,
horizontal_flip=True,
fill_mode='nearest')
datagen.fit(train_x)
# leave training data set as it is and standardize the test vector set
train_X = train_x
test_X = datagen.standardize(test_x)
# converting the input class labels to categorical labels for training
train_Y = to_categorical(train_y, num_classes=2)
test_Y = to_categorical(test_y, num_classes=2)
return train_X, train_Y, test_X, test_Y, datagen
def augment_and_save(self):
"""
An augmentation function to generate augmented RGB pictures that saves them back to disk
"""
for image in os.listdir(self.train_waldo):
img = load_img('{}/{}'.format(self.train_waldo, image))
x = img_to_array(img) # this is a numpy array with shape (3, 150, 150)
x = x.reshape((1,) + x.shape) # this is a numpy array with shape (1, 3, 150, 150)
datagen = ImageDataGenerator(
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
horizontal_flip=True,
fill_mode='nearest'
)
i = 0
for _ in datagen.flow(x,
batch_size=1,
save_to_dir=self.augmented_train_waldo,
save_prefix='augmented',
save_format='jpeg'):
i += 1
if i > 3:
break
def _load_from_path_grayscale(self, path, label):
x = []
# load images from path
for image in os.listdir(path):
x.append(cv2.imread('{}/{}'.format(path, image), 0))
# bring them into the right format for use in the model
x = np.concatenate([image[np.newaxis, :] for image in x]) # concatenate the images along the first axis
x = x[:, :, :, np.newaxis] # add a forth axis
# add truth values
if label == 1:
y = np.ones(x.shape[0])
else:
y = np.zeros(x.shape[0])
return x, y
<file_sep>/data/RunProcessor.py
import heapq
from datetime import datetime
import cv2
import numpy as np
from utils.config import config
class RunProcessor:
"""
Wrapper for functions that are for using the already trained network
"""
def __init__(self):
self.image_size = config.IMAGE_SIZE
self.mean = config.MEAN
self.std = config.STD
self.top_x = config.TOP_X
self.threshold = config.THRESHOLD
def find_waldo(self, path, stride, model):
"""
Function that takes an image and displays the image with the prediction visualized in it
:param path: path to image file
:param stride: the stride that should be used for tiling the image
:param model: model that should be used for our prediction
"""
img = self._get_wrapped_image(path)
x_org = self._get_image_tiles(img, stride)
# allow drawing to be of color
img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
# bring them into the right format for use in the model
x = np.concatenate([image[np.newaxis, :] for image in x_org]) # concatenate the images along the first axis
x = x[:, :, :, np.newaxis] # add a forth axis
x = x.astype("float32")
x = (x - self.mean) / self.std # standardize
cols = ((img.shape[1] - self.image_size) // stride) + 1
found = 0
start = datetime.now()
preds = model.predict(x)
end = datetime.now()
print('The function took {} seconds to complete'.format(end - start))
preds = [x[0] for x in preds]
max_preds = heapq.nlargest(self.top_x, preds) # find the top_x predicted elements
max_pred = max(preds) # find the best prediction
for i in range(0, len(preds)):
if preds[i] > self.threshold:
found += 1
if preds[i] in max_preds:
row = i // cols
col = i - row * cols
y1 = row * stride
y2 = y1 + self.image_size
x1 = col * stride
x2 = x1 + self.image_size
if preds[i] == max_pred:
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 0, 255), 3)
else:
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 3)
print('Pixels: x: %d-%d, y: %d-%d, Prediction: %f' % (x1, x2, y1, y2, preds[i]))
cv2.imshow('Found in total {} Waldos above our threshold {}'.format(found, self.threshold), img)
cv2.waitKey(0)
cv2.destroyAllWindows()
def _get_wrapped_image(self, path):
img = cv2.imread(path, 0) # 0 for greyscale
# amount of pixels added to the bottom so its dividable through size
bottom = self.image_size - (img.shape[0] % self.image_size) % self.image_size
# amount of pixels added to the right so its dividable through size
right = self.image_size - (img.shape[1] % self.image_size) % self.image_size
return cv2.copyMakeBorder(img, 0, bottom, 0, right, cv2.BORDER_WRAP)
def _get_image_tiles(self, wrap, stride):
# calculate the amount of rows by dividing by stride
rows = ((wrap.shape[0] - self.image_size) // stride) + 1
# calculate the amount of cols by dividing by stride
cols = ((wrap.shape[1] - self.image_size) // stride) + 1
img_tiles = []
for row in range(0, rows):
for col in range(0, cols):
y1 = row * stride
y2 = y1 + self.image_size
x1 = col * stride
x2 = x1 + self.image_size
img_tiles.append(wrap[y1:y2, x1:x2])
return img_tiles
<file_sep>/augmentation.py
from data.DataProcessor import DataProcessor
from utils.config import config
dp = DataProcessor()
print("Starting augmentation.")
dp.augment_and_save()
print("Finished augmentation. The images were saved to {}".format(config.AUGMENTED_TRAIN_WALDO))
<file_sep>/README.md
# WaldoGoneWild
## Project Description
In our project we try to apply Deep Learning techniques with Computer Vision tools to automatically find Waldo in any "Where is Waldo?" picture.
## How to run this project locally
First install all the packages in the requirements.txt file on your local machine or venv.
All global configurations are handled in the `config.yml` file found at the root.
Our data set can be found in the `data` folder, where we have separate folders for testing and training data.
Our models are contained in the ModelManager found in the `model` directory.
#### Training
To train the model, specify a version number in the config file and run the script `train_model.py`. This will save the model to an .h5 file at the project root.
#### Validating
To validate our model run the script `check_precision.py`, which will give you the number of test samples checked and the number of false positives and false negatives.
#### Running
To run our project use the script `run.py` which will take an image as input and mark the cell in which it thinks Waldo can be found.
## Who to speak to?
- Michel
- Gina
- Eric<file_sep>/run.py
from keras.models import load_model
from data.RunProcessor import RunProcessor
from utils.config import config
run_processor = RunProcessor()
print("Starting prediction run.")
model = load_model('version{}_epochs{}_model{}.h5'.format(config.VERSION, config.NUM_EPOCHS, config.MODEL_VERSION))
model.summary()
run_processor.find_waldo(config.RUN_IMAGE_PATH, config.STRIDE, model)
print("Finishing prediction run.")
|
404b2fb62a59265b6aa116bf936a3e842a22f3ba
|
[
"Markdown",
"Python",
"Text"
] | 10 |
Python
|
PnS2018/wgw
|
3cfddf6a9890e9c632c46fe967eaeae119bac6e8
|
00d5762b36c0291cdffc1c585d4d8e62a537e962
|
refs/heads/master
|
<repo_name>jakazzy/js_30<file_sep>/README.md
# js_30
This repository consist of series of mini projects under the JavaScript challenge for 30 days dubbed js 30 by <NAME>.
Consist of projects with neither libraries nor frameworks only Vanilla JavaScript with HTML and CSS. Attached to each of these projects(with the exception of Array Cardio) is the link to the hosted project. Of all the projects, Array Cardio distinguishes itself as a problem set solved using the application of JavaScript concepts such as iterator methods(filter, maps, etc).
## Project 1 DrumKit
This is a static website made with HTML, CSS and JavaScript.
Type a letter on the keyboard corresponding to the letter on the box so it generate dum sounds.
[drumkit url](drumkit_sample.surge.sh)
## Project 2 Clock
This is a simple clock project made with HTML, CSS and JavaScript.
It offers an input field where one can set an alarm.
[clock url](clock-js30.surge.sh).
## Project 3 Update CSS Variables
This is a static website made with HTML, CSS and JavaScript.
Drag the range selector for blur to make the picture clear or blur or drag the range selector to increase the padding for the image.
[update CSS variables url](update-css.surge.sh)
## Project 4 Array Cardio
Includes series of JavaScript problems solved using iterator methods etc.
## Project 5 Flex Panels Gallery Image
This is a static website made with HTML, CSS and JavaScript.
It is a simple gallery project with focus on application of css principles such as flex panel and JS DOM Manipulation.
Click on any of the images and observe the transition in and out.
[flex panel url](flex-panel.surge.sh)<file_sep>/array_cardio1/index.js
const inventors = [{
first: 'Albert',
last: 'Einstein',
year: 1879,
passed: 1955
}, {
first: 'Isaac',
last: 'Newton',
year: 1643,
passed: 1727
}, {
first: 'Galileo',
last: 'Galilei',
year: 1564,
passed: 1642
}, {
first: 'Marie',
last: 'Curie',
year: 1867,
passed: 1934
}, {
first: 'Johannes',
last: 'Kepler',
year: 1571,
passed: 1630
}, {
first: 'Nicolaus',
last: 'Copernicus',
year: 1473,
passed: 1543
}, {
first: 'Max',
last: 'Planck',
year: 1858,
passed: 1947
}, {
first: 'Katherine',
last: 'Blodgett',
year: 1898,
passed: 1979
}, {
first: 'Ada',
last: 'Lovelace',
year: 1815,
passed: 1852
}, {
first: '<NAME>.',
last: 'Goode',
year: 1855,
passed: 1905
}, {
first: 'Lise',
last: 'Meitner',
year: 1878,
passed: 1968
}, {
first: 'Hanna',
last: 'Hammarström',
year: 1829,
passed: 1909
}];
const people = ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>'];
const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck'];
const Boulevards = [
'<NAME>',
"<NAME>",
"<NAME>",
"Boulevard de l'Amiral-Bruix",
"Boulevard des Capucines",
"Boulevard de la Chapelle",
"<NAME>",
"Boulevard du Crime",
"<NAME>",
"Boulevard de l'Hôpital",
"Boulevard des Italiens",
"Boulevard de la Madeleine",
"<NAME>",
"<NAME>",
"Boulevard du Montparnasse",
"<NAME>",
"<NAME>",
"<NAME>",
"Boulevard Saint-Germain",
"<NAME>",
"<NAME>",
"<NAME>",
"Boulevard du Temple",
"Bou<NAME>",
"Boulevard de la Zone"
]
// Array.prototype.filter()
// 1. Filter the list of inventors for those who were born in the 1500's
//Answer
const fifteen = inventors.filter(inventor => {
return inventor.year >= 1500 && inventor.year < 1600;
})
console.table(fifteen);
// Array.prototype.map()
// 2. Give us an array of the inventors' first and last names
//Answer
const fullName = inventors.map(inventor => `${inventor.first} ${inventor.last}`)
console.table(fullName);
// Array.prototype.sort()
// 3. Sort the inventors by birthdate, oldest to youngest
//Answer
const ageOldToYoung = inventors.map(inventor => ({
first: inventor.first,
last: inventor.last,
year: inventor.year
})).sort(function(a, b) { return a.year - b.year; });
console.table(ageOldToYoung);
// Array.prototype.reduce()
// 4. How many years did all the inventors live?
// const agesLived = inventors.map(inventor => inventor.passed - inventor.year);
const totalAge = inventors.reduce((accumulator, inventor) => { return accumulator + (inventor.passed - inventor.year) }, 0)
console.log("totalAge: ", totalAge);
// 5. Sort the inventors by years lived
const ageLived = inventors.map(inventor => ({
first: inventor.first,
last: inventor.last,
year: inventor.passed - inventor.year
})).sort(function(a, b) { return a.year - b.year })
console.table(ageLived);
// Sort the people alphabetically by last name
const sortByLastName = people.sort();
console.table(sortByLastName);
//count instances
// const countedData = data.reduce(function(allVehicles, vehicle) {
// if (vehicle in allVehicles) { allVehicles[vehicle]++; } else { allVehicles[vehicle] = 1 }
// return allVehicles;
// }, {})
// console.table(countedData);
const transportation = data.reduce(function(obj, item) {
if (!obj[item]) {
obj[item] = 0;
// console.log("set to 0: ", obj);
}
obj[item]++;
// console.log("set to incremental", obj);
return obj;
}, {})
console.table(transportation);
//Retrieve Boulevard with De
const BoulevardWithDe = Boulevards.filter(boulevard => {
return boulevard.includes("de");
});
console.log(BoulevardWithDe);
//alt
// const category = document.querySelector(".mw-category");
// const all = category.querySelectorAll("a");
// const all_ = Array.from(all);
// const boule = all_.map(link => link.textContent);
// const boulevardsWithDe = boule.filter(link => link.includes("de"));
// console.log(BoulevardWithDe);
//Questions
// 1. Filter the list of inventors for those who were born in the 1500's
// Array.prototype.map()
// 2. Give us an array of the inventors' first and last names
// Array.prototype.sort()
// 3. Sort the inventors by birthdate, oldest to youngest
// Array.prototype.reduce()
// 4. How many years did all the inventors live?
// 5. Sort the inventors by years lived
// 6. create a list of Boulevards in Paris that contain 'de' anywhere in the name
// https://en.wikipedia.org/wiki/Category:Boulevards_in_Paris
// 7. sort Exercise
// Sort the people alphabetically by last name
// 8. Reduce Exercise
|
2485a4ef4a02f66ea666ea892ae50033d8e45b9c
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
jakazzy/js_30
|
b2e36b4be48e42f46136104ae9af00f390afb5db
|
911e7fd6bf0414f7c20ef06ef1c2e0359491b334
|
refs/heads/main
|
<file_sep># Sistema de Gerenciamento de Pacientes Hospitalares
## Projeto
O programa consiste em um sistema simples para gerenciamento de Pacientes que podem ser divididos em 3 categorias: Internação, Consulta e Exame. Os pacientes foram definidos como uma classe genérica que é usada como padrão para classes de pacientes derivados. Eles são armazenados na classe cadastro, que utiliza uma estrutura de árvore binária para armazenar todos os pacientes. A árvore foi definida como uma classe template que pode armazenar nós de qualquer tipo de dado ( no nosso caso, pacientes ). Além disso, os nós foram definidos como uma struct e a relação entre eles é dada através de ponteiros.
As classes Cadastro, Paciente, Árvore, Menu e a struct Nó foram implementadas em arquivos separados e toda a usabilidade do programa foi mapeada no arquivo main.cpp .
O programa permite a inserção de um novo paciente, a busca por um paciente já cadastrado e a exibição de todos os pacientes cadastrados no momento.
## Como utilizar
Para gerar o executável, é necessário fazer a compilação dos arquivos através do makefile e, depois, basta executar o programa pela linha de comando e, através do menu, executar os comandos desejados.
Para testar o programa basta seguir os passos:
- Abra o terminal nessa pasta e utilize o comando "make" para gerar o executável.
- Execute o programa através do comando "./main".
- Interaja com o menu e realize as operações desejadas.
Caso queira remover os arquivos .o e o executável basta realizar o comando "make clean".
<file_sep># Análise de texto através de grafos
## Projeto
O programa consiste em um sistema simples para montagem de um Grafo contendo as palavras e sequências de palavras retiradas de um arquivo .txt
As classes Grafo, Vertice e Arestas foram implementadas e toda a usabilidade do programa foi mapeada no arquivo main.cpp .
O texto a ser analisade será retirado de um arquivo .txt e, para isso, deve existir o arquivo com o noeme "texto.txt" na pasta do projeto.
## Como utilizar
Com o arquivo de texto pronto, é necessário fazer a compilação dos arquivos através do makefile e, depois, basta executar o programa pela linha de comando informando qual o valor de n (quantas palavras em sequência serão analisadas).
Para testar o programa basta seguir os passos:
- Abra o terminal nessa pasta e utilize o comando "make" para gerar o executável.
- Execute o programa através do comando "./main < n >". Substitua n por um valor inteiro entre 2 e 15.
Caso queira remover os arquivos .o e o executável basta realizar o comando "make clean".
<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: menu.h
* Autor: <NAME> - 118045099
*/
#ifndef MENU_H
#define MENU_H
#include <iostream>
#include <string>
#include "cadastro.h"
#include "excecao.h"
using namespace std;
class Menu {
public:
void mostrarMenuPrincipal();
unsigned receberOpcaoMenu();
void finalizarPrograma();
void criarPaciente(Cadastro &cadastro);
string receberNomeBusca();
};
#endif<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: menu.h
* Autor: <NAME> - 118045099
*/
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
#include "nacional.h"
class Menu {
public:
void mostrarMenuPrincipal();
unsigned receberOpcaoMenu();
void finalizarPrograma();
void mostrarMediasMoveis(Nacional);
void mostrarTotalDeObitos(Nacional);
void mostrarMaiorMenorMedia(Nacional);
void mostrarEtabilidadeEstados(Nacional);
void mostrarEstabilidadePais(Nacional);
};<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: nacional.h
* Autor: <NAME> - 118045099
*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#include "estadual.h"
class Nacional{
public:
Nacional(string);
void setNome(string);
string getNome();
void adicionarEstado(string, string);
void removerEstado(string);
bool procuraEstadoNoVetor(string);
vector <Estadual> getVetorEstados();
vector <unsigned> getVetorObitos();
void atualizarVetorObitos();
vector <vector < vector <float>>> calcularEstabilidadeEstados();
float calcularEstabilidade();
vector <unsigned> calcularMediaMovelPais();
unsigned calcularTotalObitos();
vector <unsigned> calcularObitosPorDia();
Estadual maiorMediaMovelAtual();
Estadual menorMediaMovelAtual();
private:
vector <Estadual> vetorEstados;
vector <unsigned> vetorObitos;
string nome;
};<file_sep>CC = g++
LD = g++
CFLAGS = -Wall
LFLAGS = -Wall
MAINOBJS = catalogo.o menu.o filmes.o main.o
MAIN = main
.cpp.o:
$(CC) $(CFLAGS) -c $<
all: $(MAIN)
main: $(MAINOBJS)
$(LD) $(LFLAGS) -o $@ $(MAINOBJS) -lm
clean:
rm -f *.o $(MAIN)<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: excecao.h
* Autor: <NAME> - 118045099
*/
#ifndef EXCECAO_H
#define EXCECAO_H
#include <exception>
using namespace std;
class pacienteJaInserido : public exception{
public:
const char *what() const throw(){
const char* msgErro = "\n Erro -- Um paciente com esse nome já está cadastrado \n \n";
return msgErro;
}
};
class pacienteNaoEncontrado : public exception{
public:
const char *what() const throw(){
const char* msgErro = "\n Erro -- Nenhum paciente com esse nome foi cadastrado \n";
return msgErro;
}
};
#endif<file_sep># Sistema de Gerenciamento de Filmes
## Projeto
O programa consiste em um sistema simples para gerenciamente de Filmes onde cada filme é armazenado com o seu nome, produtora e uma nota de avaliação correspondente.
As classes Catálogo, Menu e a struct filme foram implementadas e toda a usabilidade do programa foi mapeada no arquivo main.cpp .
O programa pode armazenar os filmes em um arquivo txt no seguinte formato:
- nomeFilme1
- produtoraFilme1
- notaFilme1
-
- nomeFilme2
- ...
Onde cada linha armazena um atributo e os dados devem ser armazenados na sequência nome, produtora, double. Além disso, deve-se pular uma linha entre cada filme. Quando o programa é iniciado, o programa lê o arquivo e inicia os filmes válidos contidos nele. E quando o programa é encerrado, ele salva os filmes cadastrados no arquivo.
obs.: As notas deveme estar entre 0 e 10.
## Como utilizar
Com o arquivo de texto pronto, é necessário fazer a compilação dos arquivos através do makefile e, depois, basta executar o programa pela linha de comando informando qual o valor de n (quantas palavras em sequência serão analisadas).
Para testar o programa basta seguir os passos:
- Abra o terminal nessa pasta e utilize o comando "make" para gerar o executável.
- Execute o programa através do comando "./main <numeroMaximoFilmes> <nomeArquivo>". Substitua numeroMaximoFilmes por um valor maior do que 2 e nomeArquivo por uma string contendo um caminho para o arquivo txt referente aos filmes.
Caso queira remover os arquivos .o e o executável basta realizar o comando "make clean".
<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: estadual.h
* Autor: <NAME> - 118045099
*/
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
class Estadual{
public:
Estadual(string,string);
void setNome(string);
string getNome();
void setArquivoObitos(string);
string getArquivoObitos();
void setVetorObitos();
vector <unsigned> getVetorObitos();
void mostrarVetorObitosNaTela();
vector <unsigned> calcularMediaMovel();
float calcularEstabilidade();
unsigned calcularObitosAcumulados();
private:
string nome;
string arquivoObitos;
vector <unsigned> vetorObitos;
};<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: paciente.h
* Autor: <NAME> - 118045099
*/
#ifndef PACIENTE_H
#define PACIENTE_H
#include <iostream>
#include <string>
using namespace std;
class Paciente{
public:
Paciente(string nomeEntrada, unsigned int idadeEntrada, string descricaoEntrada);
Paciente();
string getNome();
unsigned int getIdade();
string getDescricao();
string getTipo();
void setNome(string nomeEntrada);
void setIdade(unsigned int idadeEntrada);
void setDescricao(string descricaoEntrada);
void setTipo(string tipoEntrada);
// imprimir os pacientes na tela (Foi usada uma função virtual para que possa ser adaptada)
friend ostream &operator<<(ostream &out, Paciente &pacienteImprimir);
virtual void mostrarPaciente();
// Definir resultado das comparações entre pacientes
bool operator>(Paciente const &pacienteComparacao);
bool operator<(Paciente const &pacienteComparacao);
bool operator==(Paciente const &pacienteComparacao);
private:
string nome;
unsigned int idade;
string descricao;
string tipo;
};
class Paciente_Internacao : public Paciente{
public:
Paciente_Internacao(string nomeEntrada, unsigned int idadeEntrada, string descricaoEntrada, unsigned int diasInternadosEntrada);
Paciente_Internacao();
void mostrarPaciente() override;
unsigned int getDiasInternados();
void setDiasInternados(unsigned int diasInternadosEntrada);
private:
unsigned int diasInternados;
};
class Paciente_Consulta : public Paciente{
public:
Paciente_Consulta(string nomeEntrada, unsigned int idadeEntrada, string descricaoEntrada, unsigned int numConsultasEntrada);
Paciente_Consulta();
void mostrarPaciente() override;
unsigned int getNumConsultas();
void setNumConsultas(unsigned int numConsultasEntrada);
private:
unsigned int numConsultas;
};
class Paciente_Exame : public Paciente{
public:
Paciente_Exame(string nomeEntrada, unsigned int idadeEntrada, string descricaoEntrada, string nomeExameEntrada, bool exameRealizadoEntrada);
Paciente_Exame();
void mostrarPaciente() override;
string getNomeExame();
bool getExameRealizado();
void setNomeExame(string nomeExameEntrada);
void setExameRealizado(bool exameRealizadoEntrada);
private:
string nomeExame;
bool exameRealizado;
};
#endif<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: grafo.cpp
* Autor: <NAME> - 118045099
*/
#include "grafo.h"
int Grafo::procurarVertice(string palavra_vertice){
for (unsigned i=0; i<vertices.size(); i++){
if (vertices.at(i).getPalavra() == palavra_vertice){
return i;
}
}
return -1;
}
void Grafo::adicionarVertice(string palavra_vertice){
int index = procurarVertice(palavra_vertice);
if (index >= 0){
unsigned freq_atual = vertices.at(index).getFrequencia();
vertices.at(index).setFrequencia(freq_atual+1);
}
else{
Vertice vertice;
vertice.setPalavra(palavra_vertice);
vertices.push_back(vertice);
}
}
int Grafo::procurarAresta(Aresta aresta){
string vertice1 = aresta.getVertice1();
string vertice2 = aresta.getVertice2();
for (unsigned i=0; i<arestas.size(); i++){
if ((arestas.at(i).getVertice1() == vertice1) &&
(arestas.at(i).getVertice2() == vertice2)){
return i;
}
}
return -1;
}
void Grafo::adicionarAresta(Aresta aresta){
int index = procurarAresta(aresta);
if (index >= 0){
unsigned peso_atual = arestas.at(index).getPeso();
arestas.at(index).setPeso(peso_atual+1);
}
else{
arestas.push_back(aresta);
}
}
void Grafo::mostrarArestas(){
for (unsigned i = 0; i<arestas.size();i++){
arestas.at(i).mostrarArestaNaTela();
}
}
void Grafo::mostrarVertices(){
for (unsigned i = 0; i<vertices.size();i++){
vertices.at(i).mostrarVerticeNaTela();
}
}
void Grafo::mostrarVerticeMaiorFrequencia(){
unsigned maior_freq = 0, freq_aux = 0;
for (unsigned i = 0; i<vertices.size();i++){
freq_aux = vertices.at(i).getFrequencia();
if (freq_aux > maior_freq){
maior_freq = freq_aux;
}
}
cout << "------MAIOR FREQUÊNCIA = " << maior_freq << "\n\n";
for (unsigned i = 0; i<vertices.size();i++){
if (vertices.at(i).getFrequencia() == maior_freq){
vertices.at(i).mostrarVerticeNaTela();
}
}
}
void Grafo::mostrarMaiorSequenciaDuasPalavras(){
unsigned maior_peso = 0, peso_aux = 0;
for (unsigned i = 0; i<arestas.size();i++){
peso_aux = arestas.at(i).getPeso();
if (peso_aux > maior_peso){
maior_peso = peso_aux;
}
}
cout << "------MAIOR SEQUÊNCIA = " << maior_peso << "\n\n";
for (unsigned i = 0; i<arestas.size();i++){
if (arestas.at(i).getPeso() == maior_peso){
arestas.at(i).mostrarArestaNaTela();
}
}
}
void Grafo::preencherGrafo(){
fstream arquivo;
string palavra;
string nome_arquivo = "texto.txt";
arquivo.open(nome_arquivo.c_str());
if (!arquivo.is_open()){
cout << "Arquivo nao existe. \n";
}
else{
vector <string> vetorAuxPalavras;
unsigned n =2;
while (arquivo>>palavra)
{
/* Remover pontuações e deixar todas as letras minúsculas*/
palavra.erase(remove(palavra.begin(), palavra.end(), ','), palavra.end());
palavra.erase(remove(palavra.begin(), palavra.end(), ';'), palavra.end());
palavra.erase(remove(palavra.begin(), palavra.end(), '.'), palavra.end());
palavra.erase(remove(palavra.begin(), palavra.end(), '!'), palavra.end());
palavra.erase(remove(palavra.begin(), palavra.end(), '?'), palavra.end());
palavra.erase(remove(palavra.begin(), palavra.end(), ':'), palavra.end());
for (unsigned i = 0; i < palavra.size(); i++) {
palavra.at(i) = tolower(palavra.at(i));
}
adicionarVertice(palavra);
if (vetorAuxPalavras.size() < n){
vetorAuxPalavras.push_back(palavra);
}
if (vetorAuxPalavras.size() == n){
Vertice vertice1, vertice2;
vertice1.setPalavra(vetorAuxPalavras.at(0));
vertice2.setPalavra(vetorAuxPalavras.at(1));
Aresta aresta(vertice1,vertice2,1);
adicionarAresta(aresta);
vetorAuxPalavras.erase(vetorAuxPalavras.begin());
}
}
}
arquivo.close();
}
void Grafo::mostrarMaiorSequenciaNPalavras(unsigned n){
fstream arquivo;
string palavra;
string nome_arquivo = "texto.txt";
vector <pair<vector<string>,unsigned>> vetorSequencias;
/* Cada item de vetorSequencias possui um vetor com as palavras em questão e um unsigned indicando a frequencia dessa sequencia*/
arquivo.open(nome_arquivo.c_str());
if (!arquivo.is_open()){
cout << "Arquivo nao existe. \n";
}
else{
vector <string> vetorAuxPalavras;
while (arquivo>>palavra)
{
/* Remover pontuações e deixar todas as letras minúsculas*/
palavra.erase(remove(palavra.begin(), palavra.end(), ','), palavra.end());
palavra.erase(remove(palavra.begin(), palavra.end(), ';'), palavra.end());
palavra.erase(remove(palavra.begin(), palavra.end(), '.'), palavra.end());
palavra.erase(remove(palavra.begin(), palavra.end(), '!'), palavra.end());
palavra.erase(remove(palavra.begin(), palavra.end(), '?'), palavra.end());
palavra.erase(remove(palavra.begin(), palavra.end(), ':'), palavra.end());
for (unsigned i = 0; i < palavra.size(); i++) {
palavra.at(i) = tolower(palavra.at(i));
}
if (vetorAuxPalavras.size() < n){
vetorAuxPalavras.push_back(palavra);
}
if (vetorAuxPalavras.size() == n){
bool sequenciaRepetida = false;
unsigned indiceSequenciaRepetida ;
pair<vector<string>,unsigned> parAux;
parAux.first = vetorAuxPalavras;
parAux.second = 1;
for (unsigned i=0; i < vetorSequencias.size(); i++){
unsigned somaIguais = 0;
for (unsigned j=0; j < n; j++){
if (vetorSequencias.at(i).first.at(j) == vetorAuxPalavras.at(j)){
somaIguais++;
}
}
if (somaIguais == n){
indiceSequenciaRepetida = i;
sequenciaRepetida = true;
}
}
if (sequenciaRepetida){
vetorSequencias.at(indiceSequenciaRepetida).second++;
}
else {
vetorSequencias.push_back(parAux);
}
vetorAuxPalavras.erase(vetorAuxPalavras.begin());
}
}
}
arquivo.close();
/* Calcular a maior frequencia */
unsigned maior_freq = 0, freq_aux = 0;
for (unsigned i=0; i < vetorSequencias.size(); i++){
freq_aux = vetorSequencias.at(i).second;
if (freq_aux > maior_freq){
maior_freq = freq_aux;
}
}
/* Mostrar sequencias com freq == maior_freq */
cout << "------MAIOR SEQUÊNCIA = " << maior_freq << "\n\n";
for (unsigned i=0; i < vetorSequencias.size(); i++){
if (vetorSequencias.at(i).second == maior_freq){
cout << "("
<< vetorSequencias.at(i).second
<< ") :";
for (unsigned j=0; j < n; j++){
if (j != n-1){
cout << vetorSequencias.at(i).first.at(j) << " -> ";
}
else{
cout << vetorSequencias.at(i).first.at(j) << endl;
}
}
}
}
}<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: grafo.h
* Autor: <NAME> - 118045099
*/
#include <vector>
#include <fstream>
#include <algorithm>
#include "aresta.h"
#ifndef GRAFO_H
#define GRAFO_H
class Grafo{
public:
int procurarVertice(string palavra_vertice);
int procurarAresta(Aresta aresta);
void adicionarAresta(Aresta aresta);
void adicionarVertice(string palavra_vertice);
void mostrarArestas();
void mostrarVertices();
void mostrarVerticeMaiorFrequencia();
void preencherGrafo();
void mostrarMaiorSequenciaDuasPalavras();
void mostrarMaiorSequenciaNPalavras(unsigned n);
private:
vector <Aresta> arestas;
vector <Vertice> vertices;
vector <pair<Aresta, unsigned>> arestas_repetidas;
};
#endif<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: nacional.cpp
* Autor: <NAME> - 118045099
*/
#include "nacional.h"
Nacional::Nacional(string nome_pais){
setNome(nome_pais);
}
void Nacional::setNome(string nome_pais){
nome = nome_pais;
}
string Nacional::getNome(){
return nome;
}
// adiciona um estado no vetor de estados
void Nacional::adicionarEstado(string nome_estado, string arquivo_obitos){
if (procuraEstadoNoVetor(nome_estado) == true) {
cout << "\n ERRO - "<<nome_estado<<" já pertence aos Estados de "<<nome<<".";
}
else {
Estadual estado(nome_estado,arquivo_obitos);
vetorEstados.push_back(estado);
}
}
// retorna true se existir um estado com esse nome e falso caso contrário
bool Nacional::procuraEstadoNoVetor(string nome_estado){
for (unsigned i = 0; i < vetorEstados.size(); i++){
if (vetorEstados.at(i).getNome() == nome_estado){
return true;
}
}
return false;
}
// Procura um estado com esse nome no vetor de estados e o remove
void Nacional::removerEstado(string nome_estado){
for (unsigned i = 0; i < vetorEstados.size(); i++){
if (vetorEstados.at(i).getNome() == nome_estado){
vetorEstados.erase (vetorEstados.begin() + i);
i = vetorEstados.size();
}
else{
cout << "\n ERRO - "<<nome_estado<<" não pertence aos Estados de "<<nome<<".";
}
}
}
// retorna o vetor de estados
vector <Estadual> Nacional::getVetorEstados(){
return vetorEstados;
}
// retorna o vetor de óbitos
vector <unsigned> Nacional::getVetorObitos(){
return vetorObitos;
}
// Atualiza o vetor contendo os óbitos diários do país decorrente do somatório dos óbitos diários dos estados
void Nacional::atualizarVetorObitos(){
vector <unsigned> vetorAux;
unsigned soma = 0;
for (unsigned i = 0; i < vetorEstados.at(0).getVetorObitos().size(); i++){
soma = 0;
for (unsigned j = 0; j < vetorEstados.size(); j++){
soma += vetorEstados.at(j).getVetorObitos().at(i);
}
vetorAux.push_back(soma);
}
vetorObitos = vetorAux;
}
// Retorna um vetor no seguinte formato:
// índice 0 -> vetor com todos os estados em alta, ele estará no formato:
// índice 0 -> indica a posição do estado em questão no vetor de estados desse país
// índice 1 -> indica a estabilidade atual desse estado em %
//
// índice 1 -> vetor com todos os estados estáveis, seguindo o formato mostrado.
//
// índice 2 -: vetor com todos os estados em baixa, seguindo o formato mostrado.
//
// A divisão das categorias é dada através de: alta -> no mínimo 10% a mais na média móvel atual
// estável -> entre -10% e +10% na média móvel atual
// baixa > no mínimo 10% a menos na média móvel atual
vector <vector < vector <float>>> Nacional::calcularEstabilidadeEstados(){
float estabilidade;
vector <vector < vector <float>>> vetorEstabilidades;
vector <vector <float>> vetorAlta, vetorEstavel, vetorBaixa;
vector <float> vetorAux;
for (unsigned i = 0; i < vetorEstados.size(); i++){
estabilidade = vetorEstados.at(i).calcularEstabilidade();
vetorAux.clear();
vetorAux.push_back(i);
// Caso em que o estado está em alta (ao menos 10% maior)
if (estabilidade >= 1.1){
vetorAux.push_back((estabilidade - 1)*100);
vetorAlta.push_back(vetorAux);
}
// Caso em que o estado está estável ( variação menor que 10%)
else if (estabilidade < 1.1 && estabilidade > 0.9){
if (estabilidade>1){
vetorAux.push_back((estabilidade - 1)*100);
}
else{
vetorAux.push_back((1 - estabilidade)*-100);
}
vetorEstavel.push_back(vetorAux);
}
// Caso em que o estado está em baixa (ao menos 10% menor)
else if (estabilidade <= 0.9){
vetorAux.push_back((1 - estabilidade)*-100);
vetorBaixa.push_back(vetorAux);
}
}
vetorEstabilidades.push_back(vetorAlta);
vetorEstabilidades.push_back(vetorEstavel);
vetorEstabilidades.push_back(vetorBaixa);
return vetorEstabilidades;
}
// retorna a estabilidade atual do país considerando as 2 últimas médias móveis
float Nacional::calcularEstabilidade(){
vector <unsigned> mediaMovel = calcularMediaMovelPais();
float estabilidade = ((float) mediaMovel.at(0)) / ((float) mediaMovel.at(1));
return estabilidade;
}
// Retorna um vetor com as médias móveis no país. O vetor seguirá o formato:
// índice 0 -> média móvel do último dia
// índice 1 -> média móvel do penúltimo dia
// índice 2 -> média móvel do antepenúltimo dia
vector <unsigned> Nacional::calcularMediaMovelPais(){
unsigned somaUltimoDia = 0, somaPenultimoDia = 0, somaAntePenultimoDia = 0;
for (unsigned i = 0; i < vetorObitos.size(); i++){
if (i<7){
somaUltimoDia += vetorObitos.at(i);
}
if (i>0 && i<8){
somaPenultimoDia += vetorObitos.at(i);
}
if (i>1 && i<9){
somaAntePenultimoDia += vetorObitos.at(i);
}
if (i>=9){
i = vetorObitos.size();
}
}
unsigned mediaUltimoDia = somaUltimoDia/7;
unsigned mediaPenultimoDia = somaPenultimoDia/7;
unsigned mediaAntePenultimoDia = somaAntePenultimoDia/7;
vector <unsigned> vetorRetorno;
vetorRetorno.push_back(mediaUltimoDia);
vetorRetorno.push_back(mediaPenultimoDia);
vetorRetorno.push_back(mediaAntePenultimoDia);
return vetorRetorno;
}
// retorna o somatório de todas as mortes no país
unsigned Nacional::calcularTotalObitos(){
unsigned soma = 0;
for (unsigned i = 0; i < vetorEstados.size(); i++){
soma += vetorEstados.at(i).calcularObitosAcumulados();
}
return soma;
}
// retorna o estado com a maior media móvel atual
Estadual Nacional::maiorMediaMovelAtual(){
unsigned maiorMedia, index = 0;
maiorMedia = vetorEstados.at(0).calcularMediaMovel().at(1);
for (unsigned i = 0; i < vetorEstados.size(); i++){
if(vetorEstados.at(i).calcularMediaMovel().at(1) > maiorMedia){
maiorMedia = vetorEstados.at(i).calcularMediaMovel().at(1);
index = i;
}
}
return vetorEstados.at(index);
}
// retorna o estado com a menor media móvel atual
Estadual Nacional::menorMediaMovelAtual(){
unsigned menorMedia, index = 0;
menorMedia = vetorEstados.at(0).calcularMediaMovel().at(1);
for (unsigned i = 0; i < vetorEstados.size(); i++){
if(vetorEstados.at(i).calcularMediaMovel().at(1) < menorMedia){
menorMedia = vetorEstados.at(i).calcularMediaMovel().at(1);
index = i;
}
}
return vetorEstados.at(index);
}<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: arvore.h
* Autor: <NAME> - 118045099
*/
#ifndef ARVORE_H
#define ARVORE_H
#include <iostream>
#include <string>
using namespace std;
//////////////////// DEFINIÇÃO DA ESTRUTURA DOS NÓS
template <class tipoValor>
struct No{
tipoValor valor;
No* noEsquerda;
No* noDireita;
// Construtores
No();
No(tipoValor novoValor);
};
//////////////////// DEFINIÇÃO DA CLASSE ÁRVORE
template <class tipoValor>
class Arvore{
private:
No <tipoValor> *raiz;
No <tipoValor> *insercaoRecursiva(No <tipoValor> *noInicio, const tipoValor &novoValor);
No <tipoValor> *buscaRecursiva(No <tipoValor> *noInicio, const tipoValor &valorBusca);
void printRecursivo(No <tipoValor> *noInicio);
void remocaoRecursiva(No <tipoValor> *noInicio);
public:
Arvore();
~Arvore();
No <tipoValor> *operator+=(const tipoValor &novoValor);
No <tipoValor> *operator()(const tipoValor &valorBusca);
friend ostream &operator<<(ostream &out, Arvore <tipoValor> &arvoreImprimir){
if (arvoreImprimir.raiz == nullptr) {
cout << "A arvore está vazia!" << endl;
}
else {
arvoreImprimir.printRecursivo(arvoreImprimir.raiz);
}
return out;
};
friend ostream &operator<<(ostream &out, const No <tipoValor> &noImprimir){
cout << noImprimir.valor << endl;
return out;
};
};
//////////////////// NÓ
//inicialização de um nó vazio
template <class tipoValor>
No<tipoValor>::No(){
this->valor = NULL;
this->noEsquerda = nullptr;
this->noDireita = nullptr;
};
//inicialização de um nó com conteúdo(valor)
template <class tipoValor>
No<tipoValor>::No(tipoValor novoValor){
this->valor = novoValor;
this->noEsquerda = nullptr;
this->noDireita = nullptr;
};
//////////////////// ÁRVORE
template<class tipoValor>
Arvore<tipoValor>::Arvore() {
raiz = nullptr;
}
template<class tipoValor>
Arvore<tipoValor>::~Arvore() {
if (raiz != nullptr){
remocaoRecursiva(raiz);
}
}
template<class tipoValor>
No <tipoValor> *Arvore<tipoValor>::operator+=(const tipoValor &novoValor){
// Verifica se o nó atual é vazio e, em caso positivo, insere o novo valor aqui
if (raiz == nullptr){
raiz = new No <tipoValor>(novoValor);
return raiz;
}
// Caso contrário, executa a função recursiva de inserção
else{
return insercaoRecursiva(raiz, novoValor);
}
}
template<class tipoValor>
No <tipoValor> *Arvore<tipoValor>::insercaoRecursiva(No <tipoValor> *noInicio, const tipoValor &novoValor){
// verifica se há uma falha (valor já existente neste nó)
if (noInicio->valor == novoValor){
return nullptr;
}
// caminha para o nó esquerdo
if (noInicio->valor < novoValor) {
if (noInicio->noEsquerda == nullptr) {
noInicio->noEsquerda = new No <tipoValor>(novoValor);
return noInicio->noEsquerda;
}
else {
return insercaoRecursiva(noInicio->noEsquerda, novoValor);
}
}
// caminha para o nó direito
else
{
if (noInicio->noDireita == nullptr) {
noInicio->noDireita = new No <tipoValor>(novoValor);
return noInicio->noDireita;
}
else {
return insercaoRecursiva(noInicio->noDireita, novoValor);
}
}
}
template<class tipoValor>
No <tipoValor> *Arvore<tipoValor>::operator()(const tipoValor &valorBusca){
return buscaRecursiva(raiz, valorBusca);
}
template<class tipoValor>
No <tipoValor> *Arvore<tipoValor>::buscaRecursiva(No <tipoValor> *noInicio, const tipoValor &valorBusca){
// Verifica se o nó atual é vazio e, em caso positivo, retorna um ponteiro vazio
if (noInicio == nullptr){
return nullptr;
}
// Verifica se o nó procurado é o atual
else if (noInicio->valor == valorBusca){
return noInicio;
}
// caminha para direita
else if (noInicio->valor > valorBusca){
return buscaRecursiva(noInicio->noDireita, valorBusca);
}
// caminha para esquerda
else{
return buscaRecursiva(noInicio->noEsquerda, valorBusca);
}
}
// faz a impressão dos nós em ordem crescente recursivamente ( considerando noDireito < noAtual < esquerda)
template<class tipoValor>
void Arvore<tipoValor>::printRecursivo(No <tipoValor> *noInicio) {
// verifica se há algum conteúdo menor que o atual (direita)
if (noInicio->noDireita != nullptr) {
printRecursivo(noInicio->noDireita);
}
std::cout << noInicio->valor;
// verifica se há algum conteúdo maior que o atual (esquerda)
if (noInicio->noEsquerda != nullptr) {
printRecursivo(noInicio->noEsquerda);
}
}
template<class tipoValor>
void Arvore<tipoValor>::remocaoRecursiva(No <tipoValor> *noInicio){
if(noInicio->noDireita != nullptr){
remocaoRecursiva(noInicio->noDireita);
}
if(noInicio->noEsquerda != nullptr){
remocaoRecursiva(noInicio->noEsquerda);
}
delete noInicio;
}
#endif<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: filmes.cpp
* Autor: <NAME> - 118045099
*/
#include "filmes.h"
bool operator==(filme filme1, filme filme2){
if(filme1.nome == filme2.nome){
return true;
}
return false;
}
bool operator>(filme filme1, filme filme2){
if(filme1.nome > filme2.nome){
return true;
}
return false;
}
bool operator<(filme filme1, filme filme2){
if(filme1.nome < filme2.nome){
return true;
}
return false;
}
vector<filme> operator+=(vector<filme> vetorFilmes,filme filme){
for (unsigned i=0; i<vetorFilmes.size() ; i++){
if(filme < vetorFilmes.at(i)){
vetorFilmes.insert(vetorFilmes.begin() + i,filme);
return vetorFilmes;
}
else if(filme == vetorFilmes.at(i)){
cout << "\n|------------------------------------------------|"
<< "\n| O FILME JÁ EXISTE NO CATÁLOGO |"
<< "\n|------------------------------------------------|\n\n";
return vetorFilmes;
}
}
vetorFilmes.push_back(filme);
return vetorFilmes;
}
vector<filme> operator+=(vector<filme> vetorDestino, vector<filme> vetorInserir){
for(unsigned i=0; i<vetorInserir.size();i++){
vetorDestino = vetorDestino+=vetorInserir.at(i);
}
return vetorDestino;
}
vector<filme> operator-=(vector<filme> vetorFilmes,filme filme){
for (unsigned i=0; i<vetorFilmes.size() ; i++){
if(vetorFilmes.at(i) == filme){
vetorFilmes.erase(vetorFilmes.begin()+i);
return vetorFilmes;
}
}
return vetorFilmes;
}
vector<filme> operator-=(vector<filme> vetorDestino, vector<filme> vetorInserir){
for(unsigned i=0; i<vetorInserir.size();i++){
vetorDestino = vetorDestino-=vetorInserir.at(i);
}
return vetorDestino;
}
ostream &operator<<(ostream &out, filme &filme){
cout << " Nome: " << filme.nome
<< "\n Produtora: " << filme.produtora
<< "\n Nota: " << filme.nota << endl;
return out;
}
<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: catalogo.cpp
* Autor: <NAME> - 118045099
*/
#include "catalogo.h"
Catalogo::Catalogo(unsigned numMaxFilmesEnt, string nomeArquivo ){
numMaxFilmes = numMaxFilmesEnt;
inicializarFilmesArquivo(nomeArquivo);
}
void Catalogo::inicializarFilmesArquivo(string nomeArquivo){
ifstream arquivo(nomeArquivo);
string linha;
if (!arquivo.is_open()){
cout << "Arquivo nao existe. \n";
}
else{
filme filmeAux;
unsigned index = 0;
while (getline(arquivo,linha)){
if (linha != ""){
index++;
switch (index){
case 1:
filmeAux.nome = linha;
break;
case 2:
filmeAux.produtora = linha;
break;
case 3:
try{
filmeAux.nota = stod(linha);
if((filmeAux.nota>=0)&&(filmeAux.nota<=10)){
(*this)+=filmeAux;
}
index = 0;
}
catch(...){
index = 0;
}
break;
default:
index = 0;
break;
}
}
}
}
arquivo.close();
}
void Catalogo::salvarFilmesArquivo(string nomeArquivo){
ofstream arquivo(nomeArquivo);
for (unsigned i=0; i<vetorFilmes.size(); i++){
arquivo << vetorFilmes.at(i).nome << "\n"
<< vetorFilmes.at(i).produtora << "\n"
<< vetorFilmes.at(i).nota << "\n\n";
}
arquivo.close();
}
void Catalogo::mostrarFilmeCadastrado(filme filmeBusca){
filme *ponteiroFilme = (*this)(filmeBusca);
if (ponteiroFilme == NULL){
cout << "\n|------------------------------------------------|"
<< "\n| FILME NÃO ENCONTRADO |"
<< "\n|------------------------------------------------|\n\n";
}
else {
cout << "\n------------------ Filme Encontrado \n"
<< *ponteiroFilme;
}
}
void Catalogo::mostrarFilmeMelhorAvaliado(){
double maiorNota = 0, notaAux = 0;
for(unsigned i=0; i<vetorFilmes.size();i++){
notaAux = vetorFilmes.at(i).nota;
if (notaAux > maiorNota){
maiorNota = notaAux;
}
}
cout << "\n|----------------------------------------------------|"
<< "\n| FILMES COM A MELHOR AVALIAÇÃO |"
<< "\n|----------------------------------------------------|\n\n";
for (unsigned i=0; i<vetorFilmes.size();i++){
if (vetorFilmes.at(i).nota == maiorNota){
cout << vetorFilmes.at(i) << endl;
}
}
}
void Catalogo::mostrarFilmePiorAvaliado(){
double menorNota = 10, notaAux = 0;
for(unsigned i=0; i<vetorFilmes.size();i++){
notaAux = vetorFilmes.at(i).nota;
if (notaAux < menorNota){
menorNota = notaAux;
}
}
cout << "\n|----------------------------------------------------|"
<< "\n| FILMES COM A PIOR AVALIAÇÃO |"
<< "\n|----------------------------------------------------|\n\n";
for (unsigned i=0; i<vetorFilmes.size();i++){
if (vetorFilmes.at(i).nota == menorNota){
cout << vetorFilmes.at(i) << endl;
}
}
}
/////////// OPERADORES
ostream &operator<<(ostream &out, const Catalogo &catalogo){
cout << "\n|-------------------------------------|"
<< "\n| CATÁLOGO |"
<< "\n|-------------------------------------|\n\n";
for (unsigned i=0; i < catalogo.vetorFilmes.size(); i++){
cout << "------------------ Filme " << i+1 << endl
<< " Nome: " << catalogo.vetorFilmes.at(i).nome
<< "\n Produtora: " << catalogo.vetorFilmes.at(i).produtora
<< "\n Nota: " << catalogo.vetorFilmes.at(i).nota << endl;
}
return out;
}
void Catalogo::operator+=(filme filme){
if(vetorFilmes.size() < numMaxFilmes){
vetorFilmes = vetorFilmes+=filme;
}
else{
cout << "\n|------------------------------------------------|"
<< "\n| O CATÁLOGO ESTÁ CHEIO |"
<< "\n|------------------------------------------------|"
<< "\n| NÃO É POSSÍVEL ADICIONAR NOVOS FILMES |"
<< "\n|------------------------------------------------|\n\n";
}
}
void Catalogo::operator-=(filme filme){
vetorFilmes = vetorFilmes-=filme;
}
filme *Catalogo::operator()(filme filmeBusca){
filme *ponteiroAux;
for(unsigned i=0; i<vetorFilmes.size(); i++){
if( filmeBusca == vetorFilmes.at(i)){
ponteiroAux = &vetorFilmes.at(i);
return ponteiroAux;
}
}
return NULL;
}
filme *Catalogo::operator()(filme filmeBusca,string produtora){
filme *ponteiroAux;
for(unsigned i=0; i<vetorFilmes.size(); i++){
if( filmeBusca == vetorFilmes.at(i)){
vetorFilmes.at(i).produtora = produtora;
ponteiroAux = &vetorFilmes.at(i);
cout << "\n------------------ Filme Editado \n"
<< *ponteiroAux;
return ponteiroAux;
}
}
cout << "\n|------------------------------------------------|"
<< "\n| FILME NÃO ENCONTRADO |"
<< "\n|------------------------------------------------|\n\n";
return NULL;
}
filme *Catalogo::operator()(filme filmeBusca,double nota){
filme *ponteiroAux;
for(unsigned i=0; i<vetorFilmes.size(); i++){
if( filmeBusca == vetorFilmes.at(i)){
vetorFilmes.at(i).nota = nota;
ponteiroAux = &vetorFilmes.at(i);
cout << "\n------------------ Filme Editado \n"
<< *ponteiroAux;
return ponteiroAux;
}
}
cout << "\n|------------------------------------------------|"
<< "\n| FILME NÃO ENCONTRADO |"
<< "\n|------------------------------------------------|\n\n";
return NULL;
}<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: menu.cpp
* Autor: <NAME> - 118045099
*/
#include "menu.h"
// Função criada para mostrar as operações disponíveis para o usuário
void Menu::mostrarMenuPrincipal() {
cout << "\n|------------------------------------------------|"
<< "\n| MENU PRINCIPAL |"
<< "\n|------------------------------------------------|"
<< "\n| 1 - MOSTRAR EVOLUÇÃO DO NÚMERO DE ÓBITOS |"
<< "\n|------------------------------------------------|"
<< "\n| 2 - ESTABILIDADE ATUAL DOS ESTADOS |"
<< "\n|------------------------------------------------|"
<< "\n| 3 - ESTABILIDADE ATUAL DO PAÍS |"
<< "\n|------------------------------------------------|"
<< "\n| 4 - ESTADOS COM MAIOR E MENOR ESTABILIDADE |"
<< "\n|------------------------------------------------|"
<< "\n| 5 - NÚMERO DE ÓBITOS ACUMULADOS |"
<< "\n|------------------------------------------------|"
<< "\n| 6 - SAIR DO PROGRAMA |"
<< "\n|------------------------------------------------|\n";
};
// Função criada para receber a opção escolhida pelo usuário
unsigned Menu::receberOpcaoMenu(){
char entrada_usuario[256];
unsigned escolhaMenu;
cout << "\n Digite a opção desejada:";
cin >> entrada_usuario;
// vai retornar 0 se entrada_usuario nao for do tipo int
escolhaMenu = atoi(entrada_usuario);
return escolhaMenu;
};
// Função criada para avisar ao usuário que o programa foi finalizado e terminar a execução
void Menu::finalizarPrograma(){
cout << "\n|------------------------------------------------|"
<< "\n| FIM DO PROGRAMA |"
<< "\n|------------------------------------------------|\n\n";
};
// Função criada para mostrar as médias móveis do país e dos estados
void Menu::mostrarMediasMoveis(Nacional pais){
vector <Estadual> vetorEstados = pais.getVetorEstados();
string nome;
vector <unsigned> vetorAux;
vector <unsigned>vetorMMPais;
cout << "\n|----------------------------------------------------|"
<< "\n| Média Móvel Total (país) |"
<< "\n|----------------------------------------------------|\n\n";
vetorMMPais = pais.calcularMediaMovelPais();
cout <<pais.getNome()<< " :\t \t \t último dia: " << vetorMMPais.at(0) << " mortes.\n";
cout <<" \t \t \t \t penúltimo dia: " << vetorMMPais.at(1) << " mortes.\n";
cout <<" \t \t \t \t antepenúltimo dia: " << vetorMMPais.at(2) << " mortes.\n";
cout << "\n|----------------------------------------------------|"
<< "\n| Médias Móveis Por Estado |"
<< "\n|----------------------------------------------------|\n\n";
for (unsigned i = 0; i < vetorEstados.size(); i++){
nome = vetorEstados.at(i).getNome();
vetorAux = vetorEstados.at(i).calcularMediaMovel();
cout <<nome<< " :\t \t \t \t \túltimo dia: " << vetorAux.at(0) << " mortes.\n";
cout <<" \t \t \t \t penúltimo dia: " << vetorAux.at(1) << " mortes.\n";
cout <<" \t \t \t \t antepenúltimo dia: " << vetorAux.at(2) << " mortes.";
cout << "\n---------------------------------------------------- \n";
}
}
// Função criada para mostrar o total de mortes pela Covid no país e em cada estado
void Menu::mostrarTotalDeObitos(Nacional pais){
vector <Estadual> vetorEstados = pais.getVetorEstados();
cout << "\n|----------------------------------------------------|"
<< "\n| TOTAL DE ÓBITOS NO PAÍS |"
<< "\n|----------------------------------------------------|\n\n"
<< pais.getNome() << " :" << pais.calcularTotalObitos() << " mortes.\n"
<< "\n|----------------------------------------------------|"
<< "\n| TOTAL DE ÓBITOS SEPARADO POR ESTADO |"
<< "\n|----------------------------------------------------|\n\n";
for (unsigned i = 0; i < vetorEstados.size(); i++){
cout << vetorEstados.at(i).getNome() << " :" << vetorEstados.at(i).calcularObitosAcumulados() << " mortes.\n";
}
}
// Função criada para mostrar os estados com a maior e a menor média móvel atual
void Menu::mostrarMaiorMenorMedia(Nacional pais){
vector <Estadual> vetorEstados = pais.getVetorEstados();
cout << "\n|----------------------------------------------------|"
<< "\n| ESTADO COM A MAIOR MÉDIA MÓVEL ATUAL |"
<< "\n|----------------------------------------------------|\n"
<< " "
<< pais.maiorMediaMovelAtual().getNome() << " ---- "
<< pais.maiorMediaMovelAtual().calcularMediaMovel().at(1)
<< " mortes. \n";
cout << "\n|----------------------------------------------------|"
<< "\n| ESTADO COM A MENOR MÉDIA MÓVEL ATUAL |"
<< "\n|----------------------------------------------------|\n"
<< " "
<< pais.menorMediaMovelAtual().getNome() << " ---- "
<< pais.menorMediaMovelAtual().calcularMediaMovel().at(1)
<< " mortes. \n\n\n";
}
// Função criada para mostrar as estabilidades dos estados dividos em alta, estável e baixa
void Menu::mostrarEtabilidadeEstados(Nacional pais){
vector <Estadual> vetorEstados = pais.getVetorEstados();
vector <vector < vector <float>>> vetorEstabilidades = pais.calcularEstabilidadeEstados();
string nome;
float estabilidade;
unsigned indice;
// Mostrando estados em alta
cout << "\n|----------------------------------------------------|"
<< "\n| Estados em Alta |"
<< "\n|----------------------------------------------------|\n";
for (unsigned i=0; i<vetorEstabilidades.at(0).size();i++){
indice = (unsigned) vetorEstabilidades.at(0).at(i).at(0);
estabilidade = vetorEstabilidades.at(0).at(i).at(1);
nome = vetorEstados.at(indice).getNome();
cout << " "
<<nome
<< " :\t estabilidade atual: " << setprecision(2) << fixed << estabilidade << "% maior.\n";
cout << " ---------------------------------------------------- \n";
}
// Mostrando estados em estabilidade
cout << "\n|----------------------------------------------------|"
<< "\n| Estados em Estabilidade |"
<< "\n|----------------------------------------------------|\n";
for (unsigned i=0; i<vetorEstabilidades.at(1).size();i++){
indice = (unsigned) vetorEstabilidades.at(1).at(i).at(0);
estabilidade = vetorEstabilidades.at(1).at(i).at(1);
nome = vetorEstados.at(indice).getNome();
cout << " "
<<nome;
if (estabilidade<0){
cout << " :\t estabilidade atual: " << setprecision(2) << fixed << estabilidade*-1 << "% menor.\n";
}
else{
cout << " :\t estabilidade atual: " << setprecision(2) << fixed << estabilidade << "% maior.\n";
}
cout << " ---------------------------------------------------- \n";
}
// Mostrando estados em baixa
cout << "\n|----------------------------------------------------|"
<< "\n| Estados em Baixa |"
<< "\n|----------------------------------------------------|\n";
for (unsigned i=0; i<vetorEstabilidades.at(2).size();i++){
indice = (unsigned) vetorEstabilidades.at(2).at(i).at(0);
estabilidade = vetorEstabilidades.at(2).at(i).at(1);
nome = vetorEstados.at(indice).getNome();
cout << " "
<<nome
<<" :\t estabilidade atual: " << setprecision(2) << fixed << estabilidade * -1 << "% menor.\n";
cout << " ---------------------------------------------------- \n";
}
}
// Função criada para mostrar a estabilidade do país e sua categoria
void Menu::mostrarEstabilidadePais(Nacional pais){
float estabilidade = pais.calcularEstabilidade();
cout << "\n|----------------------------------------------------|"
<< "\n| Estabilidade atual do país |"
<< "\n|----------------------------------------------------|\n\n";
// caso em que o país está em alta
if (estabilidade >= 1.1){
cout << " "
<< pais.getNome()
<< " está em alta com "
<< setprecision(2) << fixed << (estabilidade -1)*100
<< "% a mais na média móvel atual. \n\n";
}
// caso em que o país estável
else if (estabilidade < 1.1 && estabilidade > 0.9 ){
if(estabilidade>0.9 && estabilidade<1){
cout << pais.getNome()
<< " está estável com "
<< setprecision(2) << fixed << (1 - estabilidade)*100
<< "% a menos na média móvel atual. \n\n";
}
else{
cout << pais.getNome()
<< " está estável com "
<< setprecision(2) << fixed << (estabilidade -1)*100
<< "% a mais na média móvel atual. \n\n";
}
}
// caso em que o país está em baixa
else if (estabilidade <= 0.9){
cout << pais.getNome()
<< " está em baixa com "
<< setprecision(2) << fixed << (1 - estabilidade)*100
<< "% a menos na média móvel atual. \n\n";
}
}<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: aresta.h
* Autor: <NAME> - 118045099
*/
#include "vertice.h"
#ifndef ARESTA_H
#define ARESTA_H
class Aresta{
public:
Aresta(Vertice vertice1, Vertice vertice2, int peso);
void setPeso(int peso_aresta);
unsigned getPeso();
string getVertice1();
string getVertice2();
void mostrarArestaNaTela();
private:
Vertice vertice1;
Vertice vertice2;
unsigned peso;
};
#endif<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: main.cpp
* Autor: <NAME> - 118045099
*/
#include "grafo.h"
#define VALOR_MAXIMO_N 15
int main(int argc, char *argv[]){
unsigned n;
if(argc != 2){
cout << "\n-----------\n"
<< " Erro\n"
<< "-----------\n"
<< "Uso: "<< argv[0] <<" <n> \n";
exit(1);
}
n = (unsigned) stoul(argv[1], NULL, 10);
if ((n<2) || (n > VALOR_MAXIMO_N)){
cout << "\n-----------\n"
<< " Erro\n"
<< "-----------\n"
<< "O valor de n deve estar entre 2 e " << VALOR_MAXIMO_N << "\n\n";
exit(1);
}
Grafo grafo;
grafo.preencherGrafo();
cout << "\n\n------------------------------------------- \n"
<< " Vértices Registrados: (<freq>) <palavra> \n"
<< "-------------------------------------------" << endl;
grafo.mostrarVertices();
cout << "\n\n---------------------------------------------------------- \n"
<< " Arestas Registradas: <vertice1> -> <peso> -> <vertice2> \n"
<< "----------------------------------------------------------" << endl;
grafo.mostrarArestas();
cout << "\n\n--------------------------- \n"
<< " Palavras mais utilizadas: \n"
<< "---------------------------" << endl;
grafo.mostrarVerticeMaiorFrequencia();
cout << "\n\n---------------------------------------- \n"
<< " Sequência de 2 palavras mais utilizada: \n"
<< "----------------------------------------" << endl;
grafo.mostrarMaiorSequenciaDuasPalavras();
cout << "\n\n---------------------------------------- \n"
<< " Sequência de "<<n<<" palavras mais utilizada: \n"
<< "----------------------------------------" << endl;
grafo.mostrarMaiorSequenciaNPalavras(n);
cout<< "\n\n";
return 0;
}<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: estadual.cpp
* Autor: <NAME> - 118045099
*/
#include "estadual.h"
Estadual::Estadual(string nome_estado, string arquivo_obitos){
setNome(nome_estado);
setArquivoObitos(arquivo_obitos);
setVetorObitos();
}
void Estadual::setNome(string nome_estado){
nome = nome_estado;
}
string Estadual::getNome(){
return nome;
}
void Estadual::setArquivoObitos(string arquivo_obitos){
arquivoObitos = arquivo_obitos;
}
string Estadual::getArquivoObitos(){
return arquivoObitos;
}
// gera os valores para o vetor de óbitos através do arquivo txt
void Estadual::setVetorObitos(){
vector <unsigned> vetorAuxiliar;
string obitos_no_dia;
fstream file;
file.open(arquivoObitos, fstream::in);
if (!file.is_open()){
cout << "Arquivo nao existe. \n";
}
else{
while (file.good()){
file >> obitos_no_dia;
vetorAuxiliar.push_back(stoul(obitos_no_dia));
}
vetorObitos = vetorAuxiliar;
}
file.close();
}
// retorna o vetor de óbitos
vector <unsigned> Estadual::getVetorObitos(){
return vetorObitos;
}
// Função auxiliar que mostra os dados do vetor de óbitos
void Estadual::mostrarVetorObitosNaTela(){
for (unsigned i = 0; i < vetorObitos.size(); i++){
cout << i <<": "<< vetorObitos.at(i) << ".\n";
}
}
// Retorna um vetor com as médias móveis no estado. O vetor seguirá o formato:
// índice 0 -> média móvel do último dia
// índice 1 -> média móvel do penúltimo dia
// índice 2 -> média móvel do antepenúltimo dia
vector <unsigned> Estadual::calcularMediaMovel(){
unsigned somaUltimoDia = 0, somaPenultimoDia = 0, somaAntePenultimoDia = 0;
for (unsigned i = 0; i < vetorObitos.size(); i++){
if (i<7){
somaUltimoDia += vetorObitos.at(i);
}
if (i>0 && i<8){
somaPenultimoDia += vetorObitos.at(i);
}
if (i>1 && i<9){
somaAntePenultimoDia += vetorObitos.at(i);
}
if (i>=9){
i = vetorObitos.size();
}
}
unsigned mediaUltimoDia = somaUltimoDia/7;
unsigned mediaPenultimoDia = somaPenultimoDia/7;
unsigned mediaAntePenultimoDia = somaAntePenultimoDia/7;
vector <unsigned> vetorRetorno;
vetorRetorno.push_back(mediaUltimoDia);
vetorRetorno.push_back(mediaPenultimoDia);
vetorRetorno.push_back(mediaAntePenultimoDia);
return vetorRetorno;
}
// retorna a estabilidade atual do estado considerando as 2 últimas médias móveis
float Estadual::calcularEstabilidade(){
vector <unsigned> mediaMovel = calcularMediaMovel();
float estabilidade = ((float) mediaMovel.at(0)) / ((float) mediaMovel.at(1));
return estabilidade;
}
// retorna o somatório de todas as mortes no estado
unsigned Estadual::calcularObitosAcumulados(){
unsigned soma = 0;
for (unsigned i = 0; i < vetorObitos.size(); i++){
soma += vetorObitos.at(i);
}
return soma;
}
<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: menu.cpp
* Autor: <NAME> - 118045099
*/
#include "menu.h"
// Função criada para mostrar as operações disponíveis para o usuário
void Menu::mostrarMenuPrincipal() {
cout << "\n|------------------------------------------------|"
<< "\n| MENU PRINCIPAL |"
<< "\n|------------------------------------------------|"
<< "\n| 1 - INSERIR UM NOVO PACIENTE |"
<< "\n|------------------------------------------------|"
<< "\n| 2 - BUSCAR POR UM PACIENTE CADASTRADO |"
<< "\n|------------------------------------------------|"
<< "\n| 3 - EXIBIR TODOS OS PACIENTES CADASTRADOS |"
<< "\n|------------------------------------------------|"
<< "\n| 4 - SAIR DO PROGRAMA |"
<< "\n|------------------------------------------------|\n";
};
// Função criada para receber a opção escolhida pelo usuário
unsigned Menu::receberOpcaoMenu(){
char entrada_usuario[256];
unsigned escolhaMenu;
cout << "\n Digite a opção desejada:";
cin >> entrada_usuario;
// vai retornar 0 se entrada_usuario nao for do tipo int
escolhaMenu = atoi(entrada_usuario);
return escolhaMenu;
};
// Função criada para avisar ao usuário que o programa foi finalizado e terminar a execução
void Menu::finalizarPrograma(){
cout << "\n|------------------------------------------------|"
<< "\n| FIM DO PROGRAMA |"
<< "\n|------------------------------------------------|\n\n";
};
void Menu::criarPaciente(Cadastro &cadastro){
unsigned escolha;
string nomeEntrada;
string idadeEntrada;
unsigned int idade;
string descricaoEntrada;
string diasInternadosEntrada;
unsigned int diasInternados;
string numConsultasEntrada;
unsigned int numConsultas;
string nomeExameEntrada;
bool entradaInvalida = false;
string exameRealizadoEntrada;
bool exameRealizado;
Paciente_Internacao *pacienteInternacaoAux;
Paciente_Consulta *pacienteConsultaAux;
Paciente_Exame *pacienteExameAux;
do {
cout << "\n|--------------------------------------------------|"
<< "\n| ESCOLHA O TIPO DE PACIENTE QUE DESEJA CRIAR |"
<< "\n|--------------------------------------------------|"
<< "\n| 1 - Paciente em Internação |"
<< "\n| 2 - Paciente para Consulta |"
<< "\n| 3 - Paciente para Exame |"
<< "\n| |"
<< "\n| 4 - CANCELAR OPERAÇÃO |"
<< "\n|--------------------------------------------------|\n";
escolha = receberOpcaoMenu();
switch (escolha) {
case 1:
cout << " Digite o nome do Paciente: ";
cin.ignore();
getline(cin, nomeEntrada);
do{
cout << " Digite a idade do Paciente: ";
cin >> idadeEntrada;
entradaInvalida = false;
try{
idade = stoul(idadeEntrada);
}
catch(...){
cout << "\n|------------------------------------------------|"
<< "\n| ERRO - IDADE INVÁLIDA, DIGITE NOVAMENTE |"
<< "\n|------------------------------------------------|\n\n";
entradaInvalida = true;
}
}while (entradaInvalida);
cout << " Digite a descrição do Paciente: ";
cin.ignore();
getline(cin, descricaoEntrada);
do{
cout << " Digite o número de dias que o paciente está internado: ";
cin >> diasInternadosEntrada;
entradaInvalida = false;
try{
diasInternados = stoul(diasInternadosEntrada);
}
catch(...){
cout << "\n|------------------------------------------------|"
<< "\n| ERRO - ENTRADA INVÁLIDA, DIGITE NOVAMENTE |"
<< "\n|------------------------------------------------|\n\n";
entradaInvalida = true;
}
}while (entradaInvalida);
escolha = 5;
pacienteInternacaoAux = new Paciente_Internacao;
pacienteInternacaoAux->setNome(nomeEntrada);
pacienteInternacaoAux->setIdade(idade);
pacienteInternacaoAux->setDescricao(descricaoEntrada);
pacienteInternacaoAux->setDiasInternados(diasInternados);
if (pacienteInternacaoAux->getNome() != ""){
try{
cadastro.insere(*pacienteInternacaoAux);
cout << *pacienteInternacaoAux;
}
catch(const pacienteJaInserido &erro){
cerr << erro.what();
}
}
cout << "\n";
break;
case 2:
cout << " Digite o nome do Paciente: ";
cin.ignore();
getline(cin, nomeEntrada);
do{
cout << " Digite a idade do Paciente: ";
cin >> idadeEntrada;
entradaInvalida = false;
try{
idade = stoul(idadeEntrada);
}
catch(...){
cout << "\n|------------------------------------------------|"
<< "\n| ERRO - IDADE INVÁLIDA, DIGITE NOVAMENTE |"
<< "\n|------------------------------------------------|\n\n";
entradaInvalida = true;
}
}while (entradaInvalida);
cout << " Digite a descrição do Paciente: ";
cin.ignore();
getline(cin, descricaoEntrada);
do{
cout << " Digite o número de consultas que o paciente já realizou: ";
cin >> numConsultasEntrada;
entradaInvalida = false;
try{
numConsultas = stoul(numConsultasEntrada);
}
catch(...){
cout << "\n|------------------------------------------------|"
<< "\n| ERRO - ENTRADA INVÁLIDA, DIGITE NOVAMENTE |"
<< "\n|------------------------------------------------|\n\n";
entradaInvalida = true;
}
}while (entradaInvalida);
escolha = 5;
pacienteConsultaAux = new Paciente_Consulta;
pacienteConsultaAux->setNome(nomeEntrada);
pacienteConsultaAux->setIdade(idade);
pacienteConsultaAux->setDescricao(descricaoEntrada);
pacienteConsultaAux->setNumConsultas(numConsultas);
if (pacienteConsultaAux->getNome() != ""){
try{
cadastro.insere(*pacienteConsultaAux);
cout << *pacienteConsultaAux;
}
catch(const pacienteJaInserido &erro){
cerr << erro.what();
}
}
cout << "\n";
break;
case 3:
cout << " Digite o nome do Paciente: ";
cin.ignore();
getline(cin, nomeEntrada);
do{
cout << " Digite a idade do Paciente: ";
cin >> idadeEntrada;
entradaInvalida = false;
try{
idade = stoul(idadeEntrada);
}
catch(...){
cout << "\n|------------------------------------------------|"
<< "\n| ERRO - IDADE INVÁLIDA, DIGITE NOVAMENTE |"
<< "\n|------------------------------------------------|\n\n";
entradaInvalida = true;
}
}while (entradaInvalida);
cout << " Digite a descrição do Paciente: ";
cin.ignore();
getline(cin, descricaoEntrada);
cout << " Digite o nome do Exame designado: ";
cin.ignore();
getline(cin, nomeExameEntrada);
do{
cout << " Digite 1 se o exame já foi realizado e 2 caso contrário: ";
cin >> exameRealizadoEntrada;
if (exameRealizadoEntrada == "1"){
exameRealizado = true;
entradaInvalida = false;
}
else if (exameRealizadoEntrada == "2"){
exameRealizado = false;
entradaInvalida = false;
}
else {
cout << "\n|------------------------------------------------|"
<< "\n| ERRO - OPÇÃO INVÁLIDA, DIGITE NOVAMENTE |"
<< "\n|------------------------------------------------|\n\n";
entradaInvalida = true;
}
}while (entradaInvalida);
escolha = 5;
pacienteExameAux = new Paciente_Exame;
pacienteExameAux->setNome(nomeEntrada);
pacienteExameAux->setIdade(idade);
pacienteExameAux->setDescricao(descricaoEntrada);
pacienteExameAux->setNomeExame(nomeExameEntrada);
pacienteExameAux->setExameRealizado(exameRealizado);
if (pacienteExameAux->getNome() != ""){
try{
cadastro.insere(*pacienteExameAux);
cout << *pacienteExameAux;
}
catch(const pacienteJaInserido &erro){
cerr << erro.what();
}
}
cout << "\n";
break;
case 4:
escolha = 5;
cout << "\n|-------------------------------------|"
<< "\n| ALTERAÇÃO CANCELADA |"
<< "\n|-------------------------------------|\n\n";
break;
default:
escolha = 0;
cout << "Opção Inválida - Tente Novamente" << endl;
}
}while(escolha!=5);
}
string Menu::receberNomeBusca(){
string nomeEntrada;
cout << "\n|--------------------------------------------------|"
<< "\n| ESCOLHA O TIPO DE PACIENTE QUE DESEJA CRIAR |"
<< "\n|--------------------------------------------------|\n \n";
cout << " Digite o nome do Paciente que deseja pesquisar: ";
cin.ignore();
getline(cin, nomeEntrada);
return nomeEntrada;
}
<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: cadastro.h
* Autor: <NAME> - 118045099
*/
#ifndef CADASTRO_H
#define CADASTRO_H
#include <string>
#include "arvore.h"
#include "paciente.h"
#include "excecao.h"
using namespace std;
class Cadastro : public Arvore <Paciente *>{
public:
Cadastro();
void insere(Paciente pacienteInserir);
void busca(string nomeBusca);
void imprime();
private:
Arvore <Paciente> arvorePacientes;
};
#endif<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: catalogo.h
* Autor: <NAME> - 118045099
*/
#include <fstream>
#include "filmes.h"
using namespace std;
#ifndef CATALOGO_H
#define CATALOGO_H
// classe
class Catalogo{
public:
Catalogo(unsigned numMaxFilmesEnt, string nomeArquivo );
void inicializarFilmesArquivo(string nomeArquivo);
void salvarFilmesArquivo(string nomeArquivo);
void mostrarFilmeCadastrado(filme filmeBusca);
void mostrarFilmeMelhorAvaliado();
void mostrarFilmePiorAvaliado();
friend ostream &operator<<(ostream &out, const Catalogo &catalogo);
void operator+=(filme filme);
void operator-=(filme filme);
filme *operator()(filme filmeBusca);
filme *operator()(filme filmeBusca,string produtora);
filme *operator()(filme filmeBusca,double nota);
private:
unsigned numMaxFilmes;
vector<filme> vetorFilmes;
};
#endif<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: vertice.cpp
* Autor: <NAME> - 118045099
*/
#include "vertice.h"
Vertice::Vertice(){
setPalavra("");
setFrequencia(1);
}
void Vertice::setPalavra(string palavra_vertice){
palavra = palavra_vertice;
}
string Vertice::getPalavra(){
return palavra;
}
void Vertice::setFrequencia(unsigned frequencia_vertice){
frequencia = frequencia_vertice;
}
unsigned Vertice::getFrequencia(){
return frequencia;
}
void Vertice::mostrarVerticeNaTela(){
cout << "("
<< getFrequencia()
<< ") "
<< getPalavra() << endl;
}<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: menu.cpp
* Autor: <NAME> - 118045099
*/
#include "menu.h"
// Função criada para mostrar as operações disponíveis para o usuário
void Menu::mostrarMenuPrincipal() {
cout << "\n|------------------------------------------------|"
<< "\n| MENU PRINCIPAL |"
<< "\n|------------------------------------------------|"
<< "\n| 1 - INSERIR UM FILME |"
<< "\n|------------------------------------------------|"
<< "\n| 2 - REMOVER UM FILME |"
<< "\n|------------------------------------------------|"
<< "\n| 3 - BUSCAR UM FILME |"
<< "\n|------------------------------------------------|"
<< "\n| 4 - EDITAR UM FILME |"
<< "\n|------------------------------------------------|"
<< "\n| 5 - MOSTRAR CATÁLOGO |"
<< "\n|------------------------------------------------|"
<< "\n| 6 - MOSTRAR FILMES COM A MELHOR AVALIAÇÃO |"
<< "\n|------------------------------------------------|"
<< "\n| 7 - MOSTRAR FILMES COM A PIOR AVALIAÇÃO |"
<< "\n|------------------------------------------------|"
<< "\n| 8 - SAIR DO PROGRAMA |"
<< "\n|------------------------------------------------|\n";
};
// Função criada para receber a opção escolhida pelo usuário
unsigned Menu::receberOpcaoMenu(){
char entrada_usuario[256];
unsigned escolhaMenu;
cout << "\n Digite a opção desejada:";
cin >> entrada_usuario;
// vai retornar 0 se entrada_usuario nao for do tipo int
escolhaMenu = atoi(entrada_usuario);
return escolhaMenu;
};
// Função criada para avisar ao usuário que o programa foi finalizado e terminar a execução
void Menu::finalizarPrograma(){
cout << "\n|------------------------------------------------|"
<< "\n| FIM DO PROGRAMA |"
<< "\n|------------------------------------------------|\n\n";
};
filme Menu::inicializarFilme(){
filme filmeAux;
char notaEntrada[256];
double nota;
bool notaInvalida = false;
cout <<" Digite o nome do filme: ";
cin.ignore();
getline(cin, filmeAux.nome);
cout <<" Digite o nome da produtora: ";
cin.ignore();
getline(cin, filmeAux.produtora);
do{
cout <<" Digite a nota da avaliação do filme: ";
cin.ignore();
cin >> notaEntrada;
notaInvalida = false;
try{
nota = stod(notaEntrada);
}
catch(...){
cout << "\n|------------------------------------------------|"
<< "\n| ERRO - NOTA INVÁLIDA, DIGITE NOVAMENTE |"
<< "\n|------------------------------------------------|\n\n";
notaInvalida = true;
}
if((nota<0)||(nota>10)){
cout << "\n|------------------------------------------------|"
<< "\n| ERRO - NOTA INVÁLIDA, DIGITE NOVAMENTE |"
<< "\n|------------------------------------------------|\n\n";
notaInvalida = true;
}
}while (notaInvalida);
filmeAux.nota = nota;
return filmeAux;
}
filme Menu::inicializarFilmeSomenteComNome(){
filme filmeAux;
cin.ignore();
getline(cin, filmeAux.nome);
filmeAux.produtora = "";
filmeAux.nota = 0;
return filmeAux;
}
filme Menu::retornarFilmeParaAdicionar(){
cout << "\n|----------------------------------------------------|"
<< "\n| ADICIONAR FILME |"
<< "\n|----------------------------------------------------|\n\n";
filme filmeAux = inicializarFilme();
return filmeAux;
}
filme Menu::retornarFilmeParaRemover(){
cout << "\n|----------------------------------------------------|"
<< "\n| REMOVER FILME |"
<< "\n|----------------------------------------------------|\n\n"
<<" Digite o nome do filme que deseja remover: ";
filme filmeAux = inicializarFilmeSomenteComNome();
return filmeAux;
}
filme Menu::retornarFilmeParaBuscar(){
cout << "\n|----------------------------------------------------|"
<< "\n| BUSCAR FILME |"
<< "\n|----------------------------------------------------|\n\n"
<<" Digite o nome do filme que deseja procurar: ";
filme filmeAux = inicializarFilmeSomenteComNome();
return filmeAux;
}
void Menu::editarFilme(Catalogo &catalogo){
filme filmeAux;
string novaProdutora;
char notaEntrada[256];
double novaNota;
bool notaInvalida = false;
cout << "\n|----------------------------------------------------|"
<< "\n| EDITAR FILME |"
<< "\n|----------------------------------------------------|\n\n";
unsigned escolha;
do {
cout << "\n|--------------------------------------------|"
<< "\n| ESCOLHA A OPÇÃO QUE DESEJA ALTERAR |"
<< "\n|--------------------------------------------|"
<< "\n| 1 - PRODUTORA |"
<< "\n| 2 - NOTA |"
<< "\n| |"
<< "\n| 3 - CANCELAR ALTERAÇÃO |"
<< "\n|--------------------------------------------|\n";
escolha = receberOpcaoMenu();
switch (escolha) {
case 1:
cout << " Digite o nome do filme que deseja editar: ";
filmeAux = inicializarFilmeSomenteComNome();
cout << " Digite o nome da nova produtora: ";
getline(cin, novaProdutora);
catalogo(filmeAux,novaProdutora);
escolha = 4;
break;
case 2:
cout << " Digite o nome do filme que deseja editar: ";
filmeAux = inicializarFilmeSomenteComNome();
do{
cout <<" Digite a nova nota de avaliação: ";
cin >> notaEntrada;
notaInvalida = false;
try{
novaNota = stod(notaEntrada);
}
catch(...){
cout << "\n|------------------------------------------------|"
<< "\n| ERRO - NOTA INVÁLIDA, DIGITE NOVAMENTE |"
<< "\n|------------------------------------------------|\n\n";
notaInvalida = true;
}
}while (notaInvalida);
catalogo(filmeAux,novaNota);
escolha = 4;
break;
case 3:
escolha = 4;
cout << "\n|-------------------------------------|"
<< "\n| ALTERAÇÃO CANCELADA |"
<< "\n|-------------------------------------|\n\n";
break;
default:
escolha = 0;
cout << "Opção Inválida - Tente Novamente" << endl;
}
}while(escolha!=4);
}
<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: filmes.h
* Autor: <NAME> - 118045099
*/
#include <iostream>
#include <string>
#include<vector>
using namespace std;
#ifndef FILMES_H
#define FILMES_H
// estrutura do filme
struct filme{
string nome;
string produtora;
double nota;
};
// operadores
bool operator==(filme filme1, filme filme2);
bool operator<(filme filme1, filme filme2);
bool operator>(filme filme1, filme filme2);
vector<filme> operator+=(vector<filme> vetorFilmes,filme filme);
vector<filme> operator+=(vector<filme> vetorDestino, vector<filme> vetorInserir);
vector<filme> operator-=(vector<filme> vetorDestino,filme filme);
vector<filme> operator-=(vector<filme> vetorDestino, vector<filme> vetorInserir);
ostream &operator<<(ostream &out, filme &filme);
#endif<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: main.cpp
* Autor: <NAME> - 118045099
*/
#include <iostream>
#include <string>
using namespace std;
#include "menu.h"
int main(int argc, char *argv[]){
unsigned numMaxFilmes;
string nomeArquivo;
if(argc != 3){
cout << "\n-----------\n"
<< " Erro\n"
<< "-----------\n"
<< "Uso: "<< argv[0] <<" <numMaxFilmes> <nomeArquivo>\n\n";
exit(1);
}
numMaxFilmes = (unsigned) stoul(argv[1], NULL, 10);
if (numMaxFilmes<2){
cout << "\n-----------\n"
<< " Erro\n"
<< "-----------\n"
<< "O valor de numMaxFilmes deve ser maior ou igual a 2.\n\n";
exit(1);
}
nomeArquivo = argv[2];
if(nomeArquivo.substr(nomeArquivo.size()-4,4)!= ".txt"){
cout << "\n-----------\n"
<< " Erro\n"
<< "-----------\n"
<< " O arquivo deve ter a extensão .txt .\n\n";
exit(1);
}
Menu menu;
unsigned escolha_menu;
/////////////////// Inicialização do Catálogo
Catalogo catalogo(numMaxFilmes, nomeArquivo);
/////////////////// Execução do menu com suas respectivas funções
do {
filme filmeAux;
menu.mostrarMenuPrincipal();
escolha_menu = menu.receberOpcaoMenu();
// código extra para limpar o terminal toda vez que o menu é reiniciado
#ifdef linux
system("clear");
#endif
#ifdef WIN32
system("cls");
#endif
switch (escolha_menu) {
// INSERIR UM FILME NO CATÁLOGO
case 1:
filmeAux = menu.retornarFilmeParaAdicionar();
catalogo+=filmeAux;
break;
// REMOVER UM FILME DO CATÁLOGO
case 2:
filmeAux = menu.retornarFilmeParaRemover();
catalogo-=filmeAux;
break;
// BUSCAR UM FILME NO CATÁLOGO
case 3:
filmeAux = menu.retornarFilmeParaBuscar();
catalogo.mostrarFilmeCadastrado(filmeAux);
break;
// EDITAR UM FILME NO CATÁLOGO
case 4:
menu.editarFilme(catalogo);
break;
// MOSTRAR CATÁLOGO
case 5:
cout << catalogo;
break;
// MOSTRAR FILME COM MELHOR AVALIAÇÃO
case 6:
catalogo.mostrarFilmeMelhorAvaliado();
break;
// MOSTRAR FILME COM PIOR AVALIAÇÃO
case 7:
catalogo.mostrarFilmePiorAvaliado();
break;
// SAIR DO PROGRAMA
case 8:
catalogo.salvarFilmesArquivo(nomeArquivo);
menu.finalizarPrograma();
escolha_menu = 9;
break;
default:
escolha_menu = 0;
cout << "Opção Inválida - Tente Novamente" << endl;
}
} while (escolha_menu != 9);
return 0;
}
<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: paciente.cpp
* Autor: <NAME> - 118045099
*/
#include "paciente.h"
////////////////////// PACIENTE BASE
Paciente::Paciente(string nomeEntrada, unsigned int idadeEntrada, string descricaoEntrada){
nome = nomeEntrada;
idade = idadeEntrada;
descricao = descricaoEntrada;
}
Paciente::Paciente(){}
string Paciente::getNome(){
return nome;
}
unsigned int Paciente::getIdade(){
return idade;
}
string Paciente::getDescricao(){
return descricao;
}
string Paciente::getTipo(){
return tipo;
}
void Paciente::setNome(string nomeEntrada){
nome = nomeEntrada;
}
void Paciente::setIdade(unsigned int idadeEntrada){
idade = idadeEntrada;
}
void Paciente::setDescricao(string descricaoEntrada){
descricao = descricaoEntrada;
}
void Paciente::setTipo(string tipoEntrada){
tipo = tipoEntrada;
}
ostream &operator<<(ostream &out, Paciente &pacienteImprimir){
pacienteImprimir.mostrarPaciente();
return out;
}
void Paciente::mostrarPaciente(){
cout <<"\n\n PACIENTE CADASTRADO PARA " << getTipo();
cout <<"\n\n Nome: " << getNome();
if (getIdade() == 1) {
cout <<"\n Idade: 1 ano";
}
else {
cout <<"\n Idade: " << getIdade() << " anos";
}
cout <<"\n Descrição: " << getDescricao();
cout <<"\n-------------------------------------";
}
bool Paciente::operator>(Paciente const &pacienteComparacao){
if((this->nome) > (pacienteComparacao.nome)){
return true;
}
return false;
}
bool Paciente::operator<(Paciente const &pacienteComparacao){
if((this->nome) < (pacienteComparacao.nome)){
return true;
}
return false;
}
bool Paciente::operator==(Paciente const &pacienteComparacao){
if((this->nome) == (pacienteComparacao.nome)){
return true;
}
return false;
}
////////////////////// PACIENTE INTERNACAO
Paciente_Internacao::Paciente_Internacao(string nomeEntrada, unsigned int idadeEntrada, string descricaoEntrada, unsigned int diasInternadosEntrada){
setNome(nomeEntrada);
setIdade(idadeEntrada);
setDescricao(descricaoEntrada);
diasInternados = diasInternadosEntrada;
setTipo("INTERNAÇÃO");
}
Paciente_Internacao::Paciente_Internacao(){
setTipo("INTERNAÇÃO");
}
unsigned int Paciente_Internacao::getDiasInternados(){
return diasInternados;
}
void Paciente_Internacao::setDiasInternados(unsigned int diasInternadosEntrada){
diasInternados = diasInternadosEntrada;
}
void Paciente_Internacao::mostrarPaciente(){
cout <<"\n\n PACIENTE CADASTRADO PARA " << getTipo();
cout <<"\n\n Nome: " << getNome();
if (getIdade() == 1) {
cout <<"\n Idade: 1 ano";
}
else {
cout <<"\n Idade: " << getIdade() << " anos";
}
cout <<"\n Descrição: " << getDescricao();
if (getDiasInternados() == 1) {
cout <<"\n Dias Internados: 1 dia";
}
else {
cout <<"\n Dias Internados: " << getDiasInternados() << " dias";
}
cout <<"\n-------------------------------------";
}
////////////////////// PACIENTE CONSULTA
Paciente_Consulta::Paciente_Consulta(string nomeEntrada, unsigned int idadeEntrada, string descricaoEntrada, unsigned int numConsultasEntrada){
setNome(nomeEntrada);
setIdade(idadeEntrada);
setDescricao(descricaoEntrada);
numConsultas = numConsultasEntrada;
setTipo("CONSULTA");
}
Paciente_Consulta::Paciente_Consulta(){
setTipo("CONSULTA");
}
unsigned int Paciente_Consulta::getNumConsultas(){
return numConsultas;
}
void Paciente_Consulta::setNumConsultas(unsigned int numConsultasEntrada){
numConsultas = numConsultasEntrada;
}
void Paciente_Consulta::mostrarPaciente(){
cout <<"\n\n PACIENTE CADASTRADO PARA " << getTipo();
cout <<"\n\n Nome: " << getNome();
if (getIdade() == 1) {
cout <<"\n Idade: 1 ano";
}
else {
cout <<"\n Idade: " << getIdade() << " anos";
}
cout <<"\n Descrição: " << getDescricao();
if (getNumConsultas() == 1) {
cout <<"\n Número de Consultas realizadas: 1 consulta";
}
else {
cout <<"\n Número de Consultas realizadas: " << getNumConsultas() << " consultas";
}
cout <<"\n-------------------------------------";
}
////////////////////// PACIENTE EXAME
Paciente_Exame::Paciente_Exame(string nomeEntrada, unsigned int idadeEntrada, string descricaoEntrada, string nomeExameEntrada, bool exameRealizadoEntrada){
setNome(nomeEntrada);
setIdade(idadeEntrada);
setDescricao(descricaoEntrada);
nomeExame = nomeExameEntrada;
exameRealizado = exameRealizadoEntrada;
setTipo("EXAME");
}
Paciente_Exame::Paciente_Exame(){
setTipo("EXAME");
}
string Paciente_Exame::getNomeExame(){
return nomeExame;
}
bool Paciente_Exame::getExameRealizado(){
return exameRealizado;
}
void Paciente_Exame::setNomeExame(string nomeExameEntrada){
nomeExame = nomeExameEntrada;
}
void Paciente_Exame::setExameRealizado(bool exameRealizadoEntrada){
exameRealizado = exameRealizadoEntrada;
}
void Paciente_Exame::mostrarPaciente(){
cout <<"\n\n PACIENTE CADASTRADO PARA " << getTipo();
cout <<"\n\n Nome: " << getNome();
if (getIdade() == 1) {
cout <<"\n Idade: 1 ano";
}
else {
cout <<"\n Idade: " << getIdade() << " anos";
}
cout <<"\n Descrição: " << getDescricao()
<<"\n Nome do Exame: "<< getNomeExame();
if (getExameRealizado() == true){
cout <<"\n (..EXAME JÁ REALIZADO..)";
}
else{
cout <<"\n (..EXAME AINDA NÃO FOI REALIZADO..)";
}
cout <<"\n-------------------------------------";
}<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: main.cpp
* Autor: <NAME> - 118045099
*/
#include <iostream>
#include <string>
using namespace std;
#include "menu.h"
#include "cadastro.h"
#include "excecao.h"
int main() {
Menu menu;
unsigned escolha_menu;
string nomeBusca;
/////////////////// Inicialização do Cadastro
Cadastro cadastro;
Paciente pacienteAux;
/////////////////// Execução do menu com suas respectivas funções
do {
menu.mostrarMenuPrincipal();
escolha_menu = menu.receberOpcaoMenu();
// código extra para limpar o terminal toda vez que o menu é reiniciado
#ifdef linux
system("clear");
#endif
#ifdef WIN32
system("cls");
#endif
switch (escolha_menu) {
// INSERIR UM NOVO PACIENTE
case 1:
menu.criarPaciente(cadastro);
break;
// BUSCAR POR UM PACIENTE CADASTRADO
case 2:
nomeBusca = menu.receberNomeBusca();
try{
cadastro.busca(nomeBusca);
}
catch(const pacienteNaoEncontrado &erro){
cerr << erro.what();
}
cout << "\n \n";
break;
// EXIBIR TODOS OS PACIENTES CADASTRADOS
case 3:
cout << "\n|--------------------------------------------------|"
<< "\n| PACIENTES CADASTRADOS |"
<< "\n|--------------------------------------------------|\n";
cadastro.imprime();
cout << "\n \n";
break;
// SAIR DO PROGRAMA
case 4:
menu.finalizarPrograma();
escolha_menu = 5;
break;
default:
escolha_menu = 0;
cout << "Opção Inválida - Tente Novamente" << endl;
}
} while (escolha_menu != 5);
return 0;
}
<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: cadastro.cpp
* Autor: <NAME> - 118045099
*/
#include "cadastro.h"
Cadastro::Cadastro(){}
void Cadastro::insere(Paciente pacienteInserir){
No<Paciente> *ponteiroAux = arvorePacientes+=pacienteInserir;
if ((ponteiroAux)==nullptr){
throw pacienteJaInserido();
}
else{
cout << "\n USUÁRIO ADICIONADO COM SUCESSO \n \n";
}
}
void Cadastro::busca(string nomeBusca){
Paciente pacienteAux(nomeBusca, 0 , "");
No<Paciente> *ponteiroAux = arvorePacientes(pacienteAux);
if (ponteiroAux == nullptr){
throw pacienteNaoEncontrado();
}
else{
cout << "\n------------------------------------- USUÁRIO ENCONTRADO";
cout << ponteiroAux->valor;
}
}
void Cadastro::imprime(){
cout << arvorePacientes;
}
<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: main.cpp
* Autor: <NAME> - 118045099
*/
#include <iostream>
#include <string>
using namespace std;
#include "menu.h"
int main() {
Menu menu;
unsigned escolha_menu;
/////////////////// Nomes para os estados e país
string nome_pais = "Brasil";
string nomes_estados[] = {"RJ","SP","BA","MG","ES","GO","PR","SC"};
/////////////////// Inicialização do País e dos Estados com os 10 últimos dados de óbitos
Nacional pais("Brasil");
for(unsigned i = 0; i < 8; i++){
pais.adicionarEstado(nomes_estados[i],"./dados_obitos/"+nomes_estados[i]+".txt");
}
pais.atualizarVetorObitos();
/////////////////// Execução do menu com suas respectivas funções
do {
menu.mostrarMenuPrincipal();
escolha_menu = menu.receberOpcaoMenu();
// código extra para limpar o terminal toda vez que o menu é reiniciado
#ifdef linux
system("clear");
#endif
#ifdef WIN32
system("cls");
#endif
switch (escolha_menu) {
// MOSTRAR EVOLUÇÃO DO NÚMERO DE ÓBITOS
case 1:
menu.mostrarMediasMoveis(pais);
break;
// ESTABILIDADE ATUAL DOS ESTADOS
case 2:
menu.mostrarEtabilidadeEstados(pais);
break;
// ESTABILIDADE ATUAL DO PAÍS
case 3:
menu.mostrarEstabilidadePais(pais);
break;
// ESTADOS COM MAIOR E MENOR ESTABILIDADE
case 4:
menu.mostrarMaiorMenorMedia(pais);
break;
// NÚMERO DE ÓBITOS ACUMULADOS
case 5:
menu.mostrarTotalDeObitos(pais);
break;
// SAIR DO PROGRAMA
case 6:
menu.finalizarPrograma();
escolha_menu = 7;
break;
default:
escolha_menu = 0;
cout << "Opção Inválida - Tente Novamente" << endl;
}
} while (escolha_menu != 7);
return 0;
}
<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: vertice.h
* Autor: <NAME> - 118045099
*/
#include <iostream>
#include <string>
#ifndef VERTICE_H
#define VERTICE_H
using namespace std;
class Vertice{
public:
Vertice();
void setPalavra(string palavra_vertice);
string getPalavra();
void setFrequencia(unsigned frequencia_vertice);
unsigned getFrequencia();
void mostrarVerticeNaTela();
private:
string palavra;
unsigned frequencia;
};
#endif<file_sep># Sistema de Dados - COVID-19
## Projeto
O programa consiste em um sistema simples para visualização de informações referentes aos dados da Covid-19.
## Armazenamento dos Dados
Para o programa funcionar, ele precisa receber dados referentes aos óbitos diários decorrentes da COVID-19.
Os dados são armazenados na pasta dados_obitos em arquivos no formato txt.
- Cada estado a ser criado deve ter seu próprio arquivo.
- Cada linha do arquivo deve indicar o número de óbitos obtidos naquele dia.
- A primeira linha indica o último dia coletado, a segunda linha indica o penúltimo e assim por diante.
- O número de dias coletados (linhas no arquivo) deve ser igual para todos os estados.
## Como utilizar
Para realizar os testes, foram escolhidos 8 estados brasileiros e seus respectivos arquivos .txt foram preenchidos com dados reais referentes a 10 dias do mês de abril. (Fonte: https://especiais.g1.globo.com/bemestar/coronavirus/estados-brasil-mortes-casos-media-movel/).
Além disso, foi criada uma classe extra(menu) para utilização visual das funções das classes nacional e estadual permitindo uma melhor interação com o usuário.
Para testar o programa basta seguir os passos:
- Abra o terminal nessa pasta e utilize o comando "make" para gerar o executável.
- Execute o programa através de "./main"
- Escolha a função desejada através do menu digitando o número escolhido
Caso queira remover os arquivos .o e o executável basta realizar o comando "make clean".
<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: menu.h
* Autor: <NAME> - 118045099
*/
#include <iostream>
#include <string>
#include "filmes.h"
#include "catalogo.h"
using namespace std;
class Menu {
public:
void mostrarMenuPrincipal();
unsigned receberOpcaoMenu();
void finalizarPrograma();
filme inicializarFilme();
filme inicializarFilmeSomenteComNome();
filme retornarFilmeParaAdicionar();
filme retornarFilmeParaRemover();
filme retornarFilmeParaBuscar();
void editarFilme(Catalogo &catalogo);
};<file_sep>/*
* Universidade Federal do Rio de Janeiro
* EEL670 - Linguagens de Programação
* Prof.: <NAME>
*
* Arquivo: aresta.cpp
* Autor: <NAME> - 118045099
*/
#include "aresta.h"
Aresta::Aresta(Vertice vertice_1, Vertice vertice_2, int peso){
vertice1 = vertice_1;
vertice2 = vertice_2;
setPeso(peso);
}
string Aresta::getVertice1(){
return vertice1.getPalavra();
}
string Aresta::getVertice2(){
return vertice2.getPalavra();
}
void Aresta::setPeso(int peso_aresta){
peso = peso_aresta;
}
unsigned Aresta::getPeso(){
return peso;
}
void Aresta::mostrarArestaNaTela(){
cout << vertice1.getPalavra()
<< " -> "
<< peso
<< " -> "
<< vertice2.getPalavra()
<< "\n";
}
|
29cbc2b2f1ed775eccec049897abbb9ea8bc4387
|
[
"Markdown",
"Makefile",
"C++"
] | 35 |
Markdown
|
gabriel-delima/LigProg_2020_2
|
bceccdbed00a3b806c8371535403d1d5db51cfb5
|
da853e0473bbb65c0623254995bc1af7b0d1dbea
|
refs/heads/master
|
<file_sep>from setuptools import setup, find_packages
import os
version = '0.1'
long_description = open('./README').read()
setup(name='gae_taggable_mixin',
version=version,
description="A mixin class that adds taggability to Google AppEngine Model classes.",
long_description=long_description,
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: GAE',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Programming Language :: Python',
],
author="<NAME>",
author_email="<EMAIL>",
url="http://bubenkoff.me",
license="GPL",
package_dir={'': 'src'},
packages=find_packages('src'),
include_package_data=True,
zip_safe=False,
install_requires=['setuptools',
],
)
|
eef5048c01f93f5972cb970391798fef0332565a
|
[
"Python"
] | 1 |
Python
|
abelenki/gae-taggable-mixin
|
7c1a6f605d14ede9629ccaac6434526ec5016bec
|
73ae790c37dbd72ec2fa26ed435139e4d2572b45
|
refs/heads/master
|
<file_sep>using AccountabilityLib.Models;
using BowlingLib.Interfaces;
using BowlingLib.Models;
using BowlingLib.Services;
using BowlingUnitTestsLib.Repositories;
using BowlingUnitTestsLib.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace BowlingUnitTestsLib
{
public class BowlingSystemTests
{
[Theory]
[InlineData(2, 2, 1, 2)]
[InlineData(3, 2, 2, 2)]
[InlineData(2, 4, 1, 2)]
public void StandardMatch(int playerAmount, int laneAmount, int expectedOnFirstLane, int expectedLanes)
{
//Assemble
IBowlingRepository fakeProvider = new FakeBowlingRepository();
BowlingSystem sut = new BowlingSystem(fakeProvider);
ICollection<Party> players = new List<Party>();
ICollection<Lane> lanes = new List<Lane>();
for (int i = 0; i < playerAmount; i++)
players.Add(new Party());
for (int i = 0; i < laneAmount; i++)
lanes.Add(new Lane());
//Act
Match result = sut.CreateStandardMatch(players, lanes, new DateTime()).Result;
//Assert
Assert.Equal(result.Rounds.First().Series.Count, expectedOnFirstLane);
Assert.Equal(result.Rounds.GroupBy(x => x.Lane).Count(), expectedLanes);
}
[Fact]
public void CorrectWinnerInMatch()
{
//Assemble
IBowlingRepository fakeProvider = new FakeBowlingRepository();
Party player1 = new Party() { PartyId = 1 };
Party player2 = new Party() { PartyId = 2 };
fakeProvider.AddMatch(BowlingTestUtility.CreateSampleMatch(1, new DateTime(), new List<Party>() { player1, player2 }));
BowlingSystem sut = new BowlingSystem(fakeProvider);
//Act
Party result = sut.GetMatchWinner(1).Result;
//Assert
Assert.Same(result, player2);
}
[Fact]
public void CorrectWinCountChampionOfYear()
{
//Assemble
IBowlingRepository fakeProvider = new FakeBowlingRepository();
List<Party> players = new List<Party>()
{
new Party() { Name = "Expected third" },
new Party() { Name = "Expected second" },
new Party() { Name = "Expected winner" }
};
List<Party> playersFromOtherYears = new List<Party>()
{
new Party() { Name = "Expected wrong year" },
new Party() { Name = "Expected wrong year" },
new Party() { Name = "Expected wrong year" },
new Party() { Name = "Expected wrong year" }
};
fakeProvider.AddMatch(BowlingTestUtility.CreateSampleMatch(1, new DateTime(1994, 01, 01), players));
fakeProvider.AddMatch(BowlingTestUtility.CreateSampleMatch(2, new DateTime(1994, 11, 01), players));
fakeProvider.AddMatch(BowlingTestUtility.CreateSampleMatch(3, new DateTime(1995, 05, 29), players));
fakeProvider.AddMatch(BowlingTestUtility.CreateSampleMatch(3, new DateTime(1995, 05, 29), playersFromOtherYears));
fakeProvider.AddMatch(BowlingTestUtility.CreateSampleMatch(3, new DateTime(1995, 05, 29), playersFromOtherYears));
fakeProvider.AddMatch(BowlingTestUtility.CreateSampleMatch(3, new DateTime(1995, 05, 29), playersFromOtherYears));
BowlingSystem sut = new BowlingSystem(fakeProvider);
//Act
Party result = sut.GetWinCountChampionOfYear(1994).Result;
//Assert
Assert.Equal("Expected winner", result.Name);
}
[Fact]
public void CorrectWinRateChampionOfYear()
{
//Assemble
IBowlingRepository fakeProvider = new FakeBowlingRepository();
Party winner = new Party() { Name = "Expected winner" };
Party second = new Party() { Name = "Expected second" };
Party third = new Party() { Name = "Expected third" };
List<Party> playerList1 = new List<Party>() { third, second, winner };
List<Party> playerList2 = new List<Party>() { winner, third, second};
List<Party> playersFromOtherYears = new List<Party>()
{
new Party() { Name = "Expected wrong year" },
new Party() { Name = "Expected wrong year" },
new Party() { Name = "Expected wrong year" },
new Party() { Name = "Expected wrong year" }
};
fakeProvider.AddMatch(BowlingTestUtility.CreateSampleMatch(1, new DateTime(1994, 01, 01), playerList1)); //winner wins
fakeProvider.AddMatch(BowlingTestUtility.CreateSampleMatch(2, new DateTime(1994, 11, 01), playerList1)); //winner wins
fakeProvider.AddMatch(BowlingTestUtility.CreateSampleMatch(3, new DateTime(1994, 11, 01), playerList1)); //winner wins
fakeProvider.AddMatch(BowlingTestUtility.CreateSampleMatch(4, new DateTime(1994, 11, 01), playerList2)); //
fakeProvider.AddMatch(BowlingTestUtility.CreateSampleMatch(5, new DateTime(1995, 05, 29), playerList1));
fakeProvider.AddMatch(BowlingTestUtility.CreateSampleMatch(6, new DateTime(1995, 05, 29), playersFromOtherYears));
fakeProvider.AddMatch(BowlingTestUtility.CreateSampleMatch(7, new DateTime(1995, 05, 29), playersFromOtherYears));
fakeProvider.AddMatch(BowlingTestUtility.CreateSampleMatch(8, new DateTime(1995, 05, 29), playersFromOtherYears));
BowlingSystem sut = new BowlingSystem(fakeProvider);
//Act
Party result = sut.GetWinRateChampionOfYear(1994).Result;
//Assert
Assert.Equal("Expected winner", result.Name);
}
[Fact]
public void CanRegisterScore()
{
//Assemble
IBowlingRepository fakeProvider = new FakeBowlingRepository();
Match match = new Match()
{
Rounds = new List<Round>()
{
new Round() { Series = new List<Series>() { new Series() { SeriesId = 1 } } }
}
};
fakeProvider.AddMatch(match);
BowlingSystem sut = new BowlingSystem(fakeProvider);
//Act
sut.RegisterScores(1, 500).Wait();
//Assert
Assert.Equal(500, fakeProvider.GetSeries(1).Result.Score);
}
[Fact]
public void CorrectWinnerInCompetition()
{
//Assemble
IBowlingRepository fakeProvider = new FakeBowlingRepository();
Party player1 = new Party() { PartyId = 1 };
Party player2 = new Party() { PartyId = 2 };
Competition competition = fakeProvider.CreateCompetition("test").Result;
competition.Matches = new List<Match>() { BowlingTestUtility.CreateSampleMatch(1, new DateTime(), new List<Party>() { player1, player2 }, competition) };
BowlingSystem sut = new BowlingSystem(fakeProvider);
//Act
Party result = sut.GetCompetitionWinner(1).Result;
//Assert
Assert.Same(player2, result);
}
[Fact]
public void GetVacantLanesProperly()
{
//Assemble
IBowlingRepository fakeProvider = new FakeBowlingRepository();
BowlingSystem sut = new BowlingSystem(fakeProvider);
DateTime start = new DateTime(1994, 01, 01, 12, 00, 00);
DateTime end = new DateTime(1994, 01, 01, 13, 00, 00);
TimePeriod bookedTime = new TimePeriod() { StartTime = start, EndTime = end };
Lane aaa = new Lane() { LaneId = 1, Name = "aaa", LaneTimePeriods = new List<LaneTimePeriod>() {
new LaneTimePeriod() { TimePeriod = bookedTime }
}};
Lane bbb = new Lane() { LaneId = 1, Name = "bbb", LaneTimePeriods = new List<LaneTimePeriod>() };
Lane ccc = new Lane() { LaneId = 1, Name = "ccc", LaneTimePeriods = new List<LaneTimePeriod>() };
fakeProvider.AddLane(aaa);
fakeProvider.AddLane(bbb);
fakeProvider.AddLane(ccc);
//Act
ICollection<Lane> result = sut.GetVacantLanes(start, end).Result;
//Assert
Assert.True(result.Count == 2);
}
[Fact]
public void CanBookLane()
{
//Assemble
IBowlingRepository fakeProvider = new FakeBowlingRepository();
BowlingSystem sut = new BowlingSystem(fakeProvider);
DateTime start = new DateTime(1994, 01, 01, 12, 00, 00);
DateTime end = new DateTime(1994, 01, 01, 13, 00, 00);
TimePeriod bookedTime = new TimePeriod() { StartTime = start, EndTime = end };
Lane aaa = new Lane()
{
LaneId = 1,
Name = "aaa",
LaneTimePeriods = new List<LaneTimePeriod>()
{
new LaneTimePeriod() { TimePeriod = bookedTime }
}
};
Lane bbb = new Lane() { LaneId = 2, Name = "bbb", LaneTimePeriods = new List<LaneTimePeriod>() };
fakeProvider.AddLane(aaa);
fakeProvider.AddLane(bbb);
//Act & assert
Assert.False(sut.BookLane(1, start, end).Result);
Assert.False(sut.BookLane(1, start.AddHours(-1), end).Result);
Assert.True(sut.BookLane(1, new DateTime(), new DateTime()).Result);
Assert.True(sut.BookLane(2, start, end).Result);
}
}
}
<file_sep>using AccountabilityLib.Interfaces;
using AccountabilityLib.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace BowlingLib.Services
{
public class PartySystem
{
private readonly IPartyRepository _partyRepository;
private readonly string _accountabilityOrigin;
public PartySystem(IPartyRepository partyRepository, string accountabilityOrigin)
{
_partyRepository = partyRepository;
_accountabilityOrigin = accountabilityOrigin;
}
public async Task<Party> RegisterNewPlayer(string name, string legalId)
{
Party newPlayer = await _partyRepository.CreateParty(name, legalId);
Party origin = await _partyRepository.GetParty(_accountabilityOrigin);
AccountabilityType type = await _partyRepository.GetAccountabilityType("Customer");
if (type != null && origin != null)
{
await _partyRepository.CreateAccountability(newPlayer, origin, type);
return newPlayer;
}
else
{
throw new NullReferenceException();
}
}
}
}
<file_sep>using AccountabilityLib.Models;
using BowlingLib.Models;
using Microsoft.EntityFrameworkCore;
namespace BowlingDbLib
{
public class BowlingDbContext : DbContext
{
public virtual DbSet<Accountability> Accountabilities { get; set; }
public virtual DbSet<AccountabilityType> AccountabilityTypes { get; set; }
public virtual DbSet<Competition> Competitions { get; set; }
public virtual DbSet<Lane> Lanes { get; set; }
public virtual DbSet<Match> Matches { get; set; }
public virtual DbSet<Party> Parties { get; set; }
public virtual DbSet<Round> Rounds { get; set; }
public virtual DbSet<Series> Series { get; set; }
public virtual DbSet<TimePeriod> TimePeriods { get; set; }
public BowlingDbContext(DbContextOptions<BowlingDbContext> options) : base(options)
{ }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Accountability>().HasKey(a => new { a.AccountabilityTypeId, a.CommissionerId, a.ResponsibleId });
builder.Entity<Accountability>().HasOne(a => a.Commissioner)
.WithMany(r => r.Commissions)
.HasForeignKey(a => a.CommissionerId);
builder.Entity<Accountability>().HasOne(a => a.Responsible)
.WithMany(r => r.Responsibilities)
.HasForeignKey(a => a.ResponsibleId);
builder.Entity<LaneTimePeriod>().HasKey(ltp => new { ltp.LaneId, ltp.TimePeriodId });
builder.Entity<LaneTimePeriod>().HasOne(ltp => ltp.Lane)
.WithMany(l => l.LaneTimePeriods)
.HasForeignKey(ltp => ltp.LaneId);
}
}
}<file_sep>using System;
namespace AccountabilityLib.Models
{
public class Accountability
{
public int CommissionerId { get; set; }
public int ResponsibleId { get; set; }
public int AccountabilityTypeId { get; set; }
public int? TimePeriodId { get; set; }
public Party Commissioner { get; set; }
public Party Responsible { get; set; }
public AccountabilityType AccountabilityType { get; set; }
public TimePeriod TimePeriod { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace AccountabilityLib.Models
{
public class Party
{
public int PartyId { get; set; }
public string Name { get; set; }
public string LegalId { get; set; }
public ICollection<Accountability> Commissions { get; set; }
public ICollection<Accountability> Responsibilities { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace BowlingLib.Models
{
public class Round
{
public int RoundId { get; set; }
public int MatchId { get; set; }
public int LaneId { get; set; }
public ICollection<Series> Series { get; set; }
public Match Match { get; set; }
public Lane Lane { get; set; }
}
}
<file_sep>using AccountabilityLib.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace BowlingLib.Models
{
public class Series
{
public int SeriesId { get; set; }
public short Score { get; set; }
public int RoundId { get; set; }
public int PlayerId { get; set; }
public Round Round { get; set; }
public Party Player { get; set; }
}
}
<file_sep>using AccountabilityLib.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace BowlingLib.Models
{
public class LaneTimePeriod
{
public int LaneId { get; set; }
public int TimePeriodId { get; set; }
public Lane Lane { get; set; }
[ForeignKey(nameof(TimePeriodId))]
public TimePeriod TimePeriod { get; set; }
}
}
<file_sep>using AccountabilityLib.Models;
using BowlingLib.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
using System;
namespace BowlingLib.Interfaces
{
public interface IBowlingRepository
{
Task<Competition> GetCompetition(int competitionId);
Task<Match> GetMatch(int matchId);
Task<ICollection<Match>> GetMatchesByYear(int year);
Task<Round> GetRound(int roundId);
Task<Series> GetSeries(int seriesId);
Task<ICollection<Lane>> GetAllLanes();
Task<Lane> GetLane(int laneId);
Task<TimePeriod> GetTimePeriod(DateTime startTime, DateTime endTime);
Task<Competition> CreateCompetition(string name);
Task<Match> CreateEmptyMatch();
Task<Match> AddMatch(Match match);
Task AddLane(Lane lane);
Task<Round> CreateRound(Match match);
Task<Lane> CreateLane(string name);
Task UpdateSeries(Series series);
Task UpdateLane(Lane lane);
}
}
<file_sep>using AccountabilityLib.Models;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace AccountabilityLib.Interfaces
{
public interface IPartyRepository
{
Task<Party> GetParty(string legalId);
Task<Party> GetParty(int partyId);
Task<Party> CreateParty(string name, string legalId);
Task<AccountabilityType> CreateAccountabilityType(string name);
Task CreateAccountability(Party commissioner, Party responsible, AccountabilityType type, DateTime? start = null, DateTime? end = null);
Task<TimePeriod> GetTimePeriod(int timePeriodId);
Task<TimePeriod> SearchForPeriod(DateTime startTime, DateTime endTime);
Task<AccountabilityType> GetAccountabilityType(string name);
Task<ICollection<Party>> GetCommissioners(Party responsible, AccountabilityType type);
Task<ICollection<Party>> GetResponsible(Party commissioner, AccountabilityType type);
Task<ICollection<Party>> GetAllParties();
}
}
<file_sep>using System.ComponentModel.DataAnnotations;
namespace AccountabilityLib.Models
{
public class AccountabilityType
{
public int AccountabilityTypeId { get; set; }
[Required]
public string Description { get; set; }
}
}<file_sep>using AccountabilityLib.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace BowlingLib.Models
{
internal class PlayerWinLossContainer
{
internal Party Player { get; set; }
internal int Wins { get; set; }
internal int Losses { get; set; }
internal double WinPercentage {
get {
return ((double)Wins / (Wins + Losses)) * 100;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace BowlingLib.Models
{
public class Match
{
public int MatchId { get; set; }
public int? CompetitionId { get; set; }
public DateTime PlayedOn { get; set; }
public Competition Competition { get; set; }
public ICollection<Round> Rounds { get; set; }
}
}
<file_sep>using BowlingLib.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
using BowlingLib.Models;
using System.Threading.Tasks;
using System.Linq;
using AccountabilityLib.Models;
namespace BowlingUnitTestsLib.Repositories
{
public class FakeBowlingRepository : IBowlingRepository
{
private List<Match> _matches { get; set; } = new List<Match>();
private List<Competition> _competitions { get; set; } = new List<Competition>();
private List<Lane> _lanes { get; set; } = new List<Lane>();
private List<TimePeriod> _timePeriods { get; set; } = new List<TimePeriod>();
public Task AddLane(Lane lane)
{
_lanes.Add(lane);
return Task.CompletedTask;
}
public async Task<Match> AddMatch(Match match)
{
_matches.Add(match);
return await Task.FromResult(match);
}
public Task<Competition> CreateCompetition(string name)
{
int id = 1;
if (_competitions.Any())
id = _competitions.OrderByDescending(x => x.CompetitionId).First().CompetitionId + 1;
Competition retVal = new Competition() { Name = name, CompetitionId = id };
_competitions.Add(retVal);
return Task.FromResult(retVal);
}
public Task<Match> CreateEmptyMatch()
{
throw new NotImplementedException();
}
public Task<Lane> CreateLane(string name)
{
Lane newLane = new Lane() { LaneId = 1, Name = name };
Lane previousTopId = _lanes.OrderByDescending(x => x.LaneId).FirstOrDefault();
if (previousTopId != null)
newLane.LaneId = previousTopId.LaneId + 1;
return Task.FromResult(newLane);
}
public Task<Round> CreateRound(Match match)
{
throw new NotImplementedException();
}
public Task<ICollection<Lane>> GetAllLanes()
{
return Task.FromResult((ICollection<Lane>)_lanes);
}
public Task<Competition> GetCompetition(int competitionId)
{
return Task.FromResult(_competitions.FirstOrDefault(x => x.CompetitionId == competitionId));
}
public Task<Lane> GetLane(int laneId)
{
return Task.FromResult(_lanes.SingleOrDefault(x => x.LaneId == laneId));
}
public async Task<Match> GetMatch(int matchId)
{
return await Task.FromResult(_matches.SingleOrDefault(x => x.MatchId == matchId));
}
public async Task<ICollection<Match>> GetMatchesByYear(int year)
{
return await Task.FromResult(_matches.Where(x => x.PlayedOn.Year == year).ToList());
}
public Task<Round> GetRound(int roundId)
{
throw new NotImplementedException();
}
public Task<Series> GetSeries(int seriesId)
{
foreach (Match match in _matches)
{
Round round = match.Rounds.SingleOrDefault(x => x.Series.Any(y => y.SeriesId == seriesId));
if (round != null)
{
return Task.FromResult(round.Series.SingleOrDefault(x => x.SeriesId == seriesId));
}
}
return Task.FromResult<Series>(null);
}
public Task<TimePeriod> GetTimePeriod(DateTime startTime, DateTime endTime)
{
return Task.FromResult(_timePeriods.SingleOrDefault(x => x.StartTime == startTime && x.EndTime == endTime));
}
public Task UpdateLane(Lane lane)
{
return Task.CompletedTask;
}
public Task UpdateSeries(Series series)
{
return Task.CompletedTask;
}
}
}
<file_sep>using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace BowlingLib.Models
{
public class Lane
{
public int LaneId { get; set; }
[Required]
public string Name { get; set; }
public ICollection<LaneTimePeriod> LaneTimePeriods { get; set; }
}
}
<file_sep>using AccountabilityLib.Models;
using BowlingDbLib;
using BowlingLib.Models;
using BowlingLib.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
using Xunit.Abstractions;
namespace BowlingIntegrationTestsLib
{
public class BowlingSystemTests
{
private string _inMemoryDbName {
get { return "BowlingSystemTestsDb"; }
}
[Fact]
public void CanCreateDrawScenarioFromScratch()
{
using (BowlingDbContext context = new BowlingDbContextFactory().CreateInMemoryDbContext(_inMemoryDbName))
{
//Assemble
SqlPartyRepository partyRepository = new SqlPartyRepository(context);
SqlBowlingRepository bowlingRepository = new SqlBowlingRepository(context);
BowlingSystem bowlingService = new BowlingSystem(bowlingRepository);
List<Party> players = new List<Party>
{
partyRepository.CreateParty("aaa", "AAA").Result,
partyRepository.CreateParty("bbb", "BBB").Result
};
List<Lane> lanes = new List<Lane>
{
bowlingRepository.CreateLane("Lane A1").Result
};
Competition competition = bowlingRepository.CreateCompetition("The incredible pin smackdown!").Result;
//Act
Match match1 = bowlingService.CreateStandardMatch(players, lanes, new DateTime(), competition).Result;
Match match2 = bowlingService.CreateStandardMatch(players, lanes, new DateTime(), competition).Result;
short matchScore = 0;
foreach (Round round in match1.Rounds) //player bbb wins
{
for (int i = 0; i < round.Series.Count; i++)
{
bowlingService.RegisterScores(round.Series.ElementAt(i).SeriesId, matchScore).Wait();
matchScore++;
}
}
matchScore = 5000;
foreach (Round round in match2.Rounds) //player aaa wins
{
for (int i = 0; i < round.Series.Count; i++)
{
bowlingService.RegisterScores(round.Series.ElementAt(i).SeriesId, matchScore).Wait();
matchScore--;
}
}
Party winner1 = bowlingService.GetMatchWinner(match1.MatchId).Result;
Party winner2 = bowlingService.GetMatchWinner(match2.MatchId).Result;
Party competitionWinner = bowlingService.GetCompetitionWinner(competition.CompetitionId).Result;
//Assert
Assert.Equal(players[1].Name, winner1.Name);
Assert.Equal(players[0].Name, winner2.Name);
Assert.Null(competitionWinner);
}
}
}
}
<file_sep>using AccountabilityLib.Interfaces;
using AccountabilityLib.Models;
using BowlingLib.Services;
using BowlingUnitTestsLib.Repositories;
using Xunit;
namespace BowlingUnitTestsLib
{
public class PartySystemTests
{
private string _accountabilityOrigin {
get { return "bengansLegalId"; }
}
[Fact]
public void PlayerRegistrationAccountabilityWorks()
{
//Assemble
IPartyRepository fakeProvider = new FakePartyRepository();
fakeProvider.CreateAccountabilityType("Customer");
Party origin = fakeProvider.CreateParty("Bengan", _accountabilityOrigin).Result;
PartySystem sut = new PartySystem(fakeProvider, _accountabilityOrigin);
//Act
Party result = sut.RegisterNewPlayer("aaa", "AAA").Result;
//Assert
Assert.True(origin.Commissions.Count == 0);
Assert.True(origin.Responsibilities.Count == 1);
Assert.True(result.Commissions.Count == 1);
Assert.True(result.Responsibilities.Count == 0);
}
}
}
<file_sep>using BowlingLib.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
using AccountabilityLib.Models;
using BowlingLib.Models;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.EntityFrameworkCore;
namespace BowlingDbLib
{
public class SqlBowlingRepository : IBowlingRepository
{
private readonly BowlingDbContext _context;
public SqlBowlingRepository(BowlingDbContext context)
{
_context = context;
}
public async Task<Competition> CreateCompetition(string name)
{
Competition competition = new Competition() { Name = name, Matches = new List<Match>() };
_context.Competitions.Add(competition);
await _context.SaveChangesAsync();
return competition;
}
public async Task<Match> AddMatch(Match match)
{
_context.Matches.Add(match);
await _context.SaveChangesAsync();
return match;
}
public Task<Round> CreateRound(Match match)
{
throw new NotImplementedException();
}
public async Task<ICollection<Lane>> GetAllLanes()
{
return await _context.Lanes
.Include(x => x.LaneTimePeriods)
.ThenInclude(x => x.TimePeriod)
.ToListAsync();
}
public async Task<Competition> GetCompetition(int competitionId)
{
return await _context.Competitions
.Include(x => x.Matches)
.ThenInclude(x => x.Rounds)
.ThenInclude(x => x.Series)
.ThenInclude(x => x.Player)
.SingleOrDefaultAsync(x => x.CompetitionId == competitionId);
}
public async Task<Lane> GetLane(int laneId)
{
return await _context.Lanes
.Include(x => x.LaneTimePeriods)
.ThenInclude(x => x.TimePeriod)
.SingleOrDefaultAsync(x => x.LaneId == laneId);
}
public async Task<Match> GetMatch(int matchId)
{
return await _context.Matches
.Include(x => x.Competition)
.Include(x => x.Rounds)
.ThenInclude(x => x.Series)
.ThenInclude(x => x.Player)
.SingleOrDefaultAsync(x => x.MatchId == matchId);
}
public async Task<Round> GetRound(int roundId)
{
return await _context.Rounds
.Include(x => x.Series)
.ThenInclude(x => x.Player)
.Include(x => x.Match)
.SingleOrDefaultAsync(x => x.RoundId == roundId);
}
public async Task<Series> GetSeries(int seriesId)
{
return await _context.Series.SingleOrDefaultAsync(x => x.SeriesId == seriesId);
}
public async Task<Match> CreateEmptyMatch()
{
Match match = new Match();
_context.Matches.Add(match);
await _context.SaveChangesAsync();
return match;
}
public async Task<ICollection<Match>> GetMatchesByYear(int year)
{
return await _context.Matches
.Include(x => x.Competition)
.Include(x => x.Rounds)
.ThenInclude(x => x.Series)
.ThenInclude(x => x.Player)
.Where(x => x.PlayedOn.Year == year).ToListAsync();
}
public async Task<Lane> CreateLane(string name)
{
Lane lane = new Lane() { Name = name };
_context.Lanes.Add(lane);
await _context.SaveChangesAsync();
return lane;
}
public async Task UpdateSeries(Series series)
{
_context.Series.Update(series);
await _context.SaveChangesAsync();
}
public async Task<TimePeriod> GetTimePeriod(DateTime startTime, DateTime endTime)
{
return await _context.TimePeriods.SingleOrDefaultAsync(x => x.StartTime == startTime && x.EndTime == endTime);
}
public async Task UpdateLane(Lane lane)
{
_context.Lanes.Update(lane);
await _context.SaveChangesAsync();
}
public Task AddLane(Lane lane)
{
throw new NotImplementedException();
}
}
}
<file_sep>using AccountabilityLib.Models;
using BowlingLib.Interfaces;
using BowlingLib.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BowlingLib.Services
{
public class BowlingSystem
{
private readonly IBowlingRepository _bowlingRepository;
public BowlingSystem(IBowlingRepository bowlingRepository)
{
_bowlingRepository = bowlingRepository;
}
public async Task<Match> CreateStandardMatch(ICollection<Party> players, ICollection<Lane> lanes, DateTime timeToPlayOn, Competition competition = null)
{
if (players.Count < 1 || lanes.Count < 1)
return null;
List<Round> allRounds = new List<Round>();
for (int i = 0; i < 3; i++)
{
List<Round> rounds = new List<Round>();
foreach (var lane in lanes)
{
rounds.Add(new Round() { Lane = lane, Series = new List<Series>() });
}
//add players to lanes
int roundIndex = 0;
foreach (Party player in players)
{
rounds[roundIndex].Series.Add(new Series() { Player = player });
roundIndex++;
if (roundIndex >= rounds.Count)
roundIndex = 0;
}
allRounds.AddRange(rounds);
}
Match retVal = new Match() { Rounds = allRounds.Where(x => x.Series.Any()).ToList(), PlayedOn = timeToPlayOn, Competition = competition };
return await _bowlingRepository.AddMatch(retVal);
}
public async Task<Party> GetMatchWinner(int matchId)
{
Match match = await _bowlingRepository.GetMatch(matchId);
List<Series> allSeries = new List<Series>();
foreach (Round round in match.Rounds)
allSeries.AddRange(round.Series);
return allSeries.GroupBy(x => x.Player).OrderByDescending(x => x.Sum(y => y.Score)).FirstOrDefault().Key;
}
public Party GetMatchWinner(Match match)
{
List<Series> allSeries = new List<Series>();
foreach (Round round in match.Rounds)
allSeries.AddRange(round.Series);
return allSeries.GroupBy(x => x.Player).OrderByDescending(x => x.Sum(y => y.Score)).FirstOrDefault().Key;
}
public async Task<Party> GetCompetitionWinner(int competitionId)
{
Competition competition = await _bowlingRepository.GetCompetition(competitionId);
Dictionary<Party, int> winners = new Dictionary<Party, int>();
foreach (Match match in competition.Matches)
{
Party winner = GetMatchWinner(match);
Party winnerExists = winners.FirstOrDefault(x => x.Key == winner).Key;
if (winnerExists != null)
winners[winnerExists]++;
else
winners.Add(winner, 1);
}
//if it's a draw, return null
if (winners.Count(x => x.Value == winners.Max(y => y.Value)) > 1)
return null;
return winners.OrderByDescending(x => x.Value).FirstOrDefault().Key;
}
public async Task<Party> GetWinCountChampionOfYear(int year)
{
ICollection<Match> matches = await _bowlingRepository.GetMatchesByYear(year);
List<Party> winners = new List<Party>();
foreach (Match match in matches)
{
winners.Add(GetMatchWinner(match));
}
return winners.GroupBy(x => x)
.Select(x => new { Value = x.Key, Count = x.Count() })
.OrderByDescending(x => x.Count)
.FirstOrDefault().Value;
}
public async Task<Party> GetWinRateChampionOfYear(int year)
{
ICollection<Match> matches = await _bowlingRepository.GetMatchesByYear(year);
List<PlayerWinLossContainer> winRatios = new List<PlayerWinLossContainer>();
foreach (Match match in matches)
{
//match winner
Party winner = GetMatchWinner(match);
PlayerWinLossContainer winRatio = winRatios.FirstOrDefault(x => x.Player == winner);
if (winRatio != null)
winRatio.Wins++;
else
winRatios.Add(new PlayerWinLossContainer() { Player = winner, Wins = 1, Losses = 0 });
//match losers
List<Party> matchLosers = new List<Party>();
foreach (Round round in match.Rounds)
{
foreach (Series series in round.Series)
if (series.Player != winner && !matchLosers.Contains(series.Player))
matchLosers.Add(series.Player);
}
foreach (Party loser in matchLosers)
{
PlayerWinLossContainer loserWinRatio = winRatios.FirstOrDefault(x => x.Player == loser);
if (loserWinRatio != null)
loserWinRatio.Losses++;
else
winRatios.Add(new PlayerWinLossContainer() { Player = loser, Wins = 0, Losses = 1 });
}
}
return winRatios.OrderByDescending(x => x.WinPercentage).FirstOrDefault()?.Player;
}
public async Task RegisterScores(int seriesId, short score)
{
Series series = await _bowlingRepository.GetSeries(seriesId);
series.Score = score;
await _bowlingRepository.UpdateSeries(series);
}
public async Task<ICollection<Lane>> GetVacantLanes(DateTime startTime, DateTime endTime)
{
ICollection<Lane> allLanes = await _bowlingRepository.GetAllLanes();
return allLanes.Where(x =>
!x.LaneTimePeriods.Any(y
=> y.TimePeriod.StartTime <= startTime
&& y.TimePeriod.EndTime >= endTime)).ToList();
}
public async Task<bool> BookLane(int laneId, DateTime startTime, DateTime endTime)
{
Lane lane = await _bowlingRepository.GetLane(laneId);
if (lane != null && !lane.LaneTimePeriods.Any(y => y.TimePeriod.StartTime >= startTime && y.TimePeriod.EndTime <= endTime))
{
TimePeriod timePeriod = await _bowlingRepository.GetTimePeriod(startTime, endTime);
if (timePeriod == null)
timePeriod = new TimePeriod() { StartTime = startTime, EndTime = endTime };
lane.LaneTimePeriods.Add(new LaneTimePeriod() { TimePeriod = timePeriod });
await _bowlingRepository.UpdateLane(lane);
return true;
}
return false;
}
}
}
<file_sep>using System;
namespace AccountabilityLib.Models
{
public class TimePeriod
{
public int TimePeriodId { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
}
}<file_sep>using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using System;
using System.Collections.Generic;
using System.Text;
namespace BowlingDbLib
{
public class BowlingDbContextFactory : IDesignTimeDbContextFactory<BowlingDbContext>
{
public BowlingDbContext CreateDbContext(string[] args)
{
var builder = new DbContextOptionsBuilder<BowlingDbContext>()
.UseSqlServer("Server=.\\SQLEXPRESS;Database=BowlingByBengan;Trusted_Connection=True;");
return new BowlingDbContext(builder.Options);
}
public BowlingDbContext CreateInMemoryDbContext(string databaseName)
{
var builder = new DbContextOptionsBuilder<BowlingDbContext>()
.UseInMemoryDatabase(databaseName);
BowlingDbContext context = new BowlingDbContext(builder.Options);
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
return context;
}
}
}
<file_sep>using AccountabilityLib.Interfaces;
using System;
using AccountabilityLib.Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace BowlingDbLib
{
public class SqlPartyRepository : IPartyRepository
{
private readonly BowlingDbContext _context;
public SqlPartyRepository(BowlingDbContext context)
{
_context = context;
}
public async Task CreateAccountability(Party commissioner, Party responsible, AccountabilityType type, DateTime? start = null, DateTime? end = null)
{
if (start == null || end == null)
{
_context.Accountabilities.Add(new Accountability() { Commissioner = commissioner, Responsible = responsible, AccountabilityType = type });
await _context.SaveChangesAsync();
}
else
{
_context.Accountabilities.Add(new Accountability() { Commissioner = commissioner, Responsible = responsible, AccountabilityType = type, TimePeriod = new TimePeriod() { StartTime = (DateTime)start, EndTime = (DateTime)end } });
await _context.SaveChangesAsync();
}
}
public async Task<AccountabilityType> CreateAccountabilityType(string name)
{
AccountabilityType type = await _context.AccountabilityTypes.SingleOrDefaultAsync(x => x.Description == name);
if (type == null)
{
type = new AccountabilityType() { Description = name };
_context.AccountabilityTypes.Add(type);
await _context.SaveChangesAsync();
}
return type;
}
public async Task<Party> CreateParty(string name, string legalId)
{
Party exists = await _context.Parties.SingleOrDefaultAsync(x => x.LegalId == legalId);
if (exists != null)
return exists;
Party newParty = new Party() { Name = name, LegalId = legalId };
_context.Parties.Add(newParty);
await _context.SaveChangesAsync();
return newParty;
}
public async Task<AccountabilityType> GetAccountabilityType(string name)
{
return await _context.AccountabilityTypes.FirstOrDefaultAsync(x => x.Description == name);
}
public async Task<ICollection<Party>> GetAllParties()
{
return await _context.Parties.ToListAsync();
}
public async Task<ICollection<Party>> GetCommissioners(Party responsible, AccountabilityType type)
{
throw new NotImplementedException();
}
public async Task<Party> GetParty(string legalId)
{
return await _context.Parties.SingleOrDefaultAsync(x => x.LegalId == legalId);
}
public async Task<Party> GetParty(int partyId)
{
return await _context.Parties.SingleOrDefaultAsync(x => x.PartyId == partyId);
}
public async Task<ICollection<Party>> GetResponsible(Party commissioner, AccountabilityType type)
{
throw new NotImplementedException();
}
public async Task<TimePeriod> GetTimePeriod(int timePeriodId)
{
return await _context.TimePeriods.SingleOrDefaultAsync(x => x.TimePeriodId == timePeriodId);
}
public async Task<TimePeriod> SearchForPeriod(DateTime startTime, DateTime endTime)
{
return await _context.TimePeriods.Where(x => x.StartTime == startTime && x.EndTime == endTime).FirstOrDefaultAsync();
}
}
}
<file_sep>using AccountabilityLib.Interfaces;
using System;
using System.Collections.Generic;
using AccountabilityLib.Models;
using System.Threading.Tasks;
using System.Linq;
namespace BowlingUnitTestsLib.Repositories
{
public class FakePartyRepository : IPartyRepository
{
private ICollection<Party> _parties = new List<Party>();
private ICollection<AccountabilityType> _accountabilityTypes = new List<AccountabilityType>();
private ICollection<Accountability> _accountability = new List<Accountability>();
public Task CreateAccountability(Party commissioner, Party responsible, AccountabilityType type, DateTime? start = null, DateTime? end = null)
{
Accountability accountability = new Accountability()
{
Commissioner = commissioner,
Responsible = responsible,
AccountabilityType = type
};
commissioner.Commissions.Add(accountability);
responsible.Responsibilities.Add(accountability);
return Task.FromResult(accountability);
}
public Task<AccountabilityType> CreateAccountabilityType(string name)
{
AccountabilityType type = _accountabilityTypes.SingleOrDefault(x => x.Description == name);
if (type != null)
return Task.FromResult(type);
type = new AccountabilityType() { AccountabilityTypeId = 1, Description = name };
AccountabilityType highestAccTypeId = _accountabilityTypes.OrderByDescending(x => x.AccountabilityTypeId).FirstOrDefault();
if (highestAccTypeId != null)
type.AccountabilityTypeId = highestAccTypeId.AccountabilityTypeId + 1;
_accountabilityTypes.Add(type);
return Task.FromResult(type);
}
public Task<Party> CreateParty(string name, string legalId)
{
Party party = new Party() { PartyId = 1, Name = name, LegalId = legalId, Commissions = new List<Accountability>(), Responsibilities = new List<Accountability>() };
Party highestPartyId = _parties.OrderByDescending(x => x.PartyId).FirstOrDefault();
if (highestPartyId != null)
party.PartyId = highestPartyId.PartyId + 1;
_parties.Add(party);
return Task.FromResult(party);
}
public Task<AccountabilityType> GetAccountabilityType(string name)
{
return Task.FromResult(_accountabilityTypes.SingleOrDefault(x => x.Description == name));
}
public Task<ICollection<Party>> GetAllParties()
{
throw new NotImplementedException();
}
public Task<ICollection<Party>> GetCommissioners(Party responsible, AccountabilityType type)
{
throw new NotImplementedException();
}
public Task<Party> GetParty(string legalId)
{
return Task.FromResult(_parties.SingleOrDefault(x => x.LegalId == legalId));
}
public Task<Party> GetParty(int partyId)
{
throw new NotImplementedException();
}
public Task<ICollection<Party>> GetResponsible(Party commissioner, AccountabilityType type)
{
throw new NotImplementedException();
}
public Task<TimePeriod> GetTimePeriod(int timePeriodId)
{
throw new NotImplementedException();
}
public Task<TimePeriod> SearchForPeriod(DateTime startTime, DateTime endTime)
{
throw new NotImplementedException();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace BowlingLib.Models
{
public class Competition
{
public int CompetitionId { get; set; }
public string Name { get; set; }
public ICollection<Match> Matches { get; set; }
}
}
<file_sep>using AccountabilityLib.Interfaces;
using AccountabilityLib.Models;
using BowlingDbLib;
using BowlingLib.Services;
using Xunit;
namespace BowlingIntegrationTestsLib
{
public class SqlPartyRepositoryTests
{
private string _inMemoryDbName {
get { return "SqlPartyRepositoryTestsDb"; }
}
[Fact]
public void CanCreateNewParty()
{
using (BowlingDbContext context = new BowlingDbContextFactory().CreateInMemoryDbContext(_inMemoryDbName))
{
//Assemble
SqlPartyRepository sut = new SqlPartyRepository(context);
//Act
sut.CreateParty("aaa", "AAA").Wait();
//Assert
Assert.NotNull(sut.GetParty("AAA").Result);
}
}
[Fact]
public void CanCreateAndGetPlayers()
{
using (BowlingDbContext context = new BowlingDbContextFactory().CreateInMemoryDbContext(_inMemoryDbName))
{
//Assemble
IPartyRepository partyRepository = new SqlPartyRepository(context);
partyRepository.CreateParty("bengan", "bengansLegalId");
partyRepository.CreateAccountabilityType("Customer");
PartySystem sut = new PartySystem(partyRepository, "bengansLegalId");
//Act
Party result = sut.RegisterNewPlayer("aaa", "AAA").Result;
//Assert
Assert.NotNull(result);
Assert.True(result.Commissions.Count == 1);
}
}
}
}
<file_sep>using AccountabilityLib.Models;
using BowlingLib.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace BowlingUnitTestsLib.Utilities
{
public static class BowlingTestUtility
{
//the last player gets the highest score in every round
public static Match CreateSampleMatch(int matchId, DateTime playedOn, List<Party> players, Competition competition = null)
{
Match match = new Match()
{
MatchId = matchId,
Rounds = new List<Round>()
{
new Round() { Series = new List<Series>() },
new Round() { Series = new List<Series>() }
},
PlayedOn = playedOn,
Competition = competition
};
for (short i = 0; i < players.Count; i++)
{
foreach (Round round in match.Rounds)
round.Series.Add(new Series() { Player = players[i], Score = i });
}
return match;
}
}
}
|
bd22bb23f7cfecfa75407f0db785e639fd3bc61f
|
[
"C#"
] | 26 |
C#
|
aeklundh/bengansbowling
|
0915f790eb21041939899034e1a8517cd893f03f
|
5633d50098d5f22b26edbec39183181842fba34c
|
refs/heads/master
|
<file_sep><?php
namespace Resi\GestionResiBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class AccesoControllerTest extends WebTestCase
{
public function testAcceder()
{
$client = static::createClient();
$crawler = $client->request('GET', '/Acceder');
}
public function testRegistro()
{
$client = static::createClient();
$crawler = $client->request('GET', '/Registro');
}
}
<file_sep><?php
namespace Resi\GestionResiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Usuario
*/
class Usuario
{
/**
* @var integer
*/
private $id;
/**
* @var string
*/
private $dNI;
/**
* @var string
*/
private $nick;
/**
* @var string
*/
private $contrasena;
/**
* @var string
*/
private $nombre;
/**
* @var string
*/
private $apellidos;
/**
* @var string
*/
private $email;
/**
* @var integer
*/
private $telefono;
/**
* @var \DateTime
*
* @ORM\Column(name="fechaRegistro", type="datetime")
*/
private $fechaRegistro;
/**
* Set fechaRegistro
*
* @param \DateTime $fechaRegistro
* @return Usuario
*/
public function setFechaRegistro($fechaRegistro)
{
$this->fechaRegistro = $fechaRegistro;
return $this;
}
/**
* Get fechaRegistro
*
* @return \DateTime
*/
public function getFechaRegistro()
{
return $this->fechaRegistro;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set dNI
*
* @param string $dNI
* @return Usuario
*/
public function setDNI($dNI)
{
$this->dNI = $dNI;
return $this;
}
/**
* Get dNI
*
* @return string
*/
public function getDNI()
{
return $this->dNI;
}
/**
* Set nick
*
* @param string $nick
* @return Usuario
*/
public function setNick($nick)
{
$this->nick = $nick;
return $this;
}
/**
* Get nick
*
* @return string
*/
public function getNick()
{
return $this->nick;
}
/**
* Set contrasena
*
* @param string $contrasena
* @return Usuario
*/
public function setContrasena($contrasena)
{
$this->contrasena = $contrasena;
return $this;
}
/**
* Get contrasena
*
* @return string
*/
public function getContrasena()
{
return $this->contrasena;
}
/**
* Set nombre
*
* @param string $nombre
* @return Usuario
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
return $this;
}
/**
* Get nombre
*
* @return string
*/
public function getNombre()
{
return $this->nombre;
}
/**
* Set apellidos
*
* @param string $apellidos
* @return Usuario
*/
public function setApellidos($apellidos)
{
$this->apellidos = $apellidos;
return $this;
}
/**
* Get apellidos
*
* @return string
*/
public function getApellidos()
{
return $this->apellidos;
}
/**
* Set email
*
* @param string $email
* @return Usuario
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set telefono
*
* @param integer $telefono
* @return Usuario
*/
public function setTelefono($telefono)
{
$this->telefono = $telefono;
return $this;
}
/**
* Get telefono
*
* @return integer
*/
public function getTelefono()
{
return $this->telefono;
}
}
<file_sep><?php
namespace Resi\GestionResiBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Constraints\Regex;
class PerfilController extends Controller{
public function actualizarPerfilAction(Request $req){
$sesion=$req->getSession();
$usu=$sesion->get('usu');
$restricciones = new Collection
(array(
'nombre' => new NotNull(),
'nombre' => new Regex(array( 'pattern'=>"/^[a-zA-Z ]{3,40}$/",
'message'=>"Debe introducir un nombre válido, de 3 a 40 caracteres",
'match'=> true)),
'apellidos' => new NotNull(),
'apellidos' => new Regex(array( 'pattern'=>"/^[a-zA-Z ]{3,40}$/",
'message'=>"Debe introducir unos apellidos válidos, de 3 a 40 caracteres",
'match'=> true)),
'telefono' => new NotNull(),
'telefono' => new Regex(array( 'pattern'=>"/^[0-9]{9}$/",
'message'=>"Debe introducir un número de teléfono válido",
'match'=> true)),
'email' => new NotNull(),
'email' => new Regex(array( 'pattern'=>"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/",
'message'=>"Debe introducir un email válido",
'match'=> true))
)
);
$defaultData = array(
'nombre' => $this->getDoctrine()
->getManager()
->getRepository('GestionResiBundle:Usuario')
->getNombreUser($usu),
'apellidos' => $this->getDoctrine()
->getManager()
->getRepository('GestionResiBundle:Usuario')
->getApellidosUser($usu),
'telefono' => $this->getDoctrine()
->getManager()
->getRepository('GestionResiBundle:Usuario')
->getTelefonoUser($usu),
'email' => $this->getDoctrine()
->getManager()
->getRepository('GestionResiBundle:Usuario')
->getEmailUser($usu),
'dni' => $this->getDoctrine()->getManager()
->getRepository('GestionResiBundle:Usuario')
->getDNIUser($usu)[0]['dNI'],
'nick' => $usu);
$form=$this->createFormBuilder($defaultData, array('constraints'=>$restricciones))
->add('nombre','text', array('label' => 'Nombre: '))
->add('apellidos','text', array('label' => 'Apellidos: '))
->add('telefono','text', array('label' => 'Teléfono: '))
->add('email','email', array('label' => 'Email: '))
->add('dni','text',array('label' => 'DNI: ', 'read_only' => true))
->add('nick','text',array('label' => 'Nickname: ','read_only' => true))
->getForm();
$form->handleRequest($req);
if($form->isValid()&&$form->isSubmitted()){
$qb = $this->getDoctrine()->getManager()->createQueryBuilder();
$q = $qb->update('GestionResiBundle:Usuario', 'u')
->set('u.nombre', '?1')
->set('u.apellidos', '?2')
->set('u.email', '?3')
->set('u.telefono', '?4')
->where('u.nick = ?5')
->setParameter(1, $form->get('nombre')->getData())
->setParameter(2, $form->get('apellidos')->getData())
->setParameter(3, $form->get('email')->getData())
->setParameter(4, $form->get('telefono')->getData())
->setParameter(5, $usu)
->getQuery();
$q->execute();
$this->getDoctrine()->getManager()->flush();
//return $this->redirectToRoute('ver_perfil');//para version 3.2
if($req->getSession()->get('admin')){
return $this->redirect($this->generateUrl('_ver_panel_control'));
}else{
return $this->redirect($this->generateUrl('ver_perfil'));
}
}
return $this->render('GestionResiBundle:Perfil:formUpdate.html.twig',array('form' => $form->createView(),
'admin' => $req->getSession()->get('admin')));
}
public function cambiarContrasenaAction(Request $req){
$sesion=$req->getSession();
$usu=$sesion->get('usu');
$restricciones = new Collection (array('newContrasena' => new NotNull(),
'oldContrasena' => new NotNull(),
'confirmContrasena' => new NotNull(),
'newContrasena' => new Regex(array( 'pattern'=>"/^[a-zA-Z0-9]{4,20}$/",
'message'=>"Debe introducir una contraseña válida, de 4 a 20 caracteres",
'match'=> true))));
$defaultData = null;
$form=$this->createFormBuilder($defaultData, array('constraints'=>$restricciones))
->add('oldContrasena','password', array('label' => '<PASSWORD>: '))
->add('newContrasena','password', array('label' => '<PASSWORD>: '))
->add('confirmContrasena','password', array('label' => 'Confirmar contraseña: '))
->getForm();
$form->handleRequest($req);
$errores = array();
if($form->isValid()&&$form->isSubmitted()){
$errores = $this->getDoctrine()->getRepository("GestionResiBundle:Usuario")->validatePasswordTextErr($form->get("oldContrasena")->getData());
if($form->get("newContrasena")->getData() != $form->get("confirmContrasena")->getData()){
$errores = 'La nueva contraseña y la contraseña de confirmación no coinciden';
}
if($errores == ''){
$qb = $this->getDoctrine()->getManager()->createQueryBuilder();
$q = $qb->update('GestionResiBundle:Usuario', 'u')
->set('u.contrasena', '?1')
->where('u.nick = ?2')
->setParameter(1, $form->get('newContrasena')->getData())
->setParameter(2, $usu)
->getQuery();
$q->execute();
$this->getDoctrine()->getManager()->flush();
if($req->getSession()->get('admin')){
return $this->redirect($this->generateUrl('_ver_panel_control'));
}else{
return $this->redirect($this->generateUrl('ver_perfil'));
}
}
}
return $this->render('GestionResiBundle:Perfil:formUpdatePass.html.twig',array('form'=>$form->createView(), 'errs'=>$errores,'admin'=>$req->getSession()->get('admin')));
}
public function verPerfilAction(Request $req){
$sesion=$req->getSession();
$usu=$sesion->get('usu');
if(!$sesion->isStarted()){
return $this->render('GestionResiBundle:Default:index.html.twig',
array('sesionIniciado'=>'No ha iniciado sesion.','userNotFound'=>null));
}else{
$usu=$sesion->get('usu');
return $this->render('GestionResiBundle:Perfil:verPerfil.html.twig',
array('user'=>$this->getDoctrine()
->getManager()
->getRepository('GestionResiBundle:Usuario')
->findByUserSinId($usu)));
}
}
public function verHistorialHabitacionesAction(Request $req){
$usu=$req->getSession()->get('usu');
return $this->render('GestionResiBundle:Perfil:verHistorialHabitaciones.html.twig',
array('habitaciones'=>$this->getDoctrine()
->getManager()
->getRepository('GestionResiBundle:Usuario')
->findHabitacionesUsuario($usu),
'usu'=>$this->getDoctrine()
->getRepository('GestionResiBundle:Usuario')
->findByUserSinId($usu),
'hoy'=> localtime()));
}
public function mostrarPagoPendienteAction(Request $req){
$usu=$req->getSession()->get('usu');
return $this->render('GestionResiBundle:Perfil:mostrarPagoPendiente.html.twig',
array('pagos'=>$this->getDoctrine()
->getManager()
->getRepository('GestionResiBundle:Usuario')
->findFacturasNoPagadas($usu),
'usu'=>$this->getDoctrine()
->getManager()
->getRepository('GestionResiBundle:Usuario')
->findByUserSinId($usu),
'hoy'=> localtime()));
}
public function verPanelDeControlAction(Request $req){
$usu=$req->getSession()->get('usu');
if((!$req->getSession()->isStarted()) || ($usu == null)){
return $this->render('GestionResiBundle:Default:index.html.twig',
array('sesionIniciado'=>'No ha iniciado sesion.','userNotFound'=>null));
}else{
return $this->render('GestionResiBundle:GestionAdmin:controlPanel.html.twig',
array('user'=>$this->getDoctrine()
->getManager()
->getRepository('GestionResiBundle:Usuario')
->findByUserSinId($usu)));
}
}
}
<file_sep><?php
namespace Resi\GestionResiBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* UsuarioRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class UsuarioRepository extends EntityRepository{
public function usernameExists($username){
//Manjeador
$usuario = $this->getEntityManager()
->createQueryBuilder()
->select('u.nick')
->from('GestionResiBundle:Usuario', 'u')
->where('u.nick = :username')
->setParameter('username', $username)
->getQuery()
->getResult();
if($usuario != null){
return true;
}
return false;
}
public function checkSimilarDNI($dni)
{
$usuario = $this->getEntityManager()
->createQueryBuilder()
->select('u.dNI')
->from('GestionResiBundle:Usuario', 'u')
->where('u.dNI = :dni')
->setParameter('dni', $dni)
->getQuery()
->getResult();
if($usuario != null)
{
return true; //ya existe un usuario registrado con ese dni!
}
return false;
}
public function getNombreUser($usu){
//Manjeador
$manejador = $this->getEntityManager();
$dql = "SELECT u.nombre "
. " FROM GestionResiBundle:Usuario u "
. " WHERE u.nick = :username";
$query = $manejador->createQuery($dql);
$query->setParameter('username', $usu);
$nombre = "";
foreach($query->getResult() as $array){
foreach($array as $params){
$nombre = $params;
}
}
return $nombre;
}
public function getApellidosUser($usu){
//Manjeador
$manejador = $this->getEntityManager();
$dql = "SELECT u.apellidos "
. " FROM GestionResiBundle:Usuario u "
. " WHERE u.nick = :username";
$query = $manejador->createQuery($dql);
$query->setParameter('username', $usu);
$apellidos = "";
foreach($query->getResult() as $array){
foreach($array as $params){
$apellidos = $params;
}
}
return $apellidos;
}
public function getEmailUser($usu){
//Manjeador
$manejador = $this->getEntityManager();
$dql = "SELECT u.email "
. " FROM GestionResiBundle:Usuario u "
. " WHERE u.nick = :username";
$query = $manejador->createQuery($dql);
$query->setParameter('username', $usu);
$email = "";
foreach($query->getResult() as $array){
foreach($array as $params){
$email = $params;
}
}
return $email;
}
public function getTelefonoUser($usu){
//Manjeador
$manejador = $this->getEntityManager();
$dql = "SELECT u.telefono "
. " FROM GestionResiBundle:Usuario u "
. " WHERE u.nick = :username";
$query = $manejador->createQuery($dql);
$query->setParameter('username', $usu);
$tlf = "";
foreach($query->getResult() as $array){
foreach($array as $params){
$tlf = $params;
}
}
return $tlf;
}
public function getDNIUser($usu){
return $this->getEntityManager()->createQueryBuilder()
->select("u.dNI")
->from("GestionResiBundle:Usuario","u")
->where("u.nick = :n")
->setParameter("n", $usu)
->getQuery()
->getResult();
}
public function validatePasswordTextErr($formPass){
//Manjeador
$usuario = $this->getEntityManager()
->createQueryBuilder()
->select('u.nick')
->from('GestionResiBundle:Usuario', 'u')
->where('u.contrasena = :formPass')
->setParameter('formPass', $formPass)
->getQuery()
->getResult();
if($usuario != null){
return null;
}
return 'Contraseña antigua incorrecta';
}
public function validatePassword($formPass){
//Manjeador
$usuario = $this->getEntityManager()
->createQueryBuilder()
->select('u.nick')
->from('GestionResiBundle:Usuario', 'u')
->where('u.contrasena = :formPass')
->setParameter('formPass', $formPass)
->getQuery()
->getResult();
if($usuario != null){
return true;
}
return false;
}
public function findByUserSinId($user){
return $this->getEntityManager()
->createQueryBuilder()
->select('u.nombre,u.apellidos,u.dNI,u.nick,u.email,u.telefono,u.fechaRegistro')
->from('GestionResiBundle:Usuario', 'u')
->where('u.nick =:user')
->setParameter('user', $user)
->getQuery()
->getResult();
}
public function findUserByDNI($dni){
return $this->getEntityManager()
->createQueryBuilder()
->select('u.nombre,u.contrasena,u.apellidos,u.nick,u.email,u.telefono,u.fechaRegistro')
->from('GestionResiBundle:Usuario', 'u')
->where('u.dNI =:lul')
->setParameter('lul', $dni)
->getQuery()
->getResult();
}
public function findAllSinId(){
return $this->getEntityManager()
->createQueryBuilder()
->select('u.nombre,u.apellidos,u.dNI,u.nick,u.email,u.telefono')
->from('GestionResiBundle:Usuario', 'u')
->getQuery()
->getResult();
}
public function findUsuarioNoArray($username){
//Manjeador
$manejador = $this->getEntityManager();
$dql = "SELECT u.nombre, u.apellidos, u.dNI, u.nick, u.email, u.telefono "
. " FROM GestionResiBundle:Usuario u "
. " WHERE u.nick = :username";
$query = $manejador->createQuery($dql);
$query->setParameter('username', $username);
return $query->getResult();
}
public function findHabitacionesUsuario($user){
$qb2=$this->getEntityManager()
->createQueryBuilder()->select('u.dNI')
->from('GestionResiBundle:Usuario', 'u')
->where('u.nick = :user')
->setParameter('user',$user)
->getQuery()->getResult();
//var_dump($qb2);
$qb1=$this->getEntityManager()
->createQueryBuilder()->select('co.CodHabitacion')
->from('GestionResiBundle:Contrato', 'co')
->where('co.DNIResidente = :d')
->setParameter('d',$qb2)
->getQuery()->getResult();
if($qb1 != null)
{
$glue=$qb1[0]["CodHabitacion"];
if(sizeof($qb1)>=1){
for ($i=1;$i<sizeof($qb1);$i++){
$glue=$glue.",".strval($qb1[$i]["CodHabitacion"]);
}
}
if($qb1==null){return null;
}else{ $qb=$this->getEntityManager()->createQueryBuilder();
return $qb->select('h.CodHabitacion,h.Descripcion,h.TipoHabitacion,h.TarifaMes,co.fechaExpiracion')
->from('GestionResiBundle:Habitacion','h')
->join('GestionResiBundle:Contrato', 'co', 'WITH', 'co.CodHabitacion=h.CodHabitacion')
->where($qb->expr()->in('h.CodHabitacion',$glue))
->getQuery()->getResult();
}
}
}
public function findFacturasNoPagadas($user){
$qb=$this->getEntityManager()->createQueryBuilder()
->select('u.dNI')
->from('GestionResiBundle:Usuario', 'u')
->where('u.nick = :user')
->setParameter('user',$user)
->getQuery()->getResult();
$qb1=$this->getEntityManager()->createQueryBuilder()
->select('co.CodContrato')
->from('GestionResiBundle:Contrato', 'co')
->where('co.DNIResidente = :d')
->setParameter('d',$qb)
->getQuery()->getResult();
if($qb1 != null )
{
$glue=$qb1[0]["CodContrato"];
if(sizeof($qb1)>=1){
for ($i=1;$i<sizeof($qb1);$i++){
$glue=$glue.",".strval($qb1[$i]["CodContrato"]);
}
}
if($qb1==null){return null;
}else{$qb2=$this->getEntityManager()->createQueryBuilder();
return $qb2->select('f.codFactura,f.fechaExpedicion,f.importe,con.CodHabitacion,con.fechaExpiracion')
->from('GestionResiBundle:Factura','f')
->join('GestionResiBundle:Contrato', 'con', 'WITH', 'con.CodContrato=f.codContrato')
->where($qb2->expr()->in('f.codContrato',$glue))
->andWhere($qb2->expr()->isNull('f.fechaPago'))
->getQuery()->getResult();
}
}
}
}<file_sep><?php
namespace Resi\GestionResiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* usuarioadmin
*/
class usuarioadmin
{
/**
* @var integer
*/
private $id;
/**
* @var integer
*/
private $idAdmin;
/**
* @var string
*/
private $dNIUser;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set idAdmin
*
* @param integer $idAdmin
* @return usuarioadmin
*/
public function setIdAdmin($idAdmin)
{
$this->idAdmin = $idAdmin;
return $this;
}
/**
* Get idAdmin
*
* @return integer
*/
public function getIdAdmin()
{
return $this->idAdmin;
}
/**
* Set dNIUser
*
* @param string $dNIUser
* @return usuarioadmin
*/
public function setDNIUser($dNIUser)
{
$this->dNIUser = $dNIUser;
return $this;
}
/**
* Get dNIUser
*
* @return string
*/
public function getDNIUser()
{
return $this->dNIUser;
}
}
<file_sep><?php
namespace Resi\GestionResiBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class FacturasControllerTest extends WebTestCase
{
public function testVerfactura()
{
$client = static::createClient();
$crawler = $client->request('GET', '/verFactura');
}
public function testPagarfactura()
{
$client = static::createClient();
$crawler = $client->request('GET', '/pagarFactura');
}
public function testGenerarfactura()
{
$client = static::createClient();
$crawler = $client->request('GET', '/generarFactura');
}
public function testEnviarnotificacionpago()
{
$client = static::createClient();
$crawler = $client->request('GET', '/enviarNotificacionPago');
}
public function testEnviarmensajefactura()
{
$client = static::createClient();
$crawler = $client->request('GET', '/enviarMensajeFactura');
}
}
<file_sep><?php
namespace Resi\GestionResiBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints\Regex;
use Resi\GestionResiBundle\Entity\Usuario;
class AccesoController extends Controller{
public function AccederAction(Request $peticion){
$sesion=$peticion->getSession();
if($sesion->isStarted()){
return $this->render('GestionResiBundle:Default:index.html.twig',
array('sesionIniciado'=>'Ya ha iniciado sesion.'));
}else{
//Log-in
$restricciones = new Collection(array( 'nombre_usuario' => new NotNull(),
'nombre_usuario' => new Regex(array( 'pattern'=>"/^[a-zA-Z ]{3,20}$/",
'message'=>"Debe introducir un nombre válido, de 3 a 20 caracteres",
'match'=> true)),
'pass' => new NotNull()));
//Creamos el formulario sin objeto Type
$formLogIn = $this->createFormBuilder(array('constraints'=>$restricciones))
->add('nombre_usuario', 'text',array('label'=>'Nombre de usuario'))
->add('pass', 'password', array('label'=>'Contraseña del usuario'))
->getForm();
if($peticion->getMethod() == 'POST'){
$formLogIn->bind($peticion);
if($formLogIn->isValid()){
//Consulta de si existe el usuario introducido como log-in
$manejador = $this->getDoctrine()->getEntityManager();
if($manejador->getRepository("GestionResiBundle:Usuario")
->usernameExists($formLogIn->get("nombre_usuario")->getData())){
//Si el que logea es el administrador
if($manejador->getRepository("GestionResiBundle:usuarioadmin")
->findAdmin($manejador->getRepository("GestionResiBundle:Usuario")
->getDNIUser($formLogIn->get("nombre_usuario")
->getData())))
{
//la contraseña introducida es correcta del administrador
if($manejador->getRepository("GestionResiBundle:Usuario")
->validatePassword($formLogIn->get("pass")->getData()))
{
$peticion->getSession()->start();
//$peticion->getSession()->setName($$formLogIn->get('nombre_usuario')->getData());
$peticion->getSession()->set('usu', $formLogIn->get('nombre_usuario')->getData());
$peticion->getSession()->set('admin', 1);
return $this->redirect($this->generateUrl("_ver_panel_control"));
}
else
{
return $this->render('GestionResiBundle:Acceso:Acceder.html.twig', array('formLogIn' => $formLogIn->createView(), 'userNotFound' => 'Nombre de usuario o contraseña incorrectos'));
}
}else{
if($manejador->getRepository("GestionResiBundle:Usuario")
->validatePassword($formLogIn->get("pass")->getData())){
//El usuario existe, establecemos como variable de sesión
//$this->get('session')->set('loginUserId', $formLogIn->get("nombre_usuario")->getData());
$peticion->getSession()->start();
//$peticion->getSession()->setName($$formLogIn->get('nombre_usuario')->getData());
$peticion->getSession()->set('usu', $formLogIn->get('nombre_usuario')->getData());
return $this->redirect($this->generateUrl("ver_perfil"));
}
}
return $this->render('GestionResiBundle:Acceso:Acceder.html.twig', array('formLogIn' => $formLogIn->createView(), 'userNotFound' => 'Nombre de usuario o contraseña incorrectos'));
}else{
return $this->render('GestionResiBundle:Acceso:Acceder.html.twig', array('formLogIn' => $formLogIn->createView(), 'userNotFound' => 'No existe un usuario con ese nombre'));
}
}
}
}
return $this->render('GestionResiBundle:Acceso:Acceder.html.twig', array('formLogIn' => $formLogIn->createView(), 'userNotFound' => null));
}
public function RegistroAction(Request $req){
//Formulario para dar de alta un usuario
$restricciones = new Collection (array('dni' => new NotNull,
'dni' => new Regex(array( 'pattern'=>"/^[0-9]{8}[a-zA-Z]{1}$/",
'message'=>"Introduzca un DNI válido",
'match'=> true)),
'nick' => new NotNull,
'nick' => new Regex(array( 'pattern'=>"/^[a-zA-Z ]{3,20}$/",
'message'=>"Debe introducir un nombre de usuario válido, de 3 a 20 caracteres",
'match'=> true)),
'contrasena' => new NotNull(),
'contrasena' => new Regex(array( 'pattern'=>"/^[a-zA-Z0-9]{4,20}$/",
'message'=>"Debe introducir una contraseña válida, de 4 a 20 caracteres",
'match'=> true)),
'confirmContrasena' => new NotNull(),
'nombre' => new NotNull(),
'nombre' => new Regex(array( 'pattern'=>"/^[a-zA-Z ]{3,40}$/",
'message'=>"Debe introducir un nombre válido, de 3 a 40 caracteres",
'match'=> true)),
'apellidos' => new NotNull(),
'apellidos' => new Regex(array( 'pattern'=>"/^[a-zA-Z ]{3,40}$/",
'message'=>"Debe introducir unos apellidos válidos, de 3 a 40 caracteres",
'match'=> true)),
'telefono' => new NotNull(),
'telefono' => new Regex(array( 'pattern'=>"/^[0-9]{9}$/",
'message'=>"Debe introducir un número de teléfono válido",
'match'=> true)),
'email' => new NotNull(),
'email' => new Regex(array( 'pattern'=>"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/",
'message'=>"Debe introducir un email válido",
'match'=> true))));
$ususario= new Usuario();
$default = array('dni'=> '');
$form=$this->createFormBuilder($default, array('constraints'=>$restricciones))
->add('dni','text', array('label'=>'DNI del usuario'))
->add('nick','text', array('label'=>'Nombre de usuario'))
->add('contrasena','password', array('label'=>'Contraseña del usuario'))
->add('confirmContrasena','password',array('label'=>'Confirme contraseña'))
->add('nombre','text', array('label'=>'Nombre real de usuario'))
->add('apellidos','text', array('label'=>'Apellidos del usuario'))
->add('telefono','text', array('label'=>'Telefono de usuario'))
->add('email','email', array('label'=>'Correo electronico'))
->getForm();
$form->handleRequest($req);
if($form->isValid()&&$form->isSubmitted()&&!($this->getDoctrine()
->getManager()
->getRepository('GestionResiBundle:Usuario')
->usernameExists($form->get('nick')->getData())))
{
//Comprobamos que no haya un NIF ni username repetido
if($this->getDoctrine()->getRepository("GestionResiBundle:Usuario")->checkSimilarDNI($form->get('dni')->getData()))
{
$default = array('dni'=> 'introduce tu dni');
return $this->render('GestionResiBundle:Acceso:Registro.html.twig',array('formRegistro'=>$form->createView(), 'unconfirmedPass' => 'Este DNI no se encuentra disponible. ¿Ya tiene una cuenta activa?'));
}
//Comprobamos que las contraseñas coinciden:
if($form->get('contrasena')->getData() != $form->get('confirmContrasena')->getData())
{
return $this->render('GestionResiBundle:Acceso:Registro.html.twig',array('formRegistro'=>$form->createView(), 'unconfirmedPass' => 'La contraseña de validación no coincide con la contraseña del usuario'));
}
$ususario->setApellidos($form->get('apellidos')->getData());
$ususario->setNombre($form->get('nombre')->getData());
$ususario->setNick($form->get('nick')->getData());
$ususario->setContrasena($form->get('contrasena')->getData());
$ususario->setDNI($form->get('dni')->getData());
$ususario->setTelefono($form->get('telefono')->getData());
$ususario->setEmail($form->get('email')->getData());
$ususario->setFechaRegistro(new \DateTime());
$em=$this->getDoctrine()->getManager();
$em->getRepository('GestionResiBundle:Usuario');
$em->persist($ususario);
$em->flush();
//return $this->redirectToRoute('ver_perfil');//para version 3.2
//Establecemos la sesión
$this->get('session')->set('usu', $form->get('nick')->getData());
return $this->redirect($this->generateUrl('ver_perfil'));
}
return $this->render('GestionResiBundle:Acceso:Registro.html.twig',array('formRegistro'=>$form->createView()));
}
public function DesconexionAction(Request $req){
$req->getSession()->clear();
return $this->render('GestionResiBundle:Default:index.html.twig',
array('userNotFound'=>'Sesion cerrada correctamente.','sesionIniciado'=>null));
}
}
<file_sep><?php
namespace Resi\GestionResiBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class HabitacionesControllerTest extends WebTestCase
{
public function testVerhabitaciones()
{
$client = static::createClient();
$crawler = $client->request('GET', '/verHabitaciones');
}
public function testAlquilarhabitacion()
{
$client = static::createClient();
$crawler = $client->request('GET', '/alquilarHabitacion');
}
}
<file_sep><?php
namespace Resi\GestionResiBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class PerfilControllerTest extends WebTestCase
{
public function testVerperfil()
{
$client = static::createClient();
$crawler = $client->request('GET', '/verPerfil');
}
public function testVerhistorialhabitaciones()
{
$client = static::createClient();
$crawler = $client->request('GET', '/verHistorialHabitaciones');
}
public function testVerfactura()
{
$client = static::createClient();
$crawler = $client->request('GET', '/verFactura');
}
public function testMostrarpagopendiente()
{
$client = static::createClient();
$crawler = $client->request('GET', '/mostrarPagoPendiente');
}
public function testPagarfactura()
{
$client = static::createClient();
$crawler = $client->request('GET', '/pagarFactura');
}
}
<file_sep><?php
namespace Resi\GestionResiBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class AlquilarHabitacionControllerTest extends WebTestCase
{
}
<file_sep><?php
namespace Resi\GestionResiBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class GestionAdminControllerTest extends WebTestCase
{
public function testGestionarhabitaciones()
{
$client = static::createClient();
$crawler = $client->request('GET', '/gestionarHabitaciones');
}
public function testGestionarfacturas()
{
$client = static::createClient();
$crawler = $client->request('GET', '/gestionarFacturas');
}
public function testGestionarresidentes()
{
$client = static::createClient();
$crawler = $client->request('GET', '/gestionarResidentes');
}
public function testDarbajaresidente()
{
$client = static::createClient();
$crawler = $client->request('GET', '/darBajaResidente');
}
}
<file_sep><?php
namespace Resi\GestionResiBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\HttpFoundation\Request;
use DateTime;
class HabitacionesController extends Controller{
public function verHabitacionesAction(Request $request){
//En caso de que el usuario ya esté en alguna habitación
$usu=$request->getSession()->get('usu');
$restriccionesFecha=new Collection(array(
'fechaIni' => new NotNull(),
'fechaFin' => new NotNull()
)
);
$minDate = date('Y');
$maxDate = date('Y', strtotime('+5 years'));
//echo $maxDate;
$a = array();
$a[] = strtotime($maxDate);
$formFechas=$this->createFormBuilder(array('constraints' => $restriccionesFecha))
->add('fechaIni','date',array('label'=>'Fecha de Entrada: ', 'years' => range($minDate, $maxDate)))
->add('fechaFin','date',array('label'=>'Fecha de Salida: ', 'years' => range($minDate, $maxDate)))
->getForm();
if($request->getMethod()=='POST'){
$formFechas->bind($request);
if($formFechas->isValid()){
if($formFechas->get('fechaIni')->getData()<$formFechas->get('fechaFin')->getData() ){
//La fecha introducida es menor que la de hoy
if($formFechas->get('fechaIni')->getData() < new \DateTime('now')){
return $this->render("GestionResiBundle:Habitaciones:verHabitaciones.html.twig",
array('formFechas' => $formFechas->createView(),
'usu' => $usu,
'fechaFin' => null,
'fechaIni' => null,
'errorFecha' => 2));
}
$request->getSession()->set('fechaIni', $formFechas->get('fechaIni')->getData());
$request->getSession()->set('fechaFin', $formFechas->get('fechaFin')->getData());
//var_dump($habitaciones);
return $this->render('GestionResiBundle:Habitaciones:verHabitaciones.html.twig',array(
'fechaIni' => $formFechas->get('fechaIni')->getData(),
'fechaFin' => $formFechas->get('fechaFin')->getData(),
'habitaciones'=>$this->getDoctrine()
->getManager()
->getRepository("GestionResiBundle:Habitacion")
->findAllSinIdConFechas($formFechas->get('fechaIni')
->getData()),
'usu' => $usu));
}else{
return $this->render("GestionResiBundle:Habitaciones:verHabitaciones.html.twig",
array('formFechas' => $formFechas->createView(),
'usu' => $usu,
'fechaFin' => null,
'fechaIni' => null,
'errorFecha' => 1));
}
}
}else {
return $this->render("GestionResiBundle:Habitaciones:verHabitaciones.html.twig",
array('formFechas' => $formFechas->createView(),
'usu' => $usu,
'fechaFin' => null,
'fechaIni' => null,
'errorFecha' => null));
}
return $this->render("GestionResiBundle:Habitaciones:verHabitaciones.html.twig",
array('formFechas' => $formFechas->createView(),
'usu' => $usu,
'fechaFin' => null,
'fechaIni' => null,
'errorFecha' => null));
}
public function alquilarHabitacionAction($CodHabitacion, Request $request){
$usu=$request->getSession()->get('usu');
if($usu==null){
return $this->render('GestionResiBundle:Default:index.html.twig',
array('sesionIniciado'=>'No ha iniciado sesion.','userNotFound'=>''));
}else{
//Calculamos estancia y precio:
$fechaIni=$request->getSession()->get('fechaIni');
$fechaFin=$request->getSession()->get('fechaFin');
//$numMeses = 0;
//$totalPrice = 0;
if(($fechaIni == null)||($fechaFin == null)||($fechaIni>$fechaFin))
{
echo 'Error de fechas';
}
//echo $fechaIni->format('Y-m-d H:i:s');
$d1 = new DateTime($fechaIni->format('Y-m-d H:i:s'));
$d2 = new DateTime($fechaFin->format('Y-m-d H:i:s'));
//var_dump($d1->diff($d2)->m); // int(4)
$numMeses = ($d1->diff($d2)->m + ($d1->diff($d2)->y*12));
if($numMeses==0){
$numMeses=1;
}
//var_dump($numMeses);
$habitacion = $this->getDoctrine()
->getManager()
->getRepository("GestionResiBundle:Habitacion")
->findHabitacionCod($CodHabitacion);
foreach($habitacion as $hab)
{
//echo $hab['TarifaMes'];
$price = $hab['TarifaMes'];
}
$totalPrice = (int)$numMeses * (int)$price;
$request->getSession()->set('totalPrice', $totalPrice);
//Enviamos a confirmación para el alquiler
return $this->render("GestionResiBundle:Habitaciones:alquilarHabitacion.html.twig",
array('habitacion'=>$this->getDoctrine()
->getManager()
->getRepository("GestionResiBundle:Habitacion")
->findHabitacionCod($CodHabitacion),
'usuario'=>$this->getDoctrine()
->getManager()
->getRepository("GestionResiBundle:Usuario")
->findByUserSinId($usu),
'estanciaIni'=>$fechaIni,
'estanciaFin'=>$fechaFin,
'numMeses'=>$numMeses,
'totalPrice'=>$totalPrice));
}
}
}
<file_sep><?php
namespace Resi\GestionResiBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Resi\GestionResiBundle\Entity\Factura;
class FacturasController extends Controller{
public function verFacturaAction(Request $req, $codFact){
$usu=$req->getSession()->get('usu');
return $this->render('GestionResiBundle:Factura:verFactura.html.twig',
array('factura'=>$this->getDoctrine()
->getManager()
->getRepository('GestionResiBundle:Factura')
->findByCodFactura($codFact),
'usu'=>$this->getDoctrine()
->getManager()
->getRepository('GestionResiBundle:Usuario')
->findByUserSinId($usu)));
}
public function pagarFacturaAction(Request $req, $CodFactura){
$usu=$req->getSession()->get('usu');
$fac=$this->getDoctrine()->getManager()->getRepository('GestionResiBundle:Factura')
->findAndUpdateByCodFactura($CodFactura);
$hab=$this->getDoctrine()->getManager()->getRepository('GestionResiBundle:Habitacion')
->findHabitacionByCodFact($CodFactura);
$this->enviarNotificacionPagoAction($req, $fac, $hab);
return $this->render('GestionResiBundle:Perfil:pagarFactura.html.twig',
array('factura'=>$fac,
'usu'=>$this->getDoctrine()
->getManager()
->getRepository('GestionResiBundle:Usuario')
->findByUserSinId($usu),
'hab'=>$hab));
}
public function generarFacturaAction(Request $req, $CodHabitacion){
$usu=$req->getSession()->get('usu');
//Alteramos en 1 el número de plazas disponibles para la habitación
$this->getDoctrine()
->getManager()
->getRepository("GestionResiBundle:Habitacion")
->updateNumDisponibles_Alquiler($CodHabitacion);
//parte del contrato
$dni=strval($this->getDoctrine()->getManager()->getRepository('GestionResiBundle:Usuario')
->findByUserSinId($usu)[0]["dNI"]);
$contrato=$this->getDoctrine()->getRepository('GestionResiBundle:Contrato')
->insertContrato($dni,$CodHabitacion);
//parte de la factura
$hab=$this->getDoctrine()->getManager()->getRepository('GestionResiBundle:Habitacion')
->findHabitacionCod($CodHabitacion);
$factura =new Factura();
$factura->setCodContrato(strval($contrato[sizeof($contrato)-1]["CodContrato"]));
$factura->setImporte(strval($this->getRequest()->getSession()->get('totalPrice')));
$factura->setFechaExpedicion(new \DateTime('now'));
$em1=$this->getDoctrine()->getManager();
$em1->getRepository('GestionResiBundle:Factura');
$em1->persist($factura);
$em1->flush();
$fac=$this->getDoctrine()->getManager()->getRepository('GestionResiBundle:Factura')->findAllSinId();
$fact=$fac[sizeof($fac)-1];
$this->enviarMensajeFacturaAction($req, $fac, $contrato, $hab);
return $this->render('GestionResiBundle:Facturas:verFactura.html.twig',
array('factura'=>$fact,
'user'=>$this->getDoctrine()
->getManager()
->getRepository('GestionResiBundle:Usuario')
->findByUserSinId($usu),
'habitacion'=>$hab));
}
public function enviarNotificacionPagoAction(Request $req,$fac,$hab){
$usu=$req->getSession()->get('usu');
$user=$this->getDoctrine()->getManager()->getRepository('GestionResiBundle:Usuario')->findByUserSinId($usu);
$titulo="Pago de Factura ".strval($fac[0]['codFactura'])." de la habitacion ".strval($hab[0]['CodHabitacion']);
$mensaje="\tNumero: ".strval($fac[0]['codFactura'])."\n
\tFecha de Expedicion: ".strval($fac[0]['fechaExpedicion']->format('d M Y'))."\n
\tFecha de Pago: ".strval($fac[0]['fechaPago']->format('d M Y'))."\n
\tImporte: ".strval($fac[0]['importe'])."\n
\nPAGADA\n";
$a=$a=strval($user[0]["email"]);
//return mail($a,$titulo,$mensaje,"de: Residencia Universitaria.");
}
public function enviarMensajeFacturaAction(Request $req,$fac,$con,$hab){
$usu=$req->getSession()->get('usu');
$user=$this->getDoctrine()->getManager()->getRepository('GestionResiBundle:Usuario')->findByUserSinId($usu);
$a=strval($user[0]["email"]);
//Para mostrar fechas sin que se queje:
//echo $fac[0]['fechaExpedicion']->format('d M Y');
$titulo="Factura: ".strval($fac[0]["codFactura"])." por habitacion: ".strval($con[0]["CodHabitacion"]);
$mensaje="\tNumero de Habitacion: ".strval($con[0]['CodHabitacion'])."\n
\tNumero maximo de inquilinos en la habitacion: ".strval($hab[0]['TipoHabitacion'])." \n
\tDescripcion de la habitacion: ".strval($hab[0]['Descripcion'])."\n
\tNumero de Factura: ".strval($fac[0]['codFactura'])."\n
\tFecha de Expedicion: ".strval($fac[0]['fechaExpedicion']->format('d M Y'))."\n
\tImporte: ".strval($fac[0]['importe'])."\n";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'From: Residencia Universitaria' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
//return mail($a,$titulo,$mensaje,$headers);
//return $this->redirect($this->generateUrl('ver_perfil'));
}
}
<file_sep><?php
namespace Resi\GestionResiBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* ContratoRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ContratoRepository extends EntityRepository{
public function insertContrato($dniUser,$codhab){
$contrato =new Contrato();
$contrato->setCodHabitacion($codhab);
$contrato->setDNIResidente($dniUser);
$contrato->setFechaContrato(new \DateTime('now'));
//Los contratos duran un mes
$expiryDate = new \DateTime('now');
$expiryDate->modify('+1 month');
$contrato->setFechaExpiracion($expiryDate);
$em=$this->getEntityManager();
$em->getRepository('GestionResiBundle:Contrato');
$em->persist($contrato);
$em->flush();
return $this->findAllSinId();
}
public function findAllSinId(){
return $this->getEntityManager()->createQueryBuilder()
->select('c.CodContrato,c.DNIResidente,c.CodHabitacion,c.FechaContrato, c.fechaExpiracion, u.nick')
->from('GestionResiBundle:Contrato', 'c')
->join('GestionResiBundle:Usuario', 'u')
->where('u.dNI = c.DNIResidente')
->getQuery()->getResult();
}
public function findByUsuarioDNI($dni){
//echo 'Contrato del usuario de: '.$dni;
return $this->getEntityManager()->createQueryBuilder()
->select('c.CodContrato,c.CodHabitacion,c.FechaContrato, c.fechaExpiracion')
->from('GestionResiBundle:Contrato', 'c')
->where("c.DNIResidente = :dni")
->setParameter("dni", $dni)
->getQuery()->getResult();
}
public function checkExpiredDate($expiryDate)
{
//Si fecha expiración > hoy, return false. El contrato sigue vigente
//Si fecha expiración < hoy, return true. El contrato ha caducado
//echo $expiryDate->getTimestamp();
if($expiryDate->getTimestamp() < time())
{
//echo 'El contrato ha expirado';
return true;
}
//echo 'El contrato no ha expirado';
return false;
}
public function findHabitacionByCodContrato($codContrato)
{
return $this->getEntityManager()->createQueryBuilder()
->select('c.CodHabitacion')
->from('GestionResiBundle:Contrato','c')
->where('c.CodContrato = :cod')
->setParameter('cod', $codContrato)
->getQuery()
->getResult();
}
}
<file_sep><?php
namespace Resi\GestionResiBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* HabitacionRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class HabitacionRepository extends EntityRepository
{
public function findHabitacionCod($cod){
return $this->getEntityManager()
->createQueryBuilder()
->select('c.CodHabitacion,c.Descripcion,c.TipoHabitacion,c.TarifaMes,c.path,c.numDisponibles')
->from('GestionResiBundle:Habitacion','c')
->where('c.CodHabitacion=:Cod')
->setParameter('Cod',$cod)
->getQuery()
->getResult();
}
public function findAllSinId() {
return $this->getEntityManager()
->createQueryBuilder()
->select('c.CodHabitacion,c.Descripcion,c.TipoHabitacion,c.TarifaMes,c.path,c.numDisponibles')
->from('GestionResiBundle:Habitacion', 'c')
->getQuery()
->getResult();
}
public function findAllSinIdConFechas($fechaIni) {
return $this->getEntityManager()->createQueryBuilder()
->select('h.CodHabitacion,h.Descripcion,h.TipoHabitacion,h.TarifaMes,h.path,h.numDisponibles')
->from('GestionResiBundle:Habitacion', 'h')
->leftJoin('GestionResiBundle:Contrato', 'con')
->where('con.fechaExpiracion < :fechaIni')
->setParameter('fechaIni', $fechaIni)
->getQuery()
->getResult();
}
public function calcular_numDisponiblesPostEliminarUsuario($codHabitacion){
//Resta -1 al numDisponibles actual de una habitación
$habitaciones = $this->findHabitacionCod($codHabitacion);
$numDisponiblesPostUpdate = +1;
foreach($habitaciones as $habit)
{
$numDisponiblesPostUpdate = $habit['numDisponibles'] + 1;
return (int)$numDisponiblesPostUpdate;
}
//echo 'numDisponiblesPostUpdate = -1';
return $numDisponiblesPostUpdate;
}
public function calcular_numDisponiblesPostUpdate($codHabitacion)
{
//Resta -1 al numDisponibles actual de una habitación
$habitaciones = $this->findHabitacionCod($codHabitacion);
$numDisponiblesPostUpdate = -1;
foreach($habitaciones as $habit)
{
$numDisponiblesPostUpdate = $habit['numDisponibles'] - 1;
return (int)$numDisponiblesPostUpdate;
}
//echo 'numDisponiblesPostUpdate = -1';
return $numDisponiblesPostUpdate;
}
public function updateNumDisponibles_Alquiler($codHabitacion)
{
$manejador = $this->getEntityManager();
$dql = "UPDATE GestionResiBundle:Habitacion h "
. " SET h.numDisponibles = :updateNumDispo "
. " WHERE h.CodHabitacion like :codHabitacion ";
$queryUpdate = $manejador->createQuery($dql);
$valorUpdate = $this->calcular_numDisponiblesPostUpdate($codHabitacion);
if($valorUpdate <= -1)
{
//echo 'Hay algún error en cod Habitación para UPDATE NUM DISPONIBLES';
return;
}
$queryUpdate->setParameter('updateNumDispo', $valorUpdate);
$queryUpdate->setParameter('codHabitacion', $codHabitacion);
$queryUpdate->getResult();
}
public function findAllEInquilinoSinId() {
return $this->getEntityManager()
->createQueryBuilder()
->select('c.CodHabitacion,c.Descripcion,c.TipoHabitacion,c.TarifaMes,c.path,c.numDisponibles,u.dNI,u.nombre,u.apellidos')
->from('GestionResiBundle:Habitacion','c')
->join('GestionResiBundle:Contrato', 'con','WITH','con.CodHabitacion=c.CodHabitacion')
->where('c.numDisponibles != c.TipoHabitacion')
->join('GestionResiBundle:Usuario', 'u','WITH','u.dNI=con.DNIResidente')
->getQuery()
->getResult();
}
//Devuelve las habitaciones que ahora mismo no tienen ocupante alguno
public function findAllSinInquilinoYSinId() {
return $this->getEntityManager()
->createQueryBuilder()
->select('c.CodHabitacion,c.Descripcion,c.TipoHabitacion,c.TarifaMes,c.path,c.numDisponibles')
->from('GestionResiBundle:Habitacion','c')
->where('c.numDisponibles = c.TipoHabitacion')
->getQuery()
->getResult();
}
//Libera una habitación = Aumenta en 1 el numDisponibles
public function liberarHabitacion_1($codHabitacion)
{
$manejador = $this->getEntityManager();
$dql = "UPDATE GestionResiBundle:Habitacion h "
. " SET h.numDisponibles = :updateNumDispo "
. " WHERE h.CodHabitacion like :codHabitacion ";
$queryUpdate = $manejador->createQuery($dql);
$valorUpdate = $this->calcular_numDisponiblesPostEliminarUsuario($codHabitacion);
if($valorUpdate <= -1)
{
//echo 'Hay algún error en cod Habitación para UPDATE NUM DISPONIBLES _ Liberar';
return;
}
$queryUpdate->setParameter('updateNumDispo', $valorUpdate);
$queryUpdate->setParameter('codHabitacion', $codHabitacion);
return $queryUpdate->getResult();
}
public function findHabitacionByCodFact($cod){
$qb=$this->getEntityManager()->createQueryBuilder()
->select('f.codContrato')
->from('GestionResiBundle:Factura','f')
->where('f.codFactura = :cod')
->setParameter('cod', $cod)
->getQuery()
->getResult();
$codCon=$qb[0]["codContrato"];
return $this->getEntityManager()->createQueryBuilder()
->select('co.CodHabitacion')
->from('GestionResiBundle:Contrato', 'co')
->where('co.CodContrato = :qb')
->setParameter('qb',$codCon)
->getQuery()
->getResult();
}
}
<file_sep><?php
namespace Resi\GestionResiBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* FacturaRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class FacturaRepository extends EntityRepository{
public function findByCodFactura($cod){
return $this->getEntityManager()
->createQueryBuilder()
->select('f.codFactura,f.fechaExpedicion,f.importe,f.fechaPago')
->from('GestionResiBundle:Factura', 'f')
->where('f.codFactura = :cod')
->setParameter('cod', $cod)
->getQuery()
->getResult();
}
public function findAndUpdateByCodFactura($cod){
$this->getEntityManager()
->createQueryBuilder()
->update('GestionResiBundle:Factura', 'f')
->set('f.fechaPago', 'CURRENT_DATE()')
->where('f.codFactura = :cod')
->setParameter('cod', $cod)
->getQuery()
->execute();
return $this->findByCodFactura($cod);
}
public function findFacturassByDNIResidente($dni)
{
//Conseguimos el contrato
$contratos = $this->getEntityManager()->getRepository("GestionResiBundle:Contrato")->findByUsuarioDNI($dni);
//echo 'Ya tenemos los contraros';
/*
foreach($contratos as $c)
{
echo $c['CodContrato'];
}
*/
if($contratos == null)
{
//echo 'No hay contratos aún para este usuario';
}
else
{
//echo 'Se han encontrado facturas';
$facturas = array();
foreach($contratos as $c)
{
$facturas = $this->getEntityManager()
->createQueryBuilder()
->select('f.codFactura,f.fechaExpedicion,f.importe,f.fechaPago')
->from('GestionResiBundle:Factura', 'f')
->where('f.codContrato = :cod')
->setParameter('cod', $c['CodContrato'])
->getQuery()
->execute();
}
return $facturas;
}
return null;
}
public function findAllSinId(){
return $this->getEntityManager()
->createQueryBuilder()
->select('f.codFactura,f.fechaExpedicion,f.importe,f.fechaPago,con.CodHabitacion,u.nick,u.dNI')
->from('GestionResiBundle:Factura', 'f')
->join('GestionResiBundle:Contrato', 'con','WITH','f.codContrato=con.CodContrato')
->join('GestionResiBundle:Usuario','u','WITH','u.dNI=con.DNIResidente')
->getQuery()
->getResult();
}
public function findFacturasByCodContrato($codContrato)
{
return $this->getEntityManager()
->createQueryBuilder()
->select('f.codFactura,f.fechaExpedicion,f.importe,f.fechaPago')
->from('GestionResiBundle:Factura', 'f')
->where('f.codContrato = :cod')
->setParameter('cod', $codContrato)
->getQuery()
->execute();
}
}
<file_sep><?php
namespace Resi\GestionResiBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class GestionResiBundle extends Bundle
{
}
<file_sep><?php
namespace Resi\GestionResiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Contrato
*/
class Contrato
{
/**
* @var integer
*/
private $id;
/**
* @var integer
*/
private $CodContrato;
/**
* @var string
*/
private $DNIResidente;
/**
* @var integer
*/
private $CodHabitacion;
/**
* @var \DateTime
*/
private $FechaContrato;
/**
* @var \DateTime
*/
private $fechaExpiracion;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set CodContrato
*
* @param integer $CodContrato
* @return Contrato
*/
public function setCodContrato($CodContrato)
{
$this->CodContrato = $CodContrato;
return $this;
}
/**
* Get CodContrato
*
* @return integer
*/
public function getCodContrato()
{
return $this->CodContrato;
}
/**
* Set dNIResidente
*
* @param string $dNIResidente
* @return Contrato
*/
public function setDNIResidente($dNIResidente)
{
$this->DNIResidente = $dNIResidente;
return $this;
}
/**
* Get dNIResidente
*
* @return string
*/
public function getDNIResidente()
{
return $this->DNIResidente;
}
/**
* Set codHabitacion
*
* @param integer $codHabitacion
* @return Contrato
*/
public function setCodHabitacion($codHabitacion)
{
$this->CodHabitacion = $codHabitacion;
return $this;
}
/**
* Get codHabitacion
*
* @return integer
*/
public function getCodHabitacion()
{
return $this->CodHabitacion;
}
/**
* Set fechaContrato
*
* @param \DateTime $fechaContrato
* @return Contrato
*/
public function setFechaContrato($fechaContrato)
{
$this->FechaContrato = $fechaContrato;
return $this;
}
/**
* Get fechaContrato
*
* @return \DateTime
*/
public function getFechaContrato()
{
return $this->FechaContrato;
}
/**
* Set fechaExpiracion
*
* @param \DateTime $fechaExpiracion
* @return Contrato
*/
public function setFechaExpiracion($fechaExpiracion)
{
$this->fechaExpiracion = $fechaExpiracion;
return $this;
}
/**
* Get fechaExpiracion
*
* @return \DateTime
*/
public function getFechaExpiracion()
{
return $this->fechaExpiracion;
}
}
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.2.11
-- http://www.phpmyadmin.net
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 19-12-2016 a las 12:39:13
-- Versión del servidor: 5.6.21
-- Versión de PHP: 5.6.3
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Base de datos: `residencia`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `contrato`
--
CREATE TABLE IF NOT EXISTS `contrato` (
`CodContrato` int(11) NOT NULL,
`DNIResidente` varchar(20) NOT NULL,
`CodHabitacion` int(11) NOT NULL,
`FechaContrato` date NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `contrato`
--
INSERT INTO `contrato` (`CodContrato`, `DNIResidente`, `CodHabitacion`, `FechaContrato`) VALUES
(1, '70891675V', 102, '2016-12-19');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `factura`
--
CREATE TABLE IF NOT EXISTS `factura` (
`CodFactura` int(11) NOT NULL,
`FechaExpedicion` date NOT NULL,
`FechaPago` date DEFAULT NULL,
`Importe` double NOT NULL,
`CodContrato` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `factura`
--
INSERT INTO `factura` (`CodFactura`, `FechaExpedicion`, `FechaPago`, `Importe`, `CodContrato`) VALUES
(1, '2016-12-19', NULL, 350, 1);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `habitacion`
--
CREATE TABLE IF NOT EXISTS `habitacion` (
`CodHabitacion` int(11) NOT NULL,
`Descripcion` varchar(40) NOT NULL,
`TipoHabitacion` int(11) NOT NULL,
`TarifaMes` double NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `habitacion`
--
INSERT INTO `habitacion` (`CodHabitacion`, `Descripcion`, `TipoHabitacion`, `TarifaMes`) VALUES
(101, 'Habitacion individual', 1, 500),
(102, 'Habitacion doble', 2, 350),
(201, 'Habitacion individual', 1, 500),
(202, 'Habitacion individual', 1, 500);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `tipos_alergias`
--
CREATE TABLE IF NOT EXISTS `tiposAlergias` (
`IdAlergia` int(11) NOT NULL,
`Tipo` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `usuario`
--
CREATE TABLE IF NOT EXISTS `usuario` (
`DNI` varchar(20) NOT NULL,
`Nick` varchar(20) NOT NULL,
`Contrasena` varchar(20) NOT NULL,
`Nombre` varchar(40) NOT NULL,
`Apellidos` varchar(40) NOT NULL,
`Email` varchar(40) NOT NULL,
`Telefono` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `usuario`
--
INSERT INTO `usuario` (`DNI`, `Nick`, `Contrasena`, `Nombre`, `Apellidos`, `Email`, `Telefono`) VALUES
('', 'nick', '123456', '', 'V', 'mail', '22'),
('70891675V', 'Linksamaru', 'Xamimejora85', 'Marcos', '<NAME>', '<EMAIL>', '667322250'),
('G19116174', 'LuisH', '123456', '<NAME>', '<NAME>', '<EMAIL>', '3314388930');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `usuario_alergia`
--
CREATE TABLE IF NOT EXISTS `usuarioAlergia` (
`DNIUsuario` varchar(20) NOT NULL,
`IdAlergia` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `contrato`
--
ALTER TABLE `contrato`
ADD PRIMARY KEY (`CodContrato`);
--
-- Indices de la tabla `factura`
--
ALTER TABLE `factura`
ADD PRIMARY KEY (`CodFactura`);
--
-- Indices de la tabla `habitacion`
--
ALTER TABLE `habitacion`
ADD PRIMARY KEY (`CodHabitacion`);
--
-- Indices de la tabla `tipos_alergias`
--
ALTER TABLE `tiposAlergias`
ADD PRIMARY KEY (`IdAlergia`);
--
-- Indices de la tabla `usuario`
--
ALTER TABLE `usuario`
ADD PRIMARY KEY (`DNI`);
--
-- Indices de la tabla `usuario_alergia`
--
ALTER TABLE `usuarioAlergia`
ADD PRIMARY KEY (`DNIUsuario`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `contrato`
--
ALTER TABLE `contrato`
MODIFY `CodContrato` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT de la tabla `factura`
--
ALTER TABLE `factura`
MODIFY `CodFactura` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
namespace Resi\GestionResiBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Resi\GestionResiBundle\Entity\Habitacion;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\Validator\Constraints\Regex;
class GestionAdminController extends Controller{
public function gestionarHabitacionesAction(Request $req){
$usu=$req->getSession()->get('usu');
$habUsu = $this->getDoctrine()
->getManager()
->getRepository("GestionResiBundle:Habitacion")
->findAllEInquilinoSinId();
$habitaciones = $this->getDoctrine()
->getManager()
->getRepository('GestionResiBundle:Habitacion')
->findAllSinInquilinoYSinId();
return $this->render("GestionResiBundle:GestionAdmin:gestionarHabitaciones.html.twig",
array('HabUsu'=>$habUsu, 'Habitaciones' => $habitaciones));
}
public function nuevaHabitacionAction(Request $req){
$usu=$req->getSession()->get('usu');
$res = new Collection(array('Descripcion' => new NotNull(),
'Descripcion' => new Regex(array('pattern'=>"/^[a-zA-Z ]+$/",
'message'=>"Debe introducir una descripcion válida",
'match'=> true)),
'codhab' => new NotNull(),
'Tipo' => new NotNull(),
/*
'Tipo' => new Regex(array('pattern'=>"/^[1-3]$/",
'message'=>"Habitación de 1, 2 ó 3 personas",
'match'=> true)),
*
*/
'Tarifa' =>new NotNull(),
'Tarifa' => new Regex(array('pattern'=>"/^[0-9]+(\.[0-9]+|)$/",
'message'=>"Debe introducir una tarifa de habitacion válida",
'match'=> true)),
'path' => new NotNull()));
$default=null;
$form = $this->createFormBuilder($default, array('constraints'=>$res))
->add('Descripcion', 'textarea', array('label'=>'Descripcion de la habitacion: ','attr'=>array('cols'=>'10','rows'=>'4','max_length'=>'40')))
->add('codhab', 'text', array('label'=>'Numero de la Habitacion: '))
->add('Tipo','choice', array('choices'=>array('1'=>'individual', '2'=>'doble', '3'=>'triple')
, 'expanded'=>false,
'multiple'=>false ,
'label'=>'Tipo de habitación: '))
->add('Tarifa','text', array('label'=>'Precio al mes del aquiler de la Habitacion: '))
->add('path', 'file',array('label'=>'Añada el path de la imagen a mostrar: '))
->getForm();
$habitacion= new Habitacion();
if($req->getMethod()=='POST'){
$form->bind($req);
if($form->isValid()&&$form->isSubmitted()&&!$this->getDoctrine()->getManager()
->getRepository("GestionResiBundle:Habitacion")
->findHabitacionCod($form->get('codhab')
->getData())){
$habitacion->setCodhabitacion($form->get('codhab')->getData());
$habitacion->setDescripcion($form->get('Descripcion')->getData());
$habitacion->setTipohabitacion($form->get('Tipo')->getData());
//var_dump($form->get('Tipo')->getData());
$habitacion->setTarifames($form->get('Tarifa')->getData());
$habitacion->setNumDisponibles($form->get('Tipo')->getData());
// $file stores the uploaded PDF file
/** @var Symfony\Component\HttpFoundation\File\UploadedFile $file */
$file = $form->get('path')->getData();
$directory = $this->container->getParameter('kernel.root_dir') . '/../web/bundles/resi/imagesHabitaciones';
$extension = $file->guessExtension();
$fileName = md5(uniqid()).'.'.$extension;
$file->move($directory, $fileName);
$habitacion->setPath('bundles/resi/imagesHabitaciones/'.$fileName);
$em=$this->getDoctrine()->getManager();
$em->getRepository('GestionResiBundle:Habitacion');
$em->persist($habitacion);
$em->flush();
//return $this->redirect($this->gestionarHabitacionesAction($req));
/*
return $this->render("GestionResiBundle:GestionAdmin:gestionarHabitaciones.html.twig",
array('habitaciones'=>$this->getDoctrine()
->getManager()
->getRepository("GestionResiBundle:Habitacion")
->findAllSinId()));
*
*/
return ($this->gestionarHabitacionesAction($req));
}
}else{
return $this->render("GestionResiBundle:GestionAdmin:nuevaHabitacion.html.twig",array('form'=>$form->createView()));
}
return $this->render("GestionResiBundle:GestionAdmin:nuevaHabitacion.html.twig",array('form'=>$form->createView()));
}
public function gestionarFacturasAction(Request $req){
$usu=$req->getSession()->get('usu');
//Obtenemos las facturas por contrato, con los datos del usuario:
$contratos = array();
$listaContratos = $this->getDoctrine()->getManager()->getRepository('GestionResiBundle:Contrato')->findAllSinId();
foreach($listaContratos as $c)
{
$contratoFacturas = array();
$contratoFacturas[0] = $c; //Info de un contrato
$contratoFacturas[1] = $this->getDoctrine()->getRepository('GestionResiBundle:Factura')
->findFacturasByCodContrato($c['CodContrato']); //array de facturas
$contratos[] = $contratoFacturas;
}
//var_dump($contratos);
return $this->render("GestionResiBundle:GestionAdmin:gestionarFacturas.html.twig",
array('contratos'=>$contratos, 'hoy'=> date("Y-m-d")));
}
public function borrarFacturaAction($cod){
$this->getDoctrine()->getManager()
->getRepository("GestionResiBundle:usuarioadmin")
->borrarFactura($cod);
return $this->gestionarFacturasAction();
}
public function gestionarResidentesAction(){
$req = $this->getRequest();
$usu=$req->getSession()->get('usu');
return $this->render('GestionResiBundle:GestionAdmin:gestionarResidentes.html.twig',
array('usuarios'=>$this->getDoctrine()
->getManager()
->getRepository('GestionResiBundle:Usuario')
->findAllSinId(),
'usu'=>$this->getDoctrine()
->getRepository('GestionResiBundle:Usuario')
->findByUserSinId($usu)));
}
public function darBajaResidenteAction($DNI){
$req = $this->getRequest();
//Comprobar que el residente no tiene facturas pendientes
$facturasResidente = $this->getDoctrine()->getManager()->getRepository("GestionResiBundle:Factura")->findFacturassByDNIResidente($DNI);
if($facturasResidente == null)
{
return $this->render('GestionResiBundle:GestionAdmin:confirmarBorrardoUsuario.html.twig', array("dniUsuVerPerfil"=>$DNI));
}
$flagTodasPagadas = 1;
foreach($facturasResidente as $f)
{
//var_dump($f["fechaPago"]);
if($f["fechaPago"] == null)
{
//echo 'Hay una factura no pagada!';
$flagTodasPagadas = 0;
break;
}
}
if($flagTodasPagadas == 1)
{
//Liberar la habitación. Todas las habitaciones cuyo contrato aún no haya expirado
$contratosNoExpirados = array();
$listaContratos = $this->getDoctrine()->getManager()
->getRepository("GestionResiBundle:Contrato")
->findByUsuarioDNI($DNI);
foreach($listaContratos as $contrato)
{
if(!($this->getDoctrine()->getManager()->getRepository("GestionResiBundle:Contrato")
->checkExpiredDate($contrato["fechaExpiracion"])))
{
$contratosNoExpirados[] = $contrato;
}
}
if($contratosNoExpirados == null)
{
//El usuario tiene todas las facturas pagadas y contratos expirados!
//SE PUEDE ELIMINAR
//echo 'Eliminamos';
return $this->render('GestionResiBundle:GestionAdmin:confirmarBorrardoUsuario.html.twig', array("dniUsuVerPerfil"=>$DNI));
}
else
{
//echo 'El usuario aún tiene algún contrato';
return $this->render('GestionResiBundle:GestionAdmin:errorResiConContratos.html.twig', array("dniUsuVerPerfil"=>$DNI));
}
/*
*
$this->getDoctrine()->getManager()
->getRepository("GestionResiBundle:Habitacion")
->liberarHabitacion_1($contrato["codHabitacion"]);
*/
}
else
{
return $this->render('GestionResiBundle:GestionAdmin:errorResiConFacturas.html.twig', array("dniUsuVerPerfil"=>$DNI));
}
}
public function borrarHabitacionAction(Request $req){
$COD = $req->get('COD');
$this->getDoctrine()->getManager()
->getRepository("GestionResiBundle:usuarioadmin")
->borraHabitacion($COD);
return $this->gestionarHabitacionesAction($req);
}
public function verPerfilUserAction($dni, Request $req)
{
//Enviamos la información completa del usuario al twig: InfoPerfil, InfoContratos, InfoFacturas
$usuarioMostrar = $this->getDoctrine()->getManager()->getRepository("GestionResiBundle:Usuario")
->findUserByDNI($dni);
$contratosUsuario = $this->getDoctrine()->getManager()->getRepository("GestionResiBundle:Contrato")
->findByUsuarioDNI($dni);
$listaContratosFacturas = array();
foreach ($contratosUsuario as $contrato)
{
$facturas = $this->getDoctrine()->getManager()->getRepository("GestionResiBundle:Factura")
->findFacturasByCodContrato($contrato['CodContrato']);
$listaContratosFacturas[] = array($contrato, $facturas);
}
$fechaActual = new \DateTime("now");
return $this->render('GestionResiBundle:GestionAdmin:mostrarUsuarioAAdmin.html.twig',
array("datosUser"=>$usuarioMostrar , "fechaActual"=> $fechaActual, "userDNI"=>$dni, "listaContratosFacturas"=>$listaContratosFacturas));
}
public function borrarUsuarioConfirmedAction($dni)
{
$this->getRequest();
$this->getDoctrine()->getManager()
->getRepository("GestionResiBundle:usuarioadmin")
->borraUser($dni);
return $this->gestionarResidentesAction();
}
public function desahuciarAction($dni)
{
//Obtenemos todos los contratos asociados al dni
$listaContratos = $this->getDoctrine()->getRepository('GestionResiBundle:Contrato')
->findByUsuarioDNI($dni);
//Aquellos con fecha de expiración > today, ponemos fecha de expiración a la de hoy, liberamos la habitacion
if($listaContratos != null)
{
foreach($listaContratos as $contrato)
{
if(!($this->getDoctrine()->getManager()
->getRepository("GestionResiBundle:Contrato")
->checkExpiredDate($contrato['fechaExpiracion'])))
{
//El contrato no ha expirado
$listaCodHabitaciones = $this->getDoctrine()->getManager()
->getRepository("GestionResiBundle:Contrato")
->findHabitacionByCodContrato($contrato['CodContrato']);
foreach($listaCodHabitaciones as $codHab)
{
//echo 'Se libera la habitacion de código: '.$codHab['CodHabitacion'];
$this->getDoctrine()->getManager()
->getRepository("GestionResiBundle:Habitacion")
->liberarHabitacion_1($codHab['CodHabitacion']);
}
}
}
}
else
{
//lista contratos es nula
echo 'No hay contratos para este usuario';
//return $this->gestionarResidentesAction();
}
//borramos usuario
return $this->borrarUsuarioConfirmedAction($dni);
}
public function modificarHabitacionAction($COD)
{
return $this->gestionarHabitacionesAction($this->getRequest());
}
}
<file_sep><?php
namespace Resi\GestionResiBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller{
public function indexAction(){
return $this->render('GestionResiBundle:Default:index.html.twig',
array('userNotFound'=>null,
'sesionIniciado'=>null));
}
}
<file_sep><?php
namespace Resi\GestionResiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Habitacion
*/
class Habitacion
{
/**
* @var integer
*/
private $id;
/**
* @var integer
*/
private $CodHabitacion;
/**
* @var integer
*/
private $numDisponibles;
/**
* @var string
*/
private $Descripcion;
/**
* @var integer
*/
private $TipoHabitacion;
/**
* @var float
*/
private $TarifaMes;
/**
* @var string
*/
private $path;
/**
* Set path
*
* @param string $path
* @return Habitacion
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Get path
*
* @return string
*/
public function getPath()
{
return $this->path;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set CodHabitacion
*
* @param integer $codhabitacion
* @return Habitacion
*/
public function setCodhabitacion($codhabitacion)
{
$this->CodHabitacion = $codhabitacion;
return $this;
}
/**
* Get CodHabitacion
*
* @return integer
*/
public function getCodhabitacion()
{
return $this->CodHabitacion;
}
/**
* Set numDisponibles
*
* @param integer $numDisponibles
* @return Habitacion
*/
public function setNumDisponibles($numDisponibles)
{
$this->numDisponibles = $numDisponibles;
return $this;
}
/**
* Get numDisponibles
*
* @return integer
*/
public function getNumDisponibles()
{
return $this->numDisponibles;
}
/**
* Set Descripcion
*
* @param string $descripcion
* @return Habitacion
*/
public function setDescripcion($descripcion)
{
$this->Descripcion = $descripcion;
return $this;
}
/**
* Get descripcion
*
* @return string
*/
public function getDescripcion()
{
return $this->Descripcion;
}
/**
* Set tipohabitacion
*
* @param integer $tipohabitacion
* @return Habitacion
*/
public function setTipohabitacion($tipohabitacion)
{
$this->TipoHabitacion = $tipohabitacion;
return $this;
}
/**
* Get tipohabitacion
*
* @return integer
*/
public function getTipohabitacion()
{
return $this->TipoHabitacion;
}
/**
* Set tarifames
*
* @param float $tarifames
* @return Habitacion
*/
public function setTarifames($tarifames)
{
$this->TarifaMes = $tarifames;
return $this;
}
/**
* Get tarifames
*
* @return float
*/
public function getTarifames()
{
return $this->TarifaMes;
}
}
<file_sep><?php
namespace Resi\GestionResiBundle\Entity;
use Doctrine\ORM\EntityRepository;
use Resi\GestionResiBundle\Entity\Habitacion;
/**
* usuarioadminRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class usuarioadminRepository extends EntityRepository{
public function findAdmin($dni){
$dql=$this->getEntityManager()->createQueryBuilder()
->select("a.idAdmin")
->from("GestionResiBundle:usuarioadmin", "a")
->where("a.dNIUser=:dni")
->setParameter("dni", $dni)
->getQuery()
->getResult();
if($dql!=null){
return true;
}else{
return false;
}
}
public function borraUser($dni){
//Eliminamos la vida
//Facturas
$listaContratos = $this->getEntityManager()->getRepository('GestionResiBundle:Contrato')->findByUsuarioDNI($dni);
//var_dump($listaContratos);
foreach ($listaContratos as $c)
{
$this->getEntityManager()->createQueryBuilder()
->delete()
->from("GestionResiBundle:Factura","f")
->where("f.codContrato = :codC")
->setParameter("codC", $c['CodContrato'])
->getQuery()
->execute();
}
//Contratos
$this->getEntityManager()->createQueryBuilder()
->delete()
->from("GestionResiBundle:Contrato","c")
->where("c.DNIResidente = :dni")
->setParameter("dni", $dni)
->getQuery()
->execute();
//El usuario
$this->getEntityManager()->createQueryBuilder()
->delete()
->from("GestionResiBundle:Usuario","u")
->where("u.dNI= :dni")
->setParameter("dni", $dni)
->getQuery()
->execute();
//Hay que actualizar los contratos
/*
$this->getEntityManager()->createQueryBuilder()
->update("GestionResiBundle:Contrato","c")
->set('c.DNIResidente', '?1')
->where("c.DNIResidente = :dni")
->setParameter("dni", $dni)
->setParameter(1, "ANONYMOUS")
->getQuery()
->execute();
$this->getEntityManager()->createQueryBuilder()
->update("GestionResiBundle:Usuario","u")
->set('u.dNI', '?1')
->where("u.dNI= :dni")
->setParameter("dni", $dni)
->setParameter(1, "ANONYMOUS")
->getQuery()
->execute();
*
*
*/
}
public function borraHabitacion($cod){
$this->getEntityManager()->createQueryBuilder()
->delete()
->from("GestionResiBundle:Habitacion","h")
->where("h.CodHabitacion= :cod")
->setParameter("cod", $cod)
->getQuery()
->execute();
}
public function borrarFactura($cod){
$this->getEntityManager()->createQueryBuilder()
->delete()
->from("GestionResiBundle:Factura","f")
->where("f.codFactura= :cod")
->setParameter("cod", $cod)
->getQuery()
->execute();
}
public function nuevaHabitacion($cod,$tipo,$desc,$tarifa){
$habitacion=new Habitacion();
$habitacion->setCodhabitacion($cod);
$habitacion->setTipohabitacion($tipo);
$habitacion->setDescripcion($desc);
$habitacion->setTarifames($tarifa);
$em=$this->getDoctrine()->getManager();
$em->getRepository('GestionResiBundle:Habitacion');
$em->persist($habitacion);
$em->flush();
}
}
<file_sep><?php
namespace Resi\GestionResiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Factura
*/
class Factura
{
/**
* @var integer
*/
private $id;
/**
* @var integer
*/
private $codFactura;
/**
* @var \DateTime
*/
private $fechaExpedicion;
/**
* @var \DateTime
*/
private $fechaPago;
/**
* @var float
*/
private $importe;
/**
* @var integer
*/
private $codContrato;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set codFactura
*
* @param integer $codFactura
* @return Factura
*/
public function setCodFactura($codFactura)
{
$this->codFactura = $codFactura;
return $this;
}
/**
* Get codFactura
*
* @return integer
*/
public function getCodFactura()
{
return $this->codFactura;
}
/**
* Set fechaExpedicion
*
* @param \DateTime $fechaExpedicion
* @return Factura
*/
public function setFechaExpedicion($fechaExpedicion)
{
$this->fechaExpedicion = $fechaExpedicion;
return $this;
}
/**
* Get fechaExpedicion
*
* @return \DateTime
*/
public function getFechaExpedicion()
{
return $this->fechaExpedicion;
}
/**
* Set fechaPago
*
* @param \DateTime $fechaPago
* @return Factura
*/
public function setFechaPago($fechaPago)
{
$this->fechaPago = $fechaPago;
return $this;
}
/**
* Get fechaPago
*
* @return \DateTime
*/
public function getFechaPago()
{
return $this->fechaPago;
}
/**
* Set importe
*
* @param float $importe
* @return Factura
*/
public function setImporte($importe)
{
$this->importe = $importe;
return $this;
}
/**
* Get importe
*
* @return float
*/
public function getImporte()
{
return $this->importe;
}
/**
* Set codContrato
*
* @param integer $codContrato
* @return Factura
*/
public function setCodContrato($codContrato)
{
$this->codContrato = $codContrato;
return $this;
}
/**
* Get codContrato
*
* @return integer
*/
public function getCodContrato()
{
return $this->codContrato;
}
}
|
3c7f526d78906ff0676d632432a4dd02e87058ed
|
[
"SQL",
"PHP"
] | 24 |
PHP
|
linksamaru/Residencia
|
44ebe9b033f2e7eec5cf9a743966d5522223b167
|
b285aa815dd4eba05f47d8b94e741d3b0f51484b
|
refs/heads/master
|
<repo_name>tungula/StrategyOrbit<file_sep>/Assets/Scripts/DB/DB.cs
using UnityEngine;
using System.Collections;
using System.Data;
using Mono.Data.Sqlite;
using System;
using System.Reflection;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
public class DB : MonoBehaviour
{
private string connectionString;
// Use this for initialization
public DB()
{
if (Application.platform == RuntimePlatform.Android)
connectionString = "URI=file:" + Application.persistentDataPath + "/Game.sqlite";
else
connectionString = "URI=file:" + Application.dataPath + "/Game.sqlite";
//InsertScore("<NAME>", 120);
//GetScores();
}
public void GetData()
{
try
{
string filepath;
if (Application.platform == RuntimePlatform.Android)
{
filepath = Application.persistentDataPath + "/Game.sqlite";
File.Delete(filepath);
}
else
filepath = Application.dataPath + "/Game.sqlite";
if (!File.Exists(filepath))
{
WWW loadDB = new WWW("jar:file://" + Application.dataPath + "!/assets/Game.sqlite"); // this is the path to your StreamingAssets in android
while (!loadDB.isDone) { } // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
// then save to Application.persistentDataPath
File.WriteAllBytes(filepath, loadDB.bytes);
//Debug.Log("Not exists");
}
else
{
Debug.Log("Exists");
}
using (IDbConnection connection = new SqliteConnection(connectionString))
{
connection.Open();
using (IDbCommand cmd = connection.CreateCommand())
{
string sqlQuery = "SELECT * FROM User";
cmd.CommandText = sqlQuery;
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Debug.Log(reader.GetString(1));
}
connection.Close();
reader.Close();
}
}
connection.Close();
}
}
catch (Exception e)
{
Debug.Log(e.Message);
throw;
}
}
public List<T> Get<T>(Expression<Func<T, bool>> predicate)
{
DB _db = new DB();
Debug.Log("Call");
List<T> result = null;
using (IDbConnection connection = new SqliteConnection(connectionString))
{
connection.Open();
using (IDbCommand cmd = connection.CreateCommand())
{
string sqlQuery = "SELECT * FROM User";
cmd.CommandText = sqlQuery;
using (IDataReader reader = cmd.ExecuteReader())
{
return _db.FromDataReader<T>(result, reader);
while (reader.Read())
{
// result.((T)reader);
// Debug.Log(reader);
Debug.Log(reader.GetString(1));
}
connection.Close();
reader.Close();
}
}
connection.Close();
}
return result;
}
void OnGUI()
{
if (GUI.Button(new Rect(0, 0, 500, 500), "GetData"))
{
GetData();
}
if (GUI.Button(new Rect(500, 0, 500, 500), "Insert"))
{
InsertScore("Cuncula");
}
}
public void InsertScore(string name)
{
using (IDbConnection connection = new SqliteConnection(connectionString))
{
connection.Open();
using (IDbCommand cmd = connection.CreateCommand())
{
string sqlQuery = String.Format("INSERT INTO User (Name) VALUES(\"{0}\") ", name);
cmd.CommandText = sqlQuery;
cmd.ExecuteScalar();
connection.Close();
}
}
}
public List<T> FromDataReader<T>(IEnumerable<T> list, IDataReader dr)
{
//Instance reflec object from Reflection class coded above
//Declare one "instance" object of Object type and an object list
System.Object instance;
List<System.Object> lstObj = new List<System.Object>();
//dataReader loop
while (dr.Read())
{
//Create an instance of the object needed.
//The instance is created by obtaining the object type T of the object
//list, which is the object that calls the extension method
//Type T is inferred and is instantiated
instance = Activator.CreateInstance(list.GetType().GetGenericArguments()[0]);
// Loop all the fields of each row of dataReader, and through the object
// reflector (first step method) fill the object instance with the datareader values
//foreach (DataRow drow in dr.GetSchemaTable().Rows)
//{
// FillObjectWithProperty(ref instance,
// drow.ItemArray[0].ToString(), dr[drow.ItemArray[0].ToString()]);
//}
////Add object instance to list
//lstObj.Add(instance);
}
List<T> lstResult = new List<T>();
foreach (System.Object item in lstObj)
{
lstResult.Add((T)Convert.ChangeType(item, typeof(T)));
}
return lstResult;
}
//public void FillObjectWithProperty(ref object objectTo, string propertyName, object propertyValue)
//{
// Type tOb2 = objectTo.GetType();
// tOb2.GetProperty(propertyName).SetValue(objectTo, propertyValue, null);
//}
}
<file_sep>/README.md
# StrategyOrbit
Strategy game
<file_sep>/Assets/Scripts/TestDBScripts.cs
using UnityEngine;
using System.Collections;
public class TestDBScripts : MonoBehaviour
{
// Use this for initialization
void Start()
{
}
void OnGUI()
{
if(GUI.Button(new Rect(0,0,200,200),"Insert"))
{
DB db = new DB();
db.InsertScore("T2");
}
if (GUI.Button(new Rect(200, 0, 200, 200), "Select"))
{
DB db = new DB();
db.GetData();
}
}
}
|
d63c86561e1c9a633c848685b60ffe62cd19a2ff
|
[
"Markdown",
"C#"
] | 3 |
C#
|
tungula/StrategyOrbit
|
b7ac55d99aedd35b18347d6939e39c4cdc5fdfdd
|
bfbf7a505c096fb8d02dd8325b0c4de76ef41fda
|
refs/heads/master
|
<repo_name>LoyRohan/woohoo<file_sep>/footTitle.js
function title() {
var xhttp2 = new XMLHttpRequest();
xhttp2.onreadystatechange = function() {
if (xhttp2.readyState == 4 && xhttp2.status == 200) {
console.log(JSON.parse(xhttp2.responseText));
var footer = JSON.parse(xhttp2.responseText);
if(footer._embedded.home_page_block_react){
var footTit = document.getElementById("foot")
var title = '';
footer._embedded.home_page_block_react.forEach( footnav => {
if(footnav.content){
title += footnav.content;
}
footTit.innerHTML = title;
console.log(title);
});
}
}
};
xhttp2.open("GET", "http://localhost/woohoo/static.json", true);
xhttp2.send();
}
title();<file_sep>/learn.js
/*var marks = function(curentMarks, totalMarks){
var percentage = (curentMarks/totalMarks)*100;
let myGrade =''
if( percentage >= 90){
myGrade = "A"
} else if( percentage >=80){
myGrade = "B"
}else if(percentage >=60){
myGrade = "C"
}else if(percentage >= 40){
myGrade = "D"
}else {
myGrade = "Student is fails"
}
return('Your grade is '+ myGrade +' garde');
}
var markssheet = marks(96,100);
console.log(markssheet);
var hello = marks(45,100);
console.log(hello);*/
var youTube = {
title : "introduction to JS",
videoLength : 15,
videoSize : '40Gb'
}
console.log('The video is about ' + youTube.title +' and size of '+ youTube.videoSize + '.');
/*crate a object its shoult about cousr with name ,price and discription*/
var student = {
name : 'Raj',
course : 'Msc',
price : 40000,
discription : "Masters in science is the hard core subject where perticular topics of science sbject u learn."
}
console.log("hello, My name is "+ student.name+". I hve taken the subject "+student.course+". ");
|
5f3c442e0f7d32d4a9390ddf509f915137e9c9e8
|
[
"JavaScript"
] | 2 |
JavaScript
|
LoyRohan/woohoo
|
99261b5091a9833ab1f510bf9e76e570335b7a7c
|
fc6011680adab9e14b6832c26138c987a1ecc69e
|
refs/heads/master
|
<file_sep>using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace _4TheRecord
{
public record ItemRecord : INotifyPropertyChanged
{
public ItemRecord(string name)
{
Name = name;
}
public string Name { get; }
private bool _isDone;
public bool IsDone
{
get => _isDone;
set => SetProperty(ref _isDone, value);
}
private bool SetProperty<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
{
if (!EqualityComparer<T>.Default.Equals(field, value))
{
field = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
return true;
}
return false;
}
public event PropertyChangedEventHandler? PropertyChanged;
}
}
<file_sep>using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace _4TheRecord
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var dataGrid = (DataGrid)sender;
var viewModel = (MainWindowViewModel)DataContext;
viewModel.SelectedClasses = dataGrid.SelectedItems.OfType<ItemClass>().ToList();
}
private void DataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var dataGrid = (DataGrid)sender;
var viewModel = (MainWindowViewModel)DataContext;
viewModel.SelectedRecords = dataGrid.SelectedItems.OfType<ItemRecord>().ToList();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace _4TheRecord
{
public class ItemClass : INotifyPropertyChanged, IEquatable<ItemClass>
{
public ItemClass(string name)
{
Name = name;
}
public string Name { get; }
private bool _isDone;
public bool IsDone
{
get => _isDone;
set => SetProperty(ref _isDone, value);
}
private bool SetProperty<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
{
if (!EqualityComparer<T>.Default.Equals(field, value))
{
field = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
return true;
}
return false;
}
public event PropertyChangedEventHandler? PropertyChanged;
public override bool Equals(object? obj)
{
return Equals(obj as ItemClass);
}
public override int GetHashCode()
{
return HashCode.Combine(_isDone, Name);
}
public bool Equals(ItemClass? other)
{
if (other is { } item)
{
return item._isDone = _isDone &&
item.Name == Name;
}
return false;
}
public static bool operator !=(ItemClass? left, ItemClass? right)
{
return !(left == right);
}
public static bool operator ==(ItemClass? left, ItemClass? right)
{
return left == right || (left != null && left.Equals(right));
}
}
}
<file_sep>using Microsoft.Toolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
namespace _4TheRecord
{
public class MainWindowViewModel
{
public ObservableCollection<ItemClass> ItemClassess { get; } = new();
public IList<ItemClass>? SelectedClasses { get; set; }
public ICommand ToggleClasses { get; }
public ObservableCollection<ItemRecord> ItemRecords { get; } = new();
public IList<ItemRecord>? SelectedRecords { get; set; }
public ICommand ToggleRecords { get; }
public MainWindowViewModel()
{
ItemClassess.Add(new ItemClass("First"));
ItemClassess.Add(new ItemClass("Second"));
ItemClassess.Add(new ItemClass("Third"));
ItemClassess.Add(new ItemClass("Fourth"));
ToggleClasses = new RelayCommand(OnToggleClasses);
ItemRecords.Add(new ItemRecord("First"));
ItemRecords.Add(new ItemRecord("Second"));
ItemRecords.Add(new ItemRecord("Third"));
ItemRecords.Add(new ItemRecord("Fourth"));
ToggleRecords = new RelayCommand(OnToggleRecords);
}
private void OnToggleClasses()
{
foreach (var item in SelectedClasses ?? Enumerable.Empty<ItemClass>())
{
item.IsDone = !item.IsDone;
}
}
private void OnToggleRecords()
{
foreach (var item in SelectedRecords ?? Enumerable.Empty<ItemRecord>())
{
item.IsDone = !item.IsDone;
}
}
}
}
|
3573ce6b6088a33c30caae8873402e67765f9d5b
|
[
"C#"
] | 4 |
C#
|
Keboo/4TheRecord
|
163f429cbfb14630c5be0c4db6cf590a538b83c6
|
15b1590a05757f83b13993bbcf60aa57f8a498cc
|
refs/heads/master
|
<repo_name>wehman/Winning-Numbers<file_sep>/RaffleTicket.rb
def winning_number_include?(my_ticket,winning_tickets)
winning_tickets.include?(my_ticket)
end
def winning_number_iterate(my_ticket,winning_tickets)
winner = false
winning_tickets.each do |ticket|
if my_ticket == ticket
winner = true
end
end
return winner
end<file_sep>/inclass_winningnumbers.rb
def raffle(winners,my_ticket)
winners.include?(my_ticket)
end
def raffle_iterate(winners,my_ticket)
winner = false
winners.each do |ticket|
if my_ticket == ticket
winner = true
end
end
return winner
end<file_sep>/test_inclass_winningnumbers.rb
require "minitest/autorun"
require_relative "inclass_winningnumbers.rb"
class TestRaffle < Minitest::Test
def test_1_returns_1
assert_equal(1,1)
end
def test_assert_true
my_ticket = 5235
winners = [5235]
assert_equal(true,raffle(winners,my_ticket))
end
def test_assert_false
my_ticket = 5235
winners = [1234,2345,3456,4567,15235]
assert_equal(false,raffle(winners,my_ticket))
end
def test_assert_unknown
my_ticket = 1234
winners = [0123,1235,3345]
assert_equal(false,raffle(winners,my_ticket))
end
def test_assert_leading_zero
my_ticket = 0234
winners = [0123,1235,3345,0234]
assert_equal(true,raffle(winners,my_ticket))
end
def test_assert_leading_zero_iterate
my_ticket = 0234
winners = [0123,1235,3345,0234]
assert_equal(true,raffle_iterate(winners,my_ticket))
end
def def test_assert_false
my_ticket = 5235
winners = [1234,2345,3456,4567,15235]
assert_equal(false,raffle_iterate(winners,my_ticket))
end
def test_assert_unknown
my_ticket = 1234
winners = [0123,1235,3345]
assert_equal(false,raffle_iterate(winners,my_ticket))
end
end <file_sep>/Test_RaffleTicket.rb
require "minitest/autorun"
require_relative "RaffleTicket.rb"
class TestRaffleTicket < Minitest::Test
def test_ticket_5423_returns_true
my_ticket = "5423"
winning_tickets = ["5423"]
assert_equal(true,winning_number_include?(my_ticket,winning_tickets))
end
def test_ticket_5455_returns_true
my_ticket = "5555"
winning_tickets = ["5423","5555"]
assert_equal(true,winning_number_include?(my_ticket,winning_tickets))
end
def test_ticket_6789_returns_false
my_ticket = "6789"
winning_tickets = ["9087","0084","1267"]
assert_equal(false,winning_number_include?(my_ticket,winning_tickets))
end
end
|
dfb7449c7e32a43139895d34f4e47dfa98fd47dd
|
[
"Ruby"
] | 4 |
Ruby
|
wehman/Winning-Numbers
|
bf5b52ea9f8d15b7e18c9593c32fa50c889337fa
|
712be4dc1c6448c21a0c7f106c58ae868b9184ec
|
refs/heads/master
|
<repo_name>nivethaaarthi98/raju<file_sep>/values.c
#include<stdio.h>
void main(){
int i=0;
char ch;
for(i=0;i<256;i++){
printf("%c",ch);
ch=ch+1;
}
}
|
f0a1f9177419088b165a4d91832ea78bccc7ebe0
|
[
"C"
] | 1 |
C
|
nivethaaarthi98/raju
|
50a8c4d77d314a3d64bfeef29ff9490ca85607a8
|
949f45b69b6bfdff895751dc23d1090980e7ed51
|
refs/heads/master
|
<file_sep>//
// DetailMapViewController.swift
// exam
//
// Created by D7702_09 on 2019. 11. 12..
// Copyright © 2019년 csd5766. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class DetailMapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
var dTitle: String?
var dAddress: String?
var userLocation: CLLocation?
var dLat: String?
var dLon: String?
var dPoint: MKPointAnnotation?
@IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
mapView.delegate = self
// Do any additional setup after loading the view.
print("dTitle = \(String(describing: dTitle))")
print("dAddress = \(String(describing: dAddress))")
print("dLat = \(String(describing: dLat))")
// navigation title 설정
self.title = dTitle
// geoCoding
// let geoCoder = CLGeocoder()
// geoCoder.geocodeAddressString(dAddress!, completionHandler: { plackmarks, error in
//
// if error != nil {
// print(error!)
// }
//
// if plackmarks != nil {
// let myPlacemark = plackmarks?[0]
//
// if (myPlacemark?.location) != nil {
//
// //self.mapView.setRegion(region, animated: true)
//
// // Pin 꼽기, title, suttitle
// let anno = MKPointAnnotation()
// anno.title = self.dTitle
// anno.subtitle = self.dAddress
// anno.coordinate = (myPlacemark?.location?.coordinate)!
// self.dPoint = anno
// self.mapView.addAnnotation(anno)
// //self.mapView.selectAnnotation(anno, animated: true)
// }
// }
//
// } )
let anno = MKPointAnnotation()
anno.title = self.dTitle
anno.subtitle = self.dAddress
anno.coordinate.latitude = Double(dLat!)!
anno.coordinate.longitude = Double(dLon!)!
self.dPoint = anno
self.mapView.addAnnotation(anno)
let center = CLLocationCoordinate2D(latitude: (anno.coordinate.latitude), longitude: anno.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
mapView.setRegion(region, animated: true)
// 나의 위치 트래킹
locationManager.startUpdatingLocation()
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
mapView.showsUserLocation = true
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let identifier = "RE"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)as? MKPinAnnotationView
if annotationView == nil && annotation.title != "My Location"{
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView!.canShowCallout = true
//annotationView?.pinTintColor = UIColor.blue
annotationView?.animatesDrop = true
}
else {
annotationView?.annotation = annotation
}
return annotationView
}
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
userLocation = locations[0]
print(userLocation)
let center = CLLocationCoordinate2D(latitude: (userLocation?.coordinate.latitude)!, longitude: userLocation!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
//mapView.setRegion(region, animated: true)
}
@IBAction func navigate(_ sender: Any) {
let source = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: (userLocation?.coordinate.latitude)!, longitude: (userLocation?.coordinate.longitude)!)))
source.name = "내 위치"
let destination = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: (dPoint?.coordinate.latitude)!, longitude: (dPoint?.coordinate.longitude)!)))
destination.name = dTitle
MKMapItem.openMaps(with: [source, destination], launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving])
}
}
<file_sep>//
// TotalMapViewController.swift
// exam
//
// Created by D7702_09 on 2019. 11. 12..
// Copyright © 2019년 csd5766. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class TotalMapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
var dContents: NSArray?
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
mapView.delegate = self
// Do any additional setup after loading the view.
print("dContents = \(String(describing: dContents))")
var annos = [MKPointAnnotation]()
if let myItems = dContents {
for item in myItems {
let _title = (item as AnyObject).value(forKey: "title")
let _subtitle = (item as AnyObject).value(forKey: "subtitle")
let _lat = (item as AnyObject).value(forKey: "lat") as! String
let _lon = (item as AnyObject).value(forKey: "lon") as! String
let anno = MKPointAnnotation()
anno.title = _title as! String
anno.subtitle = _subtitle as! String
anno.coordinate.latitude = Double(_lat)!
anno.coordinate.longitude = Double(_lon)!
self.mapView.addAnnotation(anno)
}
} else {
print("dContents의 값은 nil")
}
// 나의 위치 트래킹
locationManager.startUpdatingLocation()
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
mapView.showsUserLocation = true
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let identifier = "RE"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)as? MKPinAnnotationView
if annotationView == nil && annotation.title != "My Location"{
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView!.canShowCallout = true
//annotationView?.pinTintColor = UIColor.blue
annotationView?.animatesDrop = true
}
else {
annotationView?.annotation = annotation
}
return annotationView
}
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation: CLLocation = locations[0]
print(userLocation)
let center = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
mapView.setRegion(region, animated: true)
}
}
<file_sep>//
// ViewController.swift
// exam
//
// Created by D7702_09 on 2019. 11. 12..
// Copyright © 2019년 csd5766. All rights reserved.
//
import UIKit
import MapKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var mTableView: UITableView!
var contents = NSArray()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// 테이블 뷰 셋팅
mTableView.delegate = self
mTableView.dataSource = self
self.title = "Busan Map Tour"
// 데이터 로드
// let path = Bundle.main.path(forResource: "data", ofType: "plist")
let path = Bundle.main.path(forResource: "gil", ofType: "plist")
contents = NSArray(contentsOfFile: path!)!
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return contents.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// 셀 설정
let myCell = mTableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
let myTitle = (contents[indexPath.row] as AnyObject).value(forKey: "title")
// let myAddress = (contents[indexPath.row] as AnyObject).value(forKey: "address")
let myAddress = (contents[indexPath.row] as AnyObject).value(forKey: "subtitle")
print(myAddress!)
myCell.textLabel?.text = myTitle as? String
myCell.detailTextLabel?.text = myAddress as? String
return myCell
}
// 위치정보 등 데이터를 DetailMapViewController에 전달
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goDetail" {
let detailMVC = segue.destination as! DetailMapViewController
let selectedPath = mTableView.indexPathForSelectedRow
let myIndexedTitle = (contents[(selectedPath?.row)!] as AnyObject).value(forKey: "title")
// let myIndexedAddress = (contents[(selectedPath?.row)!] as AnyObject).value(forKey: "address")
let myIndexedAddress = (contents[(selectedPath?.row)!] as AnyObject).value(forKey: "subtitle")
let myIndexLat = (contents[(selectedPath?.row)!] as AnyObject).value(forKey: "lat")
let myIndexLon = (contents[(selectedPath?.row)!] as AnyObject).value(forKey: "lon")
print("myIndexedTitle = \(String(describing: myIndexedTitle))")
print("my = \(myIndexLat)")
detailMVC.dLat = myIndexLat as? String
detailMVC.dLon = myIndexLon as? String
detailMVC.dTitle = myIndexedTitle as? String
detailMVC.dAddress = myIndexedAddress as? String
} else if segue.identifier == "goTotalMap" {
let totalMVC = segue.destination as! TotalMapViewController
totalMVC.dContents = contents
}
}
}
|
6be3dbd4c9a7420bc0cf95a3d60db663f14f2034
|
[
"Swift"
] | 3 |
Swift
|
jhkim3217/Busan-Seagull-Walkway
|
f96ce0b3eb9c3f87065314353b5e501895985132
|
0223f63cfe8e5eb0149e4787961499711e53303b
|
refs/heads/master
|
<repo_name>chungchen/line_clustering<file_sep>/basic_k_means.py
from sklearn.cluster import KMeans
# loads data from file
# input: tab delimited file where each line is a sample. Each tab is a feature
# output: array of arrays
def load_data(filename):
data = []
with open(filename) as fin:
for l in fin:
data_line = l.strip().split()
data.append(map(lambda x : float(x), data_line))
return data
# build k means model
# input:
# n_clusters = number of clusters to generate
# data = data input
# n_init = number of times k means will run
def build_k_means_model(n_clusters, data, n_init=10):
estimator = KMeans(init='k-means++', n_clusters=n_clusters, n_init=n_init)
estimator.fit(data)
return estimator
# score a trained model. Given a model and data, assign labels to the data
# input:
# model = trained model
# data = data to label
# output:
# labels = array of labels for each sample in data
def score_model(model, data):
return model.predict(data)
<file_sep>/chart_creator.py
import pygal
import os
def get_x_bounds(data):
min_x = None
max_x = None
for d in data:
if min_x == None or d[0] < min_x:
min_x = d[0]
if max_x == None or d[0] > max_x:
max_x = d[0]
return (min_x, max_x)
def create_cluster_chart(data, labels):
config = pygal.Config()
config.js.append(os.path.join(os.getcwd(), "static", "line.js"))
config.css.append(os.path.join(os.getcwd(), "static", "line.css"))
line_chart = pygal.Line(config)
line_chart.title = 'Line Clusters'
bounds = get_x_bounds(data)
num_x = bounds[1] - bounds[0] + 1
num_x = int(num_x)
print "bounds are %s" % (bounds,)
line_chart.x_labels = map(str, range(int(bounds[0]), int(bounds[1]) + 1))
for (d, l) in zip(data, labels):
# set all values to be None at first
values = [None] * num_x
# set the y coordinate of the x coordinate
values[int(d[0])] = d[1]
# if the data point is not at 0, set the 0th point to 0
if d[0] != 0:
values[0] = 0
line_chart.add(str(d) + "#" + str(l), values)
return line_chart.render_to_file('output1.svg')
<file_sep>/server.py
from flask import Flask
from basic_k_means import *
from chart_creator import *
import os
app = Flask(__name__,
static_folder=os.path.join(os.getcwd(), 'static'))
@app.route("/")
def hello():
return "Hello World!"
@app.route("/chart")
def chart():
data = load_data('basic_k_means_input.txt')
model = build_k_means_model(3, data)
result = score_model(model, data)
print result
return create_cluster_chart(data, result)
if __name__ == "__main__":
data = load_data('basic_k_means_input.txt')
model = build_k_means_model(4, data)
result = score_model(model, data)
print result
create_cluster_chart(data, result)
#app.run()
|
3fe2f83b711a7244e6a62caa463962cb884873da
|
[
"Python"
] | 3 |
Python
|
chungchen/line_clustering
|
b42aa233c1df758c1f2dda4bce5c8385ffc30876
|
36f3624562148e7b50463bde59757e6cabd38f74
|
refs/heads/master
|
<file_sep>import "./styles.css";
document.getElementById("app").innerHTML = `
<h1>Hello Vanilla!</h1>
<div>
We use Parcel to bundle this sandbox, you can find more info about Parcel
<a href="https://parceljs.org" target="_blank" rel="noopener noreferrer">here</a>.
</div>
<div>
Time :
</div>
`;
function timer() {
const myDate = new Date();
const myHour = myDate.getHours();
const myMin = myDate.getMinutes();
const mySec = myDate.getSeconds();
document.getElementById(
"clock"
).innerHTML = `<b>${myHour}:${myMin}:${mySec}</b>`;
}
function init() {
//console.log("hello world");
timer();
setInterval(timer, 1000);
}
init();
|
2e9bee958cc7a2e23559b492349615cb30065173
|
[
"JavaScript"
] | 1 |
JavaScript
|
JoshandNancy/JOSH_MOMENTUM
|
be0f1ccb9bb142277381f7d09126e2b16c314661
|
aa68879bc791d50e15e5ca1696ab1c780bc98c3b
|
refs/heads/master
|
<repo_name>Deeathex/AndroidAppMobileProject<file_sep>/app/src/main/java/deeathex/androidapp/persistance/AppDatabase.java
package deeathex.androidapp.persistance;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.content.Context;
import deeathex.androidapp.model.Movie;
import deeathex.androidapp.model.StoredAuth;
@Database(entities = {Movie.class, StoredAuth.class}, version = 17, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
private static AppDatabase INSTANCE;
public abstract MovieDAO movieDao();
public abstract AuthDAO authDao();
public static AppDatabase getDatabase(Context context) {
if (INSTANCE == null) {
INSTANCE =
Room.databaseBuilder(context, AppDatabase.class, "moviesDb")
.allowMainThreadQueries()
// recreate the database if necessary
.fallbackToDestructiveMigration()
.build();
}
return INSTANCE;
}
public static void destroyInstance() {
INSTANCE = null;
}
}
<file_sep>/app/src/main/java/deeathex/androidapp/persistance/AuthDAO.java
package deeathex.androidapp.persistance;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.OnConflictStrategy;
import android.arch.persistence.room.Query;
import java.util.List;
import deeathex.androidapp.model.StoredAuth;
@Dao
public interface AuthDAO {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void addAuth(StoredAuth auth);
@Query("select * from storedauth")
List<StoredAuth> getAuth();
@Query("delete from storedauth")
void removeAll();
}
<file_sep>/app/src/main/java/deeathex/androidapp/TokenService.java
package deeathex.androidapp;
public class TokenService {
public static String token;
public static String username;
}
|
bd92701a7f0817d2192e8fb3c69eae1ec77d64a9
|
[
"Java"
] | 3 |
Java
|
Deeathex/AndroidAppMobileProject
|
5c6f22c982ee267f64b1d57284bb8a20c9cbc87d
|
7d5fcb578e09f34c662f1df3a530274307770ae3
|
refs/heads/master
|
<file_sep># LMAOBot
## About
Developed in Node.js
## Running The Bot
You'll need to setup Node.js, and Python 2.7+!
* [Node.js](https://nodejs.org/en/)
* [Python 2.7*](https://www.python.org/)
Install dependencies:
```sh
# Ubuntu
apt-get install build-essential autoconf libtool sqlite3 ffmpeg git
# CentOS 7
rpm -v --import http://li.nux.ro/download/nux/RPM-GPG-KEY-nux.ro
rpm -Uvh http://li.nux.ro/download/nux/dextop/el7/x86_64/nux-dextop-release-0-5.el7.nux.noarch.rpm
yum install -y autoconf gcc-c++ libtool git make ffmpeg
# CentOS 8
dnf install epel-release dnf-utils
yum-config-manager --set-enabled PowerTools
yum-config-manager --add-repo=https://negativo17.org/repos/epel-multimedia.repo
dnf install -y autoconf gcc-c++ libtool git make ffmpeg
```
Install pm2 for startup control:
```sh
npm install pm2@latest -g
```
Download the bot:
```sh
cd /opt
git clone https://github.com/calvinkatz/LMAOBot.git
```
Add user and setup permissions:
```sh
useradd -r -m lmaobot
chown -R lmaobot:lmaobot /opt/LMAOBot
chmod 664 /opt/LMAOBot/database.sql
su - lmaobot
cd /opt/LMAOBot
```
In the project's directory:
```sh
npm install node-gyp-build
npm install
npm install sqlite3 ffmpeg bufferutil erlpack@discordapp/erlpack node-opus opusscript sodium libsodium-wrappers uws
cp start.sh.sample start.sh
```
Edit *start.sh* and set TOKEN to your bot auth token then run the script.
Use pm2 to save the service config and generate the startup script:
```sh
pm2 save
pm2 startup
```
Take the output section from 'pm2 startup' and run in the terminal.
The service should be running and enabled for automatic start at boot.
Exclude the database from updates:
```sh
git update-index --assume-unchanged database.sql
```
<file_sep>const Discord = require('discord.js');
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'sqlite',
logging: false,
storage: 'database.sql',
});
const Sounds = sequelize.define('sounds', {
name: {
type: Sequelize.STRING,
unique: true,
},
url: Sequelize.STRING,
username: Sequelize.STRING,
usage_count: {
type: Sequelize.INTEGER,
defaultValue: 0,
allowNull: false,
},
});
module.exports = {
// Information
name: 'mysounds',
aliases: ['msound', '>s'],
description: 'Display all the sounds you\'ve added to LMAOBot.',
// Requirements
// Function
run: async (client, command, msg, args) => {
const sound = await Sounds.findAll({
where: {
username: {
[Sequelize.Op.like]: `% (${msg.author.id})`,
},
},
});
const soundString = sound.map(s => s.name).join(', ') || ':x: You don\'t have any sounds currently added!';
const embed = new Discord.RichEmbed()
.setTitle(`${msg.author.username}'s Sounds`)
.setDescription(`${soundString}`)
.setColor(0x2471a3);
msg.channel.send(embed);
},
};
<file_sep>// Import anything and everything required throughout the project
// *****************************************************************************
const Discord = require('discord.js');
// const snekfetch = require('snekfetch');
const ytdl = require('ytdl-core');
const Util = require('discord.js');
// const YouTube = require('simple-youtube-api');
// const youtube = new YouTube(process.env.YOUTUBE);
// const voteapi = 'https://discordbots.org/api/bots/398413630149885952/votes?onlyids=true';
const Sequelize = require('sequelize');
const fs = require('fs');
const https = require('https');
const DBL = require('dblapi.js');
const dbl = new DBL(process.env.DBL);
process.on('unhandledRejection', console.error);
// Setup Discord.js Client/Bot
// *****************************************************************************
const client = new Discord.Client({
disabledEvents: ['TYPING_START'],
});
// Setup Client's configuration
client.config = require('./configs/bot.json');
client.reaction_msgs = new Discord.Collection();
client.cooldowns = new Discord.Collection();
// Setup Client's commands
client.commands = new Discord.Collection();
const command_folders = fs.readdirSync('./commands');
for (const folder of command_folders) {
const command_files = fs.readdirSync(`./commands/${folder}`);
for (const file of command_files) {
if (file.split('.').pop() === 'js') {
const command = require(`./commands/${folder}/${file}`);
command.category = folder;
client.commands.set(command.name, command);
}
}
}
// Setup Client's custom function
// *****************************************************************************
/**
* Check wheter given user ID belongs to a bot's developer.
* @param {Integer} [id] User's ID.
* @return {Boolean} True if it's a developer's id; false, if it's not.
*/
client.is_developer = (id) => {
return client.config.developer_ids.includes(id);
};
/**
* Adds a msg to reaction listening collection.
* @param {Object} [command] Object representing a bot's command.
* @param {String/Object} [message] Discord Message's id/ Discord Message object.
* @param {Array} [reactions] Array containing all Reactions to listen for.
* @param {Object} [options] Object containing options; options: timeout: integer/false, user_id: string
* @return {Boolean} True if added; else false.
*/
client.add_msg_reaction_listener = async (command, message, reactions, options) => {
options = Object.assign({
time: 60,
extra: {},
}, options);
for (const reaction of reactions) {
await message.react(reaction);
}
client.reaction_msgs.set(message.id, {
time: options.time,
emojis: reactions,
command_name: command.name,
message: message,
extra: options.extra,
});
};
/**
* Adds a msg to reaction listening collection.
* @param {String/Object} [message] Discord Message's id/ Discord Message object.
* @return {Boolean} True if added; else false.
*/
client.remove_msg_reaction_listener = (message) => { };
// Setup SQL database conneciton
// *****************************************************************************
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'sqlite',
logging: false,
storage: 'database.sql',
});
// Setup Sound manager
// *****************************************************************************
const Sounds = sequelize.define('sounds', {
name: {
type: Sequelize.STRING,
unique: true,
},
url: Sequelize.STRING,
username: Sequelize.STRING,
usage_count: {
type: Sequelize.INTEGER,
defaultValue: 0,
allowNull: false,
},
});
// Setup Client's events handlers
// *****************************************************************************
client.on('ready', () => {
// Setup Sound and Currency system
Sounds.sync();
// userInfo.sync();
// Setup Bot
client.shard.broadcastEval('this.guilds.size').then(results => {
client.user.setActivity(`${client.config.prefix} help | ${results.reduce((prev, val) => prev + val, 0)} servers`);
});
console.log('Ready sir...');
setInterval(async () => {
client.shard.broadcastEval('this.guilds.size').then(results => {
dbl.postStats(results.reduce((prev, val) => prev + val, 0));
client.user.setActivity(`${client.config.prefix} help | ${results.reduce((prev, val) => prev + val, 0)} servers`);
});
}, 600000);
});
client.on('message', async msg => {
if (!msg.content.startsWith(client.config.prefix) || msg.author.bot) return;
// Cache data to userInfo database.
// try {
// const userinf = await userInfo.create({
// id: msg.author.id,
// user_name: `${msg.author.username}#${msg.author.discriminator}`,
// });
// } catch (err) {
// if (err.name !== 'SequelizeUniqueConstraintError') console.log(`Got an error: ${err}`);
// }
// const finduser = await userInfo.findOne({
// where: {
// id: msg.author.id,
// },
// });
// if (finduser) {
// finduser.increment('cmdsrun');
// }
// Convert input into command name & args
const args = msg.content.slice(client.config.prefix.length + 1).split(/ +/);
const command_name = args.shift().toLowerCase();
// Find a command by it's name or aliases
const command = client.commands.get(command_name) || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(command_name));
if (!command) return;
// Check that command arguments requirements are met
if ('args' in command && command.args.req && command.args.min > args.length) {
return msg.channel.send(`You didn't provide the required arguments!\nUsage: \`${client.config.prefix} ${command.name} ` + ('usage' in command ? command.usage : '') + '`');
}
// Check whether it's a developer only command
if ('dev_only' in command && command.dev_only && !client.is_developer(msg.author.id)) {
return msg.channel.send({
embed: {
color: 0x2471a3,
title: ':x: Access Denied!!!',
description: 'Nice try, but only **Bot Developers** can run this command!',
},
});
}
// Check whether it's a guild only command
if ('guild_only' in command && command.guild_only && msg.channel.type !== 'text') {
return msg.channel.send({
embed: {
color: 0x2471a3,
title: ':x: Server Command!!!',
description: 'I can only execute that command inside **Servers**!',
},
});
}
// Check whether command is on cooldown for user
if ('cooldown' in command && command.cooldown >= 1) {
const data = client.cooldowns.get(`${command.name}:${msg.author.id}`);
if (data === undefined) {
client.cooldowns.set(`${command.name}:${msg.author.id}`, {
command: command.name,
user: msg.author.id,
started: Date.now(),
});
} else {
const time_left = Math.round((command.cooldown - (Date.now() - data.started) / 1000) * 100) / 100;
if (time_left > 0) {
return msg.channel.send({
embed: {
color: 0x2471a3,
title: ':x: Command On Cooldown!!!',
description: `Please wait *${time_left} second(s)* before reusing the \`${command.name}\` command.`,
},
});
} else {
data.started = Date.now();
}
}
}
try {
command.run(client, command, msg, args);
} catch (error) {
console.error(error);
msg.channel.send('There was an error in trying to execute that command!');
}
});
client.on('messageReactionAdd', (reaction, user) => {
if (user.bot) return;
const data = client.reaction_msgs.get(reaction.message.id);
if (!data) return;
if (data.time <= ((Date.now() - data.message.createdAt) / 1000)) return client.reaction_msgs.delete(reaction.message.id);
if (data.emojis.includes(reaction.emoji.name)) {
const command = client.commands.get(data.command_name);
if (!command) return;
try {
command.on_reaction(client, command, data, 'added', reaction);
} catch (error) {
console.error(error);
data.message.channel.send('There was an error in trying to execute that command!');
}
}
});
client.on('messageReactionRemove', (reaction, user) => {
if (user.bot) return;
const data = client.reaction_msgs.get(reaction.message.id);
if (!data) return;
if (data.time <= ((new Date() - data.message.createdAt) / 1000)) return client.reaction_msgs.delete(reaction.message.id);
if (data.emojis.includes(reaction.emoji.name)) {
const command = client.commands.get(data.command_name);
if (!command) return;
try {
command.on_reaction(client, command, data, 'removed', reaction);
} catch (error) {
console.error(error);
data.message.channel.send('There was an error in trying to execute that command!');
}
}
});
client.on('guildCreate', guild => {
// Get channel in which bot is allowed to msg
const default_channel = guild.channels.find(channel => channel.type === 'text' && channel.permissionsFor(guild.me).has('SEND_MESSAGES'));
if (!default_channel) return;
default_channel.send({
embed: {
color: 0x2471a3,
author: {
name: client.user.username,
icon_url: client.user.avatarURL,
},
title: 'Howdy folks!',
url: 'https://discord.js.org/#/',
description: `Thnx veri much for inViting mi to **${guild.name}**!!1! I'm **LMAOBot**, a f4ntast1c b0t developed by *${client.config.developers.join(', ')}*! \n \nTo look at the list of my commands, type __**'${client.config.prefix} help'**__! \n \nHey you! yeah.. you!11! W4nt to upv0te LMAOBot to gain __***EXCLUSIVE***__ features such as upvote only commands, and a sexy role on the support server?!?!?11 You can do so by typing **'${client.config.prefix} upvote'** in chat! Thnx xoxo :heart: \n \nIf you're having any problems, feel free to join my support server [here](${client.config.support_server})!`,
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL,
text: client.config.embed.footer,
},
},
});
});
client.login(process.env.TOKEN);<file_sep>module.exports = {
// Information
name: 'ask',
description: 'Ask LMAOBot a yes or no question and he\'ll answer.',
usage: '<question>',
// Requirements
args: {
req: true,
min: 1,
},
// Custom Data
responses: [
'Yes!',
'No!',
],
// Function
run: (client, command, msg, args) => {
msg.channel.send(command.responses[Math.floor(Math.random() * command.responses.length)]);
},
};<file_sep>module.exports = {
// Information
name: 'magik',
aliases: ['fp', 'mp'],
description: 'LMAOBot will fuck up your profile pic.',
// Requirements
// Function
run: (client, command, msg, args) => {
const URL = msg.member.user.avatarURL;
msg.channel.send({
embed: {
author: {
name: client.user.username,
icon_url: client.user.avatarURL,
},
title: ':thinking:',
image: {
url: `https://discord.services/api/magik?url=${URL}`,
},
color: 0x2471a3,
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL,
text: client.config.embed.footer,
},
},
});
},
};<file_sep>#!/bin/bash
TOKEN=xxxxxx pm2 start index.js
<file_sep>module.exports = {
// Information
name: 'roll',
description: 'LMAOBot will roll the dice for you.',
// Requirements
// Function
run: (client, command, msg, args) => {
msg.channel.send('You rolled a ' + (Math.floor(Math.random() * 100) + 1) + '!');
},
};<file_sep>module.exports = {
// Information
name: 'agree',
aliases: ['ok'],
description: 'LMAOBot agrees with you.',
// Requirements
// Function
run: (client, command, msg, args) => {
msg.channel.send(`I agree with ${msg.member.user}`);
},
};<file_sep>const Discord = require('discord.js');
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'sqlite',
logging: false,
storage: 'database.sql',
});
const Sounds = sequelize.define('sounds', {
name: {
type: Sequelize.STRING,
unique: true,
},
url: Sequelize.STRING,
username: Sequelize.STRING,
usage_count: {
type: Sequelize.INTEGER,
defaultValue: 0,
allowNull: false,
},
});
module.exports = {
// Information
name: 'listsounds',
aliases: ['lsound', '*s'],
description: 'List of sounds from LMAOBot\'s sound board.',
// Requirements
// Function
run: async (client, command, msg, args) => {
const soundList = await Sounds.findAll({
attributes: ['name'],
});
const soundString = soundList.map(s => s.name).sort(() => Math.random() - 0.5).join(', ').slice(0, 2048) || ':x: There are no sounds currently set!';
const embed = new Discord.RichEmbed()
.setTitle('Featured Sounds:')
.setDescription(`${soundString}`)
.setColor(0x2471a3)
.setFooter('To add sounds, type \'lmao addsound <sound name> <youtube url>\'');
return msg.channel.send({
embed,
});
},
};<file_sep>module.exports = {
// Information
name: 'dankrate',
aliases: ['dank', 'd%', '%d'],
description: 'LMAOBot will rank your dankness.',
// Requirements
// Function
run: (client, command, msg, args) => {
const randomnumber = Math.floor(Math.random() * 101);
msg.channel.send({
embed: {
author: {
name: client.user.username,
icon_url: client.user.avatarURL,
},
title: 'Scanning...',
thumbnail: {
url: msg.author.avatarURL,
},
description: `${msg.member.user.username} is ${randomnumber}% dank! :fire:`,
color: 0x2471a3,
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL,
text: client.config.embed.footer,
},
},
});
},
};<file_sep>const rp = require('request-promise');
module.exports = {
// Information
name: 'reddit',
description: 'Browse through Reddit via Discord.',
usage: '<subreddit> <view>',
explanation: {
subreddit: {
description: 'Subreddit to pull post from.',
default: 'random',
},
view: {
description: 'What sort of post to view.',
default: 'hot',
options: ['hot', 'top', 'new', 'rising', 'controversial'],
},
},
aliases: ['re'],
// Requirements
// Custom Data
subreddits: [
'dankmemes',
'fffffffuuuuuuuuuuuu',
'vertical',
'AdviceAnimals',
'Inglip',
'wholesomememes',
'MemeEconomy',
'BlackPeopleTwitter',
'shittyadviceanimals',
'ProgrammerHumor',
'oddlysatisfying',
'mildlyinfuriating',
'softwaregore',
'me_irl',
'mildlyinteresting',
],
// Function
run: async (client, command, msg, args) => {
let subreddit = command.subreddits[Math.floor(Math.random() * command.subreddits.length)];
if (args.length > 0) {
subreddit = args[0].toLowerCase();
}
let endpoint = 'hot';
if (args.length >= 2 && command.explanation.view.options.includes(args[1].toLowerCase())) {
endpoint = args[1].toLowerCase();
}
const url = `https://www.reddit.com/r/${subreddit}/${endpoint}/`;
let response;
try {
response = await rp(`https://www.reddit.com/r/${subreddit}/${endpoint}.json?limit=100`);
} catch (error) {
return msg.channel.send({
embed: {
color: 0x00AE86,
author: {
name: client.user.username,
icon_url: client.user.avatarURL,
},
title: `r/${subreddit}/${endpoint}`,
description: 'Subreddit was not found :confused:',
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL,
text: client.config.embed.footer,
},
},
});
}
const posts = JSON.parse(response).data.children;
if (posts.length === 0) {
return msg.channel.send({
embed: {
color: 0x00AE86,
author: {
name: client.user.username,
icon_url: client.user.avatarURL,
},
title: `r/${subreddit}/${endpoint}`,
description: 'Nothing was found :confused:',
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL,
text: client.config.embed.footer,
},
},
});
}
let index = 0;
let checks = 0;
do {
if (checks >= 100) {
return msg.channel.send({
embed: {
color: 0x00AE86,
author: {
name: client.user.username,
icon_url: client.user.avatarURL,
},
title: `r/${subreddit}/${endpoint}`,
description: 'Nothing was found :confused:',
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL,
text: client.config.embed.footer,
},
},
});
}
checks += 1;
index = Math.floor(Math.random() * posts.length);
if (index < 0) {
index = posts.length - 1;
} else if (index > (posts.length - 1)) {
index = 0;
}
} while (posts[index].data.over_18 || !('preview' in posts[index].data) || posts[index].data.preview.images.length === 0);
const reply = await msg.channel.send({
embed: command.post_embed(client, posts[index].data, {
url: url,
subreddit: subreddit,
endpoint: endpoint,
}),
});
await client.add_msg_reaction_listener(command, reply, ['⬅', '🔄', '➡'], {
extra: {
url: url,
subreddit: subreddit,
endpoint: endpoint,
index: index,
posts: posts,
},
});
},
post_embed: (client, post, data) => {
return {
color: 0x00AE86,
author: {
name: client.user.username,
icon_url: client.user.avatarURL,
},
title: `r/${data.subreddit}/${data.endpoint}`,
url: data.url,
description: `[${post.title}](https://reddit.com${post.permalink})\n${post.selftext}`,
image: {
url: post.url,
},
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL,
text: client.config.embed.footer,
},
};
},
on_reaction: (client, command, data, operation, reaction) => {
let checks = 0;
do {
if (checks >= 100) {
return data.message.edit({
embed: {
color: 0x00AE86,
author: {
name: client.user.username,
icon_url: client.user.avatarURL,
},
title: `r/${data.extra.subreddit}/${data.extra.endpoint}`,
description: 'Nothing was found :confused:',
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL,
text: client.config.embed.footer,
},
},
});
}
checks += 1;
if (reaction.emoji.name === '⬅') {
data.extra.index -= 1;
} else if (reaction.emoji.name === '🔄') {
data.extra.index = Math.floor(Math.random() * data.extra.posts.length);
} else if (reaction.emoji.name === '➡') {
data.extra.index += 1;
}
if (data.extra.index < 0) {
data.extra.index = data.extra.posts.length - 1;
} else if (data.extra.index > (data.extra.posts.length - 1)) {
data.extra.index = 0;
}
} while (data.extra.posts[data.extra.index].data.over_18 || !('preview' in data.extra.posts[data.extra.index].data) || data.extra.posts[data.extra.index].data.preview.images.length === 0);
data.message.edit({
embed: command.post_embed(client, data.extra.posts[data.extra.index].data, {
url: data.extra.url,
subreddit: data.extra.subreddit,
endpoint: data.extra.endpoint,
}),
});
},
};<file_sep>module.exports = {
// Information
name: 'pun',
description: 'LMAOBot will tell you a pun.',
// Requirements
// Custom Data
responses: [
'About a month before he died, my uncle had his back covered in lard. After that, he went down hill fast.',
'I bought some shoes from a drug dealer. I don\'t know what he laced them with, but I\'ve been tripping all day.',
'For Halloween we dressed up as almonds. Everyone could tell we were nuts.',
'My dad died when we couldn\'t remember his blood type. As he died, he kept insisting for us to \'be positive\', but it\'s hard without him.',
'Atheists don\'t solve exponential equations because they don\'t believe in higher powers.',
'What\'s the difference of deer nuts and beer nuts? Beer nuts are a $1.75, but deer nut are under a buck.',
'The future, the present and the past walked into a bar. Things got a little tense.',
'Atheism is a non-prophet organization.',
'I just found out I\'m colorblind. The diagnosis came completely out of the purple.',
'I saw an ad for burial plots, and thought to myself this is the last thing I need.',
'What do you call a dictionary on drugs? HIGH-Definition.',
'Just burned 2,000 calories. That\'s the last time I leave brownies in the oven while I nap.',
'What did E.T.\'s mother say to him when he got home? \'Where on Earth have you been?!\'',
'Did you hear about the kidnapping at school? It\'s okay. He woke up.',
'Two blondes were driving to Disneyland. The sign said, \'Disneyland Left\'. So they started crying and went home.',
'Dr.\'s are saying not to worry about the bird flu because it\'s tweetable.',
'Heard about the drug addict fisherman who accidentally caught a duck? Now he\'s hooked on the quack.',
'I don\'t engage in mental combat with the unarmed.',
'Oxygen is proven to be a toxic gas. Anyone who inhales oxygen will normally dies within 80 years.',
'I ordered 2000 lbs. of chinese soup. It was Won Ton.',
'Claustrophobic people are more productive thinking out of the box.',
'Did you hear they banned fans from doing \'The Wave\' at all sports events? Too many blondes were drowning.',
'A termite walks into a bar and says, \'Where is the bar tender?\'',
'eBay is so useless. I tried to look up lighters and all they had was 13,749 matches',
'Did you hear about the 2 silk worms in a race? It ended in a tie!',
'What\'s the difference between a poorly dressed man on a bicycle and a nicely dressed man on a tricycle? A tire.',
'A cop just knocked on my door and told me that my dogs were chasing people on bikes. My dogs don\'t even own bikes...',
'I was addicted to the hokey pokey... but thankfully, I turned myself around.',
'Why do the French eat snails? They don\'t like fast food.',
],
// Function
run: (client, command, msg, args) => {
msg.channel.send(command.responses[Math.floor(Math.random() * command.responses.length)]);
},
};<file_sep>const ytdl = require('ytdl-core');
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'sqlite',
logging: false,
storage: 'database.sql',
});
const Sounds = sequelize.define('sounds', {
name: {
type: Sequelize.STRING,
unique: true,
},
url: Sequelize.STRING,
username: Sequelize.STRING,
usage_count: {
type: Sequelize.INTEGER,
defaultValue: 0,
allowNull: false,
},
});
module.exports = {
// Information
name: 'addsound',
aliases: ['asound', '+s'],
description: 'Add a sound to the bot\'s sound board.',
usage: '<sound name> <youtube url>',
// Requirements
args: {
req: true,
min: 2,
},
// Function
run: async (client, command, msg, args) => {
process.on('unhandledRejection', console.error);
const soundName = args[0],
soundURL = args[1];
// Check that youtube url is valid
if (!soundURL.includes('youtube.com/watch?' || 'youtu.be/')) return msg.channel.send(' :x: Invalid YouTube URL!');
if (soundURL.includes('list' || 'playlist')) return msg.channel.send(' :x: Nice try, you can\'t add a playlists!');
// Extract info from youtube url
ytdl.getInfo(soundURL, async (err, info) => {
if (info.length_seconds > 60) {
return msg.channel.send(' :x: You cannot add sounds longer than 1 minute!');
}
try {
const sound = await Sounds.create({
name: soundName,
url: soundURL,
username: `${msg.author.username}#${msg.member.user.discriminator} (${msg.author.id})`,
});
return msg.channel.send(` sound **${sound.name}** added!`);
} catch (e) {
console.log("Error occured:");
console.log(e.name);
console.log(e.message);
console.log(e.stack);
if (e.name === 'SequelizeUniqueConstraintError') return msg.channel.send(' that sound already exists!');
return msg.channel.send(' something went wrong while adding the sound: ```' + error + '```Join the support server for help on this issue.');
}
});
},
};<file_sep>module.exports = {
// Information
name: 'gayrate',
aliases: ['gay', 'g%', '%g'],
description: 'LMAOBot will tell you how gay you\'re.',
// Requirements
// Function
run: (client, command, msg, args) => {
const randomnumber = Math.floor(Math.random() * 101);
msg.channel.send({
embed: {
author: {
name: client.user.username,
icon_url: client.user.avatarURL,
},
title: 'Scanning...',
thumbnail: {
url: msg.author.avatarURL,
},
description: `${msg.member.user.username} is ${randomnumber}% gay! :gay_pride_flag:`,
color: 0x2471a3,
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL,
text: client.config.embed.footer,
},
},
});
},
};<file_sep>module.exports = {
// Information
name: '8ball',
aliases: ['8', '8b'],
description: 'Get a eight ball\'s response.',
usage: '<question>',
// Requirements
args: {
req: true,
min: 1,
},
// Custom data
responses: [
'Yes!',
'No...',
'Maybe.',
'Probably.',
'I dont think so.',
'Never!',
'Indeed.',
'Certainly.',
'There is a possibility.',
'No way!',
'As I see it, yes.',
'Most likely.',
'You may rely on it.',
'Signs point to yes.',
],
// Function
run: (client, command, msg, args) => {
msg.channel.send(command.responses[Math.floor(Math.random() * command.responses.length)]);
},
};
<file_sep>const snekfetch = require('snekfetch');
module.exports = {
// Information
name: 'chuck',
description: 'LMAOBot will tell you a Check Norris joke.',
// Requirements
// Function
run: async (client, command, msg, args) => {
const chuckapi = 'http://api.icndb.com/jokes/random?firstName=Chuck&lastName=Norris';
await snekfetch.get(chuckapi).query('joke', true).then(res => {
msg.channel.send({
embed: {
author: {
name: client.user.username,
icon_url: client.user.avatarURL,
},
title: '<NAME>',
description: `*${res.body.value.joke}*`,
color: 0x2471a3,
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL,
text: client.config.embed.footer,
},
},
});
});
},
};
|
a65baeaf45fc976a491fb12cfa1dea2796d3eb66
|
[
"Markdown",
"JavaScript",
"Shell"
] | 16 |
Markdown
|
calvinkatz/LMAOBot
|
82f0ddc66413f82438b4fb255d694db97495dbca
|
4bbe3a695cca3d20c6e2865718084545bf154b98
|
refs/heads/master
|
<file_sep>RailsAdmin.config do |config|
### Popular gems integration
## == Authenticate using Devise ==
config.authenticate_with do
warden.authenticate! scope: :user
end
config.current_user_method(&:current_user)
## == Authorize manually ==
config.authorize_with do
redirect_to main_app.root_path unless current_user.try(:admin?)
end
## == PaperTrail ==
# config.audit_with :paper_trail, 'User', 'PaperTrail::Version' # PaperTrail >= 3.0.0
### More at https://github.com/sferik/rails_admin/wiki/Base-configuration
config.actions do
dashboard # mandatory
index # mandatory
new
export
bulk_delete
show
edit
delete
show_in_app
## With an audit adapter, you can add:
# history_index
# history_show
end
config.included_models = ['User', 'Game', 'Tag', 'Log', 'Comment', 'Group']
config.model 'User' do
object_label_method :username
end
config.model 'Game' do
edit { exclude_fields :slug }
end
config.model 'Tag' do
configure :kind, :enum do
enum { ['mechanic', 'theme', 'category'] }
end
edit { exclude_fields :slug }
end
config.model 'Group' do
edit { exclude_fields :slug }
end
end
<file_sep>module Memberships
class CreateService
def initialize(group, user)
@group = group
@user = user
end
def run!
@group.members << @user unless @user.member_of?(@group)
end
end
end
<file_sep>class Group < ActiveRecord::Base
extend FriendlyId
friendly_id :name, use: [:slugged, :finders]
has_many :memberships, dependent: :destroy
has_many :admins, -> { merge Membership.admin }, through: :memberships, source: :user
has_many :members, through: :memberships, source: :user
has_many :games, -> { uniq }, through: :members
has_many :logs
with_options class_name: 'PublicActivity::Activity', as: :recipient do |group|
group.has_many :activities
group.has_many :membership_activities, -> { where(trackable_type: 'Membership') }, dependent: :destroy
group.has_many :log_activities, -> { where(trackable_type: 'Log') }, dependent: :nullify
end
validates :name, presence: true, uniqueness: true
validates :founded_at, presence: true
validates :admins, presence: true
end
<file_sep>class Play < ActiveRecord::Base
belongs_to :log
belongs_to :game
validates :log, presence: true, uniqueness: { scope: :game }
validates :game, presence: true, uniqueness: { scope: :log }
end
<file_sep>require 'rails_helper'
RSpec.describe Likes::CreateService, type: :service do
let(:user) { create(:user) }
let(:log) { create(:log) }
let(:service) { Likes::CreateService.new(user, log) }
describe "#run!" do
context "when passed a log that user has not liked" do
it "creates a like on that log" do
service.run!
expect(Like.where(user: user, log: log)).to exist
end
end
context "when passed a log that user likes" do
before { create(:like, user: user, log: log) }
it "does not change likes" do
expect { service.run! }.not_to change(user, :likes)
end
end
end
end
<file_sep>class SearchController < ApplicationController
def games
@query = params[:q]
@games = Game.search @query
end
end
<file_sep>class CreateMemberships < ActiveRecord::Migration
def change
create_table :memberships do |t|
t.references :group, index: true, null: false
t.references :user, index: true, null: false
t.integer :status, null: false, default: 0
t.timestamps null: false
end
add_foreign_key :memberships, :groups, on_delete: :cascade
add_foreign_key :memberships, :users, on_delete: :cascade
add_index :memberships, [:group_id, :user_id], unique: true
add_index :memberships, [:user_id, :group_id], unique: true
end
end
<file_sep>module Likes
class CreateService
def initialize(user, log)
@user = user
@log = log
end
def run!
@user.likes.create(log: @log) unless @user.likes?(@log)
end
end
end
<file_sep>module Likes
class DestroyService
def initialize(user, log)
@user = user
@log = log
end
def run!
@user.likes.where(log: @log).destroy_all
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe Game, type: :model do
describe "#bgg_url" do
context "when bgg_id is present" do
let(:game) { build_stubbed(:game, :with_bgg) }
it "returns a url to boardgamegeek.com's game page" do
expect(game.bgg_url).to eq("https://boardgamegeek.com/boardgame/#{game.bgg_id}")
end
end
context "when bgg_id is not present" do
let(:game) { build_stubbed(:game) }
it "returns nil" do
expect(game.bgg_url).to be_nil
end
end
end
end
<file_sep>class RenameCategoryToKindInTags < ActiveRecord::Migration
def change
rename_column :tags, :category, :kind
end
end
<file_sep>require 'rails_helper'
RSpec.describe Groups::MembersController, type: :controller do
let(:group) { create(:group, :with_members) }
let(:user) { create(:user) }
let(:other_user) { create(:user) }
describe "GET #index" do
it "shows group's members" do
get :index, group_id: group
expect(response).to have_http_status(:ok)
expect(assigns :members).to eq(group.reload.members)
end
end
describe "POST #create" do
context "when user is signed in" do
before { sign_in user }
it "requires authorization" do
post :create, group_id: group, id: other_user
expect(response).to have_http_status(:unauthorized)
end
it "adds the user to group's members" do
post :create, group_id: group, id: user
expect(response).to have_http_status(:ok)
expect(user.member_of? group).to be_truthy
end
end
context "when user is not signed in" do
it "redirects to sign in page" do
post :create, group_id: group, id: user
expect(response).to redirect_to new_user_session_path
end
end
end
describe "DELETE #destroy" do
before do
create(:membership, group: group, user: user)
create(:membership, group: group, user: other_user)
end
context "when user is signed in" do
before { sign_in user }
it "requires authorization" do
post :destroy, group_id: group, id: other_user
expect(response).to have_http_status(:unauthorized)
end
it "removes the user from group's members" do
delete :destroy, group_id: group, id: user
expect(response).to have_http_status(:no_content)
expect(user.member_of? group).to be_falsy
end
end
context "when user is not signed in" do
it "redirects to sign in page" do
delete :destroy, group_id: group, id: user
expect(response).to redirect_to new_user_session_path
end
end
end
end
<file_sep>class ChangeCommentToNonPolymorphic < ActiveRecord::Migration
def change
add_reference :comments, :log, index: true
Comment.where.not(commentable_type: 'Log').destroy_all
Comment.find_each do |comment|
comment.update log_id: comment.commentable_id
end
change_column_null :comments, :log_id, false
add_foreign_key :comments, :logs, on_delete: :cascade
remove_reference :comments, :commentable, polymorphic: true
end
end
<file_sep>class Attachment < ActiveRecord::Base
belongs_to :attachable, polymorphic: true
has_attached_file :photo, styles: { small: '200x200>', original: '1280x1280>' }
validates :attachable, presence: true
validates_attachment :photo, presence: true, content_type: { content_type: ['image/jpeg', 'image/gif', 'image/png'] }
end
<file_sep>module Memberships
class DestroyService
def initialize(group, user)
@group = group
@user = user
end
def run!
@group.members.delete @user
end
end
end
<file_sep>class CreateGames < ActiveRecord::Migration
def change
create_table :games do |t|
t.string :title, null: false
t.string :slug
t.references :base, index: true
t.timestamps null: false
end
add_foreign_key :games, :games, column: 'base_id', on_delete: :nullify
add_index :games, :slug, unique: true
end
end
<file_sep>class CreatePlays < ActiveRecord::Migration
def change
create_table :plays do |t|
t.references :log, index: true, null: false
t.references :game, index: true, null: false
t.timestamps null: false
end
add_foreign_key :plays, :logs, on_delete: :cascade
add_foreign_key :plays, :games, on_delete: :cascade
add_index :plays, [:log_id, :game_id], unique: true
add_index :plays, [:game_id, :log_id], unique: true
end
end
<file_sep>module Wishes
class CreateService
def initialize(user, game)
@user = user
@game = game
end
def run!
ActiveRecord::Base.transaction do
@user.games.delete @game if @user.owns?(@game)
@user.wished_games << @game unless @user.wishes?(@game)
end
end
end
end
<file_sep>class Tag < ActiveRecord::Base
extend FriendlyId
friendly_id :name, use: [:slugged, :finders]
enum kind: [:mechanic, :theme, :category]
has_many :taggings, dependent: :destroy
has_many :games, through: :taggings
validates :name, presence: true, uniqueness: true
validates :kind, presence: true
end
<file_sep>require 'rails_helper'
RSpec.describe Ownership, type: :model do
let(:user) { create(:user) }
let(:game) { create(:game) }
describe "#save" do
it "increments games count of the owning user by 1" do
expect { create(:ownership, user: user, game: game) }.to change { user.reload.games_count }.by 1
end
it "increments owners count of the owned game by 1" do
expect { create(:ownership, user: user, game: game) }.to change { game.reload.owners_count }.by 1
end
it "creates a ownership activity" do
create(:ownership, user: user, game: game)
expect(user.activities.where(key: "ownership.create", recipient: game)).to exist
end
end
describe "#destroy" do
let!(:ownership) { create(:ownership, user: user, game: game) }
it "decrements games count of the owning user by 1" do
expect { ownership.destroy }.to change { user.reload.games_count }.by -1
end
it "decrements owners count of the owned game by 1" do
expect { ownership.destroy }.to change { game.reload.owners_count }.by -1
end
it "destroys ownership activities associated with the game" do
ownership.destroy
expect(user.activities.where(trackable_type: "Ownership", recipient: game)).not_to exist
end
end
end
<file_sep>class LikesController < ApplicationController
before_action :authenticate_user!, only: [:create, :destroy]
before_action :set_log, only: [:create, :destroy]
def create
Likes::CreateService.new(current_user, @log).run!
head :ok
end
def destroy
Likes::DestroyService.new(current_user, @log).run!
head :no_content
end
private
def set_log
@log = Log.find(params[:log_id])
end
end
<file_sep>class User < ActiveRecord::Base
extend FriendlyId
friendly_id :username, use: [:slugged, :finders]
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :ownerships, dependent: :destroy
has_many :games, through: :ownerships
has_many :wishes, dependent: :destroy
has_many :wished_games, through: :wishes, source: :game
has_many :logs, dependent: :destroy
has_many :comments, dependent: :destroy
has_many :likes, dependent: :destroy
has_many :memberships, dependent: :destroy
has_many :groups, through: :memberships
has_many :activities, class_name: 'PublicActivity::Activity', as: :owner, dependent: :destroy
validates :username, presence: true, format: { with: /\A[a-z][a-z0-9.]+\Z/ }
validates :username, uniqueness: true, case_sensitive: false
attr_accessor :login
class << self
def find_for_database_authentication(warden_conditions)
conditions = warden_conditions.dup
if login = conditions.delete(:login)
where(conditions.to_h).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
else
where(conditions.to_h).first
end
end
end
def owns?(game)
games.include?(game)
end
def wishes?(game)
wished_games.include?(game)
end
def likes?(log)
likes.exists?(log: log)
end
def member_of?(group)
groups.include?(group)
end
private
def should_generate_new_friendly_id?
username_changed?
end
end
<file_sep>FactoryGirl.define do
factory :wish do
user
game
end
end
<file_sep>class Like < ActiveRecord::Base
include PublicActivity::Model
tracked owner: :user, recipient: :log, only: [:create]
belongs_to :user
belongs_to :log, counter_cache: true
has_many :activities, class_name: 'PublicActivity::Activity', as: :trackable, dependent: :destroy
validates :user, presence: true, uniqueness: { scope: :log }
validates :log, presence: true, uniqueness: { scope: :user }
end
<file_sep>class AddLogsCountToUsers < ActiveRecord::Migration
def change
add_column :users, :logs_count, :integer, null: false, default: 0
end
end
<file_sep>Rails.application.routes.draw do
mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
devise_for :users, controllers: { registrations: 'users/registrations' }
resources :games, only: [:index, :show]
resources :tags, only: [:index, :show]
resources :logs, only: [:index, :show] do
resources :comments
resource :likes, only: [:create, :destroy]
end
resources :groups do
resources :members, only: [:index, :create, :destroy], controller: 'groups/members'
end
scope '/search', controller: :search, as: :search do
get :games
end
get ':id', to: 'users#show', as: :user
scope ':user_id', as: 'user' do
get '', to: 'users#show'
resources :games, only: [:index, :create, :destroy], controller: 'users/games'
resources :wishes, only: [:index, :create, :destroy], controller: 'users/wishes'
end
end
<file_sep>require 'rails_helper'
RSpec.describe Like, type: :model do
let(:user) { create(:user) }
let(:log) { create(:log) }
describe "#save" do
it "increments likes count of the liked log by 1" do
expect { create(:like, user: user, log: log) }.to change { log.reload.likes_count }.by 1
end
it "creates a like activity" do
create(:like, user: user, log: log)
expect(user.activities.where(key: "like.create", recipient: log)).to exist
end
end
describe "#destroy" do
let!(:like) { create(:like, user: user, log: log) }
it "decrements likes count of the liked log by 1" do
expect { like.destroy }.to change { log.reload.likes_count }.by -1
end
it "destroys like activities associated with the like" do
like.destroy
expect(user.activities.where(trackable_type: "Like", recipient: log)).not_to exist
end
end
end
<file_sep>FactoryGirl.define do
factory :game do
title { Faker::App.name }
trait :with_bgg do
bgg_id { Faker::Number.number(6) }
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe User, type: :model do
let(:user) { create(:user) }
let(:log) { create(:log) }
let(:game) { create(:game) }
let(:group) { create(:group) }
describe "#owns?" do
context "when passed a game that user does not own" do
it "returns false" do
expect(user.owns? game).to be_falsy
end
end
context "when passed a game that user owns" do
before { create(:ownership, user: user, game: game) }
it "returns true" do
expect(user.owns? game).to be_truthy
end
end
end
describe "#wishes?" do
context "when passed a game that user does not wish to own" do
it "returns false" do
expect(user.wishes? game).to be_falsy
end
end
context "when passed a game that user wishes to own" do
before { create(:wish, user: user, game: game) }
it "returns true" do
expect(user.wishes? game).to be_truthy
end
end
end
describe "#likes?" do
context "when passed a log that user has not liked" do
it "returns false" do
expect(user.likes? log).to be_falsy
end
end
context "when passed a log that user likes" do
before { create(:like, user: user, log: log) }
it "returns true" do
expect(user.likes? log).to be_truthy
end
end
end
describe "#member_of?" do
context "when passed a group that user is not a member of" do
it "returns false" do
expect(user.member_of? group).to be_falsy
end
end
context "when passed a group that user is a member of" do
before { create(:membership, user: user, group: group) }
it "returns true" do
expect(user.member_of? group).to be_truthy
end
end
end
describe "#username" do
context "when updated" do
let(:name) { Faker::Lorem.word }
it "updates slug to the value equal to username" do
expect { user.update username: name }.to change(user, :slug).to(name)
end
end
end
end
<file_sep>module Wishes
class DestroyService
def initialize(user, game)
@user = user
@game = game
end
def run!
@user.wished_games.delete @game
end
end
end
<file_sep>class Tagging < ActiveRecord::Base
belongs_to :tag
belongs_to :game
validates :tag, presence: true, uniqueness: { scope: :game }
validates :game, presence: true, uniqueness: { scope: :tag }
end
<file_sep>class CreateTaggings < ActiveRecord::Migration
def change
create_table :taggings do |t|
t.references :tag, index: true, null: false
t.references :game, index: true, null: false
t.timestamps null: false
end
add_foreign_key :taggings, :tags, on_delete: :cascade
add_foreign_key :taggings, :games, on_delete: :cascade
add_index :taggings, [:tag_id, :game_id], unique: true
add_index :taggings, [:game_id, :tag_id], unique: true
end
end
<file_sep>class Membership < ActiveRecord::Base
include PublicActivity::Model
tracked owner: :user, recipient: :group, only: [:create]
enum status: [:member, :admin]
belongs_to :group
belongs_to :user
has_many :activities, class_name: 'PublicActivity::Activity', as: :trackable, dependent: :destroy
validates :status, presence: true
validates :group, presence: true, uniqueness: { scope: :user }
validates :user, presence: true, uniqueness: { scope: :group }
end
<file_sep>class Player < ActiveRecord::Base
belongs_to :log
belongs_to :user
validates :log, presence: true, uniqueness: { scope: :user }
validates :user, presence: true, uniqueness: { scope: :log }
end
<file_sep>FactoryGirl.define do
factory :membership do
group
user
status :member
trait :admin do
status :admin
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe Users::GamesController, type: :controller do
let(:game) { create(:game) }
let(:user) { create(:user) }
let(:other_user) { create(:user) }
describe "GET #index" do
it "shows user's games" do
get :index, user_id: user
expect(response).to have_http_status(:ok)
expect(assigns :games).to eq(user.games)
end
end
describe "POST #create" do
context "when user is signed in" do
before { sign_in user }
it "requires authorization" do
post :create, user_id: other_user, id: game
expect(response).to have_http_status(:unauthorized)
end
it "adds the game to user's games" do
post :create, user_id: user, id: game
expect(response).to have_http_status(:ok)
expect(user.owns? game).to be_truthy
end
it "removes the game from user's wished games" do
create(:wish, user: user, game: game)
post :create, user_id: user, id: game
expect(response).to have_http_status(:ok)
expect(user.wishes? game).to be_falsy
end
end
context "when user is not signed in" do
it "redirects to sign in page" do
post :create, user_id: user, id: game
expect(response).to redirect_to new_user_session_path
end
end
end
describe "DELETE #destroy" do
before { create(:ownership, user: user, game: game) }
context "when user is signed in" do
before { sign_in user }
it "requires authorization" do
post :destroy, user_id: other_user, id: game
expect(response).to have_http_status(:unauthorized)
end
it "removes the game from user's games" do
delete :destroy, user_id: user, id: game
expect(response).to have_http_status(:no_content)
expect(user.owns? game).to be_falsy
end
end
context "when user is not signed in" do
it "redirects to sign in page" do
delete :destroy, user_id: user, id: game
expect(response).to redirect_to new_user_session_path
end
end
end
end
<file_sep>module Ownerships
class CreateService
def initialize(user, game)
@user = user
@game = game
end
def run!
ActiveRecord::Base.transaction do
@user.wishes.where(game: @game).destroy_all if @user.wishes?(@game)
@user.games << @game unless @user.owns?(@game)
end
end
end
end
<file_sep>class AddGroupToLogs < ActiveRecord::Migration
def change
add_reference :logs, :group, index: true
add_foreign_key :logs, :groups, on_delete: :nullify
end
end
<file_sep>require 'rails_helper'
RSpec.describe Ownerships::DestroyService, type: :service do
let(:user) { create(:user) }
let(:game) { create(:game) }
let(:service) { Ownerships::DestroyService.new(user, game) }
describe "#run!" do
context "when passed a game that user does not own" do
it "does not change games" do
expect { service.run! }.not_to change(user, :games)
end
end
context "when passed a game that user owns" do
before { create(:ownership, user: user, game: game) }
it "destroys the ownership on that game" do
service.run!
expect(Ownership.where(user: user, game: game)).not_to exist
end
end
end
end
<file_sep>class Ownership < ActiveRecord::Base
include PublicActivity::Model
tracked owner: :user, recipient: :game, only: [:create]
belongs_to :user, counter_cache: :games_count
belongs_to :game, counter_cache: :owners_count
has_many :activities, class_name: 'PublicActivity::Activity', as: :trackable, dependent: :destroy
validates :user, presence: true, uniqueness: { scope: :game }
validates :game, presence: true, uniqueness: { scope: :user }
end
<file_sep>class AddFoundedAtToGroups < ActiveRecord::Migration
def change
add_column :groups, :founded_at, :date
Group.find_each do |group|
group.update founded_at: group.created_at
end
change_column_null :groups, :founded_at, false
end
end
<file_sep>FactoryGirl.define do
factory :group do
transient do
admins_count 1
end
name { Faker::Lorem.sentence }
founded_at { Faker::Date.backward }
admins { create_list(:user, admins_count) }
trait :with_members do
transient do
members_count 1
end
members { create_list(:user, members_count) }
end
trait :with_logs do
transient do
logs_count 1
end
logs { create_list(:log, logs_count) }
end
end
end
<file_sep>class CreateOwnerships < ActiveRecord::Migration
def change
create_table :ownerships do |t|
t.references :user, index: true, null: false
t.references :game, index: true, null: false
t.timestamps null: false
end
add_foreign_key :ownerships, :users, on_delete: :cascade
add_foreign_key :ownerships, :games, on_delete: :cascade
add_index :ownerships, [:user_id, :game_id], unique: true
add_index :ownerships, [:game_id, :user_id], unique: true
end
end
<file_sep>require "rails_helper"
RSpec.describe Wishes::DestroyService, type: :service do
let(:user) { create(:user) }
let(:game) { create(:game) }
let(:service) { Wishes::DestroyService.new(user, game) }
describe "#run!" do
context "when passed a game that user has not wished not own" do
it "does not change wishes" do
expect { service.run! }.not_to change(user, :wishes)
end
end
context "when passed a game that user wishes to own" do
before { create(:wish, user: user, game: game) }
it "destroys the wish on that game" do
service.run!
expect(Wish.where(user: user, game: game)).not_to exist
end
end
end
end
<file_sep>class Log < ActiveRecord::Base
include PublicActivity::Model
tracked owner: :author, recipient: :group, only: [:create]
belongs_to :author, class_name: 'User', foreign_key: 'user_id', counter_cache: true
belongs_to :group
has_many :plays, dependent: :destroy
has_many :games, through: :plays
has_many :players, dependent: :destroy
has_many :users, through: :players
has_many :comments, dependent: :destroy
has_many :likes, dependent: :destroy
has_many :likers, through: :likes, source: :user
has_many :activities, class_name: 'PublicActivity::Activity', as: :trackable, dependent: :destroy
has_many :attachments, as: :attachable, dependent: :destroy
with_options class_name: 'PublicActivity::Activity', as: :recipient do |log|
log.has_many :received_activities
log.has_many :comment_activities, -> { where(trackable_type: 'Comment') }, dependent: :destroy
log.has_many :like_activities, -> { where(trackable_type: 'Like') }, dependent: :destroy
end
validates :author, presence: true
validates :name, presence: true
validates :played_at, presence: true
validates :games, presence: true
validates :users, presence: true
before_validation { users << author if users.exclude?(author) }
before_save do
activities.each { |a| a.update recipient: group } if changed.include?("group_id")
end
def photos
attachments.map(&:photo)
end
end
<file_sep>class Users::WishesController < ApplicationController
before_action :authenticate_user!, only: [:create, :destroy]
before_action :authorize!, only: [:create, :destroy]
before_action :set_game, only: [:create, :destroy]
def index
@user = user
@games = user.wished_games
end
def create
Wishes::CreateService.new(current_user, @game).run!
head :ok
end
def destroy
Wishes::DestroyService.new(current_user, @game).run!
head :no_content
end
private
def user
@user ||= User.find(params[:user_id])
end
def authorize!
head :unauthorized unless current_user == user
end
def set_game
@game ||= Game.find(params[:id])
end
end
<file_sep>require 'rails_helper'
RSpec.describe Group, type: :model do
describe "#destroy" do
context "when the group has members" do
let!(:group) { create(:group, :with_members) }
it "destroys all membership activities associated with the memberships of the group" do
group.destroy
expect(PublicActivity::Activity.where(trackable_type: "Membership", recipient: group)).not_to exist
end
end
context "when the group has logs" do
let!(:group) { create(:group, :with_logs) }
it "nullifies recipients of all log activities associated with the logs from the group" do
group.destroy
expect(PublicActivity::Activity.where(trackable: group.logs).map(&:recipient)).to all be_nil
end
end
end
end
<file_sep>class Comment < ActiveRecord::Base
include PublicActivity::Model
tracked owner: :user, recipient: :log, only: [:create]
belongs_to :user
belongs_to :log
has_many :activities, class_name: 'PublicActivity::Activity', as: :trackable, dependent: :destroy
validates :user, presence: true
validates :log, presence: true
validates :body, presence: true
end
<file_sep>class CreateLikes < ActiveRecord::Migration
def change
create_table :likes do |t|
t.references :user, index: true, null: false
t.references :log, index: true, null: false
t.timestamps null: false
end
add_foreign_key :likes, :users, on_delete: :cascade
add_foreign_key :likes, :logs, on_delete: :cascade
add_index :likes, [:user_id, :log_id], unique: true
add_index :likes, [:log_id, :user_id], unique: true
end
end
<file_sep>class Groups::MembersController < ApplicationController
before_action :authenticate_user!, only: [:create, :destroy]
before_action :set_user, only: [:create, :destroy]
before_action :authorize!, only: [:create, :destroy]
def index
@group = group
@members = group.members
end
def create
Memberships::CreateService.new(group, @user).run!
head :ok
end
def destroy
Memberships::DestroyService.new(group, @user).run!
head :no_content
end
private
def group
@group ||= Group.find(params[:group_id])
end
def authorize!
head :unauthorized unless current_user == @user
end
def set_user
@user ||= User.find(params[:id])
end
end
<file_sep>require "rails_helper"
RSpec.describe Wishes::CreateService, type: :service do
let(:user) { create(:user) }
let(:game) { create(:game) }
let(:service) { Wishes::CreateService.new(user, game) }
describe "#run!" do
context "when passed a game that user has not wished to own" do
it "creates an wish on that game" do
service.run!
expect(Wish.where(user: user, game: game)).to exist
end
end
context "when passed a game that user owns" do
before { create(:ownership, user: user, game: game) }
it "create an wish on that game" do
service.run!
expect(Wish.where(user: user, game: game)).to exist
end
it "removes the ownership on that game" do
service.run!
expect(Ownership.where(user: user, game: game)).not_to exist
end
end
context "when passed a game that user wishes to own" do
before { create(:wish, user: user, game: game) }
it "does not change wishes" do
expect { service.run! }.not_to change(user, :wishes)
end
end
end
end
<file_sep>FactoryGirl.define do
factory :log do
transient do
games_count 1
users_count 1
end
author
name { Faker::Lorem.sentence }
played_at { Faker::Date.backward }
games { create_list(:game, games_count) }
users { create_list(:user, users_count) }
end
end
<file_sep>require 'rails_helper'
RSpec.describe Log, type: :model do
let(:author) { create(:author) }
let(:group) { create(:group) }
let(:log) { create(:log) }
it "includes its author in its users" do
expect(log.users).to include(log.author)
end
describe "#save" do
it "increments logs count of its author" do
expect { create(:log, author: author) }.to change { author.reload.logs_count }.by 1
end
it "creates a log activity" do
log = create(:log, author: author)
expect(author.activities.where(key: "log.create", trackable: log)).to exist
end
context "when group is updated" do
let(:log) { create(:log, author: author) }
it "updates the log activities' recipient to the updated group" do
log.update group: group
expect(author.activities.where(trackable: log).map(&:recipient)).to all eq(group)
end
end
end
describe "#destroy" do
let!(:log) { create(:log, author: author) }
it "decrements logs count of its author" do
expect { log.destroy }.to change { author.reload.logs_count }.by -1
end
it "destroys log activities associated with the log" do
log.destroy
expect(author.activities.where(trackable: log)).not_to exist
end
it "destroys all comment activities associated with the comments on the log" do
log.destroy
expect(PublicActivity::Activity.where(trackable_type: "Comment", recipient: log)).not_to exist
end
it "destroys all like activities associated with the likes on the log" do
log.destroy
expect(PublicActivity::Activity.where(trackable_type: "Like", recipient: log)).not_to exist
end
end
describe "#photos" do
context "when it has no attachments" do
it "returns an empty array" do
expect(log.photos).to eq([])
end
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe LikesController, type: :controller do
let(:log) { create(:log) }
let(:user) { create(:user) }
describe "POST #create" do
context "when user is signed in" do
before { sign_in user }
it "likes the log" do
post :create, log_id: log
expect(response).to have_http_status(:ok)
expect(user.likes? log).to be_truthy
end
end
context "when user is not signed in" do
it "redirects to sign in page" do
post :create, log_id: log
expect(response).to redirect_to new_user_session_path
end
end
end
describe "DELETE #destroy" do
before { create(:like, user: user, log: log) }
context "when user is signed in" do
before { sign_in user }
it "unlikes the log" do
delete :destroy, log_id: log
expect(response).to have_http_status(:no_content)
expect(user.likes? log).to be_falsy
end
end
context "when user is not signed in" do
it "redirects to sign in page" do
delete :destroy, log_id: log
expect(response).to redirect_to new_user_session_path
end
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe Memberships::DestroyService, type: :service do
let(:group) { create(:group) }
let(:user) { create(:user) }
let(:service) { Memberships::DestroyService.new(group, user) }
describe "#run!" do
context "when passed a group that user is not a member of" do
it "does not change group's members" do
expect { service.run! }.not_to change(group, :members)
end
end
context "when passed a group that user is a member of" do
before { create(:membership, group: group, user: user) }
it "destroys the membership on that group" do
service.run!
expect(Membership.where(group: group, user: user)).not_to exist
end
end
end
end
<file_sep>class Game < ActiveRecord::Base
extend FriendlyId
friendly_id :title, use: [:slugged, :finders]
searchkick
belongs_to :base, class_name: 'Game'
has_many :expansions, class_name: 'Game', foreign_key: 'base_id'
has_many :ownerships, dependent: :destroy
has_many :owners, through: :ownerships, source: :user
has_many :wishes, dependent: :destroy
has_many :wishers, through: :wishes, source: :user
has_many :taggings, dependent: :destroy
has_many :tags, through: :taggings
has_many :plays, dependent: :destroy
has_many :logs, through: :plays
has_attached_file :cover, styles: { thumb: '80x80>', medium: '200x200>', original: '600x600>' }
validates :title, presence: true
validates_attachment :cover, content_type: { content_type: /\Aimage\/.*\Z/ }
def bgg_url
"https://boardgamegeek.com/boardgame/#{bgg_id}" if bgg_id.present?
end
end
<file_sep>require 'rails_helper'
RSpec.describe Membership, type: :model do
let(:group) { create(:group) }
let(:user) { create(:user) }
describe "#save" do
it "creates a membership activity" do
create(:membership, group: group, user: user)
expect(user.activities.where(key: "membership.create", recipient: group)).to exist
end
end
describe "#destroy" do
let!(:membership) { create(:membership, group: group, user: user) }
it "destroys membership activities associated with the group" do
membership.destroy
expect(user.activities.where(trackable_type: "Membership", recipient: group)).not_to exist
end
end
end
|
76d6e91a0500cb705849b24cd4e47e848144ffe6
|
[
"Ruby"
] | 57 |
Ruby
|
woongy/fireside
|
ee907ce5881b00909ce2e2240fff271563e5f1aa
|
b423b54c217125da2f608eddf5a82b86d90f4953
|
refs/heads/master
|
<repo_name>joshis1/WindowsForm_EventHandler<file_sep>/EventHandler_Delegates_Tutorial/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EventHandler_Delegates_Tutorial
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Button b2 = new Button();
b2.Text = "Click Me";
b2.Size = new Size(100, 50);
b2.Location = new Point(100, 100);
this.Controls.Add(b2);
b2.Click += delegate (object s, EventArgs e1)
{
MessageBox.Show("Hello World");
};
}
}
}
|
a1b0f4d0849170aa0cced349665afd11c3f1cc72
|
[
"C#"
] | 1 |
C#
|
joshis1/WindowsForm_EventHandler
|
329b77e8b6859a9495d16f30701897d44bd864e4
|
b8340e0c7373c54c3f315fbf1df1c43b22823c2e
|
refs/heads/master
|
<file_sep>#pragma once
namespace the5{
namespace util{
const char* const toString(bool b){
return (b ? "true" : "false");
}
}
}<file_sep># The5 Utility Headers
Assorted utility functions.
## CMake
Simply use `include_directories(path/to/The5Util)`.<file_sep>#pragma once
#include <string>
#include <chrono>
#include <cstdint>
#include <iostream>
namespace the5 {
namespace util {
class ScopeTimer {
public:
ScopeTimer(const char* text = "", size_t iterations = 0) :text(text), iterations(iterations)
{
start = std::chrono::high_resolution_clock::now();
}
~ScopeTimer()
{
auto end = std::chrono::high_resolution_clock::now();
auto delta = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
long double millisec = delta / 1000.0;
if (iterations > 2) millisec /= iterations;
printf("ScopeTimer: \"%s\" ", text);
if (iterations > 1) printf("(avg. for %u iterations) ", iterations);
printf("took %f ms\n", millisec);
}
protected:
size_t iterations;
const char* text;
std::chrono::time_point<std::chrono::high_resolution_clock> start;
};
}
}<file_sep>#pragma once
namespace the5 {
namespace util {
//WIP
/* https://stackoverflow.com/questions/5530248/creating-a-string-list-and-an-enum-list-from-a-c-macro/5530947#5530947
** This simple macro only works for a fixed number of arguments since the commas are hard-coded
**
** https://www.codeproject.com/Articles/1002895/Clean-Reflective-Enums-Cplusplus-Enum-to-String-wi
** Anything more sophisticated becomes very macro-heavy
*/
#ifndef ENUM_STRING
#define ENUM_STRING(name, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9)\
enum name { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9};\
const char *name##Strings[] = { #v0, #v1, #v2, #v3, #v4, #v5, #v6, #v7, #v8, #v9};\
const char *name##ToString(value) { return name##Strings[value]; }
#endif // !Enum
}
}<file_sep>#pragma once
#include <cstdio>
#include <cstdarg>
#include <cassert>
namespace the5 {
namespace logging {
/* User Options */
#ifndef LOG_MIN_LEVEL
# define LOG_MIN_LEVEL 0
#endif
#ifndef LOG_SHOW_LINE_NUMBER
# define LOG_SHOW_LINE_NUMBER 1
#endif
#if LOG_SHOW_LINE_NUMBER > 0
# define LOG_FILE_AND_LINE_FORMAT "\n\tIn file %s line %u\n"
# define LOG_FILE_AND_LINE_PARAMS ,__FILE__ ,__LINE__
#else
# define LOG_FILE_AND_LINE_FORMAT "\n"
# define LOG_FILE_AND_LINE_PARAMS
#endif
enum Level {
Trace,
Debug,
Info,
Warning,
Error,
Assert,
};
const char* const LevelString[] = { "Trace", "Debug", "Info", "Warning", "Error", "Assert" };
/* Passing Arguments to printf
** https://stackoverflow.com/questions/1056411/how-to-pass-variable-number-of-arguments-to-printf-sprintf
*/
inline void Log_(Level level, const char * const msg, ...) {
va_list argptr;
va_start(argptr, msg);
printf("%-8s", LevelString[level]);
vprintf(msg, argptr);
va_end(argptr);
}
/* Macros for printing something with __FILE__ and __LINE__
** https://stackoverflow.com/questions/15549893/modify-printfs-via-macro-to-include-file-and-line-number-information
*/
#if 0 >= LOG_MIN_LEVEL
# define TRACE(msg, ...) the5::logging::Log_(the5::logging::Level::Trace, msg LOG_FILE_AND_LINE_FORMAT, __VA_ARGS__ LOG_FILE_AND_LINE_PARAMS);
#else
# define TRACE(msg, ...) ((void)0)
#endif
#if 1 >= LOG_MIN_LEVEL
# define LOG(msg, ...) the5::logging::Log_(the5::logging::Level::Debug, msg LOG_FILE_AND_LINE_FORMAT, __VA_ARGS__ LOG_FILE_AND_LINE_PARAMS);
#else
# define LOG(msg, ...) ((void)0)
#endif
#if 2 >= LOG_MIN_LEVEL
# define INFO(msg, ...) the5::logging::Log_(the5::logging::Level::Info, msg LOG_FILE_AND_LINE_FORMAT, __VA_ARGS__ LOG_FILE_AND_LINE_PARAMS);
#else
# define INFO(msg, ...) ((void)0)
#endif
#if 3 >= LOG_MIN_LEVEL
# define WARNING(msg, ...) the5::logging::Log_(the5::logging::Level::Warning, msg LOG_FILE_AND_LINE_FORMAT, __VA_ARGS__ LOG_FILE_AND_LINE_PARAMS);
#else
# define WARNING(msg, ...) ((void)0)
#endif
#if 4 >= LOG_MIN_LEVEL
# define ERROR(msg, ...) the5::logging::Log_(the5::logging::Level::Error, msg LOG_FILE_AND_LINE_FORMAT, __VA_ARGS__ LOG_FILE_AND_LINE_PARAMS);
#else
# define ERROR(msg, ...) ((void)0)
#endif
#if 5 >= LOG_MIN_LEVEL && !defined(NDEBUG)
# define ASSERT(condition, msg, ...) if(!(condition)){the5::logging::Log_(the5::logging::Level::Assert, msg "\n\tAssertion Failed: %s" LOG_FILE_AND_LINE_FORMAT, __VA_ARGS__ , #condition LOG_FILE_AND_LINE_PARAMS);__debugbreak();}
#else
# define ASSERT(condition, msg, ...) ((void)0)
#endif
}
}<file_sep>#pragma once
namespace the5{
namespace util{
/* replaces a classes name with a string literal.
*/
#ifndef CLASSNAME_TO_STRING
#define CLASSNAME_TO_STRING(__class__) \
({ \
__class__ *x;\
#__class__ ;\
})
#endif // !CLASSNAME_TO_STRING
}
}<file_sep>#include <string>
namespace the5 {
namespace util {
namespace file {
static std::string getDirectory(const std::string filepath)
{
std::string directory = filepath.substr(0, filepath.find_last_of('/'));
return directory;
}
static std::string getFileName(const std::string filepath)
{
auto dirLength = filepath.find_last_of('/');
auto pathlength = filepath.length();
std::string fileName = filepath.substr(dirLength, pathlength - dirLength);
return fileName;
}
static std::string getPathMistakes(const std::string &filepath)
{
std::string warning("");
if (filepath.find(':/') == std::string::npos && filepath.find(':\\') == std::string::npos) warning += "\n FILE:\tThere does not seem to be a drive letter present, is this the FULL path?";
if (filepath.size() < 20) warning += "\n FILE:\tThe Path seems quite short, did you specify the FULL path?";
return warning;
}
}
}
}
|
a191c9dddfc5d191b758e31214e83d0771148524
|
[
"Markdown",
"C++"
] | 7 |
C++
|
The5-1/The5Util
|
63cfa3b085157706f21613c36f9c758a3fbe415f
|
2d47bb49da28751daafb6c3689fccadc4959bd07
|
refs/heads/master
|
<repo_name>hsia/jsmm<file_sep>/app/handlers/__init__.py
__all__ = [
'jsmm',
'member_handler',
'member_upload',
'member_image',
'member_doc',
'document_collection_handler',
'document_handler',
'attachment_handler',
'tab',
'reminder_handler',
'member_export',
'organ_handler'
]
<file_sep>/www/scripts/tab/custom/addtab.js
$(function () {
$.get('/tab/', function (data) {
var tabData = data.docs;
for (var i = 0; i < tabData.length; i++) {
var obj = tabData[i];
$('#custom_tab').tabs('add', {
title: obj.gridTitle,
content: '<table id=' + obj.tab_id + ' data-columns=' + JSON.stringify(obj.columns) + ' style="width:100%;height:100%;"></table>',
closable: false,
selected: false
});
}
$('#custom_tab').tabs({
onSelect: function (title, index) {
var tab = $('#custom_tab').tabs('getTab', index);
var id = $('table', $(tab))[0].id;
var columns = $('table', $(tab)).data('columns');
var $grid = $('#' + id);
var gridTab = new GridTab(id, $grid);
var toolbar = [
{
text: '添加记录',
iconCls: 'icon-add',
handler: function () {
gridTab.addRow();
}
}, '-', {
text: '移除记录',
iconCls: 'icon-remove',
handler: function () {
gridTab.removeRow();
}
}, '-', {
text: '保存记录',
iconCls: 'icon-save',
handler: function () {
gridTab.saveRow();
}
}
];
gridTab.buildGrid(toolbar, columns);
gridTab.registerListeners();
}
});
});
});<file_sep>/www/scripts/tab/achievements/paperinfo.js
/**
* Created by S on 2017/2/22.
*/
// 论文著作
$(function () {
var $grid = $("#paper-list");
var tabId = 'paper';
var gridTab = new GridTab(tabId, $grid);
var columns = [
{
field: 'paperPublications',
title: '论文/著作',
width: 60,
align: 'left',
editor: {
type: 'combobox',
options: {
valueField: 'value',
textField: 'text',
method: 'get',
url: 'data/publicationsType.json',
panelHeight: 'auto',
prompt: '请选择'
}
}
},
{
field: 'paperName',
title: '作品名称',
width: 120,
align: 'left',
editor: {type: 'textbox', options: {}}
},
{
field: 'paperPress',
title: '刊物/出版社',
width: 120,
align: 'left',
editor: {type: 'textbox', options: {}}
},
{
field: 'paperAuthorSort',
title: '第几作者',
width: 50,
align: 'left',
editor: {type: 'textbox', options: {}}
},
{
field: 'paperPressDate',
title: '发行时间',
width: 60,
align: 'left',
editor: {
type: 'datebox',
options: {}
}
},
{
field: 'paperRoleDetail',
title: '角色说明',
width: 110,
align: 'left',
editor: {
type: 'combobox',
options: {
valueField: 'value',
textField: 'text',
method: 'get',
url: 'data/rolesInPublications.json',
prompt: '请选择',
panelHeight: 'auto'
}
}
}
];
var toolbar = [
{
text: '添加记录',
iconCls: 'icon-add',
handler: function () {
gridTab.addRow();
}
}, '-', {
text: '移除记录',
iconCls: 'icon-remove',
handler: function () {
gridTab.removeRow();
}
}, '-', {
text: '保存记录',
iconCls: 'icon-save',
handler: function () {
gridTab.saveRow();
}
}
];
gridTab.buildGrid(toolbar, columns);
gridTab.registerListeners();
});<file_sep>/app/handlers/member_doc.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os.path
import uuid
import tornado.web
import json
import time
from commons import couch_db, make_uuid
def newTime():
return time.strftime("%Y-%m-%d", time.localtime())
def docCallBack(file):
loadDb = couch_db.get(r'/jsmm/%(id)s' % {'id': file['member_id']})
memberInDb = json.loads(loadDb.body.decode('utf-8'))
documentInfo = {
'_id': make_uuid(),
'memberId': memberInDb['_id'],
'name': memberInDb['name'],
'type': 'document',
'branch': memberInDb['branch'],
'organ': memberInDb['organ'],
'fileUploadTime': newTime(),
'fileName': file['filename'],
'file_url': file['path'],
'fileType': file['filename'].split('.')[-1]
}
# if file['doc_type'] == 'researchReport':
# documentInfo['docType'] = 'researchReport'
# elif file['doc_type'] == 'departmentInfo':
# documentInfo['docType'] = 'departmentInfo'
# elif file['doc_type'] == 'speechesText':
# documentInfo['docType'] = 'speechesText'
# elif file['doc_type'] == 'speechesText':
# documentInfo['docType'] = 'speechesText'
if file['doc_type'] == 'researchReport':
if ('researchReport' not in memberInDb):
memberInDb['researchReport'] = []
memberInDb['researchReport'].append(documentInfo['_id'])
elif file['doc_type'] == 'unitedTheory':
if ('unitedTheory' not in memberInDb):
memberInDb['unitedTheory'] = []
memberInDb['unitedTheory'].append(documentInfo['_id'])
elif file['doc_type'] == 'politicsInfo':
if ('politicsInfo' not in memberInDb):
memberInDb['politicsInfo'] = []
memberInDb['politicsInfo'].append(documentInfo['_id'])
elif file['doc_type'] == 'propaganda':
if ('propaganda' not in memberInDb):
memberInDb['propaganda'] = []
memberInDb['propaganda'].append(documentInfo['_id'])
documentResponse = couch_db.post(r'/jsmm/', documentInfo)
memberResponse = couch_db.put(r'/jsmm/%(id)s' % {"id": file['member_id']}, memberInDb)
class UploadDoc(tornado.web.RequestHandler):
def initialize(self, callback):
self._callback = callback
@tornado.web.addslash
def post(self):
"""
接收多个上传文件,调用callback对上传的。
:return:
"""
# 文件的保存路径
inbox_path = os.path.join(os.path.dirname(__file__), '../../inbox/documents')
# 结构为:{'members': [{'filename': 'xxx.xls', 'body': b'...',
# 'content_type': 'application/vnd.ms-excel'}]}
file_infos = self.request.files['docs']
member_id = self.get_argument('doc_id')
doc_type = self.get_argument('doc_type')
for file_info in file_infos:
filename = file_info['filename']
upload_path = os.path.join(inbox_path, filename)
# 在保存的文件名和扩展名中间加6个随机字符,避免文件重名。
(root, ext) = os.path.splitext(upload_path)
path = root + '-' + uuid.uuid4().hex[0:6] + ext
with open(path, 'wb') as file:
file.write(file_info['body'])
self._callback({'filename': filename, 'path': path,
'content_type': file_info['content_type'],
'member_id': member_id, 'doc_type': doc_type})
<file_sep>/www/scripts/documentlist.js
$(function () {
var gridHeight = $('#membersinfo').height();
var $dataGrid = $('#document-list');
var toolbar = [{
text: '高级查询',
iconCls: 'icon-search',
handler: function () {
documentsSearch();
}
}];
$dataGrid.datagrid({
iconCls: 'icon-ok',
height: gridHeight,
rownumbers: true,
pageSize: 20,
nowrap: true,
striped: true,
fitColumns: true,
loadMsg: '数据装载中......',
pagination: true,
allowSorts: true,
multiSort: true,
singleSelect: true,
remoteSort: true,
toolbar: toolbar,
columns: [[
{field: 'fileName', title: '文件名称', width: 110, sortable: false, align: 'left'},
{
field: 'docType',
title: '文件类型',
width: 60,
sortable: false,
align: 'left',
formatter: changeType
},
{field: 'name', title: '社员姓名', width: 60, sortable: false, align: 'left'},
{field: 'branch', title: '所属支社', width: 90, sortable: false, align: 'left'},
{field: 'fileUploadTime', title: '创建时间', width: 80, sortable: false, align: 'left'},
{
field: 'clickDownload',
title: '操作',
width: 60,
sortable: false,
align: 'left',
formatter: function (value, row, index) {
var path = "/document/" + row._id + "/" + row.fileName;
return '<a href= ' + path + '>下载</a>';
}
}
]]
});
var organName = null;
window.addEventListener("tree-row-selection", function (event) {
organName = event.detail;
if (organName != null) {
$dataGrid.datagrid({
loader: function (param, success) {
param.branch = organName;
$.post('/documents', JSON.stringify(param), function (data) {
success(data)
}, 'json');
}
});
} else {
return false;
}
});
window.addEventListener("organ-tree-operation", function (event) {
$dataGrid.datagrid({
loader: function (param, success) {
param.branch = '';
$.post('/documents', JSON.stringify(param), function (data) {
success(data)
}, 'json');
}
});
});
$('#tabsAll').tabs({
border: false,
onSelect: function (title, index) {
$("#tb-form").form('clear');
console.log(title + "," + index);
if (index == 1 && organName == null) {
$dataGrid.datagrid({
loader: function (param, success) {
var defaultUrl = '/documents';
$.post(defaultUrl, JSON.stringify(param), function (data) {
success(data)
}, 'json');
}
})
}
}
});
function changeType(value, row, index) {
var result = '';
switch (value) {
case 'researchReport':
result = '调研报告';
break;
case 'politicsInfo':
result = '参政议政信息';
break;
case 'unitedTheory':
result = '统战理论';
break;
case 'propaganda':
result = '宣传稿';
break;
}
return result;
}
//编辑数据
function editInfo() {
//1、先判断是否有选中的数据行
var $member = $dataGrid.datagrid('getSelected');
if ($member == null) {
$.messager.alert('提示', '请选择需要编辑的数据!', 'error');
return;
}
// 2、 发送异步请求,获得信息数据
$.getJSON("/members/" + $member._id, function (data, status) {
if (status) {
$('#memberEdit-form').form('clear');
$('#memberEdit-form').form('load', data);
$('#memberEdit-dialog').dialog({
width: 800,
height: 630,
title: '编辑社员',
closed: false,
cache: false,
modal: true,
toolbar: '#tb',
buttons: [{
iconCls: 'icon-ok',
text: '保存',
handler: function () {
$('#memberEdit-form').trigger('submit');
}
}, {
text: '取消',
handler: function () {
$('#memberEdit-dialog').dialog('close');
}
}]
});
} else {
$.messager.alert('提示', '数据请求失败!', 'error');
}
})
}
//确认删除
function confirmRemove() {
//1、先判断是否有选中的数据行
var member = $dataGrid.datagrid('getSelected');
if (member == null) {
$.messager.alert('提示', '请选择需要删除的数据!', 'error');
return;
}
//2、将选中数据的_id放入到一个数组中
var id = member._id;
//3、提示删除确认
$.messager.confirm('删除提示', '确定删除选中的数据?', function (r) {
if (r) {
//4、确认后,删除选中的数据
removeItem(id)
}
});
}
//删除数据行
function removeItem(id) {
$.ajax({
url: '/members/' + id,
type: 'DELETE',
success: function (data) {
//删除成功以后,重新加载数据,并将choiceRows置为空。
$dataGrid.datagrid('reload');
$.messager.alert('提示', '数据删除成功!', 'info');
},
error: function (data) {
$.messager.alert('提示', '数据删除失败!', 'error');
}
});
}
$("#document-search-form").submit(function (event) {
var formData = $(this).serializeArray();
var documentInfo = {};
$.each(formData, function (index, element) {
documentInfo[element.name] = element.value;
});
documentInfo.branch = (branch == null ? '' : branch);
if (documentInfo.startDate != '' && documentInfo.endDate == '') {
var mydate = new Date();
currYear = mydate.getFullYear();
currMonth = mydate.getMonth() + 1;
currDay = mydate.getDate();
documentInfo.endDate = currYear + "-" + ((currMonth < 10) ? ("0" + currMonth) : currMonth) + "-" + ((currDay < 10) ? ("0" + currDay) : currDay);
} else if (documentInfo.startDate == '' && documentInfo.endDate != '') {
documentInfo.startDate = '1970-01-01';
} else {
}
$('#document-search').dialog('close');
$('#document-search-form').form('clear');
$dataGrid.datagrid({
loader: function (param, success) {
param.documentInfo = documentInfo;
param.branch = (organName == null ? '' : organName);
var defaultUrl = '/documents';
$.post(defaultUrl, JSON.stringify(param), function (data) {
success(data)
}, 'json');
}
})
});
function documentsSearch() {
$('#docTypeD').combobox({
valueField: 'value',
textField: 'text',
url: 'data/documenttype.json',
method: 'get'
})
$('#document-search').dialog({
width: 600,
height: 300,
title: '社员查询',
closed: false,
cache: false,
modal: true,
buttons: [{
iconCls: 'icon-ok',
text: '查询',
handler: function () {
$('#document-search-form').trigger('submit');
}
}, {
iconCls: 'icon-cancel',
text: '取消',
handler: function () {
$('#document-search-form').form('clear');
$('#document-search').dialog('close');
}
}]
});
}
});
<file_sep>/app/handlers/document_handler.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import tornado.web
import tornado_utils
from commons import couch_db
@tornado_utils.bind_to(r'/document/([0-9a-f]+)')
class DocumentHandler(tornado.web.RequestHandler):
"""文档处理类
URL: '/document/<document_id>
"""
def data_received(self, chunk):
pass
def get(self, document_id):
"""获取文档信息
"""
self.write(couch_db.get(r'/jsmm/%(document_id)s' %
{'document_id': document_id}))
def put(self, document_id):
"""修改文档信息
"""
pass
def delete(self, document_id):
"""删除文档:
包括删除文档记录和更新memer中的文档id
"""
response_document = couch_db.get(r'/jsmm/%(document_id)s' % {"document_id": document_id})
document = json.loads(response_document.body.decode('utf-8'))
response_member = couch_db.get(r'/jsmm/%(member_id)s' % {"member_id": document["memberId"]})
member = json.loads(response_member.body.decode('utf-8'))
if document['docType'] == 'researchReport':
member['researchReport'].remove(document['_id'])
elif document['docType'] == 'unitedTheory':
member['unitedTheory'].remove(document['_id'])
elif document['docType'] == 'politicsInfo':
member['politicsInfo'].remove(document['_id'])
elif document['docType'] == 'propaganda':
member['propaganda'].remove(document['_id'])
# 删除Document记录
couch_db.delete(r'/jsmm/%(document_id)s?rev=%(document_rev)s' %
{'document_id': document_id, 'document_rev': document['_rev']})
# 更新member中的document的id
couch_db.put(r'/jsmm/%(id)s' % {"id": member["_id"]}, member)
# del_result = json.loads(response_del_document.body.decode('utf-8'))
self.write({'success': 'true'})
<file_sep>/www/scripts/grid_tab.js
var GridTab = function (tabId, $grid) {
this.member = null;
this.memberId = null;
this.tabId = tabId;
this.$grid = $grid;
this.editIndex = undefined;
this.documentId = null;
};
GridTab.prototype.endEditing = function () {
if (this.editIndex == undefined) {
return true;
}
if (this.$grid.datagrid('validateRow', this.editIndex)) {
this.$grid.datagrid('endEdit', this.editIndex);
this.editIndex = undefined;
return true;
} else {
return false;
}
};
GridTab.prototype.addRow = function () {
if (!this.memberId) {
$.messager.alert('提示信息', '请选择一行社员信息!', 'error');
return;
}
if (this.endEditing()) {
this.$grid.datagrid('appendRow', {});
this.editIndex = this.$grid.datagrid('getRows').length - 1;
this.$grid.datagrid('selectRow', this.editIndex).datagrid('beginEdit', this.editIndex);
}
};
GridTab.prototype.removeRow = function () {
if (!this.editIndex) {
this.$grid.datagrid('cancelEdit', this.editIndex)
.datagrid('deleteRow', this.editIndex);
this.editIndex = null;
}
};
GridTab.prototype.saveRow = function () {
var memberInfo = {};
var that = this;
if (!this.memberId) {
return;
}
$.get('/members/tab/' + this.memberId, function (data) {
memberInfo = data;
if (that.endEditing()) {
memberInfo[that.tabId] = that.$grid.datagrid('getRows');
$.ajax({
url: '/members/' + memberInfo._id,
type: 'PUT',
data: JSON.stringify(memberInfo),
success: function (data) {
//删除成功以后,重新加载数据,并将choiceRows置为空。
$.messager.alert('提示', '数据保存成功!', 'info');
},
error: function (data) {
$.messager.alert('提示', '数据更新失败!', 'error');
}
});
}
});
};
GridTab.prototype.docUpload = function () {
if (this.memberId == null) {
$.messager.alert('提示信息', '请选择一行社员信息!', 'error');
return;
}
var that = this;
$('#doc_upload_form').form('clear');
$('#member_doc').dialog({
width: 300,
height: 200,
title: '文档上传',
closed: false,
cache: false,
modal: true,
buttons: [{
iconCls: 'icon-import',
text: '导入',
handler: function () {
$('#member_doc').dialog('close');
$.messager.progress({
title: 'Please waiting',
msg: 'Loading data...'
});
$('#doc_upload_form').form('submit', {
url: '/document/' + that.memberId + '/' + that.tabId,
success: function (data) {
that.reloadGridRemote();
$.messager.progress('close');
$.messager.alert('提示信息', '文档上传成功!', 'info');
}
});
}
}, {
iconCls: 'icon-cancel',
text: '取消',
handler: function () {
$('#doc_upload_form').form('clear');
$('#member_doc').dialog('close');
}
}]
})
};
GridTab.prototype.docDelete = function () {
if (this.documentId == null) {
$.messager.alert('提示信息', '未选择文档!', 'info');
return;
}
var that = this;
$.messager.confirm('删除提示', '确定删除文档?', function (r) {
if (r) {
$.ajax({
url: '/document/' + that.documentId,
type: 'DELETE',
success: function (data) {
that.reloadGridRemote();
$.messager.alert('提示信息', '删除文档成功!', 'info');
},
error: function (data) {
$.messager.alert('提示信息', '删除文档失败!', 'error');
}
});
}
});
};
GridTab.prototype.buildGrid = function (toolbar, columns) {
var height = $("#member-info").height();
var that = this;
this.$grid.datagrid({
iconCls: 'icon-ok',
height: height,
rownumbers: true,
nowrap: true,
striped: true,
fitColumns: true,
loadMsg: '数据装载中......',
allowSorts: true,
remoteSort: true,
multiSort: true,
singleSelect: true,
toolbar: toolbar,
columns: [columns],
onClickRow: function (index, row) {
if (that.editIndex != index) {
if (that.endEditing()) {
that.$grid.datagrid('selectRow', index).datagrid('beginEdit', index);
that.editIndex = index;
} else {
that.$grid.datagrid('selectRow', that.editIndex);
}
}
},
onBeginEdit: function (index, row) {
$(".combo").click(function () {
$(this).prev().combobox("showPanel");
});
}
});
};
GridTab.prototype.buildDocGrid = function (toolbar, columns) {
var gridHeight = $("#member-info").height();
var that = this;
this.$grid.datagrid({
iconCls: 'icon-ok',
height: gridHeight,
rownumbers: true,
nowrap: true,
striped: true,
fitColumns: true,
loadMsg: '数据装载中......',
allowSorts: true,
remoteSort: true,
multiSort: true,
singleSelect: true,
toolbar: toolbar,
columns: [columns],
onSelect: function (rowIndex, rowData) {
that.documentId = rowData._id;
}
});
};
GridTab.prototype.reloadGrid = function (clear) {
if (clear) {
this.$grid.datagrid('loadData', []);
return;
}
if (!$.isEmptyObject(this.member)) {
if (!$.isEmptyObject(this.member[this.tabId])) {
this.$grid.datagrid('loadData', this.member[this.tabId]);
} else {
this.$grid.datagrid('loadData', []);
}
}
};
GridTab.prototype.reloadGridRemote = function () {
var that = this;
$.get('/members/' + this.memberId, function (data) {
if (!$.isEmptyObject(data)) {
if (!$.isEmptyObject(data[that.tabId])) {
that.$grid.datagrid('loadData', data[that.tabId]);
} else {
that.$grid.datagrid('loadData', []);
}
}
});
};
GridTab.prototype.registerListeners = function () {
var that = this;
window.addEventListener("grid-row-selection", function (event) {
that.member = event.detail;
that.memberId = that.member._id;
that.reloadGrid();
});
window.addEventListener("grid-row-deleteRow", function (event) {
if (event.detail.success == true) {
that.reloadGrid(true);
}
});
window.addEventListener("tree-row-selection", function (event) {
that.reloadGrid(true);
});
};
<file_sep>/app/handlers/reminder_handler.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import tornado.web
import tornado_utils
import re
from commons import couch_db
@tornado_utils.bind_to(r'/members/reminder/(.*)')
class reminderRetireHandler(tornado.web.RequestHandler):
def get(self, retire_time):
"""
退休提醒
"""
if re.match("([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8])))", retire_time, flags=0):
obj = {
"selector": {
"retireTime": {
"$lt": retire_time
}
},
"fields": ["_id", "_rev", "name", "gender", "birthday", "nation", "idCard", "branch", "organ", "branchTime"]
}
response = couch_db.post(r'/jsmm/_find/', obj)
members = json.loads(response.body.decode('utf-8'))
self.write(members)<file_sep>/app/handlers/jsmm.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import tornado.web
import tornado_utils
from commons import couch_db, get_retire_time, make_uuid
@tornado_utils.bind_to(r'/members/search/?')
class NewMemberCollectionHandler(tornado.web.RequestHandler):
@tornado.web.addslash
def post(self):
keys = ['name', 'gender', 'sector', 'lost', 'stratum', 'jobLevel', 'titleLevel', 'highestEducation']
obj = {
"selector": {},
"fields": ["_id", "_rev", "name", "gender", "birthday", "nation", "idCard", "branch", "organ", "branchTime"]
}
objC = obj["selector"]
search = json.loads(self.request.body.decode('utf-8'))
for key in keys:
if key in search:
if search[key] != '':
objC[key] = {'$regex': search[key]}
if 'retireTime' in search:
if search['retireTime'] != '':
objC['retireTime'] = {"$lt": search["retireTime"]}
if 'branch' in search:
if search['branch'] != '' and search['branch'] != u'北京市' and search['branch'] != u'朝阳区':
objC['branch'] = {"$eq": search["branch"]}
if 'socialPositionName' in search:
if search['socialPositionName'] != '':
objC['social'] = {"$elemMatch": {"socialPositionName": {"$regex": search['socialPositionName']}}}
if 'socialPositionLevel' in search:
if search['socialPositionLevel'] != '':
objC['social'] = {
"$elemMatch": {"socialPositionLevel": {"$regex": search['socialPositionLevel']}}}
if 'formeOrganizationJob' in search:
if search['formeOrganizationJob'] != '':
objC['formercluboffice'] = {
"$elemMatch": {"formeOrganizationJob": {"$regex": search['formeOrganizationJob']}}}
if 'formeOrganizationLevel' in search:
if search['formeOrganizationLevel'] != '':
objC['formercluboffice'] = {"$elemMatch": {"formeOrganizationLevel": {"$regex": search['formeOrganizationLevel']}}}
if 'startAge' in search and 'endAge' in search:
if search['startAge'] != '' and search['endAge']:
objC['birthday'] = {"$gte": search['endAge'], "$lte": search['startAge']}
objC['type'] = {"$eq": "member"}
response = couch_db.post(r'/jsmm/_find/', obj)
members = json.loads(response.body.decode('utf-8'))
self.write(members)
@tornado_utils.bind_to(r'/members/?')
class MemberCollectionHandler(tornado.web.RequestHandler):
@tornado.web.addslash
def get(self):
"""
通过view获取对象列表。
"""
if self.request.arguments == {}:
response = couch_db.get(r'/jsmm/_design/members/_view/all')
members = json.loads(response.body.decode('utf-8'))
docs = []
for row in members['rows']:
docs.append(row['value'])
self.set_header('Content-Type', 'application/json')
self.write(json.dumps(docs))
else:
startTime = self.get_argument('startTime').split('-')
endTime = self.get_argument('endTime').split('-')
start = '[' + ','.join(startTime) + ']'
end = '[' + ','.join(endTime) + ']'
memberInfo = couch_db.get(r'/jsmm/_design/members/_view/by-birthday?startkey=%(startTime)s&endkey=%(endTime)s' % {'startTime': start, 'endTime': end})
members = json.loads(memberInfo.body.decode('utf-8'))
docs = []
for row in members['rows']:
docs.append(row['value'])
self.set_header('Content-Type', 'application/json')
self.write(json.dumps(docs))
@tornado.web.addslash
def post(self):
'''
创建member对象。
'''
print(self.request.files)
member = json.loads(self.request.body.decode('utf-8'))
member['type'] = 'member'
member['_id'] = make_uuid()
member["retireTime"] = get_retire_time(member["birthday"], member["gender"])
couch_db.post(r'/jsmm/', member)
response = {"success": "true"}
self.write(response)
def delete(self):
'''
删除一个或多个member对象
'''
memberIds = json.loads(self.request.body.decode('utf-8'))
for memberId in memberIds:
response = couch_db.get(r'/jsmm/%(id)s' % {'id': memberId})
member = json.loads(response.body.decode('utf-8'))
couch_db.delete(r'/jsmm/%(id)s?rev=%(rev)s' %
{'id': memberId, 'rev': member['_rev']})
@tornado_utils.bind_to(r'/members/tab/([0-9a-f]+)')
class MemberHandlerTab(tornado.web.RequestHandler):
def get(self, member_id):
'''
通过view获取对象列表。
'''
response = couch_db.get(r'/jsmm/%(id)s' % {"id": member_id})
members = json.loads(response.body.decode('utf-8'))
self.set_header('Content-Type', 'application/json')
self.write(json.dumps(members))
def put(self, member_id):
'''
修改_id为member_id的member对象。
'''
memberInfo = couch_db.get(r'/jsmm/%(id)s' % {"id": member_id})
rev = json.loads(memberInfo.body.decode('utf-8'))
member = json.loads(self.request.body.decode('utf-8'))
member['_id'] = member_id
member['_rev'] = rev['_rev']
couch_db.put(r'/jsmm/%(id)s' % {"id": member_id}, member)
response = {"success": "true"}
self.write(response)<file_sep>/app/handlers/organ_handler.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import tornado.web
import tornado_utils
from commons import couch_db
@tornado_utils.bind_to(r'/organ/?')
class OrganHandler(tornado.web.RequestHandler):
"""组织机构处理类
URL: '/organ
"""
def data_received(self, chunk):
pass
def get(self):
"""获取组织机构信息
"""
response = couch_db.get(r'/jsmm/_design/organ/_view/getOrgan')
organ_content = json.loads(response.body.decode('utf-8'))
organ_row = organ_content['rows'][0]
organ_value = organ_row['value']
organ = organ_value['organ']
self.set_header('Content-Type', 'application/json')
self.write(json.dumps(organ))
@tornado_utils.bind_to(r'/organ/update/(.+)/(.+)')
class OrganUpdateHandler(tornado.web.RequestHandler):
def data_received(self, chunk):
pass
def put(self, organ_id, new_organ_value):
"""修改支社
"""
result = {}
response = couch_db.get(r'/jsmm/_design/organ/_view/getOrgan')
organ_content = json.loads(response.body.decode('utf-8'))
organ_row = organ_content['rows'][0]
organ_value = organ_row['value']
organ_cy = (((organ_value['organ'])[0])['children'])[0]
organ = {'id': new_organ_value, 'text': new_organ_value}
# 判断修改后的机构是否重名
if organ in organ_cy['children']:
result['success'] = False
result['content'] = u'支社已经存在,请重新输入支社名称!'
else:
selector = {"selector": {"branch": {"$eq": organ_id}}}
response_member = couch_db.post(r'/jsmm/_find', selector)
members = json.loads(response_member.body.decode('utf-8'))['docs']
if len(members) < 1:
pass
else:
for member in members:
member['branch'] = new_organ_value
couch_db.put(r'/jsmm/%(id)s' % {"id": member['_id']}, member)
for organ in organ_cy['children']:
if organ['id'] == organ_id:
organ['text'] = new_organ_value
organ['id'] = new_organ_value
couch_db.put(r'/jsmm/%(id)s' % {"id": organ_value['_id']}, organ_value)
result['success'] = True
result['content'] = organ_value['organ']
self.set_header('Content-Type', 'application/json')
self.write(json.dumps(result))
@tornado_utils.bind_to(r'/organ/merge/(.+)/(.+)')
class OrganMergeHandler(tornado.web.RequestHandler):
def data_received(self, chunk):
pass
def put(self, source_organ_id, target_organ_id):
"""
合并支社
:param source_organ_id:
:param target_organ_id:
:return:
"""
response = couch_db.get(r'/jsmm/_design/organ/_view/getOrgan')
organ_content = json.loads(response.body.decode('utf-8'))
organ_row = organ_content['rows'][0]
organ_value = organ_row['value']
organ_cy = (((organ_value['organ'])[0])['children'])[0]
selector = {"selector": {"branch": {"$eq": source_organ_id}}}
response_member = couch_db.post(r'/jsmm/_find', selector)
members = json.loads(response_member.body.decode('utf-8'))['docs']
if len(members) < 1:
pass
else:
for member in members:
member['branch'] = target_organ_id
couch_db.put(r'/jsmm/%(id)s' % {"id": member['_id']}, member)
for organ in organ_cy['children']:
if organ['id'] == source_organ_id:
organ_cy['children'].remove(organ)
couch_db.put(r'/jsmm/%(id)s' % {"id": organ_value['_id']}, organ_value)
self.set_header('Content-Type', 'application/json')
self.write(json.dumps(organ_value['organ']))
@tornado_utils.bind_to(r'/organ/(.+)')
class OrganOperationHandler(tornado.web.RequestHandler):
def data_received(self, chunk):
pass
def put(self, new_organ_value):
"""新建支社
"""
result = {}
response = couch_db.get(r'/jsmm/_design/organ/_view/getOrgan')
organ_content = json.loads(response.body.decode('utf-8'))
organ_row = organ_content['rows'][0]
organ_value = organ_row['value']
organ_cy = (((organ_value['organ'])[0])['children'])[0]
organ = {'id': new_organ_value, 'text': new_organ_value}
if 'children' not in organ_cy:
organ_cy['children'] = list()
# 判断是否有重名的
if organ in organ_cy['children']:
result['success'] = False
result['content'] = u'支社已经存在,请重新输入支社名称!'
else:
organ_cy['children'].append(organ)
couch_db.put(r'/jsmm/%(id)s' % {"id": organ_value['_id']}, organ_value)
result["success"] = True
result['content'] = organ_value['organ']
self.set_header('Content-Type', 'application/json')
self.write(json.dumps(result))
def delete(self, organ_id):
"""删除支社
"""
result = {}
response = couch_db.get(r'/jsmm/_design/organ/_view/getOrgan')
organ_content = json.loads(response.body.decode('utf-8'))
organ_row = organ_content['rows'][0]
organ_value = organ_row['value']
organ_cy = (((organ_value['organ'])[0])['children'])[0]
selector = {"selector": {"branch": {"$eq": organ_id}}}
response_member = couch_db.post(r'/jsmm/_find', selector)
members = json.loads(response_member.body.decode('utf-8'))['docs']
if len(members) < 1:
for organ in organ_cy['children']:
if organ['id'] == organ_id:
organ_cy['children'].remove(organ)
couch_db.put(r'/jsmm/%(id)s' % {"id": organ_value['_id']}, organ_value)
result['success'] = True
result['content'] = organ_value['organ']
else:
result['success'] = False
result['content'] = u'该支社拥有社员,请将"该支社下社员删除"或者"将该支社合并到其他支社"或者"修改会员所属支社"!'
self.set_header('Content-Type', 'application/json')
self.write(result)
<file_sep>/www/scripts/tab/relations/agencybroker.js
/**
* Created by S on 2017/2/22.
*/
//介绍人
$(function () {
var $grid = $("#agencyBroker-list");
var tabId = 'agencybroker';
var gridTab = new GridTab(tabId, $grid);
var columns = [
{field: 'agencyName', title: '姓名', width: 110, align: 'left', editor: 'textbox'},
{field: 'agencyCompany', title: '单位', width: 110, align: 'left', editor: 'textbox'},
{field: 'agencyJob', title: '职务', width: 120, align: 'left', editor: 'textbox'},
{field: 'agencyRelationShip', title: '与本人关系', width: 120, align: 'left', editor: 'textbox'}
];
var toolbar = [
{
text: '添加记录',
iconCls: 'icon-add',
handler: function () {
gridTab.addRow();
}
}, '-', {
text: '移除记录',
iconCls: 'icon-remove',
handler: function () {
gridTab.removeRow();
}
}, '-', {
text: '保存记录',
iconCls: 'icon-save',
handler: function () {
gridTab.saveRow();
}
}
];
gridTab.buildGrid(toolbar, columns);
gridTab.registerListeners();
});<file_sep>/app/handlers/member_export.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import urllib
from io import BytesIO
import time
import tornado.web
import tornado_utils
import xlwt
from commons import couch_db
@tornado_utils.bind_to(r'/member/export/([0-9a-f]+)/?')
class memberInfoExport(tornado.web.RequestHandler):
@tornado.web.addslash
def get(self, member_id):
current_row = 18
response = couch_db.get(r'/jsmm/%(id)s' % {"id": member_id})
member = json.loads(response.body.decode('utf-8'))
pattern = xlwt.Pattern()
pattern.pattern = xlwt.Pattern.SOLID_PATTERN
pattern.pattern_fore_colour = 22
style = xlwt.XFStyle()
style.pattern = pattern
style.font.height = 240
style.font.name = '宋体'
memberInfoStyle = xlwt.XFStyle()
memberInfoStyle.font.name = '宋体'
memberInfoStyle.font.height = 240
wb = xlwt.Workbook()
ws = wb.add_sheet(member['name'] + '的信息', cell_overwrite_ok=True)
for c in range(0, 10):
ws.col(c).width = 4000
ws.write_merge(0, 0, 0, 9, u'基本信息', style)
ws.write(1, 0, u'姓名', memberInfoStyle)
ws.write(1, 2, u'性别', memberInfoStyle)
ws.write(1, 4, u'籍贯', memberInfoStyle)
ws.write(2, 0, u'民族', memberInfoStyle)
ws.write(2, 2, u'出生地', memberInfoStyle)
ws.write(2, 4, u'出生年月日', memberInfoStyle)
ws.write(3, 0, u'外文姓名', memberInfoStyle)
ws.write(3, 3, u'曾用名', memberInfoStyle)
ws.write(4, 0, u'健康状态', memberInfoStyle)
ws.write(4, 3, u'婚姻状态', memberInfoStyle)
ws.write(5, 0, u'所属支社', memberInfoStyle)
ws.write(5, 3, u'所属基层组织', memberInfoStyle)
ws.write(6, 0, u'入社时间', memberInfoStyle)
ws.write(6, 3, u'党派交叉', memberInfoStyle)
ws.write(7, 0, u'单位名称', memberInfoStyle)
ws.write(7, 3, u'工作部门', memberInfoStyle)
ws.write(8, 0, u'职务', memberInfoStyle)
ws.write(8, 3, u'职称', memberInfoStyle)
ws.write(9, 0, u'学术职务', memberInfoStyle)
ws.write(9, 3, u'参加工作时间', memberInfoStyle)
ws.write_merge(9, 9, 6, 7, u'是否办理退休', memberInfoStyle)
ws.write(10, 0, u'公民身份证号', memberInfoStyle)
ws.write(10, 3, u'有效证件类别', memberInfoStyle)
ws.write_merge(10, 10, 6, 7, u'证件号码', memberInfoStyle)
ws.write(11, 0, u'家庭地址', memberInfoStyle)
ws.write(11, 4, u'邮编', memberInfoStyle)
ws.write(12, 0, u'单位地址', memberInfoStyle)
ws.write(12, 4, u'邮编', memberInfoStyle)
ws.write(13, 0, u'通信地址', memberInfoStyle)
ws.write(13, 4, u'邮编', memberInfoStyle)
ws.write(14, 0, u'手机', memberInfoStyle)
ws.write(14, 4, u'家庭电话', memberInfoStyle)
ws.write(15, 0, u'电子信箱', memberInfoStyle)
ws.write(15, 4, u'单位电话', memberInfoStyle)
ws.write(16, 0, u'爱好', memberInfoStyle)
ws.write(17, 0, u'专长', memberInfoStyle)
ws.write_merge(1, 7, 8, 9, '头像', memberInfoStyle)
ws.write(1, 1, member['name'], memberInfoStyle)
ws.write(1, 3, member['gender'], memberInfoStyle)
ws.write_merge(1, 1, 5, 7, member['nativePlace'], memberInfoStyle)
ws.write(2, 1, member['nation'], memberInfoStyle)
ws.write(2, 3, member['birthPlace'], memberInfoStyle)
ws.write_merge(2, 2, 5, 7, member['birthday'], memberInfoStyle)
ws.write_merge(3, 3, 1, 2, member['foreignName'], memberInfoStyle)
ws.write_merge(3, 3, 4, 7, member['usedName'], memberInfoStyle)
ws.write_merge(4, 4, 1, 2, member['health'], memberInfoStyle)
ws.write_merge(4, 4, 4, 7, member['marriage'], memberInfoStyle)
ws.write_merge(5, 5, 1, 2, member['branch'], memberInfoStyle)
ws.write_merge(5, 5, 4, 7, member['organ'], memberInfoStyle)
ws.write_merge(6, 6, 1, 2, member['branchTime'], memberInfoStyle)
ws.write_merge(6, 6, 4, 7, member['partyCross'], memberInfoStyle)
ws.write_merge(7, 7, 1, 2, member['companyName'], memberInfoStyle)
ws.write_merge(7, 7, 4, 7, member['department'], memberInfoStyle)
ws.write_merge(8, 8, 1, 2, member['duty'], memberInfoStyle)
ws.write_merge(8, 8, 4, 9, member['jobTitle'], memberInfoStyle)
ws.write_merge(9, 9, 1, 2, member['academic'], memberInfoStyle)
ws.write_merge(9, 9, 4, 5, member['jobTime'], memberInfoStyle)
ws.write_merge(9, 9, 8, 9, member['retire'], memberInfoStyle)
ws.write_merge(10, 10, 1, 2, member['idCard'], memberInfoStyle)
ws.write_merge(10, 10, 4, 5, member['idType'], memberInfoStyle)
ws.write_merge(10, 10, 8, 9, member['idNo'], memberInfoStyle)
ws.write_merge(11, 11, 1, 3, member['homeAddress'], memberInfoStyle)
ws.write_merge(11, 11, 5, 9, member['homePost'], memberInfoStyle)
ws.write_merge(12, 12, 1, 3, member['companyAddress'], memberInfoStyle)
ws.write_merge(12, 12, 5, 9, member['companyPost'], memberInfoStyle)
ws.write_merge(13, 13, 1, 3, member['commAddress'], memberInfoStyle)
ws.write_merge(13, 13, 5, 9, member['commPost'], memberInfoStyle)
ws.write_merge(14, 14, 1, 3, member['mobile'], memberInfoStyle)
ws.write_merge(14, 14, 5, 9, member['homeTel'], memberInfoStyle)
ws.write_merge(15, 15, 1, 3, member['email'], memberInfoStyle)
ws.write_merge(15, 15, 5, 9, member['companyTel'], memberInfoStyle)
ws.write_merge(16, 16, 1, 9, member['hobby'], memberInfoStyle)
ws.write_merge(17, 17, 1, 9, member['speciality'], memberInfoStyle)
for obj in dict(member):
for case in switch(obj):
if case('specializedskill'):
if len(member['specializedskill']) > 0:
ws.write_merge(current_row, current_row, 0, 9, u'')
ws.write_merge(current_row + 1, current_row + 1, 0, 9, u'业务专长', style)
ws.write_merge(current_row + 2, current_row + 2, 0, 1, u'专业分类', memberInfoStyle)
ws.write_merge(current_row + 2, current_row + 2, 2, 4, u'专业名称', memberInfoStyle)
ws.write_merge(current_row + 2, current_row + 2, 5, 9, u'专业详细名称', memberInfoStyle)
for i in range(0, len(member['specializedskill'])):
obj = member['specializedskill'][i]
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 0, 1, obj['specializedType'],
memberInfoStyle)
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 2, 4, obj['specializedName'],
memberInfoStyle)
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 5, 9, obj['specializedDetailName'],
memberInfoStyle)
obj_row = 3 + len(member['specializedskill'])
current_row += obj_row
break
if case('educationDegree'):
if len(member['educationDegree']) > 0:
ws.write_merge(current_row, current_row, 0, 9, u'')
ws.write_merge(current_row + 1, current_row + 1, 0, 9, u'学历信息', style)
ws.write_merge(current_row + 2, current_row + 2, 0, 1, u'学校名称', memberInfoStyle)
ws.write_merge(current_row + 2, current_row + 2, 2, 3, u'起止时间', memberInfoStyle)
ws.write_merge(current_row + 2, current_row + 2, 4, 5, u'所学专业', memberInfoStyle)
ws.write(current_row + 2, 6, u'取得学历', memberInfoStyle)
ws.write_merge(current_row + 2, current_row + 2, 7, 8, u'所获学位', memberInfoStyle)
ws.write(current_row + 2, 9, u'教育类别', memberInfoStyle)
for i in range(0, len(member['educationDegree'])):
obj = member['educationDegree'][i]
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 0, 1, obj['eduSchoolName'],
memberInfoStyle)
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 2, 3,
obj['eduStartingDate'] + ' - ' + obj['eduGraduateDate'], memberInfoStyle)
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 4, 5, obj['eduMajor'],
memberInfoStyle)
ws.write(current_row + 3 + i, 6, obj['eduEducation'], memberInfoStyle)
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 7, 8, obj['eduDegree'],
memberInfoStyle)
ws.write(current_row + 3 + i, 9, obj['eduEducationType'], memberInfoStyle)
obj_row = 3 + len(member['educationDegree'])
current_row += obj_row
break
if case('familyRelations'):
if len(member['familyRelations']) > 0:
ws.write_merge(current_row, current_row, 0, 9, u'')
ws.write_merge(current_row + 1, current_row + 1, 0, 9, u'社会关系', style)
ws.write(current_row + 2, 0, u'姓名', memberInfoStyle)
ws.write(current_row + 2, 1, u'与本人关系', memberInfoStyle)
ws.write(current_row + 2, 2, u'性别', memberInfoStyle)
ws.write(current_row + 2, 3, u'出生年月', memberInfoStyle)
ws.write_merge(current_row + 2, current_row + 2, 4, 5, u'工作单位', memberInfoStyle)
ws.write(current_row + 2, 6, u'职务', memberInfoStyle)
ws.write(current_row + 2, 7, u'国籍', memberInfoStyle)
ws.write_merge(current_row + 2, current_row + 2, 8, 9, u'政治面貌', memberInfoStyle)
for i in range(0, len(member['familyRelations'])):
obj = member['familyRelations'][i]
ws.write(current_row + 3 + i, 0, obj['familyName'], memberInfoStyle)
ws.write(current_row + 3 + i, 1, obj['familyRelation'], memberInfoStyle)
ws.write(current_row + 3 + i, 2, obj['familyGender'], memberInfoStyle)
ws.write(current_row + 3 + i, 3, obj['familyBirthDay'], memberInfoStyle)
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 4, 5, obj['familyCompany'],
memberInfoStyle)
ws.write(current_row + 3 + i, 6, obj['familyJob'], memberInfoStyle)
ws.write(current_row + 3 + i, 7, obj['familyNationality'], memberInfoStyle)
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 8, 9, obj['familyPolitical'],
memberInfoStyle)
obj_row = 3 + len(member['familyRelations'])
current_row += obj_row
break
if case('jobResumes'):
if len(member['jobResumes']) > 0:
ws.write_merge(current_row, current_row, 0, 9, u'')
ws.write_merge(current_row + 1, current_row + 1, 0, 9, u'工作履历', style)
ws.write_merge(current_row + 2, current_row + 2, 0, 1, u'单位名称', memberInfoStyle)
ws.write_merge(current_row + 2, current_row + 2, 2, 3, u'工作部门', memberInfoStyle)
ws.write(current_row + 2, 4, u'职务', memberInfoStyle)
ws.write(current_row + 2, 5, u'职称', memberInfoStyle)
ws.write(current_row + 2, 6, u'学术职务', memberInfoStyle)
ws.write_merge(current_row + 2, current_row + 2, 7, 8, u'起止时间', memberInfoStyle)
ws.write(current_row + 2, 9, u'证明人', memberInfoStyle)
for i in range(0, len(member['jobResumes'])):
obj = member['jobResumes'][i]
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 0, 1, obj['jobCompanyName'],
memberInfoStyle)
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 2, 3, obj['jobDep'],
memberInfoStyle)
ws.write(current_row + 3 + i, 4, obj['jobDuties'], memberInfoStyle)
ws.write(current_row + 3 + i, 5, obj['jobTitle'], memberInfoStyle)
ws.write(current_row + 3 + i, 6, obj['jobAcademic'], memberInfoStyle)
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 7, 8,
obj['jobStartTime'] + ' - ' + obj['jobEndTime'], memberInfoStyle)
ws.write(current_row + 3 + i, 9, obj['jobReterence'], memberInfoStyle)
obj_row = 3 + len(member['jobResumes'])
current_row += obj_row
break
if case('award'):
if len(member['award']) > 0:
ws.write_merge(current_row, current_row, 0, 9, u'')
ws.write_merge(current_row + 1, current_row + 1, 0, 9, u'获奖情况', style)
ws.write_merge(current_row + 2, current_row + 2, 0, 2, u'获奖项目名称', memberInfoStyle)
ws.write(current_row + 2, 3, u'获奖时间', memberInfoStyle)
ws.write(current_row + 2, 4, u'获奖级别', memberInfoStyle)
ws.write(current_row + 2, 5, u'项目中角色', memberInfoStyle)
ws.write_merge(current_row + 2, current_row + 2, 6, 7, u'授予单位', memberInfoStyle)
ws.write_merge(current_row + 2, current_row + 2, 8, 9, u'备注', memberInfoStyle)
for i in range(0, len(member['award'])):
obj = member['award'][i]
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 0, 2, obj['awardProjectName'],
memberInfoStyle)
ws.write(current_row + 3 + i, 3, obj['awardDate'], memberInfoStyle)
ws.write(current_row + 3 + i, 4, obj['awardNameAndLevel'], memberInfoStyle)
ws.write(current_row + 3 + i, 5, obj['awardRoleInProject'], memberInfoStyle)
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 6, 7, obj['awardCompany'],
memberInfoStyle)
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 8, 9, obj['awardMemo'],
memberInfoStyle)
obj_row = 3 + len(member['award'])
current_row += obj_row
break
if case('patents'):
if len(member['patents']) > 0:
ws.write_merge(current_row, current_row, 0, 9, u'')
ws.write_merge(current_row + 1, current_row + 1, 0, 9, u'专利情况', style)
ws.write_merge(current_row + 2, current_row + 2, 0, 3, u'获专利名称', memberInfoStyle)
ws.write_merge(current_row + 2, current_row + 2, 4, 5, u'获专利时间', memberInfoStyle)
ws.write_merge(current_row + 2, current_row + 2, 6, 9, u'专利号', memberInfoStyle)
for i in range(0, len(member['patents'])):
obj = member['patents'][i]
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 0, 3, obj['patentName'],
memberInfoStyle)
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 4, 5, obj['patentDate'],
memberInfoStyle)
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 6, 9, obj['patenNo'],
memberInfoStyle)
obj_row = 3 + len(member['patents'])
current_row += obj_row
break
if case('paper'):
if len(member['paper']) > 0:
ws.write_merge(current_row, current_row, 0, 9, u'')
ws.write_merge(current_row + 1, current_row + 1, 0, 9, u'主要论文著作', style)
ws.write(current_row + 2, 0, u'论文/著作', memberInfoStyle)
ws.write_merge(current_row + 2, current_row + 2, 1, 3, u'作品名称', memberInfoStyle)
ws.write_merge(current_row + 2, current_row + 2, 4, 6, u'刊物/出版社', memberInfoStyle)
ws.write(current_row + 2, 7, u'第几作者', memberInfoStyle)
ws.write(current_row + 2, 8, u'发行时间', memberInfoStyle)
ws.write(current_row + 2, 9, u'角色说明', memberInfoStyle)
for i in range(0, len(member['paper'])):
obj = member['paper'][i]
ws.write(current_row + 3 + i, 0, obj['paperPublications'], memberInfoStyle)
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 1, 3, obj['paperName'],
memberInfoStyle)
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 4, 6, obj['paperPress'],
memberInfoStyle)
ws.write(current_row + 3 + i, 7, obj['paperAuthorSort'], memberInfoStyle)
ws.write(current_row + 3 + i, 8, obj['paperPressDate'], memberInfoStyle)
ws.write(current_row + 3 + i, 9, obj['paperRoleDetail'], memberInfoStyle)
obj_row = 3 + len(member['paper'])
current_row += obj_row
break
if case('professionalSkill'):
if len(member['professionalSkill']) > 0:
ws.write_merge(current_row, current_row, 0, 9, u'')
ws.write_merge(current_row + 1, current_row + 1, 0, 9, u'专业技术工作', style)
ws.write_merge(current_row + 2, current_row + 2, 0, 3, u'项目名称', memberInfoStyle)
ws.write(current_row + 2, 4, u'项目类别', memberInfoStyle)
ws.write_merge(current_row + 2, current_row + 2, 5, 6, u'项目下达单位', memberInfoStyle)
ws.write(current_row + 2, 7, u'项目中所任角色', memberInfoStyle)
ws.write_merge(current_row + 2, current_row + 2, 8, 9, u'起止时间', memberInfoStyle)
for i in range(0, len(member['professionalSkill'])):
obj = member['professionalSkill'][i]
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 0, 3, obj['proProjectName'],
memberInfoStyle)
ws.write(current_row + 3 + i, 4, obj['proProjectType'], memberInfoStyle)
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 5, 6, obj['proProjectCompany'],
memberInfoStyle)
ws.write(current_row + 3 + i, 7, obj['proRolesInProject'], memberInfoStyle)
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 8, 9,
obj['proStartDate'] + ' - ' + obj['porEndDate'], memberInfoStyle)
obj_row = 3 + len(member['professionalSkill'])
current_row += obj_row
break
if case('achievements'):
if len(member['achievements']) > 0:
ws.write_merge(current_row, current_row, 0, 9, u'')
ws.write_merge(current_row + 1, current_row + 1, 0, 9, u'专业技术成果', style)
ws.write_merge(current_row + 2, current_row + 2, 0, 2, u'成果名称', memberInfoStyle)
ws.write_merge(current_row + 2, current_row + 2, 3, 5, u'成果水平', memberInfoStyle)
ws.write_merge(current_row + 2, current_row + 2, 6, 7, u'鉴定单位', memberInfoStyle)
ws.write_merge(current_row + 2, current_row + 2, 8, 9, u'备注', memberInfoStyle)
for i in range(0, len(member['achievements'])):
obj = member['achievements'][i]
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 0, 2, obj['achievementsName'],
memberInfoStyle)
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 3, 5, obj['achievementsLevel'],
memberInfoStyle)
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 6, 7, obj['identificationUnit'],
memberInfoStyle)
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 8, 9, obj['achievementsRemark'],
memberInfoStyle)
obj_row = 3 + len(member['achievements'])
current_row += obj_row
break
if case('agencybroker'):
if len(member['agencybroker']) > 0:
ws.write_merge(current_row, current_row, 0, 9, u'')
ws.write_merge(current_row + 1, current_row + 1, 0, 9, u'入社介绍人', style)
ws.write_merge(current_row + 2, current_row + 2, 0, 1, u'姓名', memberInfoStyle)
ws.write_merge(current_row + 2, current_row + 2, 2, 4, u'单位', memberInfoStyle)
ws.write_merge(current_row + 2, current_row + 2, 5, 6, u'职务', memberInfoStyle)
ws.write_merge(current_row + 2, current_row + 2, 7, 9, u'与本人关系', memberInfoStyle)
for i in range(0, len(member['agencybroker'])):
obj = member['agencybroker'][i]
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 0, 1, obj['agencyName'],
memberInfoStyle)
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 2, 4, obj['agencyCompany'],
memberInfoStyle)
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 5, 6, obj['agencyJob'],
memberInfoStyle)
ws.write_merge(current_row + 3 + i, current_row + 3 + i, 7, 9, obj['agencyRelationShip'],
memberInfoStyle)
obj_row = 3 + len(member['agencybroker'])
current_row += obj_row
break
if self.request.arguments:
current_row = customizeObj(obj, current_row, ws, style, memberInfoStyle, member)
tall_style = xlwt.easyxf('font:height 360;')
for i in range(0, current_row):
first_row = ws.row(i)
first_row.set_style(tall_style)
sio = BytesIO()
wb.save(sio)
self.set_header('Content-Type', 'application/vnd.ms-excel')
self.set_header('Content-Disposition',
'attachment; filename=' + urllib.parse.quote(member['name'] + '的信息.xls', "utf-8"))
self.write(sio.getvalue())
self.finish()
class switch(object):
def __init__(self, value):
self.value = value
self.fall = False
def __iter__(self):
yield self.match
raise StopIteration
def match(self, *args):
if self.fall or not args:
return True
elif self.value in args:
self.fall = True
return True
else:
return False
def customizeObj(obj, current_row, ws, style, memberInfoStyle, member):
if len(obj) > 6:
if obj[0:7] == 'custab_':
selector = {
"selector": {
"type": {
"$eq": "tab"
},
"tab_id": {
"$eq": obj
}
}
}
response = couch_db.post(r'/jsmm/_find/', selector)
tab = json.loads(response.body.decode('utf-8'))
tabObj = tab['docs'][0]
ws.write_merge(current_row, current_row, 0, 9, u'')
ws.write_merge(current_row + 1, current_row + 1, 0, 9, tabObj['gridTitle'], style)
columns = tabObj['columns']
for y in range(0, len(columns)):
ws.write(current_row + 2, y, columns[y]['title'], memberInfoStyle)
for i in range(0, len(member[obj])):
memberObj = member[obj][i]
for z in range(0, len(columns)):
ws.write(current_row + 3 + i, z, memberObj['file_' + str(z)], memberInfoStyle)
obj_row = 3 + len(member[obj])
current_row += obj_row
return current_row
@tornado_utils.bind_to(r'/member/information/(.+)')
class MembersExport(tornado.web.RequestHandler):
@tornado.web.addslash
def get(self, search_obj):
keys = ['name', 'gender', 'sector', 'lost', 'stratum', 'jobLevel', 'titleLevel', 'highestEducation']
column_name = ["name", "gender", "highestEducation", "jobTitle", "duty", "mobile",
"email", "companyName", "companyTel", "commAddress", "commPost"]
titles = {u'姓名': 10, u'性别': 6, u'最高学历': 10, u'职称': 12, u'职务': 12, u'移动电话': 13, u'邮箱': 25, u'单位名称': 26,
u'单位电话': 15, u'单位地址': 40, u'邮编': 10}
selector = {
"selector": {},
"fields": column_name
}
selector_content = selector["selector"]
search = json.loads(search_obj.replace('/', ''))
for key in keys:
if key in search:
if search[key] != '':
selector_content[key] = {'$eq': search[key]}
if 'retireTime' in search:
if search['retireTime'] != '':
selector_content['retireTime'] = {"$lt": search["retireTime"]}
if 'branch' in search:
if search['branch'] != '' and search['branch'] != u'北京市' and search['branch'] != u'朝阳区':
selector_content['branch'] = {"$eq": search["branch"]}
if 'socialPositionName' in search:
if search['socialPositionName'] != '':
selector_content['social'] = {
"$elemMatch": {"socialPositionName": {"$regex": search['socialPositionName']}}}
if 'socialPositionLevel' in search:
if search['socialPositionLevel'] != '':
selector_content['social'] = {
"$elemMatch": {"socialPositionLevel": {"$regex": search['socialPositionLevel']}}}
if 'formeOrganizationJob' in search:
if search['formeOrganizationJob'] != '':
selector_content['formercluboffice'] = {
"$elemMatch": {"formeOrganizationJob": {"$regex": search['formeOrganizationJob']}}}
if 'formeOrganizationLevel' in search:
if search['formeOrganizationLevel'] != '':
selector_content['formercluboffice'] = {
"$elemMatch": {"formeOrganizationLevel": {"$regex": search['formeOrganizationLevel']}}}
if 'startAge' in search and 'endAge' in search:
if search['startAge'] != '' and search['endAge']:
selector_content['birthday'] = {"$gte": search['endAge'], "$lte": search['startAge']}
selector_content['type'] = {"$eq": "member"}
response = couch_db.post(r'/jsmm/_find/', selector)
members_simple_info = json.loads(response.body.decode('utf-8'))["docs"]
style_heading = xlwt.easyxf("""
font:
name 微软雅黑,
colour_index black,
bold on,
height 200;
align:
wrap off,
vert center,
horiz centre;
pattern:
pattern solid,
fore-colour 22;
borders:
left THIN,
right THIN,
top THIN,
bottom THIN;
""")
style_data = xlwt.easyxf("""
font:
name 微软雅黑,
colour_index black,
bold off,
height 180;
align:
wrap off,
vert center,
horiz left;
pattern:
pattern solid,
fore-colour 1;
borders:
left thin,
right thin,
top thin,
bottom thin;
""")
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook.add_sheet('社员信息简表')
column = 0
row = 0
for title in titles:
worksheet.write(row, column, title, style_heading)
worksheet.col(column).width = titles[title] * 256
column += 1
if len(members_simple_info) > 0:
row = 1
for member in members_simple_info:
column = 0
for key in column_name:
worksheet.write(row, column, '', style_data) if key not in member else worksheet.write(row, column,
member[key],
style_data)
column += 1
row += 1
else:
pass
sio = BytesIO()
workbook.save(sio)
self.set_header('Content-Type', 'application/vnd.ms-excel')
self.set_header('Content-Disposition', 'attachment; filename=' + urllib.parse.quote('社员信息简表.xls', "utf-8"))
self.write(sio.getvalue())
self.finish()
<file_sep>/app/handlers/member_handler.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import tornado.web
import tornado_utils
from commons import couch_db
@tornado_utils.bind_to(r'/members/([0-9a-f]+)')
class MemberHandler(tornado.web.RequestHandler):
"""
MemberHandler
"""
def get(self, member_id):
"""
获取_id为member_id的member对象。
"""
query = {'keys': [member_id]}
documents_response = couch_db.post(
r'/jsmm/_design/documents/_view/by_memberid', query)
documents = json.loads(documents_response.body.decode('utf-8'))
member_response = couch_db.get(r'/jsmm/%(id)s' % {'id': member_id})
member = json.loads(member_response.body.decode('utf-8'))
member['researchReport'] = [doc['value'] for doc in documents[
'rows'] if doc['value']['docType'] == 'researchReport']
member['unitedTheory'] = [doc['value'] for doc in documents[
'rows'] if doc['value']['docType'] == 'unitedTheory']
member['politicsInfo'] = [doc['value'] for doc in documents[
'rows'] if doc['value']['docType'] == 'politicsInfo']
member['propaganda'] = [doc['value'] for doc in documents[
'rows'] if doc['value']['docType'] == 'propaganda']
self.write(member)
def put(self, member_id):
"""
修改_id为member_id的member对象。
"""
# 获得前台对象#
member_updated = json.loads(self.request.body.decode('utf-8'))
# 根据memeber_id,查询数据库中的memeber对象
response = couch_db.get(r'/jsmm/%(id)s' % {'id': member_id})
member = json.loads(response.body.decode('utf-8'))
# 将前台数据赋予后台对象,然后将后台对象保存。
member.update(member_updated)
# 将document中的member数据更新
query = {'keys': [member_id]}
documents_response = couch_db.post(
r'/jsmm/_design/documents/_view/by_memberid', query)
documents = json.loads(documents_response.body.decode('utf-8'))
for doc in documents['rows']:
doc['value']['name'] = member['name']
doc['value']['branch'] = member['branch']
doc['value']['organ'] = member['organ']
couch_db.put(r'/jsmm/%(id)s' %
{'id': doc['value']['_id']}, doc['value'])
couch_db.put(r'/jsmm/%(id)s' % {'id': member_id}, member)
response = {'success': 'true'}
self.write(response)
def delete(self, member_id):
"""
删除_id为member_id的member对象。
"""
# 通过HEAD方法查询Etag(即_rev)。
response = couch_db.head(r'/jsmm/%(id)s' % {'id': member_id})
# 从返回的headers中查找包含"Etag"的数据,取第一条,并去除头尾的双引号。
rev = response.headers.get_list('Etag')[0][1:-1]
# couch_db.delete(r'/jsmm/%(id)s?rev=%(rev)s' % {'id': member_id, 'rev': rev})
query = {'keys': [member_id]}
documents_response = couch_db.post(
r'/jsmm/_design/documents/_view/by_memberid', query)
documents = json.loads(documents_response.body.decode('utf-8'))
for doc in documents['rows']:
couch_db.delete(r'/jsmm/%(id)s?rev=%(rev)s' %
{'id': doc['value']['_id'], 'rev': doc['value']['_rev']})
couch_db.delete(r'/jsmm/%(id)s?rev=%(rev)s' %
{'id': member_id, 'rev': rev})
response = {'success': 'true'}
self.write(response)
<file_sep>/www/scripts/tab/relations/familyrelations.js
/**
* Created by S on 2017/2/21.
*/
//社会关系
$(function () {
var $grid = $("#familyRelation-list");
var tabId = 'familyRelations';
var gridTab = new GridTab(tabId, $grid);
var columns = [
{field: 'familyName', title: '姓名', width: 110, align: 'left', editor: 'textbox'},
{
field: 'familyRelation',
title: '与本人的关系',
width: 100,
align: 'left',
editor: {
type: 'combobox',
options: {
valueField: 'value',
textField: 'text',
method: 'get',
url: 'data/relationship.json',
prompt: '请选择'
}
}
},
{
field: 'familyGender',
title: '性别',
width: 120,
align: 'left',
editor: {
type: 'combobox',
options: {
valueField: 'value',
textField: 'text',
method: 'get',
url: 'data/gender.json',
prompt: '请选择'
}
}
},
{field: 'familyBirthDay', title: '出生年月', width: 120, align: 'left', editor: 'datebox'},
{field: 'familyCompany', title: '工作单位', width: 120, align: 'left', editor: 'textbox'},
{field: 'familyJob', title: '职务', width: 120, align: 'left', editor: 'textbox'},
{field: 'familyNationality', title: '国籍', width: 120, align: 'left', editor: 'textbox'},
{
field: 'familyPolitical ',
title: '政治面貌',
width: 120,
align: 'left',
editor: {
type: 'combobox',
options: {
valueField: 'value',
textField: 'text',
method: 'get',
url: 'data/party.json',
prompt: '请选择'
}
}
}
];
var toolbar = [
{
text: '添加记录',
iconCls: 'icon-add',
handler: function () {
gridTab.addRow();
}
}, '-', {
text: '移除记录',
iconCls: 'icon-remove',
handler: function () {
gridTab.removeRow();
}
}, '-', {
text: '保存记录',
iconCls: 'icon-save',
handler: function () {
gridTab.saveRow();
}
}
];
gridTab.buildGrid(toolbar, columns);
gridTab.registerListeners();
});<file_sep>/app/member_importer.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Copyright <EMAIL>
'''
import uuid
from xlrd import open_workbook
from commons import couch_db, get_retire_time
import json
def make_uuid():
'''
生成随机的UUID,并返回16进制字符串
'''
return uuid.uuid4().hex
def format_date(date_str):
"""
格式化从社员信息文件中导入的日期数据:
YYYY.MM.DD -> YYYY-MM-DD
YYYY.MM -> YYYY-MM-01
"""
date_str = date_str.rstrip('.') # 去除尾部的'.', 如'2010.01.'
if date_str == u'至今': # '至今'
return ''
splited = date_str.split('.') # 'YYYY', 'YYYY.MM'或'YYYY.MM.DD'
if len(splited) == 1: # ['YYYY']
splited += ['01', '01'] # ['YYYY', '01', '01']
elif len(splited) == 2: # ['YYYY', 'MM']
splited.append('01') # ['YYYY', 'MM', '01']
return '-'.join(splited) # 'YYYY-MM-DD'
def import_info(file_info):
member_info_importer = MemberInfoImporter(file_info['path'])
member_info_importer.get_basic_info()
member_info_importer.main_function()
return member_info_importer.save_member()
class MemberInfoImporter():
"""
导入社员信息。
"""
def __init__(self, path):
"""
打开一个包含社员基本信息的Excel文件。
:param path:
"""
self.current_row = 19
self._book = open_workbook(path)
self._sheet = self._book.sheet_by_index(0)
self._member = {
'type': 'member',
'_id': make_uuid(),
'educationDegree': [], # 学历信息 1
'jobResumes': [], # 工作履历 1
'professionalSkill': [], # 专业技术工作 1
'familyRelations': [], # 社会关系 1
'paper': [], # 主要论文著作 1
'achievements': [], # 专业技术成果 1
'award': [], # 获奖情况 1
'patents': [], # 专利情况 1
'professor': [], # 专家情况 0
'specializedskill': [], # 业务专长 1
'formerClubOffice': [], # 社内职务 0
'social': [], # 社会职务 0
'socialduties': [], # 其它职务 0
'agencybroker': [] # 入社介绍人 1
}
self._tabs_name = {
u"学历信息": self.member_edu_degree, # 学历信息
u"工作履历": self.member_job_esumes, # 工作履历
u"专业技术工作": self.member_professional, # 专业技术工作
u"社会关系": self.member_family_relation, # 社会关系
u"主要论文著作": self.member_paper, # 主要论文著作
u"专业技术成果": self.member_achievements, # 专业技术成果
u"获奖情况": self.member_award, # 获奖情况
u"专利情况": self.member_patents, # 专利情况
u"专家情况": self.member_professor, # 专家情况
u"业务专长": self.member_specialized_skill, # 业务专长
u"社内职务": self.member_former_club_office, # 社内职务
u"社会职务": self.member_social, # 社会职务
u"其它职务": self.member_social_duties, # 其它职务
u"入社介绍人": self.member_agency_broker # 入社介绍人
}
# print(r'正在处理%(path)s' % {'path': path})
def get_basic_info(self):
"""
获取"基本信息页"
:return:
"""
mapper = {
(1, 1): "name", # 姓名
(1, 3): "gender", # 性别
(1, 5): "nativePlace", # 籍贯
(2, 1): "nation", # 民族
(2, 3): "birthPlace", # 出生地
(2, 5): "birthday", # 出生日期
(3, 1): "foreignName", # 外文姓名
(3, 4): "usedName", # 曾用名
(4, 1): "health", # 健康状态
(4, 4): "marriage", # 婚姻状态
(5, 1): "branch", # 所属支社
(5, 4): "organ", # 所属基层组织名称
(6, 1): "branchTime", # 入社时间
(6, 4): "partyCross", # 党派交叉
(7, 1): "companyName", # 单位名称
(7, 4): "department", # 工作部门
(8, 1): "duty", # 职务
(8, 4): "jobTitle", # 职称
(9, 1): "academic", # 学术职务
(9, 4): "jobTime", # 参加工作时间
(9, 8): "retire", # 是否办理退休手续
(10, 1): "idCard", # 公民身份证号码
(10, 4): "idType", # 有效证件类别
(10, 8): "idNo", # 证件号码
(11, 1): "homeAddress", # 家庭地址
(11, 5): "homePost", # 家庭地址邮编
(12, 1): "companyAddress", # 单位地址
(12, 5): "companyPost", # 单位地址邮编
(13, 1): "commAddress", # 通信地址
(13, 5): "commPost", # 通信地址邮编
(14, 1): "mobile", # 移动电话
(14, 5): "homeTel", # 家庭电话
(15, 1): "email", # 电子信箱
(15, 5): "companyTel", # 单位电话
(16, 1): "hobby", # 爱好
(17, 1): "speciality" # 专长
}
for key in mapper.keys():
self._member[mapper[key]] = self._sheet.cell_value(key[0], key[1])
self._member['branchTime'] = format_date(str(self._member['branchTime']))
self._member['birthday'] = format_date(str(self._member['birthday']))
self._member['jobTime'] = format_date(str(self._member['jobTime']))
def main_function(self):
for row_index in range(self.current_row, self._sheet.nrows):
name = self._sheet.cell_value(row_index, 0)
if name in self._tabs_name:
self._tabs_name[name](row_index+2)
def member_edu_degree(self, row_index):
"""
学历信息
:param row_index:
:return:
"""
for i in range(row_index, self._sheet.nrows):
self.current_row = i
if self._sheet.cell_value(i, 0) == "":
return
else:
[start_time, end_time] = self._sheet.cell_value(i, 2).split(' - ')
edu_degree = {"eduSchoolName": self._sheet.cell_value(i, 0),
"eduStartingDate": format_date(start_time),
"eduGraduateDate": format_date(end_time),
"eduMajor": self._sheet.cell_value(i, 4),
"eduEducation": self._sheet.cell_value(i, 6),
"eduDegree": self._sheet.cell_value(i, 7),
"eduEducationType": self._sheet.cell_value(i, 9)}
self._member["educationDegree"].append(edu_degree)
def member_job_esumes(self, row_index):
"""
工作履历
:param row_index:
:return:
"""
for i in range(row_index, self._sheet.nrows):
self.current_row = i
if self._sheet.cell_value(i, 0) == "":
return
else:
[start_time, end_time] = self._sheet.cell_value(i, 7).split(' - ')
job_esumes = {"jobCompanyName": self._sheet.cell_value(i, 0),
"jobDep": self._sheet.cell_value(i, 2),
"jobDuties": self._sheet.cell_value(i, 4),
"jobTitle": self._sheet.cell_value(i, 5),
"jobAcademic": self._sheet.cell_value(i, 6),
"jobStartTime": format_date(start_time),
"jobEndTime": format_date(end_time),
"jobReterence": self._sheet.cell_value(i, 9)}
self._member["jobResumes"].append(job_esumes)
def member_professional(self, row_index):
"""
专业技术工作
:param row_index:
:return:
"""
for i in range(row_index, self._sheet.nrows):
self.current_row = i
if self._sheet.cell_value(i, 0) == "":
return
else:
[start_time, end_time] = self._sheet.cell_value(i, 8).split(' - ')
professional_skill = {
"proProjectName": self._sheet.cell_value(i, 0),
"proProjectType": self._sheet.cell_value(i, 4),
"proProjectCompany": self._sheet.cell_value(i, 5),
"proRolesInProject": self._sheet.cell_value(i, 7),
"proStartDate": format_date(start_time),
"porEndDate": format_date(end_time)}
self._member["professionalSkill"].append(professional_skill)
def member_family_relation(self, row_index):
"""
社会关系
:param row_index:
:return:
"""
for i in range(row_index, self._sheet.nrows):
self.current_row = i
if self._sheet.cell_value(i, 0) == "":
return
else:
family_relations = {
"familyName": self._sheet.cell_value(i, 0),
"familyRelation": self._sheet.cell_value(i, 1),
"familyGender": self._sheet.cell_value(i, 2),
"familyBirthDay": format_date(str(self._sheet.cell_value(i, 3))),
"familyCompany": self._sheet.cell_value(i, 4),
"familyJob": self._sheet.cell_value(i, 6),
"familyNationality": self._sheet.cell_value(i, 7),
"familyPolitical": self._sheet.cell_value(i, 8)}
self._member["familyRelations"].append(family_relations)
def member_paper(self, row_index):
"""
主要论文著作
:param row_index:
:return:
"""
for i in range(row_index, self._sheet.nrows):
self.current_row = i
if self._sheet.cell_value(i, 0) == "":
return
else:
paper = {
"paperPublications": self._sheet.cell_value(i, 0),
"paperName": self._sheet.cell_value(i, 1),
"paperPress": self._sheet.cell_value(i, 4),
"paperAuthorSort": self._sheet.cell_value(i, 7),
"paperPressDate": format_date(str(self._sheet.cell_value(i, 8))),
"paperRoleDetail": self._sheet.cell_value(i, 9)}
self._member["paper"].append(paper)
def member_achievements(self, row_index):
"""
专业技术成果
:param row_index:
:return:
"""
for i in range(row_index, self._sheet.nrows):
self.current_row = i
if self._sheet.cell_value(i, 0) == "":
return
else:
achievements = {
"achievementsName": self._sheet.cell_value(i, 0),
"achievementsLevel": self._sheet.cell_value(i, 3),
"identificationUnit": self._sheet.cell_value(i, 6),
"achievementsRemark": self._sheet.cell_value(i, 8)}
self._member["achievements"].append(achievements)
def member_patents(self, row_index):
"""
专利情况
:param row_index:
:return:
"""
for i in range(row_index, self._sheet.nrows):
self.current_row = i
if self._sheet.cell_value(i, 0) == "":
return
else:
patents = {
"patentName": self._sheet.cell_value(i, 0),
"patentDate": format_date(str(self._sheet.cell_value(i, 4))),
"patenNo": self._sheet.cell_value(i, 6)}
self._member["patents"].append(patents)
def member_specialized_skill(self, row_index):
"""
业务专长
:param row_index:
:return:
"""
for i in range(row_index, self._sheet.nrows):
self.current_row = i
if self._sheet.cell_value(i, 0) == "":
return
else:
specialized_skill = {
"specializedType": self._sheet.cell_value(i, 0),
"specializedName": self._sheet.cell_value(i, 2),
"specializedDetailName": self._sheet.cell_value(i, 5)}
self._member["specializedskill"].append(specialized_skill)
def member_agency_broker(self, row_index):
"""
入社介绍人
:param row_index:
:return:
"""
for i in range(row_index, self._sheet.nrows):
self.current_row = i
if self._sheet.cell_value(i, 0) == "":
return
else:
agency_broker = {
"agencyName": self._sheet.cell_value(i, 0),
"agencyCompany": self._sheet.cell_value(i, 2),
"agencyJob": self._sheet.cell_value(i, 5),
"agencyRelationShip": self._sheet.cell_value(i, 7)}
self._member["agencybroker"].append(agency_broker)
def member_award(self, row_index):
"""
工作获奖
:param row_index:
:return:
"""
for i in range(row_index, self._sheet.nrows):
self.current_row = i
if self._sheet.cell_value(i, 0) == "":
return
else:
award = {
"awardProjectName": self._sheet.cell_value(i, 0),
"awardDate": format_date(str(self._sheet.cell_value(i, 3))),
"awardNameAndLevel": self._sheet.cell_value(i, 4),
"awardRoleInProject": self._sheet.cell_value(i, 5),
"awardCompany": self._sheet.cell_value(i, 6),
"awardMemo": self._sheet.cell_value(i, 8)
}
self._member["award"].append(award)
def member_professor(self, row_index):
"""
专家情况
:param row_index:
:return:
"""
for i in range(row_index, self._sheet.nrows):
self.current_row = i
if self._sheet.cell_value(i, 0) == "":
return
else:
professor = {}
self._member["professor"].append(professor)
def member_former_club_office(self, row_index):
"""
社内职务
:param row_index:
:return:
"""
for i in range(row_index, self._sheet.nrows):
self.current_row = i
if self._sheet.cell_value(i, 0) == "":
return
else:
former_club_office = {}
self._member["formerClubOffice"].append(former_club_office)
def member_social(self, row_index):
"""
社会职务
:param row_index:
:return:
"""
for i in range(row_index, self._sheet.nrows):
self.current_row = i
if self._sheet.cell_value(i, 0) == "":
return
else:
social = {}
self._member["social"].append(social)
def member_social_duties(self, row_index):
"""
其它职务
:param row_index:
:return:
"""
for i in range(row_index, self._sheet.nrows):
self.current_row = i
if self._sheet.cell_value(i, 0) == "":
return
else:
social_duties = {}
self._member["socialduties"].append(social_duties)
def save_member(self):
"""
保存社员信息
:return:
"""
query_name = self._member["name"]
query_id_card = self._member["idCard"]
obj = {
"selector": {
"name": {"$eq": query_name},
"idCard": {"$eq": query_id_card}
},
"fields": ["_id", "name", "idCard"]
}
request = couch_db.post(r'/jsmm/_find/', obj)
member = json.loads(request.body.decode('utf-8'))
if len(member["docs"]):
memberInfo = member["docs"]
msg = {"success": False, "name": memberInfo[0]["name"], "idCard": memberInfo[0]["idCard"]}
return msg
else:
self._member["retireTime"] = get_retire_time(self._member["birthday"], self._member["gender"])
self._member["lost"] = "否"
self._member["stratum"] = "否"
couch_db.post(r'/jsmm/', self._member)
return {"success": True}
# if __name__ == "__main__":
# import sys
# sys.path[:0] = ['app', 'lib']
# from couchdb import CouchDB
# couch_db = CouchDB('http://127.0.0.1:5984')
# member_info_importer = MemberInfoImporter('inbox/殷大发的信息.xls')
# member_info_importer.get_basic_info()
# member_info_importer.main_function()
# member_info_importer.save_member()
<file_sep>/www/scripts/tab/documents/politicsinfo.js
/**
* Created by S on 2017/2/21.
*/
// 参政议政信息
$(function () {
var tabId = 'politicsInfo';
var $grid = $("#politics-info");
var gridTab = new GridTab(tabId, $grid);
var columns = [
{
field: 'fileUploadTime',
title: '上传时间',
width: 80,
align: 'left',
editor: {type: 'datetimebox', options: {}}
}, {
field: 'fileName',
title: '文件名称',
width: 160,
align: 'left',
editor: {type: 'textbox', options: {}}
}, {
field: 'clickDownload',
title: '操作',
width: 60,
sortable: false,
align: 'left',
formatter: function (value, row, index) {
var path = "/document/" + row._id + "/" + row.fileName;
return '<a href= ' + path + ' >下载</a>';
}
}
];
var toolbar = [{
text: '参政议政信息上传',
iconCls: 'icon-import',
handler: function () {
gridTab.docUpload()
}
}, '-', {
text: '文档删除',
iconCls: 'icon-cancel',
handler: function () {
gridTab.docDelete()
}
}];
gridTab.buildDocGrid(toolbar, columns);
gridTab.registerListeners();
});<file_sep>/app/handlers/member_upload.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os.path
import uuid
import tornado.web
class UploadHandler(tornado.web.RequestHandler):
def initialize(self, callback):
'''
callback(file_info),其中file_info格式为:
{'filename': 'xxx.xls', 'path': 'aaa/bbb/xxx.xls', 'content_type': 'application/vnd.ms-excel'}
filename为原文件名,path为实际保存路径,content_type为文件类型
'''
self._callback = callback
@tornado.web.addslash
def get(self):
self.write('''
<html>
<head><title>Upload File</title></head>
<body>
<form action='/members/upload/' enctype="multipart/form-data" method='post'>
<input type='file' name='members'/><br/>
<input type='submit' value='submit'/>
</form>
</body>
</html>
''')
@tornado.web.addslash
def post(self):
"""
接收多个上传文件,调用callback对上传的。
:return:
"""
# 文件的保存路径
inbox_path = os.path.join(os.path.dirname(__file__), '../../inbox/members')
# 结构为:{'members': [{'filename': 'xxx.xls', 'body': b'...',
# 'content_type': 'application/vnd.ms-excel'}]}
file_infos = self.request.files['members']
error_message = []
for file_info in file_infos:
filename = file_info['filename']
upload_path = os.path.join(inbox_path, filename)
# 在保存的文件名和扩展名中间加6个随机字符,避免文件重名。
(root, ext) = os.path.splitext(upload_path)
path = root + '-' + uuid.uuid4().hex[0:6] + ext
with open(path, 'wb') as file:
file.write(file_info['body'])
msgs = self._callback({'filename': filename, 'path': path, 'content_type': file_info['content_type']})
if not msgs["success"]:
error_message.append({"name": msgs["name"], "idCard": msgs["idCard"]})
if len(error_message):
self.write({"success": False, "msg": error_message})
else:
self.write({"success": True, "msg": error_message})
<file_sep>/start.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import commons
if __name__ == "__main__":
print("Starting...")
import tornado_utils
from handlers import *
from member_importer import import_info
tornado_utils.registered_handlers += [
(r'/members/upload/?', member_upload.UploadHandler, dict(callback=import_info))
, (r'/image/upload/?', member_image.UploadImage, dict(callback=member_image.imageCallBack))
# ,(r'/doc/upload/?', member_doc.UploadDoc, dict(callback=member_doc.docCallBack))
]
tornado_utils.serve(2063, debug=True)
<file_sep>/app/handlers/document_collection_handler.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import urllib
import tornado.web
import tornado_utils
from commons import couch_db, couchLucene_db
@tornado_utils.bind_to(r'/documents/?')
class DocumentHandler(tornado.web.RequestHandler):
def data_received(self, chunk):
pass
def get(self):
"""修改_id为member_id的member对象。
"""
response = couch_db.get(r'/jsmm/_design/documents/_view/by-memberid')
doucment_list = json.loads(response.body.decode('utf-8'))
documents = []
for row in doucment_list['rows']:
documents.append(row['value'])
self.set_header('Content-Type', 'application/json')
self.write(json.dumps(documents))
def post(self):
"""
修改_id为member_id的member对象。
"""
params = json.loads(self.request.body.decode('utf-8'))
page_number = params['page']
page_size = params['rows']
params_str = ""
if "documentInfo" in params:
# name = params["documentInfo"]["name"]
# fileName = params["documentInfo"]["fileName"]
key_world = params["documentInfo"]["keyWord"].replace(' ', '')
key_word_attachment = params["documentInfo"]["keyWordAttachment"]
start_date = params["documentInfo"]["startDate"]
end_date = params["documentInfo"]["endDate"]
doc_type = params["documentInfo"]["docType"]
if key_word_attachment != '':
params_str += key_word_attachment
else:
pass
# if name != '' and params_str != '':
# params_str += ' AND name:"' + name + '"'
# elif name != '' and params_str == '':
# params_str += 'name:"' + name + '"'
# else:
# pass
#
# if fileName != '' and params_str != '':
# params_str += ' AND fileName:"' + fileName + '"'
# elif fileName != '' and params_str == '':
# params_str += 'fileName:"' + fileName + '"'
# else:
# pass
if key_world != '' and params_str != '':
params_str += ' AND (fileName:' + key_world + ' OR name:' + key_world + ')'
elif key_world != '' and params_str == '':
params_str += '(fileName:' + key_world + ' OR name:' + key_world + ')'
else:
pass
if start_date != '' and end_date != '' and params_str != '':
params_str += ' AND fileUploadTime<date>:[' + start_date + ' TO ' + end_date + ']'
elif start_date != '' and end_date != '' and params_str == '':
params_str += 'fileUploadTime<date>:[' + start_date + ' TO ' + end_date + ']'
else:
pass
if doc_type != '' and params_str != '':
params_str += ' AND docType:"' + doc_type + '"'
elif doc_type != '' and params_str == '':
params_str += 'docType:"' + doc_type + '"'
else:
pass
if "branch" in params:
branch = params["branch"]
if branch != '' and params_str != '' and branch != '北京市' and branch != '朝阳区':
params_str += ' AND branch:"' + branch + '"'
elif branch != '' and params_str == '' and branch != '北京市' and branch != '朝阳区':
params_str += 'branch:"' + branch + '"'
else:
pass
print('params_str = ' + params_str)
if params_str != '':
response = couchLucene_db.get(
r'/_fti/local/jsmm/_design/documents/by_doc_info?q=%(params_str)s&limit=%(limit)s&skip=%(skip)s' % {
"params_str": urllib.parse.quote(params_str, "utf-8"), 'limit': page_size,
'skip': (page_number - 1) * page_size})
else:
response = couch_db.get(
'/jsmm/_design/documents/_view/by_memberid?limit=%(page_size)s&skip=%(page_number)s' % {
'page_size': page_size, 'page_number': (page_number - 1) * page_size})
documents_result = {}
if response.code == 200:
documents = []
document_list = json.loads(response.body.decode('utf-8'))
print(document_list)
if params_str != '':
for row in document_list['rows']:
row['fields']['_id'] = row['id']
documents.append(row['fields'])
else:
for row in document_list['rows']:
documents.append(row['value'])
documents_result['total'] = document_list['total_rows']
documents_result['rows'] = documents
else:
documents_result['total'] = 0
documents_result['rows'] = []
documents_result['page_size'] = page_size
documents_result['page_number'] = page_number
self.set_header('Content-Type', 'application/json')
self.write(json.dumps(documents_result))
<file_sep>/app/handlers/member_image.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os.path
import uuid
import tornado.web
import json
from commons import couch_db
def imageCallBack(file):
loadDb = couch_db.get(r'/jsmm/%(id)s' % {'id': str(file['member_id'], encoding="utf-8")})
memberInDb = json.loads(loadDb.body.decode('utf-8'))
memberInDb['picture'] = '/image/'+file['filename']
couch_db.put(r'/jsmm/%(id)s' % {"id": str(file['member_id'], encoding="utf-8")}, memberInDb)
class UploadImage(tornado.web.RequestHandler):
def initialize(self, callback):
self._callback = callback
@tornado.web.addslash
def post(self):
"""
接收多个上传文件,调用callback对上传的。
:return:
"""
# 文件的保存路径
inbox_path = os.path.join(os.path.dirname(__file__), '../../www/image')
# 结构为:{'members': [{'filename': 'xxx.xls', 'body': b'...',
# 'content_type': 'application/vnd.ms-excel'}]}
file_infos = self.request.files['picture']
member_id = self.request.arguments['picture_id'][0]
for file_info in file_infos:
filename = file_info['filename']
upload_path = os.path.join(inbox_path)
# 在保存的文件名和扩展名中间加6个随机字符,避免文件重名。
# (root, ext) = os.path.splitext(upload_path)
(name, ext) = os.path.splitext(filename)
file_name = name + '-' + uuid.uuid4().hex[0:6] + ext
path = upload_path + '/' + file_name
with open(path, 'wb') as file:
file.write(file_info['body'])
self._callback({'filename': file_name, 'path': path, 'content_type': file_info['content_type'], 'member_id': member_id})
response = {"fileName": file_name}
self.write(response)
<file_sep>/www/scripts/tab/duties/socialduties.js
/**
* Created by S on 2017/2/22.
*/
// 其他职务
$(function () {
var $grid = $("#socialDuties-list");
var tabId = 'achievements';
var gridTab = new GridTab(tabId, $grid);
var columns = [
{field: 'socialOrganizationCategory', title: '社会组织类别', width: 110, align: 'left', editor: 'textbox'},
{field: 'socialOrganizationName', title: '社会组织名称', width: 110, align: 'left', editor: 'textbox'},
{field: 'socialOrganizationLevel', title: '社会职务级别', width: 120, align: 'left', editor: 'textbox'},
{field: 'socialOrganizationJob', title: '社会职务名称', width: 120, align: 'left', editor: 'textbox'},
{field: 'socialTheTime', title: '届次', width: 120, align: 'left', editor: 'textbox'},
{field: 'socialStartTime', title: '开始时间', width: 120, align: 'left', editor: 'datebox'},
{field: 'socialEndTime', title: '结束时间', width: 120, align: 'left', editor: 'datebox'}
];
var toolbar = [
{
text: '添加记录',
iconCls: 'icon-add',
handler: function () {
gridTab.addRow();
}
}, '-', {
text: '移除记录',
iconCls: 'icon-remove',
handler: function () {
gridTab.removeRow();
}
}, '-', {
text: '保存记录',
iconCls: 'icon-save',
handler: function () {
gridTab.saveRow();
}
}
];
gridTab.buildGrid(toolbar, columns);
gridTab.registerListeners();
});
<file_sep>/www/scripts/tab/achievements/patentsinfo.js
/**
* Created by S on 2017/2/22.
*/
// 专利情况
$(function () {
var $grid = $("#patents-list");
var tabId = 'patents';
var gridTab = new GridTab(tabId, $grid);
var columns = [
{
field: 'patentName',
title: '获专利名称',
width: 150,
align: 'left',
editor: {
type: 'textbox',
options: {}
}
},
{
field: 'patentDate',
title: '获专利时间',
width: 60,
align: 'left',
editor: {type: 'datebox', options: {}}
},
{
field: 'patenNo',
title: '专利号',
width: 120,
align: 'left',
editor: {type: 'textbox', options: {}}
}
];
var toolbar = [
{
text: '添加记录',
iconCls: 'icon-add',
handler: function () {
gridTab.addRow();
}
}, '-', {
text: '移除记录',
iconCls: 'icon-remove',
handler: function () {
gridTab.removeRow();
}
}, '-', {
text: '保存记录',
iconCls: 'icon-save',
handler: function () {
gridTab.saveRow();
}
}
];
gridTab.buildGrid(toolbar, columns);
gridTab.registerListeners();
});<file_sep>/lib/couchdb.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Copyright <EMAIL>
'''
import json
from tornado.httpclient import HTTPClient, HTTPError, HTTPRequest
class CouchDB(object):
"""
封装访问CouchDB的GET、HEAD、PUT、POST、DELETE方法。
"""
def __init__(self, base_uri):
self.__base_uri = base_uri
def __fetch(self, method, path, content_type=None, data=None):
assert path[0] == '/'
headers = {}
body = None
if method == 'PUT' or method == 'POST':
if content_type is None:
headers['Content-Type'] = 'application/json'
if data is None:
body = ''
else:
str(data)
body = json.dumps(data)
else:
headers['Content-Type'] = content_type
body = data
request = HTTPRequest(
self.__base_uri + path,
method,
headers=headers,
body=body
)
http_client = HTTPClient()
try:
return http_client.fetch(request)
except HTTPError as error:
return error
finally:
http_client.close()
def get(self, path):
"""
GET方法。
"""
return self.__fetch('GET', path)
def head(self, path):
"""
HEAD方法。
"""
return self.__fetch('HEAD', path)
def put(self, path, data=None, content_type=None):
"""
PUT方法。
"""
return self.__fetch(
'PUT',
path,
content_type=content_type,
data=data
)
def post(self, path, data=None, content_type=None):
"""
POST方法。
"""
return self.__fetch(
'POST',
path,
content_type=content_type,
data=data
)
def delete(self, path):
"""
DELETE方法。
"""
return self.__fetch('DELETE', path)
<file_sep>/app/handlers/attachment_handler.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright <EMAIL>
"""
import json
import time
import urllib
import tornado.web
import tornado_utils
from commons import couch_db, make_uuid
@tornado_utils.bind_to(r'/document/([0-9a-f]+)/(.+)')
class AttachmentHandler(tornado.web.RequestHandler):
"""附件处理类
URL: '/document/<document_id>/<attachment_name>'
"""
def _parse_header(self, response):
"""获取附件的状态、大小、文件类型信息。
返回:(<status_code>, <content_length>, <content_type>)
"""
# status_code = response.headers.get_list('HTTP/1.1')[0][1:-1]
print(response.code)
status_code = str(response.code)
content_length = 0
content_type = 0
if response.code == 200:
content_length = response.headers.get_list('Content-Length')[0][1:-1]
content_type = response.headers.get_list('Content-Type')[0][1:-1]
return (status_code, content_length, content_type)
def head(self, document_id, attachment_name):
"""获取附件的状态、大小、文件类型信息。
返回:
{
"success": <'true'/'false'>, # 仅当statusCode为200时为'true'
"statusCode": <status_code>, # 200, 304, 401, 404
"contentLength": <content_length>,
"contentType": <content-type>
}
"""
response = couch_db.head(r'/jsmm/%(document_id)s/%(attachment_name)s' %
{'document_id': document_id, 'attachment_name': attachment_name})
(status_code, content_length, content_type) = self._parse_header(response)
output = {'statusCode': status_code,
'contentLength': content_length,
'contentType': content_type}
if status_code.startswith('200'):
self.write(output.update({'success': 'true'}))
else:
self.write(output.update({'success': 'false'}))
def get(self, document_id, attachment_name):
"""获取附件内容
返回:
{
"success": <'true'/'false'>, # 仅当statusCode为200时为'true'
"statusCode": <status_code>, # 200, 304, 401, 404
"contentLength": <content_length>,
"contentType": <content_type>,
"body": <response.body> # 仅当statusCode为200时提供
}
"""
response = couch_db.get(r'/jsmm/%(document_id)s/%(attachment_name)s' %
{'document_id': document_id, 'attachment_name': attachment_name})
(status_code, content_length, content_type) = self._parse_header(response)
output = {'statusCode': status_code,
'contentLength': content_length,
'contentType': content_type}
if status_code.startswith('200'):
self.set_header('Content-Type', content_type)
self.set_header('Content-Disposition',
'attachment; filename=' + urllib.parse.quote(attachment_name, "utf-8"))
self.write(response.body)
else:
self.set_header('Content-Type', 'application/json')
output.update({'success': 'false'})
self.write(json.dumps(output))
def put(self, document_id, attachment_name):
"""保存附件
如果保存任何一个附件时出现错误,返回:{'success': 'false', 'errors': <errors>}
如果全部保存成功,返回:{'success': 'true'}
"""
# 前端file input的name属性应指定为"docs"。
# 接收到的文件列表结构为:{'docs': [{'filename': <filename>, 'body': <body>,
# 'content_type': <content_type>}]}
docs = self.request.files['docs']
# 格式为:[{'filename': <filename>, 'error': <error>, 'reason': <reason>}]
errors = []
for doc in docs:
body = doc['body']
content_type = doc['content_type']
# 每次保存附件后,文档的rev都会变
head_response = couch_db.head(r'/jsmm/%(document_id)s' %
{'document_id': document_id})
rev = head_response.headers.get_list('Etag')[0][1:-1]
put_response = couch_db.put(r'/jsmm/%(document_id)s/%(attachment_name)s?rev=%(rev)s' %
{'document_id': document_id,
'attachment_name': attachment_name,
'rev': rev},
body, content_type)
status_code = self._parse_header(put_response)[0]
if status_code.startswith('4'): # 400, 401, 404, 409
error = json.loads(put_response.body.decode('utf-8'))
errors.append({'filename': doc['filename']}.update(error))
if len(errors) > 0:
self.write({'success': 'false', 'errors': errors})
else:
self.write({'success': 'true'})
def delete(self, document_id, attachment_name):
"""删除附件
返回:
{
"success": <'true'/'false'>, # 当statusCode为200, 202时为'true'
"error": <error> # 当statusCode为400, 401, 404, 409时
}
"""
head_response = couch_db.head(r'/jsmm/%(document_id)s' %
{'document_id': document_id})
rev = head_response.headers.get_list('Etag')[0][1:-1]
delete_response = couch_db.delete(r'/jsmm/%(document_id)s/%(attachment_name)s?rev=%(rev)s' %
{'document_id': document_id,
'attachment_name': attachment_name,
'rev': rev})
status_code = self._parse_header(delete_response)[0]
if status_code.startswith('4'): # 400, 401, 404, 409
error = json.loads(delete_response.body.decode('utf-8'))
self.write({'success': 'false', 'error': error})
else:
self.write({'success': 'true'})
def post(self, member_id, doc_type):
response_member = couch_db.get(r'/jsmm/%(member_id)s' % {"member_id": member_id})
member_in_db = json.loads(response_member.body.decode('utf-8'))
docs = self.request.files['docs']
doc_name = docs[0]['filename']
document_info = {
'_id': make_uuid(),
'memberId': member_in_db['_id'],
'name': member_in_db['name'],
'type': 'document',
'branch': member_in_db['branch'],
'organ': member_in_db['organ'],
'fileUploadTime': time.strftime("%Y-%m-%d", time.localtime()),
'docType': doc_type,
'fileName': doc_name
}
document_response = couch_db.post(r'/jsmm/', document_info)
result = json.loads(document_response.body.decode('utf-8'))
document_id = result["id"]
if doc_type == 'researchReport':
if 'researchReport' not in member_in_db:
member_in_db['researchReport'] = []
member_in_db['researchReport'].append(document_id)
elif doc_type == 'unitedTheory':
if 'unitedTheory' not in member_in_db:
member_in_db['unitedTheory'] = []
member_in_db['unitedTheory'].append(document_id)
elif doc_type == 'politicsInfo':
if 'politicsInfo' not in member_in_db:
member_in_db['politicsInfo'] = []
member_in_db['politicsInfo'].append(document_id)
elif doc_type == 'propaganda':
if 'propaganda' not in member_in_db:
member_in_db['propaganda'] = []
member_in_db['propaganda'].append(document_id)
couch_db.put(r'/jsmm/%(id)s' % {"id": member_id}, member_in_db)
return self.put(document_id, doc_name)
<file_sep>/setup.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from tornado.httpclient import HTTPError
from commons import couch_db, make_uuid
def try_(operation_result):
if isinstance(operation_result, Exception):
raise operation_result
# !!!注意:此处会删除原有的数据库!!!
if not isinstance(couch_db.get('/jsmm'), HTTPError):
try_(couch_db.delete('/jsmm'))
try_(couch_db.put('/jsmm'))
try_(couch_db.put('/jsmm/_design/members', {
'views': {
'all': {
'map': '''
function(doc) {
if (doc.type == 'member') {
emit([doc.id, doc.name], doc);
}
}'''
},
'by-name': {
'map': '''
function (doc) {
if (doc.type == 'member') {
if(doc.name) {
var name = doc.name.replace(/^(A|The) /, '');
emit(name, doc);
}
}
}'''
},
'by-memberid': {
'map': '''
function (doc) {
if(doc.type == 'document'){
emit(doc.memberId, doc);
}
}'''
},
"by-birthday": {
"map": '''
function (doc) {
if (doc.type == 'member') {
var birthday = doc.birthday.split('-');
if (birthday.length == 3) {
emit([parseInt(birthday[1], 10), parseInt(birthday[2], 10)], doc);
}
}
}'''
}
},
'fulltext': {
'by_basic_info': {
'analyzer': 'chinese',
'index': '''
function (doc) {
var result = new Document();
function makeIndex(obj, field, store, type) {
var value = null;
field = field || 'default';
store = store || 'no';
type = type || 'text';
if (field != 'default') {
value = obj[field];
}
switch (type) {
case 'date':
if (!value) break;
value = value.split('-');
result.add(new Date(value[0], value[1], value[2]), {'field': field, 'store': store, 'type': 'date'});
break;
default:
result.add(value, {'field': field, 'store': store, 'type': type});
break;
}
}
if (doc.type == 'member') {
makeIndex(doc, 'name', 'yes');
makeIndex(doc, 'gender', 'yes');
makeIndex(doc, 'idCard', 'yes');
makeIndex(doc, 'nation', 'yes');
makeIndex(doc, 'birthPlace', 'yes');
makeIndex(doc, 'birthday', 'yes', 'date');
makeIndex(doc, 'branch', 'yes');
makeIndex(doc, 'branchTime', 'yes', 'date');
doc.agencybroker.forEach(function(introducer) {
makeIndex(introducer, 'agencyName', 'yes');
});
return result;
} else {
return null;
}
}'''
}
}
}))
try_(couch_db.put('/jsmm/_design/documents', {
"views": {
"by_branch": {
"map": "\nfunction (doc) {\n if(doc.type == 'document'){\n emit(doc.branch, doc);\n }\n}"
},
"by_memberid": {
"map": "\nfunction (doc) {\n if(doc.type == 'document'){\n emit(doc.memberId, doc);\n }\n}"
}
},
"fulltext": {
"by_attachment": {
"index": "\n function(doc) {\n var result = new Document();\n if (doc.type == 'document') {\n for(var a in doc._attachments) {\n result.attachment(\"default\", a);\n }\n return result;\n } else {\n return null;\n }\n }\n"
},
"by_doc_info": {
"analyzer": "chinese",
"index": "\nfunction (doc) {\n var result = new Document();\n if (doc.type == 'document') {\n result.add(doc.fileName, {'field':'fileName', 'store':'yes', 'type':'text'});\n result.add(doc.name, {'field':'name', 'store':'yes','type':'text'});\n result.add(doc.branch, {'field':'branch', 'store':'yes','type':'text'});\n result.add(doc.fileUploadTime, {'field':'fileUploadTime', 'store':'yes', 'type':'date'});\n result.add(doc.fileUploadTime, {'field':'fileUploadTime','store':'yes','type':'text'});\n result.add(doc.docType, {'field':'docType', 'store':'yes','type':'text'});\n for (var a in doc._attachments) {\n result.attachment('default', a);\n }\n return result;\n } else {\n return null;\n }\n }"
}
}
}))
try_(couch_db.put('/jsmm/_design/organ', {
"views": {
"getOrgan": {
"map": "function (doc) {\n if(doc.typeFlag == 'organ'){\n emit(doc.typeFlag,doc);\n }\n}"
}
}
}))
organ = {
"typeFlag": "organ",
"organ": [
{
"id": "北京市",
"text": "北京市",
"children": [
{
"id": "朝阳区",
"text": "朝阳区",
"children": []
}
]
}
]
}
try_(couch_db.post(r'/jsmm/', organ))
<file_sep>/www/scripts/tab/resume/jobresumes.js
/**
* Created by S on 2017/2/21.
*/
// 工作履历
$(function () {
var tabId = 'jobResumes';
var $grid = $("#job-resumes");
var gridTab = new GridTab(tabId, $grid);
var columns = [
{field: 'jobCompanyName', title: '单位名称', width: 110, align: 'left', editor: 'textbox'},
{field: 'jobDep', title: '工作部门', width: 50, align: 'left', editor: 'textbox'},
{field: 'jobDuties', title: '职务', width: 120, align: 'left', editor: 'textbox'},
{field: 'jobTitle', title: '职称', width: 120, align: 'left', editor: 'textbox'},
{field: 'jobAcademic', title: '学术职务', width: 120, align: 'left', editor: 'textbox'},
{field: 'jobStartTime', title: '开始时间', width: 120, align: 'left', editor: 'datebox'},
{field: 'jobEndTime', title: '结束时间', width: 120, align: 'left', editor: 'datebox'},
{field: 'jobReterence', title: '证明人', width: 120, align: 'left', editor: 'textbox'}
];
var toolbar = [
{
text: '添加记录',
iconCls: 'icon-add',
handler: function () {
gridTab.addRow();
}
}, '-', {
text: '移除记录',
iconCls: 'icon-remove',
handler: function () {
gridTab.removeRow();
}
}, '-', {
text: '保存记录',
iconCls: 'icon-save',
handler: function () {
gridTab.saveRow();
}
}
];
gridTab.buildGrid(toolbar, columns);
gridTab.registerListeners();
});
<file_sep>/www/scripts/tab/custom/clienttab.js
$(function () {
var $dataGrid = $('#client_add_tab_table');
var toolbar = [{
text: '添加列',
iconCls: 'icon-add',
handler: function () {
append();
}
}, '-', {
text: '移除列',
iconCls: 'icon-remove',
handler: function () {
removeit();
}
}, '-', {
text: '保存表',
iconCls: 'icon-save',
handler: function () {
save();
}
}, '-', {
text: '删除表',
iconCls: 'icon-cancel',
handler: function () {
deleteTab();
}
}];
$dataGrid.datagrid({
iconCls: 'icon-ok',
height: 280,
rownumbers: true,
nowrap: true,
striped: true,
fitColumns: true,
loadMsg: '数据装载中......',
allowSorts: true,
remoteSort: true,
multiSort: true,
singleSelect: true,
toolbar: toolbar,
columns: [[
{field: 'title', title: '名称', width: 200, align: 'left', editor: 'textbox'},
{
field: 'editor',
title: '文本/时间',
width: 200,
align: 'left',
editor: {
type: 'combobox',
options: {
data: [
{value: 'textbox', text: '文本'},
{value: 'datebox', text: '时间'}
],
panelHeight: 'auto',
prompt: '请选择'
}
}
}
]],
onClickRow: function (index, row) {
if (editIndex != index) {
if (endEditing()) {
$dataGrid.datagrid('selectRow', index).datagrid('beginEdit', index);
editIndex = index;
} else {
$dataGrid.datagrid('selectRow', editIndex);
}
}
},
onBeginEdit: function (index, row) {
$(".combo").click(function () {
$(this).prev().combobox("showPanel");
});
}
});
var editIndex = undefined;
function endEditing() {
if (editIndex == undefined) {
return true
}
if ($dataGrid.datagrid('validateRow', editIndex)) {
$dataGrid.datagrid('endEdit', editIndex);
editIndex = undefined;
return true;
} else {
return false;
}
}
function append() {
if (endEditing()) {
$dataGrid.datagrid('appendRow', {});
editIndex = $dataGrid.datagrid('getRows').length - 1;
$dataGrid.datagrid('selectRow', editIndex)
.datagrid('beginEdit', editIndex);
}
}
function removeit() {
if (editIndex == undefined) {
return
}
$dataGrid.datagrid('cancelEdit', editIndex)
.datagrid('deleteRow', editIndex);
editIndex = undefined;
}
function save() {
if (endEditing()) {
var tab = {};
var gridTitle = $('#tab_title').val();
if (gridTitle == null || gridTitle == '') {
return;
}
var list = $dataGrid.datagrid('getRows');
for (var i = 0; i < list.length; i++) {
list[i].align = 'left';
list[i].width = 100;
list[i].field = 'file_' + i;
}
tab.gridTitle = gridTitle;
tab.columns = list;
$.post('/tab/', JSON.stringify(tab), function (data) {
if (data.success) {
$('#client_add_tab').dialog('close');
window.location.href = '/'; //成功以后刷新页面
$.messager.alert('提示信息', '添加tab成功!', 'info');
} else if (!data.success) {
$.messager.alert('提示信息', data.content, 'warning');
} else {
$.messager.alert('提示信息', "添加自定义tab失败", 'error');
}
})
}
}
function deleteTab() {
var tab = {};
var gridTitle = $('#tab_title').val();
if (gridTitle == null || gridTitle == '') {
return;
}
$.messager.confirm('删除提示', '该删除操作将会删除自定义tab及社员中包含该自定义tab数据,请谨慎删除!如确定删除,请点击“确定按钮”', function (r) {
if (r) {
$.ajax({
type: "DELETE",
url: '/tab/' + gridTitle,
dataType: 'json',
success: function (data) {
if (data.success) {
window.location.href = '/'; //成功以后刷新页面
$('#client_add_tab').dialog('close');
$.messager.alert('提示信息', '删除tab成功!', 'info');
} else {
$.messager.alert('提示信息', data.content, 'warning');
}
},
error: function () {
$('#client_add_tab').dialog('close');
$.messager.alert('提示信息', "刪除tab失败", 'error');
}
});
}
});
}
});<file_sep>/lib/tornado_utils.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Copyright <EMAIL>
'''
import tornado.web
from tornado.web import StaticFileHandler
registered_handlers = []
def register(pattern, handler):
registered_handlers.append((pattern, handler))
def bind_to(pattern):
def append(handler):
register(pattern, handler)
return append
static_file_dir = 'www'
default_filename = 'index.html'
def serve(port, **options):
from tornado.web import Application
application = Application(
registered_handlers + [
(
r'/(.*)',
StaticFileHandler,
{
'path': static_file_dir,
'default_filename': default_filename
}
)
],
**options
)
print(registered_handlers)
application.listen(port)
from tornado.ioloop import IOLoop
IOLoop.instance().start()
<file_sep>/www/scripts/tab/duties/formercluboffice.js
/**
* Created by S on 2017/2/22.
*/
// 社内职务
$(function () {
var $grid = $("#formerClubOffice-list");
var tabId = 'formercluboffice';
var gridTab = new GridTab(tabId, $grid);
var columns = [
{field: 'formeOrganizationCategory', title: '社内组织类别', width: 110, align: 'left', editor: 'textbox'},
{field: 'formeOrganizationName', title: '社内组织名称', width: 110, align: 'left', editor: 'textbox'},
{
field: 'formeOrganizationLevel',
title: '社内组织级别',
width: 120, align: 'left',
editor: {
type: 'combobox',
options: {
valueField: 'value',
textField: 'text',
method: 'get',
url: 'data/formeOrganizationLevel.json',
prompt: '请选择'
}
}
},
{field: 'formeOrganizationJob', title: '社内职务名称', width: 120, align: 'left', editor: 'textbox'},
{field: 'formeTheTime', title: '届次', width: 120, align: 'left', editor: 'textbox'},
{field: 'formeStartTime', title: '开始时间', width: 120, align: 'left', editor: 'datebox'},
{field: 'formeEndTime', title: '结束时间', width: 120, align: 'left', editor: 'datebox'}
];
var toolbar = [
{
text: '添加记录',
iconCls: 'icon-add',
handler: function () {
gridTab.addRow();
}
}, '-', {
text: '移除记录',
iconCls: 'icon-remove',
handler: function () {
gridTab.removeRow();
}
}, '-', {
text: '保存记录',
iconCls: 'icon-save',
handler: function () {
gridTab.saveRow();
}
}
];
gridTab.buildGrid(toolbar, columns);
gridTab.registerListeners();
});
<file_sep>/www/scripts/tab/specialty/professionalinfo.js
/**
* Created by S on 2017/2/22.
*/
//专业技术
$(function () {
var $grid = $("#professional-list");
var tabId = 'professionalSkill';
var gridTab = new GridTab(tabId, $grid);
var columns = [
{
field: 'proProjectName',
title: '项目名称',
width: 120,
align: 'left',
editor: {type: 'textbox', options: {}}
},
{
field: 'proProjectType',
title: '项目类型',
width: 90,
align: 'left',
editor: {
type: 'combobox',
options: {
valueField: 'value',
textField: 'text',
method: 'get',
url: 'data/projectType.json',
prompt: '请选择'
}
}
},
{
field: 'proProjectCompany',
title: '项目下达单位',
width: 120,
align: 'left',
editor: {type: 'textbox', options: {}}
},
{
field: 'proRolesInProject',
title: '项目中所任角色',
width: 60,
align: 'left',
editor: {
type: 'combobox',
options: {
valueField: 'value',
textField: 'text',
method: 'get',
url: 'data/roleInProject.json',
prompt: '请选择'
}
}
},
{
field: 'proStartDate',
title: '开始时间',
width: 60,
align: 'left',
editor: {type: 'datebox', options: {}}
},
{field: 'porEndDate', title: '结束时间', width: 60, align: 'left', editor: {type: 'datebox', options: {}}},
];
var toolbar = [
{
text: '添加记录',
iconCls: 'icon-add',
handler: function () {
gridTab.addRow();
}
}, '-', {
text: '移除记录',
iconCls: 'icon-remove',
handler: function () {
gridTab.removeRow();
}
}, '-', {
text: '保存记录',
iconCls: 'icon-save',
handler: function () {
gridTab.saveRow();
}
}
];
gridTab.buildGrid(toolbar, columns);
gridTab.registerListeners();
});<file_sep>/app/handlers/tab.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import tornado.web
import tornado_utils
from pypinyin import lazy_pinyin
from commons import couch_db, make_uuid
@tornado_utils.bind_to(r'/tab/?')
class TabCollectionHandler(tornado.web.RequestHandler):
@tornado.web.addslash
def get(self):
"""
通过find获取对象列表。
"""
obj = {
"selector": {
"type": {
"$eq": "tab"
}
}
}
response = couch_db.post(r'/jsmm/_find/', obj)
tab = json.loads(response.body.decode('utf-8'))
self.write(tab)
@tornado.web.addslash
def post(self):
"""
创建tab对象。
"""
print(self.request.files)
tab = json.loads(self.request.body.decode('utf-8'))
tab['type'] = 'tab'
tab['_id'] = make_uuid()
tab['tab_id'] = 'custab_' + ''.join(lazy_pinyin(tab['gridTitle']))
# 判断自定义tab名称是否已经存在
obj = {
"selector": {
"tab_id": {
"$eq": tab['tab_id']
}
}
}
response = couch_db.post(r'/jsmm/_find/', obj)
tabs = json.loads(response.body.decode('utf-8'))
if len(tabs["docs"]) > 0:
result = {"success": False, "content": u"该tab名称已经存在,请重新输入!"}
else:
couch_db.post(r'/jsmm/', tab)
result = {"success": True}
self.write(result)
@tornado_utils.bind_to(r'/tab/(.+)')
class TabDeleteHandler(tornado.web.RequestHandler):
def data_received(self, chunk):
pass
def delete(self, tab_name):
# 判断自定义tab名称是否已经存在
tab_id = 'custab_' + ''.join(lazy_pinyin(tab_name))
tab_selector = {
"selector": {
"tab_id": {
"$eq": tab_id
}
}
}
response = couch_db.post(r'/jsmm/_find/', tab_selector)
tabs = json.loads(response.body.decode('utf-8'))
tab_list = tabs["docs"]
# 判断是否存在名称为tab_name的tab
if len(tab_list) <= 0:
result = {"success": False, "content": u"该tab名称不存在,请重新输入!"}
else:
tab_target = tab_list[0]
# 刪除member中的tab信息
member_selector = {
"selector": {
"$and": [
{"type": {
"$eq": "member"
}
},
{tab_id: {
"$ne": "null"
}
}
]
}
}
member_response = couch_db.post(r'/jsmm/_find/', member_selector)
member_list = json.loads(member_response.body.decode('utf-8'))["docs"]
for member in member_list:
del member[tab_id]
couch_db.put(r'/jsmm/%(id)s' % {"id": member["_id"]}, member)
# 刪除tab
couch_db.delete(r'/jsmm/%(id)s?rev=%(rev)s' %
{'id': tab_target["_id"], 'rev': tab_target["_rev"]})
result = {"success": True}
self.write(result)
<file_sep>/www/scripts/tab/achievements/awardinfo.js
/**
* Created by S on 2017/2/22.
*/
// 工作获奖
$(function () {
var $grid = $("#award-list");
var tabId = 'award';
var gridTab = new GridTab(tabId, $grid);
var columns = [
{
field: 'awardProjectName',
title: '获奖项目名称',
width: 150,
align: 'left',
editor: {
type: 'textbox',
options: {}
}
},
{
field: 'awardDate',
title: '获奖时间',
width: 60,
align: 'left',
editor: {type: 'datebox', options: {}}
},
{
field: 'awardNameAndLevel',
title: '获奖级别',
width: 120,
align: 'left',
editor: {type: 'textbox', options: {}}
},
{
field: 'awardRoleInProject',
title: '项目中角色',
width: 50,
align: 'left',
editor: {type: 'textbox', options: {}}
},
{
field: 'awardCompany',
title: '授予单位',
width: 100,
align: 'left',
editor: {
type: 'textbox',
options: {}
}
},
{
field: 'awardMemo',
title: '备注',
width: 150,
align: 'left',
editor: {
type: 'textbox',
options: {}
}
}
];
var toolbar = [
{
text: '添加记录',
iconCls: 'icon-add',
handler: function () {
gridTab.addRow();
}
}, '-', {
text: '移除记录',
iconCls: 'icon-remove',
handler: function () {
gridTab.removeRow();
}
}, '-', {
text: '保存记录',
iconCls: 'icon-save',
handler: function () {
gridTab.saveRow();
}
}
];
gridTab.buildGrid(toolbar, columns);
gridTab.registerListeners();
});<file_sep>/commons.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Copyright <EMAIL>
'''
import os
import sys
import uuid
from datetime import datetime
from dateutil.relativedelta import *
os.chdir(os.path.dirname(__file__))
sys.path[:0] = ['app', 'lib']
from couchdb import CouchDB
couch_db = CouchDB('http://127.0.0.1:5984')
couchLucene_db = CouchDB('http://127.0.0.1:5986')
def make_uuid():
'''
生成随机的UUID,并返回16进制字符串
'''
return uuid.uuid4().hex
def get_now():
'''
返回当前日期时间的ISO 8601格式字符串,格式为:YYYY-MM-DDTHH:MM:SS.mmmmmm
'''
return datetime.now().isoformat()
def get_retire_time(birthday, gender):
start_date = datetime.strptime(birthday, "%Y-%m-%d")
if gender == '男':
return (start_date + relativedelta(years=+65)).strftime('%Y-%m-%d')
else:
return (start_date + relativedelta(years=+60)).strftime('%Y-%m-%d')
|
c2f59bda8934b19dfc1abdda69ee2b4c0aefd8c9
|
[
"JavaScript",
"Python"
] | 33 |
Python
|
hsia/jsmm
|
731a75b4060578013579247d16c281d00667f8e3
|
a31b55dba4291b8d402efe8a1f950c6384221913
|
refs/heads/master
|
<file_sep>#include "pch.h"
#include "Event.h"
using namespace std;
int Event::getStartYear() {
return startYear;
}
int Event::getEndYear() {
return endYear;
}
int Event::getLength() {
return length;
}
string Event::getName() {
return name;
}
string Event::getDescription() {
return description;
}
Event Event::n() {
return Event(1, 2, 3, "efs");
}
ostream & operator<<(std::ostream & os, Event & event)
{
if (event.getStartYear() < 0) {
if (event.Event::getStartYear() != event.Event::getEndYear()) {
os << event.Event::getName() << " from " << event.Event::getStartYear() * -1 << " BCE to " << event.Event::getEndYear() * -1 << " BCE";
}
else {
os << event.Event::getName() << " in " << event.Event::getStartYear() * -1 << " BCE";
}
}
return os;
}
<file_sep>#ifndef READER_H
#define READER_H
#include "pch.h"
#include "Event.h"
#include <fstream>
#include <string>
using namespace std;
Event readEvent(ifstream &is, string filename, int lineNum);
#endif
<file_sep>#include "pch.h"
#include "Timeline.h"
#include <iostream>
int Timeline::getLength() {
return length;
}
void Timeline::printTimeline() {
for (int i = 0; i < getLength(); i++) {
if (i != length - 1) {
if (events[i].getStartYear() && events[i + 1].getStartYear()) {
cout << "| " << events[i].getStartYear() << " " << events[i] << " and " << events[i + 1] << endl;
}
}
else {
cout << "| " << events[i].getStartYear() << " " << events[i] << endl;
}
if (i == length - 1) {
break;
}
int q = -1 * (events[i].getStartYear() - events[i + 1].getStartYear()) / 10;
for (int j = 0; j < q; j++) {
cout << "| " << endl;
}
}
}
void Timeline::timelineInit(int numEvents, string filename) {
ifstream in;
for (int i = 0; i < numEvents; i++) {
events.push_back(readEvent(in, filename, i));
length++;
}
}
<file_sep>#ifndef TIMELINE_H
#define TIMELINE_H
#include "pch.h"
#include "Event.h"
#include "Reader.h"
#include <istream>
#include <string>
#include <vector>
using namespace std;
const int MAX_LENGTH = 200;
class Timeline {
private:
int length;
public:
Timeline(vector<Event> e)
: length(0), events(e) {}
vector<Event> events;
int getLength();
void printTimeline();
void timelineInit(int numEvents, string filename);
};
#endif
<file_sep>#include "pch.h"
#include <fstream>
#include <iostream>
#include <string>
#include "Reader.h"
using namespace std;
Event readEvent(ifstream &is, string filename, int lineNum) {
string line;
int ticker = 0;
string startYearIn;
string endYearIn;
int lengthIn = 0;
string nameIn;
string descriptionIn;
is.open(filename);
if (!is.is_open()) {
cout << "failed to open file";
}
for (int i = 0; i < lineNum + 1; i++) {
getline(is, line);
}
int lineLength = line.length();
char input = line[ticker];
while (1){
input = line[ticker];
if (input != '\t') {
startYearIn += int(input);
ticker++;
}
else {
ticker++;
break;
}
}
while (1) {
input = line[ticker];
if (input != '\t') {
endYearIn += input;
ticker++;
}
else {
ticker++;
break;
}
}
while (1) {
input = line[ticker];
if (input != '\t') {
nameIn += input;
ticker++;
}
else {
ticker++;
break;
}
}
while (ticker < lineLength){
input = line[ticker];
if (input != '\t') {
descriptionIn += input;
ticker++;
}
else {
ticker++;
break;
}
}
is.close();
lengthIn = stoi(endYearIn) - stoi(startYearIn);
if (descriptionIn.length() > 1) {
Event newEvent(stoi(startYearIn), stoi(endYearIn), lengthIn, nameIn, descriptionIn);
return newEvent;
}
else {
Event newEvent(stoi(startYearIn), stoi(endYearIn), lengthIn, nameIn);
return newEvent;
}
}<file_sep>#ifndef EVENT_H
#define EVENT_H
//#include "pch.h"
#include <string>
using namespace std;
class Event {
private:
int startYear;
int endYear;
int length;
string name;
string description;
public:
Event(int startYearIn, int endYearIn, int lengthIn, string nameIn)
: startYear(startYearIn), endYear(endYearIn), length(lengthIn), name(nameIn) {}
Event(int startYearIn, int endYearIn, int lengthIn, string nameIn, string descriptionIn)
: Event(startYearIn, endYearIn, lengthIn, nameIn) {
description = descriptionIn;
}
int getStartYear();
int getEndYear();
int getLength();
string getName();
string getDescription();
Event n();
};
ostream & operator<<(std::ostream & os, Event & event);
#endif
|
7948247b8dd4a3297431eef1680a5e096d27743b
|
[
"C++"
] | 6 |
C++
|
jakobadel/timeline
|
33e84d4fac949abcb3117155a98dedcb5a1fd5c0
|
d1120318a740f84e4fc00551a767b9691a53ef3c
|
refs/heads/master
|
<repo_name>bcalloway/spree-calculators<file_sep>/models/calculator/per_quantity.rb
class Calculator::PerQuantity < Calculator
preference :amount, :decimal, :default => 0
def self.description
"Flat Rate Per Quantity"
end
def self.register
super
ShippingMethod.register_calculator(self)
ShippingRate.register_calculator(self)
end
def compute(line_items)
#return if order.line_items.nil?
number = 0
line_items.each do |q|
number += q.quantity
end
number * self.preferred_amount
end
end
<file_sep>/spree_calculators_extension.rb
class SpreeCalculatorsExtension < Spree::Extension
version "1.0"
description "Provides a few extra calculators for shipping, etc."
url "http://github.com/bcalloway/spree-calculators"
include Spree::BaseHelper
def activate
[ Calculator::PerQuantity, Calculator::FlexratePerQuantity ].each(&:register)
end
end<file_sep>/models/calculator/flexrate_per_quantity.rb
class Calculator::FlexratePerQuantity < Calculator
preference :first_item, :decimal, :default => 0
preference :additional_item, :decimal, :default => 0
preference :max_items, :decimal, :default => 0
def self.description
"Flexible Rate Per Quantity"
end
def self.available?(object)
true
end
def self.register
super
Coupon.register_calculator(self)
ShippingMethod.register_calculator(self)
ShippingRate.register_calculator(self)
end
def compute(line_items)
sum = 0
max = self.preferred_max_items
number_of_items = line_items.map(&:quantity).sum
normal_price_items = max > 0 ? (number_of_items / max) + 1 : 0
discounted_price_items = number_of_items - normal_price_items
return(
self.preferred_first_item * normal_price_items +
self.preferred_additional_item * discounted_price_items
)
end
end
|
979bf35eba07250be24557382de6dba2e5766ece
|
[
"Ruby"
] | 3 |
Ruby
|
bcalloway/spree-calculators
|
f795ae0f37a48ccc33f56490b38b3d348737f98c
|
ccfb46fa8f31c6b180777ba77dd2c720206964e6
|
refs/heads/main
|
<repo_name>space-isa/page-views<file_sep>/src/tests/test_retrieve_csv.py
import unittest
# Enable unittest to find source code
import sys
sys.path.insert(0, '../../src/')
# Import module to test
from retrieve_csv import retrive_csv_file
class TestRetrieveFunction(unittest.TestCase):
"""
Assumes there exists a csv input file that can be located without
explicit user input.
METHODS
-------
test_findCSV : Given filename, return csv file.
test_noInputSpecified : Return csv file without user-specified filename.
test_wrongFile : Given incorrect filename, return SystemExit code 1,
as file does not exist.
"""
def test_findCSV(self,
filename="page-views.csv",
input_folder='../../input/raw-data/'):
"""Ensure correct filepath given filename."""
csv_file = retrive_csv_file(filename, input_folder)
expected_output = input_folder + filename
self.assertEqual(csv_file, expected_output)
def test_noInputSpecified(self,
filename=None,
input_folder='../../input/raw-data/'):
"""Test if file can be found without explicit filename input."""
csv_file = retrive_csv_file(filename, input_folder)
expected_output = "../../input/raw-data/page-views.csv"
self.assertEqual(csv_file, expected_output)
def test_wrongFile(self,
filename='pages.csv',
input_folder='../../input/raw-data/'):
"""Ensure code stops when file doesn't exist."""
with self.assertRaises(SystemExit) as check_assert:
retrive_csv_file(filename=filename,
input_folder=input_folder)
self.assertEqual(check_assert.exception.code, 1)
def runTests():
test_classes = [TestRetrieveFunction]
load_tests = unittest.TestLoader()
test_list = []
for test in test_classes:
load_test_cases = load_tests.loadTestsFromTestCase(test)
test_list.append(load_test_cases)
test_suite = unittest.TestSuite(test_list)
run_test = unittest.TextTestRunner()
run_test.run(test_suite)
if __name__ == "__main__":
runTests()<file_sep>/src/page_views_insights.py
#!/usr/bin/python3
# Tested with Python 3.8.6
#------------------------------------------------------------------------------
# page_views_insights.py
#------------------------------------------------------------------------------
# Author: <NAME>
# GitHub Take-Home Exam: Page Views
# Due: 2021.05.12
#------------------------------------------------------------------------------
"""
Accept an input csv file containing aggregated GitHub user page view data
and reports:
1) The top 5 most frequently issued queries (include counts).
2) The top 5 queries in terms of total number of results clicked (include counts).
3) The average length of a search session.
INPUTS
------
Input file:
"aggregated-page-views.csv"
Each row contains:
Query search word
Total number of queries
Total time spent in a search session (seconds)
Total number of clients
Number of results clicked
Average number of search clicks per client
Average time spent on search query per click
RETURNS
-------
None
"""
# Standard Python library imports
from typing import List, Dict, Tuple, Any
from collections import OrderedDict
from operator import getitem
import csv
def pull_aggregated_data(filepath:
str) -> Tuple[List[str], List[str], List[str]]:
agg_data = []
total_times = []
results_clicked = []
with open(filepath, mode='r') as datafile:
for row in csv.reader(datafile):
agg_data.append(row[:5])
total_times.append(float(row[2]))
results_clicked.append(float(row[4]))
return agg_data, total_times, results_clicked
def create_dictionary(dataset:
List[List[str]])-> Dict[str, Dict[str, int]]:
agg_dict = {row[0]: {} for row in dataset}
for row in dataset:
agg_dict[row[0]]["num queries"] = int(row[1])
agg_dict[row[0]]["num results clicked"] = int(row[4])
return agg_dict
def calculate_average_time(total_times: List[float],
num_clicks: List[float]):
sum_time = sum(total_times)
sum_clicks = sum(num_clicks)
average_time_per_query = sum_time / sum_clicks
return average_time_per_query
def find_top_results(dictionary: Dict[str, Dict[str, Any]],
num_results: int,
result_key: str,
reverse: bool = True) -> List[Tuple[str, int]]:
"""Create an ordered dictionary sorted by a user-defined key
and return the top N results in descending order."""
most_freq_queries = []
result = OrderedDict(sorted(dictionary.items(),
key = lambda x: getitem(x[1], result_key),
reverse=reverse))
top_queries = list(result.keys())[:num_results]
for query in top_queries:
result_val = result[query][result_key]
most_freq_queries.append((query, result_val))
return most_freq_queries
def main(filepath):
"""Run the pipeline and report insights"""
agg_data, total_times, results_clicked = pull_aggregated_data(filepath)
agg_dict = create_dictionary(agg_data)
print("Reporting insights...\n")
# Q1: Report top 5 most frequent queries
most_freq_queries = find_top_results(agg_dict, N, "num results clicked")
print("""The top {} most issued queries are: {} \n""".format(N, most_freq_queries))
# Q2: Report top 5 queries in terms of total number of results clicked
top_queries = find_top_results(agg_dict, N, "num queries")
print("""The top {} queries in terms of total number of search results clicked: {} \n""".format(N,
top_queries))
# Q3: Report average time
average_time_per_query = calculate_average_time(total_times, results_clicked)
print("""The average length of a search session is {:.2f} seconds \n""".format(
average_time_per_query))
if __name__ == "__main__":
# Number of results to return
N = 5
folder = '../output/processed-data/'
filename = 'aggregated-page-views.csv'
filepath = folder + filename
main(filepath)<file_sep>/run.sh
#!/bin/bash
# Make code executable and run.
cd ./src/
chmod +x aggregate_page_views.py, page_views_insights.py
python3.8 aggregate_page_views.py page-views.csv
python3.8 page_views_insights.py<file_sep>/src/aggregate_page_views.py
#!/usr/bin/python3
# Tested with Python 3.8.6
#------------------------------------------------------------------------------
# aggregate_page_views.py
#------------------------------------------------------------------------------
# Author: <NAME>
# GitHub Take-Home Exam: Page Views
# Due: 2021.05.12
#------------------------------------------------------------------------------
"""
Accept an input csv file containing GitHub user page view data, and aggregates
in order to be able to answer the following questions:
1) The top 5 most frequently issued queries (include counts).
2) The top 5 queries in terms of total number of results clicked (include counts).
3) The average length of a search session.
Write out the aggregated page view data into a csv file.
INPUTS
------
Input file:
"page-views.csv"
Each row contains:
timestamp: The UNIX timestamp at time of page view [seconds]
path: The path of the page visited
referrer: The path that referred the user to the current page
This is empty for the search page
cid: A client id that is unique to each user
OUTPUTS
-------
Output file:
"aggregated-page-views.csv"
Contains:
Query search word
Total number of queries
Total time spent in a search session (seconds)
Total number of clients
Number of results clicked
Average number of search clicks per client
Average time spent on search query per click
"""
# Standard Python library imports
import csv
import sys
import time
from typing import List, Dict, Tuple, Any
import string
from collections import Counter
# Companion scripts
from exception_handler import exception_handler
from write_to_csv import write_to_csv
from retrieve_csv import retrive_csv_file
def validate_data(csv_file: str,
header: bool = False,
output_filename: str = None,
output_folder: str = None) -> List[List[str]]:
"""
Pull data from csv and store as a list of lists. If any of the following
columns are missing data: timestamp, search path, or client id, then that
row will not be included in the final list.
"""
page_views_lst = []
# Initialize counter
rows_read = 0
with open(csv_file, mode="r", encoding="utf-8") as data:
read_data = csv.reader(data)
for row in read_data:
rows_read += 1
# Skip rows with missing data
if row[0] != "" and row[1] != "" and row[3] != "":
page_views_lst.append(row)
accepted = len(page_views_lst)
rejected = rows_read - len(page_views_lst)
print("""
Out of {:,} lines read, {:,} lines were accepted and {:,} lines were rejected.
""".format(rows_read, accepted, rejected))
# If no data can be pulled, write out a failed report file
if len(page_views_lst) == 0:
datestamp = time.strftime("%Y%m%d")
failed_report_folder = output_folder + "failed/"
output_filename = "failed_no_valid_data_{}.csv".format(datestamp)
write_to_csv(output_filename=output_filename,
output_folder=failed_report_folder,
output=page_views_lst)
print("No valid data to pull. Failed report generated.")
if header:
return page_views_lst[1:]
return page_views_lst
def clean_query(path: str) -> str:
"""Take a path and extract and clean query keyword."""
punctuation = string.punctuation
# Remove punctuation and return lowercase term
if "search" in path:
term = path.split('=')[1]
term = term.lower()
term = term.translate(str.maketrans("", "", punctuation))
return term
else:
print("The path should contain a search key.")
def find_unique_attributes(dataset: List[List[str]],
column: int,
path: bool = True) -> Tuple[List[str], List[str]]:
all_items = []
# If path, extract search term before compiling
if path:
for i in range(len(dataset)):
path = dataset[i][column]
if "search" in path:
term = clean_query(path)
all_items.append(term)
unique_items = list(set(all_items))
unique_items.sort()
else:
for row in dataset:
all_items.append(row[column])
unique_items = list(set(all_items))
return all_items, unique_items
def create_dictionary(dataset: List[List[str]],
unique_terms: List[str]) -> Dict[str, Dict[str, Any]]:
"""Compile search data using query keyword and group by user client id."""
query_table = {query: {} for query in unique_terms}
for i in range(len(dataset)):
# Path is an initial search
if dataset[i][2] == "":
keyword = clean_query(dataset[i][1])
start_time = int(dataset[i][0])
cid = dataset[i][3]
clicks = 0
nested_dict = query_table[keyword]
nested_dict[cid] = {}
nested_dict[cid]["start time"] = start_time
nested_dict[cid]["num search clicks"] = clicks
nested_dict[cid]["end times"] = []
# Path referred by intial search
elif dataset[i][2] != "":
check_next = clean_query(dataset[i][2])
if keyword == check_next:
nested_dict[cid]["num search clicks"] += 1
end_time = int(dataset[i][0])
nested_dict[cid]["end times"].append(end_time)
else:
nested_dict[cid]["num search clicks"] += 1
end_time = int(dataset[i][0])
nested_dict[cid]["end times"].append(end_time)
# Calculate time spent in a search session
for term in unique_terms:
for key, val in query_table[term].items():
total_time = max(val["end times"]) - val["start time"]
val["total time"] = total_time
return query_table
def aggregated_dictionary(compiled_dict: Dict[str, Dict[str, Any]],
freq_table: Dict[str, int],
unique_terms: List[str]) -> Dict[str, Dict[str, Any]]:
"""Aggregate search query data and place into new dictionary."""
summary_table = {query: { "results clicked": 0,
"num users": 0,
"total time": 0}
for query in unique_terms}
total_time_all = 0
total_clicks_all = 0
for term in unique_terms:
for key, val in compiled_dict[term].items():
if val and 'num search clicks' in val.keys():
num_clicks_sum = 0
total_time = 0
summary_table[term]["num queries"] = freq_table[term]
num_clicks_sum += val["num search clicks"]
num_users = len(compiled_dict[term])
total_time += val["total time"]
total_time_all += total_time
total_clicks_all += num_clicks_sum
summary_table[term][
"results clicked"] += num_clicks_sum
summary_table[term]["num users"] = num_users
summary_table[term][
"total time"] += total_time
summary_table[term][
"av clicks per user"] = num_clicks_sum / num_users
summary_table[term][
"av time per click"] = total_time / num_clicks_sum
return summary_table
def write_data_to_csv(compiled_dict: Dict[str, Dict[str, Any]],
output_folder: str):
"""Pull data from aggregated dict and store in a csv."""
output = []
# Order and sort data into output container
for key, val in compiled_dict.items():
output.append([key,
val["num queries"],
val["total time"],
val["num users"],
val["results clicked"],
val["av clicks per user"],
val["av time per click"]])
output.sort(key=lambda header: header[0])
processed_folder = output_folder + 'processed-data/'
output_filename = 'aggregated-page-views.csv'
write_to_csv(output_filename=output_filename,
output_folder=processed_folder,
output=output)
@exception_handler
def main(input_filename: str = None):
"""
Contains a pipeline that accepts an input csv file and processes the aggregate
data. Outputs processed data into a csv file and prints results of basic data
insight queries.
ARGUMENTS
---------
input_filename : str
e.g., "page-views.csv"
RETURNS
-------
None
"""
csv_file = retrive_csv_file(filename=input_filename,
input_folder=input_folder)
page_views_data = validate_data(csv_file,
header=False,
output_filename=None,
output_folder=None)
terms, unique_terms = find_unique_attributes(page_views_data, 1)
print("There are {} unique search keywords out of {}.".format(len(unique_terms), len(terms)))
count_queries = Counter(terms)
cids, unique_cids = find_unique_attributes(page_views_data, 3, path=False)
print("There are {} unique client ids out of {}.".format(len(unique_cids), len(cids)))
query_table = create_dictionary(page_views_data, unique_terms)
summary_table = aggregated_dictionary(query_table, count_queries, unique_terms)
write_data_to_csv(summary_table, output_folder)
if __name__ == "__main__":
input_folder = "../input/raw-data/"
output_folder = "../output/"
main(input_filename=sys.argv[1])
<file_sep>/README.md
# page-views
Take in, clean, and process a log repository search requests on GitHub.com.
---
## Table of Contents
1. [Solution Approach](#solution-approach)
2. [Requirements](#requirements)
3. [How to use?](#how-to-use)
4. [Tests](#tests)
---
### Project requirements
- Input file
- Pull data from `page-views.csv` input file. Data includes:
- Timestamp: The UNIX timestamp of the page view (in seconds).
- path: The path of the visited page.
- referrer: The path that referred the user to the current page. This is empty for the search page.
- cid: A client id which uniquely identifies a user.
- Questions code should answer:
1) What are the top 5 most frequently issued queries (include query counts)?
2) What are the top 5 queries in terms of total number of results clicked (include click counts)?
3) What is the average length of a search session?
The answers to these questions are displayed to the user when the code is run.
- Example output:
```The top 5 most issued queries are: [('crop', 21), ('entosphere', 19), ('gaudete', 17), ('kerchunk', 16), ('hemosalpinx', 16)]```
A complete set of answers Q1-Q4 can be found in ```IJRodriguez-take-home-exam.pdf```.
- Additionally, the code generates a csv file containing aggregated data.
- Aggregated data is saved in `/output/processed-data/` in the following order:
- Query search term
- Total number of queries
- Total time spent in a search session (in seconds)
- Total number of clients**
- Number of results clicked
- Average clicks per user
- Average time spent per click
(** in this example, each client searches a particular query exactly once)
- Sample output:
```
contrabandage,16,699,16,44,0.125,22.0
cowled,10,393,10,23,0.4,10.0
crood,10,389,10,22,0.2,25.5
...
...
```
- An empty failed report file is generated if there are no valid data found in input file.
---
## Solution Approach
```aggregate_page_views.py```
- Define relative paths for input and output files.
- Search `input` folder for `page-views.csv`.
- If incorrect filename provided, inform the user and exit the program.
- Read csv file:
- If csv is empty, or if there are no valid data, write out an empty report file to ```/output/failed/```.
- Else, pull columns of interest, skipping rows with critical data missing.
- Report the number of lines accepted and rejected.
- Clean and compile a unique set and a total list of query search words.
- Compile a unique set and total list of client ids.
- Build a nested dictionary, using uniqe terms and cids as keys.
- Fill the nested dictionary with data from all paths in dataset.
- Aggregate search data and create a new nested dictionary with unique terms as keys.
- Write out aggregated search data into a csv ```aggregated-page-views.csv```.
```page_views_insights.py```
- Define paths to input file.
- Pull data from ```aggregated-page-views.csv```
- Create a frequency table containing click counts and results counts per query.
- Sort frequency table to find most frequent query and report top 5 (Q1).
- Sort frequency table to find query with most results clicks and report top 5 (Q2).
- Calculate average search time and report (Q3).
---
## Requirements
This code was developed and tested using Python 3.8.6.
No additional installations are required, as this project uses only standard Python libraries.
---
## How to use?
This repository contains a shell script `run.sh` containing the following commands:
```shell
cd ./src/
chmod +x aggregate_page_views.py, page_views_insights.py
python3.8 aggregate_page_views.py page-views.csv
python3.8 page_views_insights.py
```
In your terminal, change to the `page-views` directory and run the shell script:
```shell
$ bash run.sh
```
---
## Tests
### Unit testing
Tests were conducted using Python's `unittest` module. In the interest of time, the unit tests provided are not exhaustive.
To run tests:
1. In your terminal, change directories from `page-views` to the test suite:
```shell
$ cd src/tests/
```
2. If, for example, you wanted to run the test script `test_retrieve_csv.py` run:
```shell
$ python3.8 test_retrieve_csv
```
3. A an example output of a successful run for this script:
```bash
-------------------------------------------------
Ran 3 tests in 0.002s
OK
```
---
## Author
<NAME>
<file_sep>/src/retrieve_csv.py
import os
import glob
import sys
def retrive_csv_file(filename=None, input_folder=None):
"""
Searches for and retrieves csv file. If no name provided, returns
the most recent file found.
ARGUMENTS
---------
filename : str
e.g., 'page-views.csv'
input folder : str
RETURNS
-------
csv_file : str
Full path to file, i.e., '.../input/raw-data/page-views.csv'
"""
if filename is not None:
# Both filename and folder were specified
if input_folder is not None:
# Generate path to file.
csv_file = input_folder + filename
else:
csv_file = filename
# No file name provided
else:
if input_folder is not None:
files = glob.glob(input_folder + "/*.csv")
csv_file = max(files)
print(csv_file)
# Neither a filename nor a folder was provided
else:
files = glob.glob("./*.csv")
print(files)
csv_file = max(files)
# Check if this is a valid file
if os.path.isfile(csv_file):
return csv_file
else:
print("This file does not exist.")
sys.exit(1)
<file_sep>/src/tests/test_aggregate_page_views.py
import unittest
# Enable unittest to find source code
import os
import sys
sys.path.insert(0, '../../src/')
# Import module to test
from aggregate_page_views import *
class TestExtractionData(unittest.TestCase):
"""
Edge cases aggregating page view data from csv file.
METHODS
-------
test_emptyCSV : Given empty file, no data should be pulled and a failed report
is generated.
"""
def test_emptyCSV(self,
csv_file="./empty_csv.csv",
output_filename=None,
output_folder="../../output/"):
"""Ensure an empty failed report is generated."""
validate_data(csv_file,
output_filename,
output_folder=output_folder)
filepath = '../../output/failed/'
dir = os.listdir(filepath)
self.assertGreater(len(dir), 0)
class TestCleanData(unittest.TestCase):
"""
METHODS
-------
test_clean_query : Ensure no duplicate search queries with different spellings
returns the same search term.
test_find_unique_attributes : Ensure set of unique terms does not contain duplicates.
"""
def test_clean_query(self):
"""Ensure the same queries containig different letter cases and punctuations
returns the same word (without punctuation and in lowercase)."""
path_lower = '/search?q=geophysics'
path_mixed = '/search?q=GeoPhysics!'
path_punc = '/search?q=geophysics?!'
result_lower = clean_query(path_lower)
result_mixed = clean_query(path_mixed)
result_punc = clean_query(path_punc)
expected_output = 'geophysics'
self.assertEqual(result_lower, expected_output)
self.assertEqual(result_mixed, expected_output)
self.assertEqual(result_punc, expected_output)
def test_find_unique_attributes(self):
"""Ensure there are no repeat search terms."""
data_list = [[1496253932,'/search?q=geophysics', "" ,1689],
[1496253946,'/repository/1207','/search?q=geophysics,1689'],
[1496253979,'/repository/8057','/search?q=geophysics,1689'],
[1496229649,'/search?q=millstream', "" ,7040]]
expected_output = ['geophysics', 'millstream']
all_items, unique_items = find_unique_attributes(data_list, 1, path=True)
self.assertEqual(unique_items, expected_output)
class TestDictionary(unittest.TestCase):
"""
METHODS
-------
test_dictStructure : Ensure correct storage structure.
"""
def test_dictStructure(self):
"""Validate construction of basic dictionary structure."""
unique_terms = ['millyrock']
start = 1496253932
end = 1496253946
time = end - start
dataset = [[1496253932,'/search?q=millyrock', "" ,'1738'],
[1496253946,'/repository/1207','/search?q=millyrock','1738']]
expected_output = {'millyrock': {'1738': {"start time" : 1496253932,
"num search clicks" : 1,
"end times" : [1496253946],
"total time" : time} }}
my_dict = create_dictionary(dataset, unique_terms)
self.assertEqual(my_dict, expected_output)
class TestAggregatedData(unittest.TestCase):
"""
METHODS
-------
test_aggregatedDict : Calculate the correct averages and
totals from query data.
"""
def test_aggregatedDict(self):
"""Validate method for determining query averages and totals."""
unique_terms = ['millyrock']
start = 1496253932
end = 1496253946
time = end - start
stored_data = {'millyrock': {'1738': {"start time" : 1496253932,
"num search clicks" : 1,
"end times" : 1496253946,
"total time" : time}}}
expected_output = {'millyrock': { "results clicked": 1,
"num users": 1,
"total time": time,
"av clicks per user": 1,
"av time per click": time}}
summary_table, total_time_all, total_clicks = aggregated_dictionary(stored_data, unique_terms)
self.assertEqual(total_clicks, 1)
self.assertEqual(total_time_all, time)
self.assertEqual(summary_table, expected_output)
def runTests():
"""Run test from all above classes."""
test_classes = [TestExtractionData, TestCleanData,
TestDictionary, TestAggregatedData]
load_tests = unittest.TestLoader()
test_list = []
for test in test_classes:
load_test_cases = load_tests.loadTestsFromTestCase(test)
test_list.append(load_test_cases)
test_suite = unittest.TestSuite(test_list)
run_test = unittest.TextTestRunner()
run_test.run(test_suite)
if __name__ == '__main__':
runTests()
|
ffd6ceab001746f127a95ddf167ad81d9e71af96
|
[
"Markdown",
"Python",
"Shell"
] | 7 |
Python
|
space-isa/page-views
|
0084329e0400db547c9d5e9158e2d185cd33a51f
|
47d7760eacbb144710c560cf7ec78a5d4f389a42
|
refs/heads/master
|
<repo_name>suhas5979/Portfolio-GraphQL-Web-App<file_sep>/client/src/components/Dataset.js
export const Dataset = {
projects: [
{
title:"Web Classifier",
image:'Machine-Learning.jpg',
description:"A web appication thats classifies color using Tensorflow Model that Traines on User data in real Time",
tech:["tensorflow","React" ,"mongoDb","express"]
},
{
title:"Web Recommendation system",
image:'KNN.jpg',
description:"A movie recommendation web application thats uses K Nearest Neibhers (KNN) ",
tech:["React" ,"mongoDb","express"]
},
{
title:"SCube Cetral Hub",
image:'graphql.jpg',
description:"A Web app which stores project using GraphQL",
tech:["React","GraphQL" ,"mongoDb","express"]
},
{
title:"Restaurent Web app",
image:'rest-api.jpg',
description:"A restaurent web app that uses outside api for fetching data and loads data on beautiful UI",
tech:["React" ,"mealDb api"]
},
]
}<file_sep>/client/src/components/CommentList.js
import React from 'react';
import { useQuery } from 'react-apollo';
import { query } from './queries';
import { Comment } from '../components'
const CommentList = ({ user }) => {
const { loading, error, data } = useQuery(query);
if (loading) {
return <ul className="comment-list"><h3 style={{textAlign:'center'}}>Loading....</h3></ul>
}
if (error) {
return <ul className="comment-list"> <li>Something Went Wrong</li></ul>
}
if (data != null && data != 'undefined') {
const { allComments} = data;
return (
<ul className="comment-list">
{allComments != null && allComments != 'undefined' && allComments.map((comment) =>
<Comment user={user} key={comment.id} comment={comment} />
)}
</ul>
)
}
}
export default CommentList;<file_sep>/routes/authRoutes.js
const passport = require('passport');
module.exports = function (app) {
app.get('/api/auth/google', passport.authenticate('google', {
scope: ['email', 'profile']
}));
app.get('/api/auth/google/callback', passport.authenticate('google'),(req,res)=>{
res.redirect('http://localhost:3000/');
});
// app.get('/api/auth/facebook',
// passport.authenticate('facebook',{
// scope: ['email']
// }));
// app.get('/api/auth/facebook/callback',
// passport.authenticate('facebook', { failureRedirect: '/login' }),
// function (req, res) {
// // Successful authentication, redirect home.
// console.log("redirected by facebook")
// });
}<file_sep>/client/src/components/Landing.js
import React, { Component } from 'react';
import { graphql } from 'react-apollo';
import axios from 'axios';
import { Project, CommentBox, Bottom, Header, Dataset ,Service } from '../components'
import { fetchUser as query } from './queries';
const Landing = ({ data: { user } }) => {
const { projects } = Dataset;
return (
<div className="landing-wrapper">
<Header user={user === 'undefined' ? null : user} />
<h2 className="prj-title">Projects</h2>
<div className="projects-wrapper">
{projects.map((project) =>
<Project data={project} />)}
</div>
<CommentBox user={user === 'undefined' ? null : user} />
<div className="services-wrapper">
<Service />
<Service />
<Service />
</div>
<Bottom />
</div>
);
}
export default graphql(query)(Landing);
<file_sep>/services/passport.js
const passport = require('passport');
const keys = require('../config/keys');
const googleStrategy = require('passport-google-oauth20').Strategy;
// const facebookStrategy = require('passport-facebook').Strategy
const mongoose = require('mongoose');
const User = mongoose.model('user');
passport.serializeUser((user, done) => {
return done(null, user.id)
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, res) => {
if (err) {
return done(err);
}
return done(null, res);
})
});
// google strategy
passport.use(new googleStrategy({
clientID: keys.googleAuth.CLIENT_ID,
clientSecret: keys.googleAuth.CLIENT_SECRET,
callbackURL: keys.googleAuth.CALL_BACK_URL
}, async (accessToken, refreshToken, profile, done) => {
const existingUser = await User.findOne({ googleId: profile.id });
if (existingUser) {
return done(null, existingUser);
}
const user = new User({
name: profile.displayName,
email: profile.emails[0].value,
googleId: profile.id,
profileUrl: profile.photos[0].value
});
await user.save();
console.log(user);
return done(null, user);
}));
// facebook statregy
// passport.use(new facebookStrategy({
// clientID: keys.facebookAuth.CLIENT_ID,
// clientSecret: keys.facebookAuth.CLIENT_SECRET,
// callbackURL: keys.facebookAuth.CALL_BACK_URL,
// profileFields: ['id', 'displayName', 'photos', 'email', 'gender', 'name','profileUrl']
// },
// function(accessToken, refreshToken, profile, cb) {
// console.log(profile);
// //console.log(profile._json.picture.data.url)
// }
// ));
<file_sep>/client/src/components/Comment.js
import React from 'react';
import { useMutation } from 'react-apollo';
import { query, likeComment as mutation } from './queries';
import { UserIcon, HeartIcon, TimeIcon } from '../assets/icons';
const Comment = (props) => {
const [likeComment, { data }] = useMutation(mutation);
const { comment, user } = props;
function calculateTimeDiff(time) {
if (time.getFullYear() === (new Date()).getFullYear()) {
if (time.getMonth() === (new Date()).getMonth()) {
if (time.getDate() === (new Date()).getDate()) {
if (time.getHours() === (new Date()).getHours()) {
return `${(new Date()).getMinutes() - time.getMinutes()}min`;
}
return `${(new Date()).getHours() - time.getHours()}h`;
}
return `${(new Date()).getDate() - time.getDate()}d`;
}
return `${(new Date()).getMonth() - time.getMonth()}m`;
}
return `${(new Date()).getFullYear() - time.getFullYear()}y`;
}
function renderUrl(url) {
if (!url) return <div className="avtar"><UserIcon /></div>;
return <img alt="" className="user-picture" src={url} />
}
console.log(props)
return (
<li >
{renderUrl(comment.user.profileUrl)}
<div className="comment-content">
<div className="cmt-up">
<span className="comment-user">{comment.user.name}</span>
<span className="comment-time" ><TimeIcon /> {calculateTimeDiff(new Date(comment.date))}</span>
</div>
<span className="comment-text">{comment.text}</span>
<div className="cmt-info"><HeartIcon onClick={() => {
likeComment({
variables: { user: user.id, id: comment.id, payload: comment.likes + 1 },
refetchQueries: [{ query }]
});
}} /><span>{`${comment.likes} likes`}</span></div>
</div>
</li>
);
};
export default Comment;<file_sep>/client/src/components/Service.js
import React from 'react';
const Service = () => {
return (
<div className="srvs-wrpr">
<h2 className="srvs-title" >Backend Developement</h2>
<span className="srvs-disc">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</span>
</div>
);
};
export default Service;<file_sep>/client/src/assets/icons/index.js
import { ReactComponent as FacebookIcon } from './facebook.svg';
import { ReactComponent as InstagramIcon } from './instagram.svg';
import { ReactComponent as GithubIcon } from './github.svg';
import { ReactComponent as LinkedinIcon } from './linkedin.svg';
import { ReactComponent as TwitterIcon } from './twitter.svg';
import { ReactComponent as TimeIcon } from './clock.svg';
import { ReactComponent as UserIcon } from './user.svg';
import { ReactComponent as HeartIcon } from './heart.svg';
import { ReactComponent as TensorFlowIcon } from './tensorflow.svg';
export {
FacebookIcon,InstagramIcon,TwitterIcon,GithubIcon,LinkedinIcon,TimeIcon,UserIcon,HeartIcon,TensorFlowIcon
}<file_sep>/client/src/components/Project.js
import React from 'react';
const Project = ({data}) => {
const { image, title, description,tech } = data;
return (
<div className="project-wrpr">
<img alt="" src={require(`../assets/${image}`)} />
<h2>{title}</h2>
<span >{description}</span>
<ul>{tech.map((e)=>
<li key={e}>{e}</li>)}</ul>
<a className="prj-btn" href="/" >CheckOut</a>
</div>
)
}
export default Project;
<file_sep>/client/src/components/Header.js
import React from 'react';
import gql from 'graphql-tag';
import { useMutation } from 'react-apollo';
import { logoutUser as mutation, refetchUser as query } from './queries'
const Header = ({ user }) => {
const [logOut, { data }] = useMutation(mutation);
function renderUser() {
if (!user) {
return <a className="nav-btn" href="/api/auth/google" >Sign In</a>
}
return <div className="nav-user">
<img alt="" className="header-user-pic" src={user.profileUrl} />
<button className="nav-btn" onClick={logout} > Log out</button>
</div>
}
function logout() {
if (user) {
logOut({
refetchQueries: [{ query }]
});
}
}
console.log({ user })
return (
<div className="header-wrpr">
<span className="logo">Suryavanshi</span>
<div className="spacer" />
{renderUser()}
</div>
);
};
export default Header;<file_sep>/client/src/components/index.js
import Landing from './Landing';
import CommentBox from './CommentBox';
import CommentList from './CommentList';
import Project from './Project';
import Bottom from './Bottom';
import Header from './Header';
import Comment from './Comment';
import { Dataset } from './Dataset';
import Service from './Service';
export {
Landing, CommentBox, Project, CommentList, Bottom, Header, Comment,Dataset,Service
}<file_sep>/models/user.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
email:String,
googleId:String,
name:String,
profileUrl:String
});
mongoose.model('user',userSchema);<file_sep>/client/src/components/Bottom.js
import React from 'react';
import { GithubIcon, FacebookIcon, InstagramIcon, TwitterIcon, LinkedinIcon } from '../assets/icons'
const Bottom = () => {
return (
<div className="btm-wrpr">
<div className="ic-cntr" >
<LinkedinIcon />
<InstagramIcon />
<TwitterIcon />
<FacebookIcon />
<GithubIcon />
</div>
<div className="dev-tg">
<span> Develope with passion by <NAME></span>
</div>
</div>
);
};
export default Bottom;
|
2fd27a081d0a67436503cbde6b7771806d1b520f
|
[
"JavaScript"
] | 13 |
JavaScript
|
suhas5979/Portfolio-GraphQL-Web-App
|
490e189d027a72c166c976ebed4bee3ae5f88130
|
01f2aec87d867b1e8adc40eff1ce8947bc1933c4
|
refs/heads/main
|
<file_sep>package be.intecbrussel.TestApps;
import be.intecbrussel.Daos.OrderDao;
import be.intecbrussel.Daos.OrderDaoImpl;
import be.intecbrussel.Entities.Order;
public class OrderApp {
public static void main(String[] args) {
Order order = new Order();
OrderDao orderDao = new OrderDaoImpl();
orderDao.createOrder(order);
System.out.println(orderDao.readOrder(10101));
//orderDao.updateOrder();
//orderDao.deleteOrder();
}
}
<file_sep>package be.intecbrussel.Daos;
import be.intecbrussel.Entities.Order;
import be.intecbrussel.Entities.Orderdetail;
import be.intecbrussel.Utils.EntityManagerFactoryProvider;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;
public class OrderDetailDaoImpl implements OrderDetailDao {
private EntityManagerFactory emf = EntityManagerFactoryProvider.getInstance().getEmf();
private EntityManager em = null;
@Override
public void createOrderDetail(Orderdetail orderdetail) {
try {
em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(orderdetail);
tx.commit();
System.out.println("Orderdetail saved");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (em != null) {
em.close();
}
}
}
@Override
public Orderdetail readOrderDetail(int orderNumber) {
Orderdetail orderdetail = null;
try {
em = emf.createEntityManager();
TypedQuery<Orderdetail> query = em.createQuery("SELECT b from Orderdetail b where b.orderNumber =?1", Orderdetail.class);
query.setParameter(1, orderNumber);
orderdetail = query.getSingleResult();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (em != null) {
em.close();
}
}
return orderdetail;
}
@Override
public void updateOrderDetail (Orderdetail orderdetail) {
try {
em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
em.merge(orderdetail);
transaction.commit();
System.out.println("Orderdetail updated");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (em != null) {
em.close();
}
}
}
@Override
public void deleteOrderDetail(Orderdetail orderdetail) {
try {
em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
Orderdetail order1 = em.find(Orderdetail.class, orderdetail.getOrderNumber());
transaction.begin();
em.remove(order1);
transaction.commit();
System.out.println("Orderdetail removed");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (em != null) {
em.close();
}
}
}
}
<file_sep>package be.intecbrussel.Entities;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Objects;
@Entity
@Table(name = "payments")
public class Payment implements Serializable {
@Id
@OneToOne
private Customer customerNumber;
private String checkNumber;
private Date paymentDate;
private BigDecimal amount;
public Customer getCustomerNumber() {
return customerNumber;
}
public void setCustomerNumber(Customer customerNumber) {
this.customerNumber = customerNumber;
}
public String getCheckNumber() {
return checkNumber;
}
public void setCheckNumber(String checkNumber) {
this.checkNumber = checkNumber;
}
public Date getPaymentDate() {
return paymentDate;
}
public void setPaymentDate(Date paymentDate) {
this.paymentDate = paymentDate;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Payment payment = (Payment) o;
return Objects.equals(customerNumber, payment.customerNumber) &&
Objects.equals(checkNumber, payment.checkNumber) &&
Objects.equals(paymentDate, payment.paymentDate) &&
Objects.equals(amount, payment.amount);
}
@Override
public int hashCode() {
return Objects.hash(customerNumber, checkNumber, paymentDate, amount);
}
@Override
public String toString() {
return "Payment{" +
"customerNumber=" + customerNumber +
", checkNumber='" + checkNumber + '\'' +
", paymentDate=" + paymentDate +
", amount=" + amount +
'}';
}
}
<file_sep>package be.intecbrussel.Daos;
import be.intecbrussel.Entities.Payment;
import be.intecbrussel.Entities.Product;
import be.intecbrussel.Utils.EntityManagerFactoryProvider;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;
public class ProductDaoImpl implements ProductDao{
private EntityManagerFactory emf = EntityManagerFactoryProvider.getInstance().getEmf();
private EntityManager em = null;
@Override
public void createProduct (Product product) {
try {
em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(product);
tx.commit();
System.out.println("Product saved");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (em != null) {
em.close();
}
}
}
@Override
public Product readProduct (String productCode) {
Product product = null;
try {
em = emf.createEntityManager();
TypedQuery<Product> query = em.createQuery("SELECT b from Product b where b.productCode =?1", Product.class);
query.setParameter(1, productCode);
product = query.getSingleResult();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (em != null) {
em.close();
}
}
return product;
}
@Override
public void updateProduct (Product product) {
try {
em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
em.merge(product);
transaction.commit();
System.out.println("Product updated");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (em != null) {
em.close();
}
}
}
@Override
public void deleteProduct (Product product) {
try {
em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
Product product1 = em.find(Product.class, product.getProductCode());
transaction.begin();
em.remove(product1);
transaction.commit();
System.out.println("Product removed");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (em != null) {
em.close();
}
}
}
}
<file_sep>package be.intecbrussel.Entities;
import org.dom4j.Text;
import org.hibernate.type.TextType;
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(name ="orders")
public class Order {
@Id
private int orderNumber;
private Date orderDate;
private Date requiredDate;
private Date shippedDate;
private String status;
private TextType comments;
@ManyToOne
private Customer customerNumber;
public int getOrderNumber() {
return orderNumber;
}
public void setOrderNumber(int orderNumber) {
this.orderNumber = orderNumber;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public Date getRequiredDate() {
return requiredDate;
}
public void setRequiredDate(Date requiredDate) {
this.requiredDate = requiredDate;
}
public Date getShippedDate() {
return shippedDate;
}
public void setShippedDate(Date shippedDate) {
this.shippedDate = shippedDate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public TextType getComments() {
return comments;
}
public void setComments(TextType comments) {
this.comments = comments;
}
public Customer getCostumerNumber() {
return customerNumber;
}
public void setCostumerNumber(Customer costumerNumber) {
this.customerNumber = costumerNumber;
}
@Override
public String toString() {
return "Order{" +
"orderNumber=" + orderNumber +
", orderDate=" + orderDate +
", requiredDate=" + requiredDate +
", shippedDate=" + shippedDate +
", status='" + status + '\'' +
", comments=" + comments +
", costumerNumber=" + customerNumber +
'}';
}
}
<file_sep>package be.intecbrussel.Daos;
import be.intecbrussel.Entities.ProductLine;
import be.intecbrussel.Utils.EntityManagerFactoryProvider;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;
public class ProductLineDaoImpl implements ProductLineDao {
private EntityManagerFactory emf = EntityManagerFactoryProvider.getInstance().getEmf();
private EntityManager em = null;
@Override
public void createProductLine (ProductLine productLine) {
try {
em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(productLine);
tx.commit();
System.out.println("Productline saved");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (em != null) {
em.close();
}
}
}
@Override
public ProductLine readProductLine(String productLine) {
ProductLine productLine1 = null;
try {
em = emf.createEntityManager();
TypedQuery<ProductLine> query = em.createQuery("SELECT b from ProductLine b where b.productLine =?1", ProductLine.class);
query.setParameter(1, productLine);
productLine1 = query.getSingleResult();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (em != null) {
em.close();
}
}
return productLine1;
}
@Override
public void updateProductLine (ProductLine productLine) {
try {
em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
em.merge(productLine);
transaction.commit();
System.out.println("Productline updated");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (em != null) {
em.close();
}
}
}
@Override
public void deleteProductline (ProductLine productLine) {
try {
em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
ProductLine productLine1 = em.find(ProductLine.class, productLine.getProductLine());
transaction.begin();
em.remove(productLine1);
transaction.commit();
System.out.println("Productline removed");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (em != null) {
em.close();
}
}
}
}
<file_sep>package be.intecbrussel.TestApps;
import be.intecbrussel.Daos.PaymentDao;
import be.intecbrussel.Daos.PaymentDaoImpl;
import be.intecbrussel.Entities.Payment;
public class PaymentApp {
public static void main(String[] args) {
Payment payment = new Payment();
PaymentDao paymentDao = new PaymentDaoImpl();
}
}
|
8c2f35c6f1d8c432c64a9536d628364e8649c82c
|
[
"Java"
] | 7 |
Java
|
JorisDDaems/JpaAssignment
|
ad37de25de11dbcd45c0227c5328e6926b66d837
|
b2210ad3acb32ee7ca2dd87ac49780502a3a3918
|
refs/heads/master
|
<file_sep>import numpy as np
import pandas as pd
import datetime
from matplotlib import pyplot as plt
import gc
from tqdm import tqdm
from sklearn.linear_model import HuberRegressor
from sklearn.model_selection import cross_val_predict, KFold
from sklearn.decomposition import PCA
from keras.layers.normalization import BatchNormalization
from keras.models import Sequential, Model
from keras.layers import Input, Embedding, Dense, Activation, Dropout, Flatten
from keras import regularizers
import keras
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from sklearn.model_selection import GroupKFold
import keras.backend as K
def init():
np.random.seed = 0
def smape(y_true, y_pred):
denominator = (np.abs(y_true) + np.abs(y_pred)) / 2.0
diff = np.abs(y_true - y_pred) / denominator
diff[denominator == 0] = 0.0
return np.nanmean(diff)
def smape2D(y_true, y_pred):
return smape(np.ravel(y_true), np.ravel(y_pred))
def smape_mask(y_true, y_pred, threshold):
denominator = (np.abs(y_true) + np.abs(y_pred))
diff = np.abs(y_true - y_pred)
diff[denominator == 0] = 0.0
return diff <= (threshold / 2.0) * denominator
def get_date_index(date, train_all=train_all):
for idx, c in enumerate(train_all.columns):
if date == c:
break
if idx == len(train_all.columns):
return None
return idx
def add_median(test, train, train_diff, train_diff7, train_diff7m,
train_key, periods, max_periods, first_train_weekday):
train = train.iloc[:,:7*max_periods]
df = train_key[['Page']].copy()
df['AllVisits'] = train.median(axis=1).fillna(0)
test = test.merge(df, how='left', on='Page', copy=False)
test.AllVisits = test.AllVisits.fillna(0).astype('float32')
for site in sites:
test[site] = (1 * (test.Site == site)).astype('float32')
for access in accesses:
test[access] = (1 * (test.AccessAgent == access)).astype('float32')
for (w1, w2) in periods:
df = train_key[['Page']].copy()
c = 'median_%d_%d' % (w1, w2)
cm = 'mean_%d_%d' % (w1, w2)
cmax = 'max_%d_%d' % (w1, w2)
cd = 'median_diff_%d_%d' % (w1, w2)
cd7 = 'median_diff7_%d_%d' % (w1, w2)
cd7m = 'median_diff7m_%d_%d' % (w1, w2)
cd7mm = 'mean_diff7m_%d_%d' % (w1, w2)
df[c] = train.iloc[:,7*w1:7*w2].median(axis=1, skipna=True)
df[cm] = train.iloc[:,7*w1:7*w2].mean(axis=1, skipna=True)
df[cmax] = train.iloc[:,7*w1:7*w2].max(axis=1, skipna=True)
df[cd] = train_diff.iloc[:,7*w1:7*w2].median(axis=1, skipna=True)
df[cd7] = train_diff7.iloc[:,7*w1:7*w2].median(axis=1, skipna=True)
df[cd7m] = train_diff7m.iloc[:,7*w1:7*w2].median(axis=1, skipna=True)
df[cd7mm] = train_diff7m.iloc[:,7*w1:7*w2].mean(axis=1, skipna=True)
test = test.merge(df, how='left', on='Page', copy=False)
test[c] = (test[c] - test.AllVisits).fillna(0).astype('float32')
test[cm] = (test[cm] - test.AllVisits).fillna(0).astype('float32')
test[cmax] = (test[cmax] - test.AllVisits).fillna(0).astype('float32')
test[cd] = (test[cd] ).fillna(0).astype('float32')
test[cd7] = (test[cd7] ).fillna(0).astype('float32')
test[cd7m] = (test[cd7m] ).fillna(0).astype('float32')
test[cd7mm] = (test[cd7mm] ).fillna(0).astype('float32')
for c_norm, c in zip(y_norm_cols, y_cols):
test[c_norm] = (np.log1p(test[c]) - test.AllVisits).astype('float32')
gc.collect()
return test
def smape_error(y_true, y_pred):
return K.mean(K.clip(K.abs(y_pred - y_true), 0.0, 1.0), axis=-1)
max_size = 181 # number of days in 2015 with 3 days before end
offset = 1/2
train_all = pd.read_csv("train_2.csv")
all_page = train_all.Page.copy()
train_key = train_all[['Page']].copy()
train_all = train_all.iloc[:,1:] * offset
trains = []
tests = []
train_end = get_date_index('2016-09-10') + 1
test_start = get_date_index('2016-09-13')
for i in range(-3,4):
train = train_all.iloc[ : , (train_end - max_size + i) : train_end + i].copy().astype('float32')
test = train_all.iloc[:, test_start + i : (63 + test_start) + i].copy().astype('float32')
train = train.iloc[:,::-1].copy().astype('float32')
trains.append(train)
tests.append(test)
train_all = train_all.iloc[:,-(max_size):].astype('float32')
train_all = train_all.iloc[:,::-1].copy().astype('float32')
test_3_date = tests[3].columns
data = [page.split('_') for page in tqdm(train_key.Page)]
access = ['_'.join(page[-2:]) for page in data]
site = [page[-3] for page in data]
page = ['_'.join(page[:-3]) for page in data]
page[:2]
train_key['PageTitle'] = page
train_key['Site'] = site
train_key['AccessAgent'] = access
train_norms = [np.log1p(train).astype('float32') for train in trains]
train_all_norm = np.log1p(train_all).astype('float32')
for i,test in enumerate(tests):
first_day = i-2 # 2016-09-13 is a Tuesday
test_columns_date = list(test.columns)
test_columns_code = ['w%d_d%d' % (i // 7, (first_day + i) % 7) for i in range(63)]
test.columns = test_columns_code
for test in tests:
test.fillna(0, inplace=True)
test['Page'] = all_page
test.sort_values(by='Page', inplace=True)
test.reset_index(drop=True, inplace=True)
tests = [test.merge(train_key, how='left', on='Page', copy=False) for test in tests]
test_all_id = pd.read_csv('key_2.csv')
test_all_id['Date'] = [page[-10:] for page in tqdm(test_all_id.Page)]
test_all_id['Page'] = [page[:-11] for page in tqdm(test_all_id.Page)]
test_all = test_all_id.drop('Id', axis=1)
test_all['Visits_true'] = np.NaN
test_all.Visits_true = test_all.Visits_true * offset
test_all = test_all.pivot(index='Page', columns='Date', values='Visits_true').astype('float32').reset_index()
test_all['2017-11-14'] = np.NaN
test_all.sort_values(by='Page', inplace=True)
test_all.reset_index(drop=True, inplace=True)
test_all_columns_date = list(test_all.columns[1:])
first_day = 2 # 2017-13-09 is a Wednesday
test_all_columns_code = ['w%d_d%d' % (i // 7, (first_day + i) % 7) for i in range(63)]
cols = ['Page']
cols.extend(test_all_columns_code)
test_all.columns = cols
test_all = test_all.merge(train_key, how='left', on='Page')
y_cols = test.columns[:63]
for test in tests:
test.reset_index(inplace=True)
test_all = test_all.reset_index()
test = pd.concat(tests[2:5], axis=0).reset_index(drop=True)
test_all = test_all[test.columns].copy()
train_cols = ['d_%d' % i for i in range(train_norms[0].shape[1])]
for train_norm in train_norms:
train_norm.columns = train_cols
train_all_norm.columns = train_cols
train_norm = pd.concat(train_norms[2:5], axis=0).reset_index(drop=True)
train_norm_diff = train_norm - train_norm.shift(-1, axis=1)
train_all_norm_diff = train_all_norm - train_all_norm.shift(-1, axis=1)
train_norm_diff7 = train_norm - train_norm.shift(-7, axis=1)
train_all_norm_diff7 = train_all_norm - train_all_norm.shift(-7, axis=1)
train_norm = train_norm.iloc[:,::-1]
train_norm_diff7m = train_norm - train_norm.rolling(window=7, axis=1).median()
train_norm = train_norm.iloc[:,::-1]
train_norm_diff7m = train_norm_diff7m.iloc[:,::-1]
train_all_norm = train_all_norm.iloc[:,::-1]
train_all_norm_diff7m = train_all_norm - train_all_norm.rolling(window=7, axis=1).median()
train_all_norm = train_all_norm.iloc[:,::-1]
train_all_norm_diff7m = train_all_norm_diff7m.iloc[:,::-1]
sites = train_key.Site.unique()
test_site = pd.factorize(test.Site)[0]
test['Site_label'] = test_site
test_all['Site_label'] = test_site[:test_all.shape[0]]
accesses = train_key.AccessAgent.unique()
test_access = pd.factorize(test.AccessAgent)[0]
test['Access_label'] = test_access
test_all['Access_label'] = test_access[:test_all.shape[0]]
test0 = test.copy()
test_all0 = test_all.copy()
y_norm_cols = [c+'_norm' for c in y_cols]
y_pred_cols = [c+'_pred' for c in y_cols]
max_periods = 16
periods = [(0,1), (1,2), (2,3), (3,4),
(4,5), (5,6), (6,7), (7,8),
(0,2), (2,4),(4,6),(6,8),
(0,4),(4,8),(8,12),(12,16),
(0,8), (8,16), (0,12),
(0,16),
]
site_cols = list(sites)
access_cols = list(accesses)
test, test_all = test0.copy(), test_all0.copy()
for c in y_pred_cols:
test[c] = np.NaN
test_all[c] = np.NaN
test1 = add_median(test, train_norm, train_norm_diff, train_norm_diff7, train_norm_diff7m,
train_key, periods, max_periods, 3)
test_all1 = add_median(test_all, train_all_norm, train_all_norm_diff, train_all_norm_diff7, train_all_norm_diff7m,
train_key, periods, max_periods, 5)
num_cols = (['median_%d_%d' % (w1,w2) for (w1,w2) in periods])
num_cols.extend(['mean_%d_%d' % (w1,w2) for (w1,w2) in periods])
num_cols.extend(['max_%d_%d' % (w1,w2) for (w1,w2) in periods])
num_cols.extend(['median_diff_%d_%d' % (w1,w2) for (w1,w2) in periods])
num_cols.extend(['median_diff7m_%d_%d' % (w1,w2) for (w1,w2) in periods])
num_cols.extend(['mean_diff7m_%d_%d' % (w1,w2) for (w1,w2) in periods])
def get_model_NN(input_dim, num_sites, num_accesses, output_dim):
dropout = 0.5
regularizer = 0.00004
main_input = Input(shape=(input_dim,), dtype='float32', name='main_input')
site_input = Input(shape=(num_sites,), dtype='float32', name='site_input')
access_input = Input(shape=(num_accesses,), dtype='float32', name='access_input')
x0 = keras.layers.concatenate([main_input, site_input, access_input])
x = Dense(200, activation='relu',
kernel_initializer='lecun_uniform', kernel_regularizer=regularizers.l2(regularizer))(x0)
x = Dropout(dropout)(x)
x = keras.layers.concatenate([x0, x])
x = Dense(200, activation='relu',
kernel_initializer='lecun_uniform', kernel_regularizer=regularizers.l2(regularizer))(x)
x = BatchNormalization(beta_regularizer=regularizers.l2(regularizer),
gamma_regularizer=regularizers.l2(regularizer)
)(x)
x = Dropout(dropout)(x)
x = Dense(100, activation='relu',
kernel_initializer='lecun_uniform', kernel_regularizer=regularizers.l2(regularizer))(x)
x = Dropout(dropout)(x)
x = Dense(200, activation='relu',
kernel_initializer='lecun_uniform', kernel_regularizer=regularizers.l2(regularizer))(x)
x = Dropout(dropout)(x)
x = Dense(output_dim, activation='linear',
kernel_initializer='lecun_uniform', kernel_regularizer=regularizers.l2(regularizer))(x)
model = Model(inputs=[main_input, site_input, access_input], outputs=[x])
model.compile(loss=smape_error, optimizer='adam')
return model
def get_model_lgb(X_train, num_rounds, if_ip=False):
predictors = list(X_train.columns)
params = {
'boosting_type': 'gbdt', 'objective': 'binary', 'nthread': -1, 'silent': True, 'metric':'auc', 'seed':77,
'num_leaves': 48, 'learning_rate': 0.01, 'max_depth': -1, 'gamma':47,
'max_bin': 255, 'subsample_for_bin': 70000, 'bagging_fraction':0.7, 'bagging_freq':1, 'bagging_seed':55,
'colsample_bytree': 0.65, 'reg_alpha': 19.45, 'reg_lambda': 0,
'min_split_gain': 0.35, 'min_child_weight': 0, 'scale_pos_weight':205}
xgtrain = lgb.Dataset(X_train[predictors].values, label=y_train, feature_name=predictors)
bst = lgb.X_train(params, xgtrain, num_boost_round = num_rounds, verbose_eval=False)
return bst, predictors
group = pd.factorize(test1.Page)[0]
n_bag = 20
kf = GroupKFold(n_bag)
batch_size=4096
test2 = test1
test_all2 = test_all1
X, Xs, Xa, y = test2[num_cols].values, test2[site_cols].values, test2[access_cols].values, test2[y_norm_cols].values
X_all, Xs_all, Xa_all, y_all = test_all2[num_cols].values, test_all2[site_cols].values, test_all2[access_cols].values, test_all2[y_norm_cols].fillna(0).values
y_true = test2[y_cols]
y_all_true = test_all2[y_cols]
models = [get_model_NN(len(num_cols), len(site_cols), len(access_cols), len(y_cols)) for bag in range(n_bag)]
print('offset:', offset)
print('batch size:', batch_size)
best_score = 100
best_all_score = 100
save_pred = 0
saved_pred_all = 0
for n_epoch in range(10, 201, 10):
print('************** start %d epochs **************************' % n_epoch)
y_pred0 = np.zeros((y.shape[0], y.shape[1]))
y_all_pred0 = np.zeros((n_bag, y_all.shape[0], y_all.shape[1]))
for fold, (train_idx, test_idx) in enumerate(kf.split(X, y, group)):
print('train fold', fold, end=' ')
model = models[fold]
X_train, Xs_train, Xa_train, y_train = X[train_idx,:], Xs[train_idx,:], Xa[train_idx,:], y[train_idx,:]
X_test, Xs_test, Xa_test, y_test = X[test_idx,:], Xs[test_idx,:], Xa[test_idx,:], y[test_idx,:]
model.fit([ X_train, Xs_train, Xa_train], y_train,
epochs=10, batch_size=batch_size, verbose=0, shuffle=True,
#validation_data=([X_test, Xs_test, Xa_test], y_test)
)
y_pred = model.predict([ X_test, Xs_test, Xa_test], batch_size=batch_size)
y_all_pred = model.predict([X_all, Xs_all, Xa_all], batch_size=batch_size)
y_pred0[test_idx,:] = y_pred
y_all_pred0[fold,:,:] = y_all_pred
y_pred += test2.AllVisits.values[test_idx].reshape((-1,1))
y_pred = np.expm1(y_pred)
y_pred[y_pred < 0.5 * offset] = 0
res = smape2D(test2[y_cols].values[test_idx, :], y_pred)
y_pred = offset*((y_pred / offset).round())
res_round = smape2D(test2[y_cols].values[test_idx, :], y_pred)
y_all_pred += test_all2.AllVisits.values.reshape((-1,1))
y_all_pred = np.expm1(y_all_pred)
y_all_pred[y_all_pred < 0.5 * offset] = 0
res_all = smape2D(test_all2[y_cols], y_all_pred)
y_all_pred = offset*((y_all_pred / offset).round())
res_all_round = smape2D(test_all2[y_cols], y_all_pred)
print('smape train: %0.5f' % res, 'round: %0.5f' % res_round)
#y_pred0 = np.nanmedian(y_pred0, axis=0)
y_all_pred0 = np.nanmedian(y_all_pred0, axis=0)
y_pred0 += test2.AllVisits.values.reshape((-1,1))
y_pred0 = np.expm1(y_pred0)
y_pred0[y_pred0 < 0.5 * offset] = 0
res = smape2D(y_true, y_pred0)
print('smape train: %0.5f' % res, end=' ')
y_pred0 = offset*((y_pred0 / offset).round())
res_round = smape2D(y_true, y_pred0)
print('round: %0.5f' % res_round)
y_all_pred0 += test_all2.AllVisits.values.reshape((-1,1))
y_all_pred0 = np.expm1(y_all_pred0)
y_all_pred0[y_all_pred0 < 0.5 * offset] = 0
#y_all_pred0 = y_all_pred0.round()
res_all = smape2D(y_all_true, y_all_pred0)
print(' smape LB: %0.5f' % res_all, end=' ')
y_all_pred0 = offset*((y_all_pred0 / offset).round())
res_all_round = smape2D(y_all_true, y_all_pred0)
print('round: %0.5f' % res_all_round, end=' ')
if res_round < best_score:
print('saving')
best_score = res_round
best_all_score = res_all_round
test.loc[:, y_pred_cols] = y_pred0
test_all.loc[:, y_pred_cols] = y_all_pred0
else:
print()
print('*************** end %d epochs **************************' % n_epoch)
print('best saved LB score:', best_all_score)
filename = 'prediction'
test_all_columns_save = [c+'_pred' for c in test_all_columns_code]
test_all_columns_save.append('Page')
test_all_save = test_all[test_all_columns_save]
test_all_save.columns = test_all_columns_date+['Page']
test_all_save.to_csv('%s_test_all_save.csv' % filename, index=False)
test_all_save_columns = test_all_columns_date[:-1]+['Page']
test_all_save = test_all_save[test_all_save_columns]
test_all_save = pd.melt(test_all_save, id_vars=['Page'], var_name='Date', value_name='Visits')
test_all_sub = test_all_id.merge(test_all_save, how='left', on=['Page','Date'])
test_all_sub.Visits = (test_all_sub.Visits / offset).round()
#print('%.5f' % smape(test_all_sub.Visits_true, test_all_sub.Visits))
test_all_sub_sorted = test_all_sub[['Id', 'Visits']].sort_values(by='Id')
test_all_sub[['Id', 'Visits']].to_csv('%s_test.csv' % filename, index=False)
<file_sep># Web-Traffic-Time Prediction
Download the training dataset train_2.csv from https://www.kaggle.com/c/web-traffic-time-series-forecasting/data.
Put the data into the same directory with the code, then you can run the code. The code uses the NN model by defult, which gets the best prediction result in our implementations
The trianing time is about 7 hours on server.
|
b64abda2a4c65b17a5a59574fdc7d1161d80e57d
|
[
"Markdown",
"Python"
] | 2 |
Python
|
boourbon/WebTrafficTimePrediction
|
b96989485de7822aeed20ba48e91696a43168cee
|
b0e6f95a64411840bcdf78d2053f2892521960ed
|
refs/heads/main
|
<file_sep># mark12
This web app is divided into four sections.
- Triangle Quiz
- Area calculator
- Hypotenuse calculator
- Valid Triangle checker
It is made using
- Javascript
- HTML
- CSS
<file_sep>const page = document.body.id;
switch (page) {
case "quiz":
quiz();
break;
case "triangle":
triangle();
break;
case "area":
area();
break;
case "hypotenuse":
hypotenuse();
break;
}
function hypotenuse() {
const a = document.getElementById("input-one");
const b = document.getElementById("input-two");
const button = document.querySelector("button");
const finalScoreA = document.querySelector(".score_h1-a");
button.addEventListener("click", () => {
const s1 = parseInt(a.value);
const s2 = parseInt(b.value);
if (s1 > 0 && s2 > 0) {
const result = Math.sqrt(Math.pow(s1, 2) + Math.pow(s2, 2));
finalScoreA.innerHTML = `Hypotenuse is ${result.toFixed(2)}`;
} else {
finalScoreA.innerHTML = `Please enter proper values 😐`;
}
});
}
function area() {
const a = document.getElementById("input-one");
const b = document.getElementById("input-two");
const c = document.getElementById("input-three");
const button = document.querySelector("button");
const finalScoreA = document.querySelector(".score_h1-a");
const finalScoreB = document.querySelector(".score_h1-b");
button.addEventListener("click", () => {
const s1 = parseInt(a.value);
const s2 = parseInt(b.value);
const s3 = parseInt(c.value);
if ((s1 > 0) & (s2 > 0) & (s3 > 0)) {
const p = (s1 + s2 + s3) / 2;
const result = Math.sqrt(p * (p - s1) * (p - s2) * (p - s3));
if (result || result > 0) {
finalScoreA.innerHTML = `Area of triangle is ${result.toFixed(2)}`;
finalScoreB.innerHTML = "";
} else {
finalScoreA.innerHTML = ``;
finalScoreB.innerHTML = `That is not a Triangle `;
}
}
else{
finalScoreA.innerHTML = ``;
finalScoreB.innerHTML = `Please enter proper values 😐`;
}
});
}
function triangle() {
const a = document.getElementById("input-one");
const b = document.getElementById("input-two");
const c = document.getElementById("input-three");
const button = document.querySelector("button");
const finalScoreA = document.querySelector(".score_h1-a");
const finalScoreB = document.querySelector(".score_h1-b");
button.addEventListener("click", () => {
let valueA = Number(a.value);
let valueB = Number(b.value);
let valueC = Number(c.value);
if (valueA < 0 || valueB < 0 || valueC < 0) {
finalScoreA.innerHTML = ``;
finalScoreB.innerHTML = "Enter proper values 😐";
} else if (
parseInt(a.value) + parseInt(b.value) + parseInt(c.value) ===
180
) {
finalScoreA.innerHTML = `It's a Triangle 🙂`;
finalScoreB.innerHTML = "";
} else {
finalScoreA.innerHTML = ``;
finalScoreB.innerHTML = "It's not a Triangle 🥺";
}
});
}
function quiz() {
const myQuestions = [
{
question:
"A triangle that has no equal sides and no equal angles is known as?",
answers: {
a: "isosceles triangle",
b: "scalene triangle",
c: "equilateral triangle",
d: "right angle",
},
correctAnswer: "b",
},
{
question:
"A triangle that has 2 equal sides and 2 equal angles is known as?",
answers: {
a: "isosceles triangle",
b: "equilateral triangle",
c: "scalene triangle",
d: "right angle",
},
correctAnswer: "a",
},
{
question: "A triangle with the angle of 90 ° is called?",
answers: {
a: "vertical triangle",
b: "supplementary triangle",
c: "right angle triangle",
d: "reflective triangle",
},
correctAnswer: "c",
},
{
question:
"A triangle that has 3 equal sides and 3 equal angles is known as?",
answers: {
a: "scalene triangle",
b: "isosceles triangle",
c: "isosceles triangle",
d: "equilateral triangle",
},
correctAnswer: "d",
},
{
question:
"Area of a triangle with base b and height h is represented by?",
answers: {
a: "1⁄2 × bh",
b: "2 + bh",
c: "2 × bh",
d: "2⁄bh",
},
correctAnswer: "a",
},
];
let marks = 0;
const quiz = document.querySelector(".quiz");
const button = document.querySelector(".score_button");
const finalScore = document.querySelector(".score_h1");
myQuestions.forEach((item, i) => {
const div = document.createElement("div");
div.classList.add("question");
div.classList.add("has-text-grey-dark");
div.innerHTML = `<p>${i + 1}) ${item.question}</p>
<label class="radio">
<input type="radio" value='a' name="${i}" />
a) ${item.answers.a}
</label>
<label class="radio">
<input type="radio" value='b' name="${i}" />
b) ${item.answers.b}
</label>
<label class="radio">
<input type="radio" value='c' name="${i}" />
c) ${item.answers.c}
</label>
<label class="radio">
<input type="radio" value='d' name="${i}" />
d) ${item.answers.d}
</label>`;
quiz.appendChild(div);
});
function clickHandler() {
marks = 0;
myQuestions.forEach((item, i) => {
const ans = document.getElementsByName(i);
for (a = 0; a < 4; a++) {
if (ans[a].checked) {
if (ans[a].value === item.correctAnswer) {
marks++;
}
}
}
});
finalScore.innerHTML = `Your score is ${marks}`;
}
button.addEventListener("click", clickHandler);
}
|
3caea43432aa0fa38841080563e7bcb7953f490a
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
AnuragSahu11/mark12
|
85906bb51358142a3985498b5d4a7629ee67de6a
|
a73934a54a0ca710ac3b93f492426494a7f350fa
|
refs/heads/master
|
<file_sep>package com.paterns.colors;
import com.paterns.AbstractFactory;
import com.paterns.vehicles.Vehicle;
public class ColorFactory implements AbstractFactory{
@Override
public Color getColor(String color) {
if(color==null) return null;
if(color.equalsIgnoreCase("YELLOW")){
return new Yellow();
}else if(color.equalsIgnoreCase("GREEN")){
return new Green();
}else if(color.equalsIgnoreCase("RED")){
return new Red();
}
return null;
}
@Override
public Vehicle getVehicle(String vehicle) {
return null;
}
}
<file_sep>package com.paterns.vehicles;
public class Bike implements Vehicle {
@Override
public void Ride() {
System.out.println("Inside bike::Ride() method.");
}
}
<file_sep>package com.paterns;
public class Main {
public static void main(String[] args) {
User robert = new User("Robert");
User peter = new User("Peter");
robert.sendMessage("hi");
peter.sendMessage("hello");
}
}
<file_sep>package com.paterns;
public interface Order {
void exeute();
}<file_sep>package com.paterns;
import java.util.ArrayList;
import java.util.List;
public class Subject {
//list which holds all observers
private List<Observer> observers = new ArrayList<Observer>();
private int state;
//get value with bin, octa and hexa update function works
public int getState() {
return state;
}
//called in main and automatically calls all observers in list an their update functions
public void setState(int state) {
this.state = state;
notifyAllObservers();
}
public void attach(Observer observer){
observers.add(observer);
}
//iterate trough list and call update function
public void notifyAllObservers(){
for (Observer observer : observers) {
observer.update();
}
}
}
<file_sep>package com.paterns.colors;
import com.paterns.colors.Color;
public class Yellow implements Color {
@Override
public void fill() {
System.out.println("Inside Yellow::fill() method.");
}
}<file_sep>package com.patterns;
public interface Strategy {
//create interface with one universal function
int doOperation(int num1, int num2);
}
<file_sep>package com.patterns;
public class OperationPow implements Strategy {
//override function from interface
@Override
public int doOperation(int num1, int num2) {
return (int) Math.pow(num1, num2);
}
}
<file_sep>package com.company;
public class Cricket extends Game {
@Override
void initialize() {
System.out.println("Cricked INITIALIZED");
}
@Override
void startPlay() {
System.out.println("Cricked PLAY");
}
@Override
void endPlay() {
System.out.println("Cricked END");
}
}
<file_sep># JavaPatterns
In this project I just show some of design patterns which I learning for my exam. I upload it to git so you can benefit from this examples too.
As you may notice not all patterns are implemented yet. You need to give me some time ;)
## Install
You can download what ever folder and in it you can find whole InetelliJ project which you can run on your computer.
If you want olny .java files you navigate like this (pattern)/src/com/patterns/ and there you can find theese files.
## Project structure
* Creational patterns ->
Deal with initializing and configuring classes and objects
* Structural patterns ->
Deal with decoupling interface and implementation of classes and objects
* Behavioral patterns ->
Deal with dynamic interactions among societies of classes and objects
### Creational
- abstract factory
- builder
- factory method
- lazy initialization
- multiton
- object pool
- prototype
- singleton
### Structural
- adapter
- bridge
- composite
- decorator
- facade
- flyweight
- front controller
- module
- proxy
### Behavioral
- blackboard
- chain of responsibility
- command
- interpreter
- iterator
- mediator
- memento
- null object
- observer
- servant
- specification
- state
- strategy
- template method
- visitor
## Source
I use [this page](https://www.tutorialspoint.com/design_pattern/) for source codes. You can find more info there.
|
afe2345f78755964ab43c5dd31749679a7df9c01
|
[
"Markdown",
"Java"
] | 10 |
Java
|
kubekbreha/JavaPaterns
|
02426cf2236f82df8e10cb65570ac0c86621b75c
|
1baebba238b03266098ca37ae51deb0c3c222f0a
|
refs/heads/master
|
<file_sep># raul-ortiz
hola buenos dias
hago cambio a rama
este es otro cambio
<file_sep>
function suma(a, b) {
console.log(a + b);
}
function mostrarvalores() {
alert(campo_text.value);
}
var memo = "r";
function moverboton() {
if (memo == "r") {
boton.className = "ui button left floated";
memo = "l";
}
else if(memo=="l"){ boton.className = "ui button right floated";
memo="r" ;}
}
|
2d04ab7387d81c702414dd6f2a53059c1747ea35
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
reog3/raul-ortiz
|
91a226b9d2b83e90bc57d1036b512bcf45ae728b
|
bf88d70544a1fa2a671daac316c0f77fc8f153d8
|
refs/heads/master
|
<file_sep>package eu.einfracentral.domain;
import io.swagger.annotations.ApiModelProperty;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import java.net.URL;
import java.util.List;
@XmlType
@XmlRootElement(namespace = "http://einfracentral.eu")
public class Provider implements Identifiable {
@XmlElement(required = true)
private String id;
@XmlElement(required = true)
private String name;
@XmlElement(required = true)
private URL website;
@XmlElement
private URL catalogueOfResources;
@XmlElement
private URL publicDescOfResources;
@XmlElement
private URL logo;
@XmlElement(required = true)
private String additionalInfo;
@XmlElement
private String contactInformation;
@XmlElementWrapper(name = "users")
@XmlElement(name = "user")
@ApiModelProperty(required = true)
// @JsonInclude(JsonInclude.Include.USE_DEFAULTS)
private List<User> users;
@XmlElement
@ApiModelProperty(hidden = true)
private Boolean active;
@XmlElement
@ApiModelProperty(hidden = true)
private String status;
public Provider() {
}
public Provider(Provider provider) {
this.id = provider.getId();
this.name = provider.getName();
this.contactInformation = provider.getContactInformation();
this.website = provider.getWebsite();
this.catalogueOfResources = provider.getCatalogueOfResources();
this.publicDescOfResources = provider.getPublicDescOfResources();
this.additionalInfo = provider.getAdditionalInfo();
this.users = provider.getUsers();
this.active = provider.getActive();
this.status = provider.getStatus();
}
public enum States {
// TODO: probably change states
INIT("initialized"),
APPROVED("approved"),
REJECTED("rejected"),
PENDING_1("pending initial approval"),
PENDING_2("pending service template approval"),
REJECTED_ST("rejected service template");
private final String type;
States(final String type) {
this.type = type;
}
public String getKey() {
return type;
}
}
@Override
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContactInformation() {
return contactInformation;
}
public void setContactInformation(String contactInformation) {
this.contactInformation = contactInformation;
}
@ApiModelProperty(hidden = true)
public List<User> getUsers() {
return users;
}
@ApiModelProperty(hidden = true)
public void setUsers(List<User> users) {
this.users = users;
}
public URL getWebsite() {
return website;
}
public void setWebsite(URL website) {
this.website = website;
}
public URL getCatalogueOfResources() {
return catalogueOfResources;
}
public void setCatalogueOfResources(URL catalogueOfResources) {
this.catalogueOfResources = catalogueOfResources;
}
public URL getPublicDescOfResources() {
return publicDescOfResources;
}
public void setPublicDescOfResources(URL publicDescOfResources) {
this.publicDescOfResources = publicDescOfResources;
}
public URL getLogo() {
return logo;
}
public void setLogo(URL logo) {
this.logo = logo;
}
public String getAdditionalInfo() {
return additionalInfo;
}
public void setAdditionalInfo(String additionalInfo) {
this.additionalInfo = additionalInfo;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
<file_sep>package eu.einfracentral.domain;
import java.util.List;
// FIXME: change to composition instead of inheritance.
public class RichService extends Service {
// private Service service;
private ServiceMetadata serviceMetadata;
private String categoryName;
private String subCategoryName;
private List<String> languageNames;
private int views;
private int ratings;
private float userRate;
private float hasRate;
private int favourites;
private boolean isFavourite;
public RichService() {
}
public RichService(Service service, ServiceMetadata serviceMetadata) {
// this.service = service;
super(service);
this.serviceMetadata = serviceMetadata;
}
public RichService(InfraService service) {
// this.service = (Service) service;
super(service);
this.serviceMetadata = service.getServiceMetadata();
}
/* public Service getService() {
return service;
}
public void setService(Service service) {
this.service = service;
}*/
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getSubCategoryName() {
return subCategoryName;
}
public void setSubCategoryName(String subCategoryName) {
this.subCategoryName = subCategoryName;
}
public List<String> getLanguageNames() {
return languageNames;
}
public void setLanguageNames(List<String> languageNames) {
this.languageNames = languageNames;
}
public int getViews() {
return views;
}
public void setViews(int views) {
this.views = views;
}
public int getRatings() {
return ratings;
}
public void setRatings(int ratings) {
this.ratings = ratings;
}
public float getHasRate() {
return hasRate;
}
public void setHasRate(float hasRate) {
this.hasRate = hasRate;
}
public int getFavourites() {
return favourites;
}
public void setFavourites(int favourites) {
this.favourites = favourites;
}
public boolean getIsFavourite() {
return isFavourite;
}
public void setFavourite(boolean favourite) {
isFavourite = favourite;
}
public float getUserRate() {
return userRate;
}
public void setUserRate(float userRate) {
this.userRate = userRate;
}
}
<file_sep>package eu.einfracentral.domain;
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
import org.springframework.security.core.Authentication;
import javax.xml.bind.annotation.*;
@XmlType
@XmlRootElement(namespace = "http://einfracentral.eu")
public class User implements Identifiable {
@XmlElement
private String id;
@XmlElement
private String email;
@XmlElement
private String name;
@XmlElement
private String surname;
public User() {
}
public User(String id, String email, String name, String surname) {
this.id = id;
this.email = email;
this.name = name;
this.surname = surname;
}
public User(Authentication auth) {
if (auth instanceof OIDCAuthenticationToken) {
this.id = ((OIDCAuthenticationToken) auth).getUserInfo().getSub();
this.email = ((OIDCAuthenticationToken) auth).getUserInfo().getEmail();
this.name = ((OIDCAuthenticationToken) auth).getUserInfo().getGivenName();
this.surname = ((OIDCAuthenticationToken) auth).getUserInfo().getFamilyName();
} else {
throw new RuntimeException("Could not create user. Authentication is not an instance of OIDCAuthentication");
}
}
@Override
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
<file_sep>package eu.einfracentral.domain;
public class ServiceHistory extends ServiceMetadata {
private String version;
private boolean versionChange;
public ServiceHistory() {
}
public ServiceHistory(ServiceMetadata serviceMetadata, String version) {
super(serviceMetadata);
this.version = version;
this.versionChange = false;
}
public ServiceHistory(ServiceMetadata serviceMetadata, String version, boolean versionChange) {
super(serviceMetadata);
this.version = version;
this.versionChange = versionChange;
}
public void setVersion(String version) {
this.version = version;
}
public String getVersion() {
return version;
}
public boolean isVersionChange() {
return versionChange;
}
public void setVersionChange(boolean versionChange) {
this.versionChange = versionChange;
}
}
<file_sep>package eu.einfracentral.domain;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import java.util.List;
@XmlType
@XmlRootElement(namespace = "http://einfracentral.eu")
public class Vocabulary implements Identifiable {
@XmlElement(required = true)
private String id;
@XmlElement(required = true)
private String name;
@XmlElement(required = true)
private String type;
@XmlElement
private String parent;
@XmlElementWrapper(name = "extras")
@XmlElement(name = "extra")
private List<String> extras;
@Override
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
public List<String> getExtras() {
return extras;
}
public void setExtras(List<String> extras) {
this.extras = extras;
}
}
<file_sep>#eic-registry-model
This is the very model of the eInfraCentral registry
|
63f4c7febe2672405b81ebb053128ea331cd8c8e
|
[
"Markdown",
"Java"
] | 6 |
Java
|
eInfraCentral/eic-registry-model
|
a0c74766172bf7af162b3537eac5660d8d4bd40a
|
647e6b630546b0ada8e5ac12899445884a76a474
|
refs/heads/master
|
<repo_name>LongLiveChitakasha/injinius<file_sep>/sidebars.js
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
module.exports = {
"docs": [
{ type: 'category', label: 'Introduction', items: ['about', 'faq']},
{
type: 'category',
label: 'Library',
items: [
'library/getting-started',
'library/user-management',
'library/get',
'library/post',
'library/patch',
'library/delete',
'library/subscribe',
'library/stored-procedures',
],
},
{
type: 'category',
label: 'Track',
items: [
"track/index",
{
type: 'category',
label: 'Software',
items:[
'track/software/inheritance',
'track/software/constructors',
'track/software/overloads',
'track/software/exceptionHandling',
'track/software/pointerArithmetic',
],
},
{
type: 'category',
label: 'business',
items:[
'track/software/inheritance',
'track/software/constructors',
'track/software/overloads',
'track/software/exceptionHandling',
//'track/software/pointerArithmetic',
],
},
]
},
// {
// type: 'category',
// label: 'Legal',
// items: [
// 'legal/privacyNotice',
// 'legal/cookiePolicy',
// 'legal/termsOfUse',
// 'legal/disclaimer'
// ],
// },
{
type: 'category',
label: 'Realtime',
items: [
'realtime/about',
'realtime/docker',
'realtime/aws',
'realtime/digitalocean',
'realtime/source',
],
},
{ type: 'category', label: 'Postgres', items: ['postgres/postgres-intro'] },
{
type: 'category',
label: 'See Also',
items: ['guides/examples', 'pricing', 'support', 'handbook/contributing'],
},
// Handbook: ['handbook/introduction', 'handbook/contributing'],
],
}
|
c6d73d10d1d393e4f5729039da55faba8ee31c79
|
[
"JavaScript"
] | 1 |
JavaScript
|
LongLiveChitakasha/injinius
|
feeb62311dc32554b71d055f8af6563229d8b71a
|
fee86951492083ef5b2b53781660805a4c1c323b
|
refs/heads/master
|
<repo_name>steelx/tilepix<file_sep>/go.mod
module github.com/steelx/tilepix
go 1.12
require (
github.com/faiface/glhf v0.0.0-20181018222622-82a6317ac380 // indirect
github.com/faiface/mainthread v0.0.0-20171120011319-8b78f0a41ae3
github.com/faiface/pixel v0.8.1-0.20190416082708-9aca3bfe7af3
github.com/go-gl/gl v0.0.0-20190320180904-bf2b1f2f34d7 // indirect
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1 // indirect
github.com/go-gl/mathgl v0.0.0-20190415092908-39e6cc4dcc59 // indirect
github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect
github.com/pkg/errors v0.8.1 // indirect
github.com/sirupsen/logrus v1.4.1
github.com/stretchr/objx v0.2.0 // indirect
golang.org/x/crypto v0.0.0-20190411191339-88737f569e3a // indirect
golang.org/x/sys v0.0.0-20190415145633-3fd5a3612ccd // indirect
)
<file_sep>/examples/wiki/basics.go
package main
import (
"image/color"
_ "image/png"
"github.com/steelx/tilepix"
"github.com/faiface/pixel"
"github.com/faiface/pixel/pixelgl"
)
var (
winBounds = pixel.R(0, 0, 800, 600)
)
func run() {
m, err := tilepix.ReadFile("map.tmx")
if err != nil {
panic(err)
}
cfg := pixelgl.WindowConfig{
Title: "TilePix basics",
Bounds: winBounds,
VSync: true,
}
win, err := pixelgl.NewWindow(cfg)
if err != nil {
panic(err)
}
for !win.Closed() {
win.Clear(color.White)
m.DrawAll(win, color.Transparent, pixel.IM)
win.Update()
}
}
func main() {
pixelgl.Run(run)
}
<file_sep>/tilelayer.go
package tilepix
import (
"errors"
"fmt"
"github.com/faiface/pixel"
log "github.com/sirupsen/logrus"
)
/*
_____ _ _ _
|_ _(_) |___| | __ _ _ _ ___ _ _
| | | | / -_) |__/ _` | || / -_) '_|
|_| |_|_\___|____\__,_|\_, \___|_|
|__/
*/
// TileLayer is a TMX file structure which can hold any type of Tiled layer.
type TileLayer struct {
Name string `xml:"name,attr"`
Opacity float32 `xml:"opacity,attr"`
OffSetX float64 `xml:"offsetx,attr"`
OffSetY float64 `xml:"offsety,attr"`
Visible bool `xml:"visible,attr"`
Properties []*Property `xml:"properties>property"`
Data Data `xml:"data"`
// DecodedTiles is the attribute you should use instead of `Data`.
// Tile entry at (x,y) is obtained using l.DecodedTiles[y*map.Width+x].
DecodedTiles []*DecodedTile
// Tileset is only set when the layer uses a single tileset and NilLayer is false.
Tileset *Tileset
// Empty should be set when all entries of the layer are NilTile.
Empty bool
Batch_ *pixel.Batch
IsDirty bool
StaticBool bool
// parentMap is the map which contains this object
parentMap *Map
}
// Batch returns the batch with the picture data from the tileset associated with this layer.
func (l *TileLayer) Batch() (*pixel.Batch, error) {
if l.Batch_ == nil {
log.Debug("TileLayer.Batch: Batch_ not initialised, creating")
if l.Tileset == nil {
err := errors.New("cannot create sprite from nil tileset")
log.WithError(err).Error("TileLayer.Batch: layers' tileset is nil")
return nil, err
}
pictureData := l.Tileset.setSprite()
l.Batch_ = pixel.NewBatch(&pixel.TrianglesData{}, pictureData)
}
l.Batch_.Clear()
return l.Batch_, nil
}
// Draw will use the TileLayers' batch to draw all tiles within the TileLayer to the target.
func (l *TileLayer) Draw(target pixel.Target) error {
// Only draw if the layer is dirty.
if l.IsDirty {
// Initialise the Batch_
if _, err := l.Batch(); err != nil {
log.WithError(err).Error("TileLayer.Draw: could not get Batch_")
return err
}
ts := l.Tileset
numRows := ts.Tilecount / ts.Columns
// Loop through each decoded tile
for tileIndex, tile := range l.DecodedTiles {
// The Y component of the offset is set in Tiled from top down, setting here to negative because we want
// from the bottom up.
layerOffset := pixel.V(l.OffSetX, -l.OffSetY)
tile.Draw(tileIndex, ts.Columns, numRows, ts, l.Batch_, layerOffset)
}
// Batch is drawn to, layer is no longer dirty.
l.SetDirty(false)
}
l.Batch_.Draw(target)
// Reset the dirty flag if the layer is not StaticBool
if !l.StaticBool {
l.SetDirty(true)
}
return nil
}
// SetDirty will update the TileLayers' `dirty` property. If true, this will cause the TileLayers' batch be cleared and
// re-drawn next time `TileLayer.Draw` is called.
func (l *TileLayer) SetDirty(newVal bool) {
log.WithField("Dirty", newVal).Trace("TileLayer.SetDirty: setting dirty property")
l.IsDirty = newVal
}
// SetStatic will update the TileLayers' `static` property. If false, this will set the dirty property to true each
// time after `TileLayer.Draw` is called, so that the layer is drawn everytime.
func (l *TileLayer) SetStatic(newVal bool) {
log.WithField("Static", newVal).Debug("TileLayer.SetStatic: setting static property")
l.StaticBool = newVal
}
func (l *TileLayer) String() string {
return fmt.Sprintf("TileLayer{Name: '%s', Properties: %v, TileCount: %d}", l.Name, l.Properties, len(l.DecodedTiles))
}
func (l *TileLayer) decode(width, height int) ([]GID, error) {
log.WithField("Encoding", l.Data.Encoding).Debug("TileLayer.decode: determining encoding")
l.SetStatic(true)
l.SetDirty(true)
if l.Tileset != nil {
l.Tileset.setSprite()
}
switch l.Data.Encoding {
case "csv":
return l.decodeLayerCSV(width, height)
case "base64":
return l.decodeLayerBase64(width, height)
case "":
// XML "encoding"
return l.decodeLayerXML(width, height)
}
log.WithError(ErrUnknownEncoding).Error("TileLayer.decode: unrecognised encoding")
return nil, ErrUnknownEncoding
}
func (l *TileLayer) decodeLayerXML(width, height int) ([]GID, error) {
if len(l.Data.DataTiles) != width*height {
log.WithError(ErrInvalidDecodedDataLen).WithFields(log.Fields{"Length datatiles": len(l.Data.DataTiles), "W*H": width * height}).Error("TileLayer.decodeLayerXML: data length mismatch")
return nil, ErrInvalidDecodedDataLen
}
gids := make([]GID, len(l.Data.DataTiles))
for i := 0; i < len(gids); i++ {
gids[i] = l.Data.DataTiles[i].GID
}
return gids, nil
}
func (l *TileLayer) decodeLayerCSV(width, height int) ([]GID, error) {
gids, err := l.Data.decodeCSV()
if err != nil {
log.WithError(err).Error("TileLayer.decodeLayerCSV: could not decode CSV")
return nil, err
}
if len(gids) != width*height {
log.WithError(ErrInvalidDecodedDataLen).WithFields(log.Fields{"Length GIDSs": len(gids), "W*H": width * height}).Error("TileLayer.decodeLayerCSV: data length mismatch")
return nil, ErrInvalidDecodedDataLen
}
return gids, nil
}
func (l *TileLayer) decodeLayerBase64(width, height int) ([]GID, error) {
dataBytes, err := l.Data.decodeBase64()
if err != nil {
log.WithError(err).Error("TileLayer.decodeLayerBase64: could not decode base64")
return nil, err
}
if len(dataBytes) != width*height*4 {
log.WithError(ErrInvalidDecodedDataLen).WithFields(log.Fields{"Length databytes": len(dataBytes), "W*H": width * height}).Error("TileLayer.decodeLayerBase64: data length mismatch")
return nil, ErrInvalidDecodedDataLen
}
gids := make([]GID, width*height)
j := 0
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
gid := GID(dataBytes[j]) +
GID(dataBytes[j+1])<<8 +
GID(dataBytes[j+2])<<16 +
GID(dataBytes[j+3])<<24
j += 4
gids[y*width+x] = gid
}
}
return gids, nil
}
func (l *TileLayer) setParent(m *Map) {
l.parentMap = m
for _, p := range l.Properties {
p.setParent(m)
}
for _, dt := range l.DecodedTiles {
dt.setParent(m)
}
if l.Tileset != nil {
l.Tileset.setParent(m)
}
}
<file_sep>/map_test.go
package tilepix_test
import (
"image/color"
"os"
"testing"
_ "image/png"
"github.com/faiface/pixel"
"github.com/faiface/pixel/pixelgl"
"github.com/steelx/tilepix"
)
func TestMain(m *testing.M) {
pixelgl.Run(func() {
os.Exit(m.Run())
})
}
func TestGetLayerByName(t *testing.T) {
m, err := tilepix.ReadFile("testdata/poly.tmx")
if err != nil {
t.Fatal(err)
}
layer := m.GetTileLayerByName("Tile Layer 1")
if layer.Name != "Tile Layer 1" {
t.Error("error get layer")
}
}
func TestGetObjectLayerByName(t *testing.T) {
m, err := tilepix.ReadFile("testdata/poly.tmx")
if err != nil {
t.Fatal(err)
}
layer := m.GetObjectLayerByName("Object Layer 1")
if layer.Name != "Object Layer 1" {
t.Error("error get object layer")
}
}
func TestGetObjectByName(t *testing.T) {
m, err := tilepix.ReadFile("testdata/poly.tmx")
if err != nil {
t.Fatal(err)
}
objs := m.GetObjectByName("Polygon")
if len(objs) != 1 {
t.Error("error invalid objects found")
}
for _, obj := range objs {
if obj.Name != "Polygon" {
t.Error("error get object by name")
}
}
}
func TestBounds(t *testing.T) {
m, err := tilepix.ReadFile("testdata/poly.tmx")
if err != nil {
t.Fatal(err)
}
rect := m.Bounds()
if rect.H() != 256 {
t.Error("error height bound invalid")
}
if rect.W() != 256 {
t.Error("error width bound invalid")
}
}
func TestCentre(t *testing.T) {
m, err := tilepix.ReadFile("testdata/poly.tmx")
if err != nil {
t.Fatal(err)
}
centre := m.Centre()
if centre.X != 128 {
t.Error("error centre X invalid")
}
if centre.Y != 128 {
t.Error("error centre Y invalid")
}
}
func TestMap_GenerateTileObjectLayer(t *testing.T) {
m, err := tilepix.ReadFile("testdata/tileobjectgroups.tmx")
if err != nil {
t.Fatal(err)
}
if err := m.GenerateTileObjectLayer(); err != nil {
t.Fatal(err)
}
const objectLayerName = "singleWhite-objectgroup"
l := m.GetObjectLayerByName(objectLayerName)
if l == nil {
t.Fatalf("no object group by name '%s", objectLayerName)
}
if len(l.Objects) != 5 {
t.Fatalf("Expected 5 objects, got %d", len(l.Objects))
}
expectedPos := [...]pixel.Rect{
pixel.R(16, 144, 48, 176),
pixel.R(48, 144, 80, 176),
pixel.R(80, 144, 112, 176),
pixel.R(112, 144, 144, 176),
pixel.R(144, 144, 176, 176),
}
for i, obj := range l.Objects {
r, err := obj.GetRect()
if err != nil {
t.Fatal(err)
}
expR := expectedPos[i]
if !r.Max.Eq(expR.Max) || !r.Min.Eq(expR.Min) {
t.Fatalf("Mismatching objects, expected %v, got %v", expR, r)
}
}
}
func TestMap_DrawAll(t *testing.T) {
m, err := tilepix.ReadFile("examples/t1.tmx")
if err != nil {
t.Fatalf("Could not create TilePix map: %v", err)
}
target, err := pixelgl.NewWindow(pixelgl.WindowConfig{Bounds: pixel.R(0, 0, 100, 100)})
if err != nil {
t.Fatal(err)
}
if err := m.DrawAll(target, color.Transparent, pixel.IM); err != nil {
t.Fatalf("Could not draw map: %v", err)
}
}
func BenchmarkMap_DrawAll(b *testing.B) {
m, err := tilepix.ReadFile("examples/t1.tmx")
if err != nil {
b.Fatalf("Could not create TilePix map: %v", err)
}
target, err := pixelgl.NewWindow(pixelgl.WindowConfig{Bounds: pixel.R(0, 0, 100, 100)})
if err != nil {
b.Fatal(err)
}
// Run as sub benchmark to prevent multiple windows being created
b.Run("Drawing", func(bb *testing.B) {
for i := 0; i < bb.N; i++ {
_ = m.DrawAll(target, color.Transparent, pixel.IM)
}
})
}
<file_sep>/object_i_test.go
package tilepix_test
import (
"reflect"
"testing"
// Required to decode PNG for object tile testing
_ "image/png"
"github.com/faiface/pixel"
"github.com/steelx/tilepix"
)
func TestObject_GetEllipse(t *testing.T) {
m, err := tilepix.ReadFile("testdata/ellipse.tmx")
if err != nil {
t.Fatal(err)
}
o := m.GetObjectLayerByName("Object Layer 1").Objects[0]
tests := []struct {
name string
object *tilepix.Object
want pixel.Circle
wantErr bool
}{
{
name: "getting ellipse",
object: o,
want: pixel.C(pixel.V(50, 150), 100),
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := o.GetEllipse()
if (err != nil) != tt.wantErr {
t.Errorf("Object.GetEllipse() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("Object.GetEllipse() = %v, want %v", got, tt.want)
}
})
}
}
func TestObject_GetPoint(t *testing.T) {
m, err := tilepix.ReadFile("testdata/point.tmx")
if err != nil {
t.Fatal(err)
}
o := m.GetObjectLayerByName("Object Layer 1").Objects[0]
tests := []struct {
name string
object *tilepix.Object
want pixel.Vec
wantErr bool
}{
{
name: "getting point",
object: o,
want: pixel.V(160, 160),
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := o.GetPoint()
if (err != nil) != tt.wantErr {
t.Errorf("Object.GetPoint() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("Object.GetPoint() = %v, want %v", got, tt.want)
}
})
}
}
func TestObject_GetRect(t *testing.T) {
m, err := tilepix.ReadFile("testdata/rectangle.tmx")
if err != nil {
t.Fatal(err)
}
o := m.GetObjectLayerByName("Object Layer 1").Objects[0]
tests := []struct {
name string
object *tilepix.Object
want pixel.Rect
wantErr bool
}{
{
name: "getting rectangle",
object: o,
want: pixel.R(0, 0, 100, 100),
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := o.GetRect()
if (err != nil) != tt.wantErr {
t.Errorf("Object.GetRect() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("Object.GetRect() = %v, want %v", got, tt.want)
}
})
}
}
func TestObject_GetPolygon(t *testing.T) {
m, err := tilepix.ReadFile("testdata/poly.tmx")
if err != nil {
t.Fatal(err)
}
o := m.GetObjectLayerByName("Object Layer 1").Objects[0]
tests := []struct {
name string
object *tilepix.Object
want []pixel.Vec
wantErr bool
}{
{
name: "getting polygon",
object: o,
want: []pixel.Vec{
pixel.V(0, 256),
pixel.V(2, 165),
pixel.V(100, 202),
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := o.GetPolygon()
if (err != nil) != tt.wantErr {
t.Errorf("Object.GetPolygon() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("Object.GetPolygon() = %v, want %v", got, tt.want)
}
})
}
}
func TestObject_GetPolyLine(t *testing.T) {
m, err := tilepix.ReadFile("testdata/poly.tmx")
if err != nil {
t.Fatal(err)
}
o := m.GetObjectLayerByName("Object Layer 1").Objects[1]
tests := []struct {
name string
object *tilepix.Object
want []pixel.Vec
wantErr bool
}{
{
name: "getting polyline",
object: o,
want: []pixel.Vec{
pixel.V(0, 256),
pixel.V(-46, 202),
pixel.V(-1, 179),
pixel.V(-43, 142),
pixel.V(5, 102),
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := o.GetPolyLine()
if (err != nil) != tt.wantErr {
t.Errorf("Object.GetPolyLine() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("Object.GetPolyLine() = %v, want %v", got, tt.want)
}
})
}
}
func TestObjectProperties(t *testing.T) {
m, err := tilepix.ReadFile("testdata/poly.tmx")
if err != nil {
t.Fatal(err)
}
var foundProperty bool
for _, group := range m.ObjectGroups {
for _, object := range group.Objects {
if object.Properties[0].Name != "foo" {
t.Error("No properties")
}
foundProperty = true
}
}
if !foundProperty {
t.Fatal("No property found")
}
}
func TestObject_GetTile(t *testing.T) {
m, err := tilepix.ReadFile("testdata/tileobject.tmx")
if err != nil {
t.Fatal(err)
}
o := m.GetObjectLayerByName("Object Layer 1").Objects[0]
tests := []struct {
name string
object *tilepix.Object
want *tilepix.DecodedTile
wantErr bool
}{
{
name: "getting tile",
object: o,
want: &tilepix.DecodedTile{
ID: 1,
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := o.GetTile()
if (err != nil) != tt.wantErr {
t.Errorf("Object.GetTile() error = %v, wantErr %v", err, tt.wantErr)
return
}
if err != nil {
return
}
if got.ID != tt.want.ID ||
got.HorizontalFlip != tt.want.HorizontalFlip ||
got.VerticalFlip != tt.want.VerticalFlip ||
got.DiagonalFlip != tt.want.DiagonalFlip ||
got.Nil != tt.want.Nil {
t.Errorf("Object.GetTile() = %v, want %v", got, tt.want)
}
})
}
}
<file_sep>/tile.go
package tilepix
import (
"fmt"
"math"
"github.com/faiface/pixel"
)
/*
_____ _ _
|_ _(_) |___
| | | | / -_)
|_| |_|_\___|
*/
// Tile is a TMX file structure which holds a Tiled tile.
type Tile struct {
ID ID `xml:"id,attr"`
Image *Image `xml:"image"`
// ObjectGroup is set if objects have been added to individual sprites in Tiled.
ObjectGroup *ObjectGroup `xml:"objectgroup,omitempty"`
// parentMap is the map which contains this object
parentMap *Map
}
func (t *Tile) String() string {
return fmt.Sprintf("Tile{ID: %d}", t.ID)
}
func (t *Tile) setParent(m *Map) {
t.parentMap = m
if t.Image != nil {
t.Image.setParent(m)
}
}
// DecodedTile is a convenience struct, which stores the decoded data from a Tile.
type DecodedTile struct {
ID ID
Tileset *Tileset
HorizontalFlip bool
VerticalFlip bool
DiagonalFlip bool
Nil bool
sprite *pixel.Sprite
transform pixel.Matrix
// parentMap is the map which contains this object
parentMap *Map
}
// Draw will draw the tile to the target provided. This will calculate the sprite from the provided tileset and set the
// DecodedTiles' internal `sprite` property; this is so it is only calculated the first time.
func (t *DecodedTile) Draw(ind, columns, numRows int, ts *Tileset, target pixel.Target, offset pixel.Vec) {
if t.IsNil() {
return
}
if t.sprite == nil {
t.setSprite(columns, numRows, ts)
// Calculate the framing for the tile within its tileset's source image
pos := t.Position(ind, ts)
transform := pixel.IM.Moved(pos)
if t.DiagonalFlip {
transform = transform.Rotated(pos, math.Pi/2)
transform = transform.ScaledXY(pos, pixel.V(1, -1))
}
if t.HorizontalFlip {
transform = transform.ScaledXY(pos, pixel.V(-1, 1))
}
if t.VerticalFlip {
transform = transform.ScaledXY(pos, pixel.V(1, -1))
}
t.transform = transform
}
t.sprite.Draw(target, t.transform.Moved(offset))
}
// Position returns the relative game position.
func (t DecodedTile) Position(ind int, ts *Tileset) pixel.Vec {
gamePos := indexToGamePos(ind, t.parentMap.Width, t.parentMap.Height)
return gamePos.ScaledXY(pixel.V(float64(ts.TileWidth), float64(ts.TileHeight))).Add(pixel.V(float64(ts.TileWidth), float64(ts.TileHeight)).Scaled(0.5))
}
func (t *DecodedTile) String() string {
return fmt.Sprintf("DecodedTile{ID: %d, Is nil: %t}", t.ID, t.Nil)
}
// IsNil returns whether this tile is nil. If so, it means there is nothing set for the tile, and should be skipped in
// drawing.
func (t *DecodedTile) IsNil() bool {
return t.Nil
}
func (t *DecodedTile) setParent(m *Map) {
t.parentMap = m
}
func (t *DecodedTile) setSprite(columns, numRows int, ts *Tileset) {
if t.IsNil() {
return
}
if t.sprite == nil {
// Calculate the framing for the tile within its tileset's source image
x, y := tileIDToCoord(t.ID, columns, numRows)
iX := float64(x)*float64(ts.TileWidth) + float64(ts.Margin+ts.Spacing*(x-1))
fX := iX + float64(ts.TileWidth)
iY := float64(y)*float64(ts.TileHeight) + float64(ts.Margin+ts.Spacing*(y-1))
fY := iY + float64(ts.TileHeight)
t.sprite = pixel.NewSprite(ts.setSprite(), pixel.R(iX, iY, fX, fY))
}
}
<file_sep>/tileset.go
package tilepix
import (
"encoding/xml"
"fmt"
"io"
"os"
"path/filepath"
"github.com/faiface/pixel"
log "github.com/sirupsen/logrus"
)
/*
_____ _ _ _
|_ _(_) |___ ___ ___| |_
| | | | / -_|_-</ -_) _|
|_| |_|_\___/__/\___|\__|
*/
// Tileset is a TMX file structure which represents a Tiled Tileset
type Tileset struct {
FirstGID GID `xml:"firstgid,attr"`
Source string `xml:"source,attr"`
Name string `xml:"name,attr"`
TileWidth int `xml:"tilewidth,attr"`
TileHeight int `xml:"tileheight,attr"`
Spacing int `xml:"spacing,attr"`
Margin int `xml:"margin,attr"`
Properties []*Property `xml:"properties>property"`
Image *Image `xml:"image"`
Tiles []*Tile `xml:"tile"`
Tilecount int `xml:"tilecount,attr"`
Columns int `xml:"columns,attr"`
sprite *pixel.Sprite
picture pixel.Picture
// parentMap is the map which contains this object
parentMap *Map
// dir is the directory the tsx file is located in. This is used to access assets via a relative path.
dir string
}
func readTileset(r io.Reader, dir string) (*Tileset, error) {
log.Debug("readTileset: reading from io.Reader")
d := xml.NewDecoder(r)
var t Tileset
if err := d.Decode(&t); err != nil {
log.WithError(err).Error("readTileset: could not decode to Tileset")
return nil, err
}
t.dir = dir
return validate(t)
}
func readTilesetFile(filePath string) (*Tileset, error) {
log.WithField("Filepath", filePath).Debug("readTilesetFile: reading file")
f, err := os.Open(filePath)
if err != nil {
log.WithError(err).Error("ReadFile: could not open file")
return nil, err
}
defer f.Close()
dir := filepath.Dir(filePath)
return readTileset(f, dir)
}
// GenerateTileObjectLayer will create a new ObjectGroup for the mapping of Objects to individual tiles.
func (ts Tileset) GenerateTileObjectLayer(tileLayers []*TileLayer) ObjectGroup {
group := ObjectGroup{Name: fmt.Sprintf("%s-objectgroup", ts.Name)}
objs := ts.TileObjects()
// Loop all TileLayers in map.
for _, tl := range tileLayers {
// Loop all DecodedTiles in the TileLayer
for ind, t := range tl.DecodedTiles {
if t.Nil {
// Skip blank tiles.
continue
}
// Try get the Tiles' ObjectGroup.
og, ok := objs[t.ID]
if !ok {
// Not object groups for this Tile.
continue
}
// Loop all objects in the Tiles' ObjectGroup.
for _, obs := range og.Objects {
// Create a new Object based on the relative position of the Object and the DecodedTile.
o := *obs
tilePos := t.Position(ind, &ts)
o.X += tilePos.X
o.Y += tilePos.Y
group.Objects = append(group.Objects, &o)
}
}
}
return group
}
func validate(t Tileset) (*Tileset, error) {
if t.Columns < 1 {
return nil, fmt.Errorf("Tileset columns value not valid")
}
return &t, nil
}
func (ts *Tileset) String() string {
return fmt.Sprintf(
"TileSet{Name: %s, Tile size: %dx%d, Tile spacing: %d, Tilecount: %d, Properties: %v}",
ts.Name,
ts.TileWidth,
ts.TileHeight,
ts.Spacing,
ts.Tilecount,
ts.Properties,
)
}
func (ts *Tileset) setParent(m *Map) {
ts.parentMap = m
for _, p := range ts.Properties {
p.setParent(m)
}
for _, t := range ts.Tiles {
t.setParent(m)
}
if ts.Image != nil {
ts.Image.setParent(m)
}
}
func (ts *Tileset) setSprite() pixel.Picture {
if ts.sprite != nil {
// Return if sprite already set
return ts.picture
}
dir := ts.dir
if dir == "" {
dir = ts.parentMap.dir
}
sprite, pictureData, err := loadSpriteFromFile(filepath.Join(dir, ts.Image.Source))
if err != nil {
log.WithField("Filepath", filepath.Join(dir, ts.Image.Source)).WithError(err).Error("Tileset.setSprite: could not load sprite from file")
return nil
}
ts.sprite = sprite
ts.picture = pictureData
return ts.picture
}
// TileObjects will return all ObjectGroups contained in Tiles.
func (ts Tileset) TileObjects() map[ID]*ObjectGroup {
objs := make(map[ID]*ObjectGroup)
for _, t := range ts.Tiles {
if t.ObjectGroup != nil {
objs[t.ID] = t.ObjectGroup
}
}
return objs
}
func getTileset(l *TileLayer) (tileset *Tileset, isEmpty, usesMultipleTilesets bool) {
for _, tile := range l.DecodedTiles {
if !tile.Nil {
if tileset == nil {
tileset = tile.Tileset
} else if tileset != tile.Tileset {
return tileset, false, true
}
}
}
if tileset == nil {
return nil, true, false
}
return tileset, false, false
}
<file_sep>/tilepix_test.go
package tilepix_test
import (
"bytes"
"encoding/xml"
"io"
"io/ioutil"
"testing"
"github.com/steelx/tilepix"
log "github.com/sirupsen/logrus"
)
func init() {
log.SetOutput(ioutil.Discard)
}
func TestReadFile(t *testing.T) {
tests := []struct {
name string
filepath string
want *tilepix.Map
wantErr bool
}{
{
name: "base64",
filepath: "testdata/base64.tmx",
want: nil,
wantErr: false,
},
{
name: "base64-zlib",
filepath: "testdata/base64-zlib.tmx",
want: nil,
wantErr: false,
},
{
name: "base64-gzip",
filepath: "testdata/base64-gzip.tmx",
want: nil,
wantErr: false,
},
{
name: "csv",
filepath: "testdata/csv.tmx",
want: nil,
wantErr: false,
},
{
name: "xml",
filepath: "testdata/xml.tmx",
want: nil,
wantErr: false,
},
{
name: "missing file",
filepath: "testdata/foo.tmx",
want: nil,
wantErr: true,
},
{
name: "map is infinite",
filepath: "testdata/infinite.tmx",
want: nil,
wantErr: true,
},
{
name: "external tileset",
filepath: "testdata/external_tileset.tmx",
want: nil,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := tilepix.ReadFile(tt.filepath)
if !tt.wantErr && err != nil {
t.Errorf("tmx.ReadFile(): got unexpected error: %v", err)
}
if tt.wantErr && err == nil {
t.Errorf("tmx.ReadFile(): expected error but not nil")
}
})
}
}
func TestRead(t *testing.T) {
tests := []struct {
name string
input io.Reader
dir string
want *tilepix.Map
wantErr bool
expectedErr string
}{
{
name: "Missing columns parameter in tileset",
input: getInput(),
dir: "testdata",
want: nil,
wantErr: true,
expectedErr: "Tileset columns value not valid",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := tilepix.Read(tt.input, tt.dir)
if tt.wantErr && err == nil {
t.Errorf("tsx.Read: expected error but not nil")
}
if tt.wantErr && err != nil && err.Error() != tt.expectedErr {
t.Errorf("tsx.Read: expected error '%s' but not '%s'", tt.expectedErr, err.Error())
}
})
}
}
func getInput() io.Reader {
m := tilepix.Map{
Version: "1.2",
Orientation: "orthogonal",
Width: 640,
Height: 480,
TileWidth: 32,
TileHeight: 32,
Tilesets: []*tilepix.Tileset{
&tilepix.Tileset{
Source: "tileset_no_columns.tsx",
},
},
}
byteMap, _ := xml.Marshal(m)
return bytes.NewReader(byteMap)
}
<file_sep>/examples/basics/basics.go
package main
import (
"image/color"
"math"
"time"
_ "image/png"
"github.com/steelx/tilepix"
"github.com/faiface/pixel"
"github.com/faiface/pixel/pixelgl"
)
var (
winBounds = pixel.R(0, 0, 800, 600)
camPos = pixel.ZV
camSpeed = 64.0
camZoom = 1.0
camZoomSpeed = 1.2
)
func run() {
m, err := tilepix.ReadFile("map.tmx")
if err != nil {
panic(err)
}
cfg := pixelgl.WindowConfig{
Title: "TilePix basics",
Bounds: winBounds,
VSync: true,
}
win, err := pixelgl.NewWindow(cfg)
if err != nil {
panic(err)
}
last := time.Now()
for !win.Closed() {
win.Clear(color.White)
dt := time.Since(last).Seconds()
last = time.Now()
cam := pixel.IM.Scaled(camPos.Add(winBounds.Center()), camZoom).Moved(pixel.ZV.Sub(camPos))
win.SetMatrix(cam)
if win.Pressed(pixelgl.KeyA) || win.Pressed(pixelgl.KeyLeft) {
camPos.X -= camSpeed * dt
}
if win.Pressed(pixelgl.KeyD) || win.Pressed(pixelgl.KeyRight) {
camPos.X += camSpeed * dt
}
if win.Pressed(pixelgl.KeyS) || win.Pressed(pixelgl.KeyDown) {
camPos.Y -= camSpeed * dt
}
if win.Pressed(pixelgl.KeyW) || win.Pressed(pixelgl.KeyUp) {
camPos.Y += camSpeed * dt
}
camZoom *= math.Pow(camZoomSpeed, win.MouseScroll().Y)
m.DrawAll(win, color.Transparent, pixel.IM) // nolint: errcheck
win.Update()
}
}
func main() {
pixelgl.Run(run)
}
<file_sep>/map.go
package tilepix
import (
"fmt"
"image/color"
"github.com/faiface/pixel"
"github.com/faiface/pixel/pixelgl"
log "github.com/sirupsen/logrus"
)
/*
__ __
| \/ |__ _ _ __
| |\/| / _` | '_ \
|_| |_\__,_| .__/
|_|
*/
// Map is a TMX file structure representing the map as a whole.
type Map struct {
Version string `xml:"title,attr"`
Orientation string `xml:"orientation,attr"`
// Width is the number of tiles - not the width in pixels
Width int `xml:"width,attr"`
// Height is the number of tiles - not the height in pixels
Height int `xml:"height,attr"`
TileWidth int `xml:"tilewidth,attr"`
TileHeight int `xml:"tileheight,attr"`
Properties []*Property `xml:"properties>property"`
Tilesets []*Tileset `xml:"tileset"`
TileLayers []*TileLayer `xml:"layer"`
ObjectGroups []*ObjectGroup `xml:"objectgroup"`
Infinite bool `xml:"infinite,attr"`
ImageLayers []*ImageLayer `xml:"imagelayer"`
Canvas_ *pixelgl.Canvas
// dir is the directory the tmx file is located in. This is used to access images for tilesets via a relative path.
dir string
}
// DrawAll will draw all tile layers and image layers to the target.
// Tile layers are first draw to their own `pixel.Batch`s for efficiency.
// All layers are drawn to a `pixel.Canvas` before being drawn to the target.
//
// - target - The target to draw layers to.
// - clearColour - The colour to clear the maps' canvas before drawing.
// - mat - The matrix to draw the canvas to the target with.
func (m *Map) DrawAll(target pixel.Target, clearColour color.Color, mat pixel.Matrix) error {
if m.Canvas_ == nil {
m.Canvas_ = pixelgl.NewCanvas(m.Bounds())
}
m.Canvas_.Clear(clearColour)
for _, l := range m.TileLayers {
if err := l.Draw(m.Canvas_); err != nil {
log.WithError(err).Error("Map.DrawAll: could not draw layer")
return err
}
}
for _, il := range m.ImageLayers {
// The matrix shift is because images are drawn from the top-left in Tiled.
if err := il.Draw(m.Canvas_, pixel.IM.Moved(pixel.V(0, m.pixelHeight()))); err != nil {
log.WithError(err).Error("Map.DrawAll: could not draw image layer")
return err
}
}
m.Canvas_.Draw(target, mat.Moved(m.Bounds().Center()))
return nil
}
// GenerateTileObjectLayer will create an object layer which contains all objects as defined by individual tiles.
func (m *Map) GenerateTileObjectLayer() error {
for _, ts := range m.Tilesets {
objGroup := ts.GenerateTileObjectLayer(m.TileLayers)
if err := objGroup.decode(); err != nil {
log.WithField("ObjectGroup", objGroup).WithError(err).Error("Map.GenerateTileObjectLayer: could not deccode object group")
return err
}
m.ObjectGroups = append(m.ObjectGroups, &objGroup)
}
return nil
}
// GetImageLayerByName returns a Map's ImageLayer by its name
func (m *Map) GetImageLayerByName(name string) *ImageLayer {
for _, l := range m.ImageLayers {
if l.Name == name {
return l
}
}
return nil
}
// GetObjectLayerByName returns a Map's ObjectGroup by its name
func (m *Map) GetObjectLayerByName(name string) *ObjectGroup {
for _, l := range m.ObjectGroups {
if l.Name == name {
return l
}
}
return nil
}
// GetTileLayerByName returns a Map's TileLayer by its name
func (m *Map) GetTileLayerByName(name string) *TileLayer {
for _, l := range m.TileLayers {
if l.Name == name {
return l
}
}
return nil
}
// GetObjectByName returns the Maps' Objects by their name
func (m *Map) GetObjectByName(name string) []*Object {
var objs []*Object
for _, og := range m.ObjectGroups {
objs = append(objs, og.GetObjectByName(name)...)
}
return objs
}
func (m *Map) String() string {
return fmt.Sprintf(
"Map{Version: %s, Tile dimensions: %dx%d, Properties: %v, Tilesets: %v, TileLayers: %v, Object layers: %v, Image layers: %v}",
m.Version,
m.Width,
m.Height,
m.Properties,
m.Tilesets,
m.TileLayers,
m.ObjectGroups,
m.ImageLayers,
)
}
// Bounds will return a pixel rectangle representing the width-height in pixels.
func (m *Map) Bounds() pixel.Rect {
return pixel.R(0, 0, m.pixelWidth(), m.pixelHeight())
}
// Centre will return a pixel vector reprensenting the center of the bounds.
func (m *Map) Centre() pixel.Vec {
return m.Bounds().Center()
}
func (m *Map) pixelWidth() float64 {
return float64(m.Width * m.TileWidth)
}
func (m *Map) pixelHeight() float64 {
return float64(m.Height * m.TileHeight)
}
func (m *Map) decodeGID(gid GID) (*DecodedTile, error) {
if gid == 0 {
return NilTile, nil
}
gidBare := gid &^ gidFlip
for i := len(m.Tilesets) - 1; i >= 0; i-- {
if m.Tilesets[i].FirstGID <= gidBare {
return &DecodedTile{
ID: ID(gidBare - m.Tilesets[i].FirstGID),
Tileset: m.Tilesets[i],
HorizontalFlip: gid&gidHorizontalFlip != 0,
VerticalFlip: gid&gidVerticalFlip != 0,
DiagonalFlip: gid&gidDiagonalFlip != 0,
Nil: false,
}, nil
}
}
log.WithError(ErrInvalidGID).Error("Map.decodeGID: GID is invalid")
return nil, ErrInvalidGID
}
func (m *Map) decodeLayers() error {
// Decode tile layers
for _, l := range m.TileLayers {
gids, err := l.decode(m.Width, m.Height)
if err != nil {
log.WithError(err).Error("Map.decodeLayers: could not decode layer")
return err
}
l.DecodedTiles = make([]*DecodedTile, len(gids))
for j := 0; j < len(gids); j++ {
decTile, err := m.decodeGID(gids[j])
if err != nil {
log.WithError(err).Error("Map.decodeLayers: could not GID")
return err
}
l.DecodedTiles[j] = decTile
}
}
// Decode object layers
for _, og := range m.ObjectGroups {
if err := og.decode(); err != nil {
log.WithError(err).Error("Map.decodeLayers: could not decode Object Group")
return err
}
}
return nil
}
func (m *Map) setParents() {
for _, p := range m.Properties {
p.setParent(m)
}
for _, t := range m.Tilesets {
t.setParent(m)
}
for _, og := range m.ObjectGroups {
og.setParent(m)
}
for _, im := range m.ImageLayers {
im.setParent(m)
}
for _, l := range m.TileLayers {
l.setParent(m)
}
}
<file_sep>/object.go
package tilepix
import (
"fmt"
"github.com/faiface/pixel"
log "github.com/sirupsen/logrus"
)
/*
___ _ _ _
/ _ \| |__ (_)___ __| |_
| (_) | '_ \| / -_) _| _|
\___/|_.__// \___\__|\__|
|__/
*/
// Object is a TMX file struture holding a specific Tiled object.
type Object struct {
Name string `xml:"name,attr"`
Type string `xml:"type,attr"`
X float64 `xml:"x,attr"`
Y float64 `xml:"y,attr"`
Width float64 `xml:"width,attr"`
Height float64 `xml:"height,attr"`
GID ID `xml:"gid,attr"`
ID ID `xml:"id,attr"`
Visible bool `xml:"visible,attr"`
Polygon *Polygon `xml:"polygon"`
PolyLine *PolyLine `xml:"polyline"`
Properties []*Property `xml:"properties>property"`
Ellipse *struct{} `xml:"ellipse"`
Point *struct{} `xml:"point"`
objectType ObjectType
tile *DecodedTile
// parentMap is the map which contains this object
parentMap *Map
}
// GetEllipse will return a pixel.Circle representation of this object relative to the map (the co-ordinates will match
// those as drawn in Tiled). If the object type is not `EllipseObj` this function will return `pixel.C(pixel.ZV, 0)`
// and an error.
//
// Because there is no pixel geometry code for irregular ellipses, this function will average the width and height of
// the ellipse object from the TMX file, and return a regular circle about the centre of the ellipse.
func (o *Object) GetEllipse() (pixel.Circle, error) {
if o.GetType() != EllipseObj {
log.WithError(ErrInvalidObjectType).WithField("Object type", o.GetType()).Error("Object.GetEllipse: object type mismatch")
return pixel.C(pixel.ZV, 0), ErrInvalidObjectType
}
// In TMX files, ellipses are defined by the containing rectangle. The X, Y positions are the bottom-left (after we
// have flipped them).
// Because Pixel does not support irregular ellipses, we take the average of width and height.
radius := (o.Width + o.Height) / 4
// The centre should be the same as the ellipses drawn in Tiled, this will make outputs more intuitive.
centre := pixel.V(o.X+(o.Width/2), o.Y+(o.Height/2))
return pixel.C(centre, radius), nil
}
// GetPoint will return a pixel.Vec representation of this object relative to the map (the co-ordinates will match those
// as drawn in Tiled). If the object type is not `PointObj` this function will return `pixel.ZV` and an error.
func (o *Object) GetPoint() (pixel.Vec, error) {
if o.GetType() != PointObj {
log.WithError(ErrInvalidObjectType).WithField("Object type", o.GetType()).Error("Object.GetPoint: object type mismatch")
return pixel.ZV, ErrInvalidObjectType
}
return pixel.V(o.X, o.Y), nil
}
// GetRect will return a pixel.Rect representation of this object relative to the map (the co-ordinates will match those
// as drawn in Tiled). If the object type is not `RectangleObj` this function will return `pixel.R(0, 0, 0, 0)` and an
// error.
func (o *Object) GetRect() (pixel.Rect, error) {
if o.GetType() != RectangleObj {
log.WithError(ErrInvalidObjectType).WithField("Object type", o.GetType()).Error("Object.GetRect: object type mismatch")
return pixel.R(0, 0, 0, 0), ErrInvalidObjectType
}
return pixel.R(o.X, o.Y, o.X+o.Width, o.Y+o.Height), nil
}
// GetPolygon will return a pixel.Vec slice representation of this object relative to the map (the co-ordinates will match
// those as drawn in Tiled). If the object type is not `PolygonObj` this function will return `nil` and an error.
func (o *Object) GetPolygon() ([]pixel.Vec, error) {
if o.GetType() != PolygonObj {
log.WithError(ErrInvalidObjectType).WithField("Object type", o.GetType()).Error("Object.GetPolygon: object type mismatch")
return nil, ErrInvalidObjectType
}
points, err := o.Polygon.Decode()
if err != nil {
log.WithError(err).Error("Object.GetPolygon: could not decode Polygon")
return nil, err
}
var pixelPoints []pixel.Vec
for _, p := range points {
pixelPoints = append(pixelPoints, p.V())
}
return pixelPoints, nil
}
// GetPolyLine will return a pixel.Vec slice representation of this object relative to the map (the co-ordinates will match
// those as drawn in Tiled). If the object type is not `PolylineObj` this function will return `nil` and an error.
func (o *Object) GetPolyLine() ([]pixel.Vec, error) {
if o.GetType() != PolylineObj {
log.WithError(ErrInvalidObjectType).WithField("Object type", o.GetType()).Error("Object.GetPolyLine: object type mismatch")
return nil, ErrInvalidObjectType
}
points, err := o.PolyLine.Decode()
if err != nil {
log.WithError(err).Error("Object.GetPolyLine: could not decode Polyline")
return nil, err
}
var pixelPoints []pixel.Vec
for _, p := range points {
pixelPoints = append(pixelPoints, p.V())
}
return pixelPoints, nil
}
// GetTile will return the object decoded into a DecodedTile struct. If this
// object is not a DecodedTile, this function will return `nil` and an error.
func (o *Object) GetTile() (*DecodedTile, error) {
if o.GetType() != TileObj {
log.WithError(ErrInvalidObjectType).WithField("Object type", o.GetType()).Error("Object.GetTile: object type mismatch")
return nil, ErrInvalidObjectType
}
if o.tile == nil {
// Setting tileset to the first tileset in the map. Will need updating when dealing with multiple
// tilesets.
ts := o.parentMap.Tilesets[0]
o.tile = &DecodedTile{
ID: o.GID,
Tileset: ts,
parentMap: o.parentMap,
}
numRows := ts.Tilecount / ts.Columns
o.tile.setSprite(ts.Columns, numRows, ts)
}
return o.tile, nil
}
// GetType will return the ObjectType constant type of this object.
func (o *Object) GetType() ObjectType {
return o.objectType
}
func (o *Object) String() string {
return fmt.Sprintf("Object{%s, Name: '%s'}", o.objectType, o.Name)
}
func (o *Object) flipY() {
o.Y = o.parentMap.pixelHeight() - o.Y - o.Height
}
// hydrateType will work out what type this object is.
func (o *Object) hydrateType() {
if o.Polygon != nil {
o.objectType = PolygonObj
return
}
if o.PolyLine != nil {
o.objectType = PolylineObj
return
}
if o.Ellipse != nil {
o.objectType = EllipseObj
return
}
if o.Point != nil {
o.objectType = PointObj
return
}
if o.GID != 0 {
o.objectType = TileObj
return
}
o.objectType = RectangleObj
}
func (o *Object) setParent(m *Map) {
o.parentMap = m
if o.Polygon != nil {
o.Polygon.setParent(m)
}
if o.PolyLine != nil {
o.PolyLine.setParent(m)
}
for _, p := range o.Properties {
p.setParent(m)
}
}
|
c8caaff22feced90c43c82fd31e1ae336e9e40bf
|
[
"Go",
"Go Module"
] | 11 |
Go Module
|
steelx/tilepix
|
435012148c0987724745ad058e413bff5f6845cf
|
792426f74b9f43eef35106c3c8e41b14f2c185e0
|
refs/heads/master
|
<file_sep>from flask import Flask, request, jsonify, g
from flask_httpauth import HTTPBasicAuth
from itsdangerous import (
TimedJSONWebSignatureSerializer as Serializer,
BadSignature,
SignatureExpired,
)
# filesystem
from os import listdir, getcwd, path, makedirs
from os.path import isfile, join
import config
app = Flask(__name__)
auth = HTTPBasicAuth()
class FileSystemModel:
def __init__(self, folder):
self.path = folder
def ls(self):
return [f for f in listdir(self.path) if isfile(join(self.path, f))]
def upload(self, f):
f.save(join(self.path, f.filename))
class Session:
APP_SECRET_KEY = "1234567890"
def __init__(self):
self.data = FileSystemModel(join(getcwd(), config.uploadDir))
@staticmethod
def verify_auth_token(token):
s = Serializer(Session.APP_SECRET_KEY)
try:
s.loads(token)
except:
return None
def token(self):
s = Serializer(Session.APP_SECRET_KEY, expires_in=1000)
return s.dumps({"id": 0})
def fileSystem():
return self.data
@auth.verify_password
def verify_password(token, password):
data = Session.verify_auth_token(token)
if not data:
if token == "admin" and password == "<PASSWORD>":
g.session = Session()
return True
else:
return False
else:
return True
@app.route("/api/token")
@auth.login_required
def get_auth_token():
token = g.session.token()
return jsonify({"token": token.decode("ascii")})
@app.route("/api/ls")
@auth.login_required
def list_contents():
files = g.session.data.ls()
return jsonify({"files": files})
@app.route("/api/upload", methods=["POST"])
@auth.login_required
def upload_file():
if "file" in request.files:
print("Found file:", request.files["file"].filename)
g.session.data.upload(request.files["file"])
return ("", 201)
else:
print("file not present in", request.files.to_dict())
return ("", 501)
if __name__ == "__main__":
if not path.exists(config.uploadDir):
makedirs(config.uploadDir)
app.run(debug=True)
<file_sep>serverUrl = 'http://127.0.0.1:5000/api'
uploadDir = 'uploads'
<file_sep>import sys
import config
from PySide2.QtCore import (
Signal,
QAbstractTableModel,
QStandardPaths,
QFile,
QIODevice,
Qt,
QModelIndex,
QMimeDatabase,
QFileInfo,
)
from PySide2.QtGui import QIcon
from PySide2.QtWidgets import (
QDialog,
QWidget,
QFrame,
QFormLayout,
QLineEdit,
QPushButton,
QHBoxLayout,
QVBoxLayout,
QApplication,
QTableView,
QFileDialog,
QHeaderView,
QStyledItemDelegate,
QStyleOptionProgressBar,
QStyle,
QSystemTrayIcon,
QMenu,
QMessageBox,
)
from PySide2.QtNetwork import (
QNetworkAccessManager,
QNetworkReply,
QHttpMultiPart,
QAuthenticator,
QNetworkRequest,
QHttpMultiPart,
QHttpPart,
)
# Delegate for progress column, we want to display a progress bar instead of numbers
class ProgressBarDelegate(QStyledItemDelegate):
def __init__(self, parent=None):
super(ProgressBarDelegate, self).__init__(parent)
def paint(self, painter, option, index):
progress = index.data()
# In case of upload error just show a 'error' string
if progress == UploadingModel.UPLOAD_STATUS_ERROR:
painter.setPen(Qt.red)
painter.drawText(
option.rect, Qt.AlignHCenter | Qt.AlignVCenter, self.tr("Error")
)
return
if progress == UploadingModel.UPLOAD_STATUS_CANCEL:
painter.drawText(
option.rect, Qt.AlignHCenter | Qt.AlignVCenter, self.tr("Canceled")
)
return
progressBarOption = QStyleOptionProgressBar()
progressBarOption.rect = option.rect
progressBarOption.minimum = 0
progressBarOption.maximum = 100
progressBarOption.progress = progress
# If file was uploaded successful show 'Done' in the progress bar text
if progress == UploadingModel.UPLOAD_STATUS_FINISHED:
progressBarOption.text = self.tr("Done")
else:
progressBarOption.text = "%d%%" % progress
progressBarOption.textVisible = True
QApplication.style().drawControl(
QStyle.CE_ProgressBar, progressBarOption, painter
)
# Implement a model to show the active upload jobs
class UploadingModel(QAbstractTableModel):
authenticationRequired = Signal(object)
# Model columns
FILE_COLUMN = 0
PROGRESS_COLUMN = 1
# Job status
UPLOAD_STATUS_CANCEL = -3
UPLOAD_STATUS_ERROR = -2
UPLOAD_STATUS_STARTING = -1
UPLOAD_STATUS_FINISHED = 101
def __init__(self, parent=None):
super(UploadingModel, self).__init__(parent)
self.manager = QNetworkAccessManager(self)
self.manager.authenticationRequired.connect(self.onAuthenticationRequired)
self.manager.finished.connect(self.onUploadFinished)
self.jobs = []
# Start a new upload job
def startUpload(self, filename):
f = QFile(filename)
if not f.open(QIODevice.ReadOnly):
print("Upload file is not readable:", filename)
return
multiPart = QHttpMultiPart(QHttpMultiPart.FormDataType)
filePart = QHttpPart()
info = QFileInfo(f)
db = QMimeDatabase()
filePart.setHeader(
QNetworkRequest.ContentTypeHeader, db.mimeTypeForFile(filename).name()
)
filePart.setHeader(
QNetworkRequest.ContentDispositionHeader,
'form-data; name="file"; filename="' + info.fileName() + '"',
)
filePart.setBodyDevice(f)
multiPart.append(filePart)
request = QNetworkRequest(config.serverUrl + "/upload")
reply = self.manager.post(request, multiPart)
if not reply:
print("Failed to request upload file")
return
if reply.error() != QNetworkReply.NoError:
print("Error uploading file:", reply.error())
return
multiPart.setParent(reply)
reply.uploadProgress.connect(self.onUploadProgressChanged)
actualRowCount = self.rowCount()
self.beginInsertRows(QModelIndex(), actualRowCount, actualRowCount)
self.jobs.append(
{
"file": f,
"reply": reply,
"progress": UploadingModel.UPLOAD_STATUS_STARTING,
}
)
self.endInsertRows()
def cancelUpload(self, index):
job = self.jobs[index.row()]
job["reply"].abort()
# Ask for user and password
def onAuthenticationRequired(self, reply, authenticator):
self.authenticationRequired.emit(authenticator)
# Upload job finished update job status
def onUploadFinished(self, reply):
status = UploadingModel.UPLOAD_STATUS_FINISHED
if reply.error() != QNetworkReply.NoError:
print("Upload error:", reply.error())
if reply.error() == QNetworkReply.OperationCanceledError:
status = UploadingModel.UPLOAD_STATUS_CANCEL
else:
status = UploadingModel.UPLOAD_STATUS_ERROR
replyRow = self.indexOf(reply)
if replyRow == -1:
return
replyIndex = self.index(replyRow, UploadingModel.PROGRESS_COLUMN)
self.jobs[replyRow]["progress"] = status
self.dataChanged.emit(replyIndex, replyIndex)
# Update job progress
def onUploadProgressChanged(self, bytesSent, bytesTotal):
reply = self.sender()
if not reply:
return
replyRow = self.indexOf(reply)
if replyRow == -1:
print("Reply not found in job list", reply, replyRow)
return
# avoid division by zero
if bytesSent == 0:
self.jobs[replyRow]["progress"] = 0
else:
self.jobs[replyRow]["progress"] = (bytesSent * 100) / bytesTotal
progressIndex = self.index(replyRow, UploadingModel.PROGRESS_COLUMN)
self.dataChanged.emit(progressIndex, progressIndex)
# Helper function to find the model index for a specific reply object
def indexOf(self, reply):
for i in range(len(self.jobs)):
if self.jobs[i]["reply"] == reply:
return i
return -1
# QAbstractListModel virtual functions
def columnCount(self, parent=QModelIndex()):
return 2
def rowCount(self, parent=QModelIndex()):
return len(self.jobs)
def data(self, index, role=Qt.DisplayRole):
if not self.hasIndex(index.row(), index.column()):
return None
if role == Qt.DisplayRole:
replyRow = index.row()
if index.column() == UploadingModel.FILE_COLUMN:
return self.jobs[replyRow]["file"].fileName()
elif index.column() == UploadingModel.PROGRESS_COLUMN:
return self.jobs[replyRow]["progress"]
return None
def headerData(self, section, orientation, role=Qt.DisplayRole):
if role != Qt.DisplayRole or orientation == Qt.Vertical:
return None
if section == UploadingModel.FILE_COLUMN:
return self.tr("Filename")
elif section == UploadingModel.PROGRESS_COLUMN:
return self.tr("Progress")
return None
def parent(self, index):
return QModelIndex()
# Login window allow user to enter credentials
class LoginWindow(QDialog):
abort = Signal()
def __init__(self, tray, parent=None):
super(LoginWindow, self).__init__(parent)
self.trayIcon = tray
frame = QFrame(self)
frameLayout = QFormLayout()
self.usernameField = QLineEdit(frame)
self.passwordField = QLineEdit(frame)
self.passwordField.setEchoMode(QLineEdit.Password)
frameLayout.addRow(self.tr("Username"), self.usernameField)
frameLayout.addRow(self.tr("Password"), self.passwordField)
frame.setLayout(frameLayout)
okButton = QPushButton(self.tr("&Ok"), frame)
okButton.clicked.connect(self.accept)
cancelButton = QPushButton(self.tr("&Cancel"), frame)
cancelButton.clicked.connect(self.reject)
buttonLayout = QHBoxLayout()
buttonLayout.addStretch(1)
buttonLayout.addWidget(okButton)
buttonLayout.addWidget(cancelButton)
layout = QVBoxLayout()
layout.addWidget(frame)
layout.addLayout(buttonLayout)
self.setLayout(layout)
# returns username
def username(self):
return self.usernameField.text()
# returns password
def password(self):
return self.passwordField.text()
# Application main window
class MainWindow(QWidget):
def __init__(self, tray, parent=None):
super(MainWindow, self).__init__(parent)
self.tray = tray
self.model = UploadingModel()
self.model.authenticationRequired.connect(self.onAuthenticationRequired)
layout = QVBoxLayout()
# Create a table view to show upload jobs
self.tableview = QTableView(self)
self.tableview.setModel(self.model)
self.tableview.setItemDelegateForColumn(
UploadingModel.PROGRESS_COLUMN, ProgressBarDelegate(self)
)
self.tableview.activated.connect(self.onItemActivated)
h = self.tableview.horizontalHeader()
h.setSectionResizeMode(0, QHeaderView.Stretch)
layout.addWidget(self.tableview, 1)
uploadButton = QPushButton(self.tr("&Upload"), self)
uploadButton.clicked.connect(self.onUploadButtonClicked)
buttonsLayout = QHBoxLayout()
buttonsLayout.addStretch(1)
buttonsLayout.addWidget(uploadButton)
layout.addLayout(buttonsLayout)
self.setLayout(layout)
# Start a new upload process
def onUploadButtonClicked(self):
filename = QFileDialog.getOpenFileName(
self,
self.tr("Select file to upload"),
QStandardPaths.standardLocations(QStandardPaths.DocumentsLocation)[0],
)
if filename == "":
return
self.model.startUpload(filename[0])
# Cancel upload?
def onItemActivated(self, index):
reply = QMessageBox.question(
self, self.tr("Cancel"), self.tr("Cancel upload for: %s") % index.data()
)
if reply == QMessageBox.Yes:
self.model.cancelUpload(index)
# When model require a new authentication
def onAuthenticationRequired(self, authenticator):
login = LoginWindow(self)
r = login.exec_()
login.hide()
if r == QDialog.Accepted:
authenticator.setUser(login.username())
authenticator.setPassword(login.password())
# Avoid close window when clicked on close button
def closeEvent(self, event):
self.hide()
event.ignore()
if __name__ == "__main__":
app = QApplication(sys.argv)
tray = QSystemTrayIcon()
tray.setToolTip("Uploading files")
tray.setIcon(QIcon("icon.png"))
win = MainWindow(tray)
menu = QMenu()
menu.addAction(menu.tr("Quit"), app.quit)
menu.addAction(menu.tr("Open"), win.showMaximized)
tray.setContextMenu(menu)
tray.show()
win.showMaximized()
app.exec_()
<file_sep>Uploaders
=========
Rodando o server
----------------
Configure a pasta onde os arquivos serao armazenados editando: 'config.py'
Para rodar o server basta executar no shell:
$ python ./server.py
Rodando o cliente
-----------------
Configure o endereço do server editando o arquivo: 'config.py'
Para rodar o cliente basta executar no shell:
$ python ./client.py
|
76d46228d8434ab2d096947089b643def4b1ea87
|
[
"Markdown",
"Python"
] | 4 |
Python
|
renatofilho/uploaders
|
d6b223e2e9e922c8d5199da69ec5a82e7c2a109e
|
acb1880b5c2e757f90d8eddaa2f33941d41d44cb
|
refs/heads/master
|
<repo_name>kevincchang13/Practice-Problems<file_sep>/hammingDistance-oneCharDifference.js
// Please implement the following functions:
// 1. Hamming Distance (https://en.wikipedia.org/wiki/Hamming_distance).
// This function takes in two strings of equal length, and calculates the distance between them. Here, "distance" is defined as the number of characters that differ at the same position. The function should ignore case.
// If the inputs do not have the same length, the function should return "Input strings must have the same length."
// Examples:
// hammingDistance("hello", "jello") // 1
// hammingDistance("cool", "kewl") // 3
// hammingDistance("sweet", "Sweet") // 0
// hammingDistance("yoyo", "yoyoyo") // "Input strings must have the same length."
function hammingDistance(str1, str2) {
if (str1.length !== str2.length) {
return 'Input strings must have the same length'
}
var count = 0
for (let i = 0; i < str1.length; i++) {
if (str1[i].toLowerCase() !== str2[i].toLowerCase()) {
count++
}
}
return count
}
// 2. Implement a function called
// oneCharDifference
// which checks whether there two strings differ by a single character.
// The difference may consist of one character being added, removed, or replaced, in which case the function must return true. In all other cases it must return false. As with hammingDistance, this function should ignore case.
// Examples:
// oneCharDifference("grate", "grape") // true
// oneCharDifference("male", "maple") // true
// oneCharDifference("help", "helping") // false
// oneCharDifference("boom", "boo") // true
// oneCharDifference("same", "same") // false
function oneCharDifference(str1, str2) {
let count = 0
let i = 0
let j = 0
while (j < str1.length) {
if (str1[i] === str2[j]) {
i++
j++
} else if (str1[i] !== str2[j] && str1[i+1] === str2[j+1]) {
count++
j++
i++
} else if(str1[i] !== str2[j] && str1[i] === str2[j+1]) {
count++
j++
}
}
if (count === 1) {
return true
} else {
return false
}
}
<file_sep>/Recursion1-redo.js
// Part I
// Write a recursive function called fib which accepts a number and returns the nth number in the Fibonacci sequence. Recall that the Fibonacci sequence is the sequence of whole numbers 1, 1, 2, 3, 5, 8, ... which starts with 1 and 1, and where every number thereafter is equal to the sum of the previous two numbers.
// fib(4); // 3
// fib(10); // 55
// fib(28); // 317811
// fib(35); // 9227465
function fib(num, prev=1, current=1, i=2) {
if (i === num) {return current}
return fib(num, current, prev+current, i++)
}
// Part II
// Write a recursive function called isPalindrome which returns true if the string passed to it is a palindrome (reads the same forward and backward). Otherwise it returns false.
// isPalindrome('awesome') // false
// isPalindrome('foobar') // false
// isPalindrome('tacocat') // true
// isPalindrome("amanaplanacanalpanama"); // true
// isPalindrome("amanaplanacanalpandemonium"); // false
//doesnt account for spaces
function isPalindrome(str, start=0, end=str.length-1) {
if (start >= end) {return true}
if (str[start].toLowerCase() !== str[end].toLowerCase()) {
return false
} else {
return isPalindrome(str,start+1,end-1)
}
}
//accounts for spaces
function isPalindrome(str, start=0, end=str.length-1) {
if (start >= end) {return true}
if (str[start] === " ") {
start++
}
if (str[end] === " ") {
end--
}
if (str[start].toLowerCase() !== str[end].toLowerCase()) {
return false
} else {
return isPalindrome(str,start+1,end-1)
}
}
// Part III
// Write a recursive function called someRecursive which accepts an array and a callback. The function returns true if a single value in the array returns true when passed to the callback. Otherwise it returns false.
// const isOdd = val => val % 2 !== 0;
// someRecursive([1,2,3,4], isOdd) // true
// someRecursive([4,6,8,9], isOdd) // true
// someRecursive([4,6,8], isOdd) // false
// someRecursive([4,6,8], val => val > 10); // false
function someRecursive(arr, fn, i=0) {
if (i === arr.length) {return false}
if (fn(arr[i])) {
return true
} else {
return someRecursive(arr,fn, i+1)
}
}
// Part IV
// Write a recursive function called reverse which accepts a string and returns a new string in reverse.
// reverse('awesome') // 'emosewa'
// reverse('rithmschool') // 'loohcsmhtir'
//recurse
function reverse(str, newStr="", end=str.length-1) {
if (end < 0) {return newStr}
return reverse(str,newStr.concat(str[end]), end-1)
}
//iteration
function reverse(str) {
var arr = str.split("")
var i = 0
var j = arr.length-1
while(i<j){
[arr[i], arr[j]] = [arr[j], arr[i]]
i++
j--
}
return arr.join("")
}
// Part V
// Write a recursive function called collectOddValues which accepts an array of numbers and returns a new array of only the odd values.
// collectOddValues([1,2,3,4,5,6,7]) // [1,3,5,7]
// collectOddValues([-2,1,-11,3,9,16,17]) // [-1,-11,3,9,17]
function collectOddValues(arr,odds=[]) {
if (arr.length === 0) {return odds}
var val = arr.pop()
if (Math.abs(val%2) === 1) {
odds.push(val)
}
return collectOddValues(arr,odds)
}
// Part VI
// Write a recursive function called flatten which accepts an array of arrays and returns a new array with all values flattened.
// flatten([1, 2, 3, [4, 5] ]) // [1, 2, 3, 4, 5]
// flatten([1, [2, [3, 4], [[5]]]]) // [1, 2, 3, 4, 5]
// flatten([[1],[2],[3]]) // [1,2,3]
// flatten([[[[1], [[[2]]], [[[[[[[3]]]]]]]]]]) // [1,2,3]
//doesnt work
// function flatten(arr, result=[]) {
// for (let i = 0; i < arr.length; i++) {
// if (Array.isArray(arr[i])) {
// return flatten(arr[i], result)
// } else {
// result.push(arr[i])
// }
// }
// return result
// }
// Part VII
// Write a recursive function called capitalizeWords. Given an array of words, return a new array containing each word capitalized.
// var words = ['i', 'am', 'learning', 'recursion'];
// capitalizedWords(words); // ['I', 'AM', 'LEARNING', 'RECURSION']
function capitalizeWords (arr, result=[], i=0) {
if (i > arr.length-1) {return result}
var upper = arr[i].toUpperCase()
result.push(upper)
return capitalizeWords(arr,result,i+1)
}
// Part VIII
// Write a recursive function called capitalizeFirst. Given an array of strings, capitalize the first letter of each string in the array.
// capitalizeFirst(['car','taco','banana']); // ['Car','Taco','Banana']
function capitalizeFirst(arr, result=[], i=0) {
if (i > arr.length-1) {return result}
var upper = arr[i][0].toUpperCase().concat(arr[i].slice(1))
result.push(upper)
return capitalizeFirst(arr,result,i+1)
}
// Part IX
// Write a recursive function called nestedEvenSum. Return the sum of all even numbers in an object which may contain nested objects.
// var obj1 = {
// outer: 2,
// obj: {
// inner: 2,
// otherObj: {
// superInner: 2,
// notANumber: true,
// alsoNotANumber: "yup"
// }
// }
// }
// var obj2 = {
// a: 2,
// b: {b: 2, bb: {b: 3, bb: {b: 2}}},
// c: {c: {c: 2}, cc: 'ball', ccc: 5},
// d: 1,
// e: {e: {e: 2}, ee: 'car'}
// };
// nestedEvenSum(obj1); // 6
// nestedEvenSum(obj2); // 10
<file_sep>/isSubsequence.js
// Implement a function called isSubsequence which takes in two strings and checks whether the characters in the first string form a subsequence of the characters in the second string. In other words, the function should check whether the characters in the first string appear somewhere in the second string, without their order changing.
// Examples:
// isSubsequence('hello', 'hello world'); // true
// isSubsequence('sing', 'sting'); // true
// isSubsequence('abc', 'abracadabra'); // true
// isSubsequence('abc', 'acb'); // false - order matters!
function isSubsequence(s1,s2) {
var i = 0
var j = 0
while (j < s2.length) {
if (s1[i] === s2[j]) {
i++
j++
} else {
j++
}
}
if (i === s1.length) {
return true
} else {
return false
}
}
// BONUS:
// Solve this problem in O(1) space complexity, and O(n + m) time complexity, where n is the length of the first string and m is the length of the second string.
<file_sep>/averagePair.js
// Write a function called averagePair. Given a sorted array of integers and a target average, determine if there is a pair of values in the array where the average of the pair equals the target average. There may be more than one pair that matches the average target.
// Your solution MUST have the following complexities:
// Time: O(N)
// Space: O(1)
// Sample Input:
// averagePair([1,2,3],2.5) // true
// averagePair([1,3,3,5,6,7,10,12,19],8) // true
// averagePair([-1,0,3,4,5,6], 4.1) // false
// averagePair([],4) // false
function averagePair(arr, n) {
var lookFor = n*2
let i = 0
let j = arr.length-1
while (i < j) {
if (arr[i] + arr[j] === lookFor) {
return true
} else if (arr[i]+arr[j] < lookFor) {
i++
} else if (arr[i]+arr[j] > lookFor) {
j--
}
}
return false
}
<file_sep>/areThereDuplicates-addCommas.js
// 1. Implement a function called
// areThereDuplicates
// which checks whether there are any duplicates among the arguments passed in. The function should either run in O(n) time and O(n) space or O(n log n) time and O(1) space.
// Examples:
// areThereDuplicates(1, 2, 3) // false
// areThereDuplicates(1, 2, 2) // true
// areThereDuplicates('a', 'b', 'c', 'a') // true
function areThereDuplicates(...args) {
var counter = {}
for (let i = 0; i < args.length; i++) {
counter[args[i]] = ++counter[args[i]] || 1
}
const count = Object.values(counter)
for (let i = 0; i < count.length; i++) {
if (count[i] > 1) {
return true
}
}
return false
}
function areThereDuplicates(...args) {
var argsObj = {...args}
var sortedArgs = Object.values(argsObj).sort()
for (let i = 0; i < sortedArgs.length; i++) {
if (sortedArgs[i] === sortedArgs[i+1]) {
return true
}
}
return false
}
// 2. Add commas.
// This function takes in a number and formats that number so that it has commas after every third digit to the left of the decimal point. You can assume that all numbers are non-negative.
// Examples:
// addCommas(1) // "1"
// addCommas(1000) // "1,000"
// addCommas(123456789) // "123,456,789"
// addCommas(3.141592) // "3.141592"
// addCommas(54321.99) // "54,321.99"
<file_sep>/collatzSequence.js
// Implement the following functions:
// Collatz sequence.
// Given a positive whole number n, this function should produce an array given by the following rules:
// 1. The first element in the array should be n.
// 2. After the first element, each subsequent element should be equal to:
// - Half the previous element, if the previous element is even,
// - Three times the previous element plus one, if the previous element is odd.
// Note that in either case, the result should be an integer.
// 3. The last element in the array should be 1. When you encounter your first 1, you should push it to the array and return the array.
// Examples:
// collatzSequence(4); // [4, 2, 1]
// collatzSequence(6); // [6, 3, 10, 5, 16, 8, 4, 2, 1]
// collatzSequence(7); // [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
// collatzSequence(0); // "Input must be a positive whole number."
// collatzSequence([]); // "Input must be a positive whole number."
//Iteration
function collatzSequence(n) {
if (n === null || n === 0) {
return "Input must be a positive whole number."
}
var answer = [n]
var temp = n
while (temp !== 1) {
if (temp%2 === 0) {
temp = temp/2
} else if (temp%2 === 1) {
temp = temp*3+1
}
answer.push(temp)
}
answer.push(1)
return answer
}
//Recursive
function collatzSequence(n, answer=[]) {
if (n === null || n === 0) return "Input must be a positive whole number."
if (n === 1) {
answer.push(n)
return answer
}
answer.push(n)
if (n%2 === 0) {
collatzSequence(n/2, answer)
} else {
collatzSequence((n*2+1), answer)
}
}
<file_sep>/findPair.js
// Given an unsorted array and a number n, find if there exists a pair of elements in the array whose difference is n. This function should return true if the pair exists or false if it does not.
// findPair([6,1,4,10,2,4], 2) // true
// findPair([8,6,2,4,1,0,2,5,13],1) // true
// findPair([4,-2,3,10],-6) // true
// findPair([6,1,4,10,2,4], 22) // false
// findPair([], 0) // false
// findPair([5,5], 0) // true
//O(n^2)
function findPair(a,n) {
for (let i = 0; i < a.length; i++) {
for (let j = i+1; j < a.length; j++) {
if (Math.abs(a[i] - a[j] === n)) {
return true
}
}
}
return false
}
// Bonus 1 - solve this with the following requirements:
// Time Complexity Requirement - O(n)
// Space Complexity Requirement - O(n)
function findPair(a,n) {
var aSet = new Set(a)
var aObj = {}
for (let i = 0; i < a.length; i++) {
aObj[a[i]] = Math.abs(a[i]-n)
}
for (var key in aObj) {
if (aSet.has(aObj[key])) {
return true
}
}
return false
}
// Bonus 2 - solve this with the following requirements:
// Time Complexity Requirement - O(n log n)
// Space Complexity Requirement - O(1)
// Bonus 3 - implement both bonuses in Python!
<file_sep>/truncate.js
// Implement the following function:
// 1. Truncate.
// Given a string and a number n, truncate the string to a shorter string containing at most n characters. If the string gets truncated, the truncated return string should have a "..." at the end. Because of this, the smallest number passed in as a second argument should be 3.
// Examples:
// truncate("Hello World", 6) // "Hel..."
// truncate("Problem solving is the best!", 10) // "Problem..."
// truncate("Yo", 100) // "Yo"
// truncate("Super cool", 3) // "..."
// truncate("Super cool", 2) // "Truncation must be at least 3 characters."
// Implement this function in two ways: iteratively and recursively.
function truncate(str, n) {
if (n < 3) return "Truncation must be at least 3 characters."
if (str.length < n) return str
return str.slice(0,n-3).concat("...")
}
<file_sep>/Repl Problems.js
// Implement a function called addUpTo which takes a number as an argument and adds up all the whole numbers from 1 up to and including the number passed in.
// Some edge cases to consider:
// If the argument passed in is not a number, the function should return NaN.
// If the argument passed in is less than 1, the function should return 0.
// If the argument passed in is not a whole number, the function should add up all the whole numbers between 1 and the largest whole number less than the argument passed in.
// Examples:
// addUpTo(5); // 15, since 1 + 2 + 3 + 4 + 5 = 15
// addUpTo(10); // 55
// addUpTo("three"); // NaN
// addUpTo(null); // NaN
// addUpTo(0); // 0
// addUpTo(-100); // 0
// addUpTo(3.4); // 6
// addUpTo(5.9999999); // 15
function addUpTo(num) {
if (typeof(num) !== 'number') {
return NaN
}
if (num < 1) {return 0}
return (Math.floor(num)*(Math.floor(num)+1))/2
}
// Write a function called twoArrayObject which accepts to arrays of varying lengths.The first array consists of keys and the second one consists of values. Your function should return an object created from the keys and values. If there are not enough values, the rest of keys should have a value of null. If there not enough keys, just ignore the rest of values.
// twoArrayObject(['a', 'b', 'c', 'd'], [1, 2, 3]) // {'a': 1, 'b': 2, 'c': 3, 'd': null}
// twoArrayObject(['a', 'b', 'c'] , [1, 2, 3, 4]) // {'a': 1, 'b': 2, 'c': 3}
// twoArrayObject(['x', 'y', 'z'] , [1,2]) // {'x': 1, 'y': 2, 'z': null}
function twoArrayObject(arr1, arr2) {
var result = {}
for (let i = 0; i < arr1.length; i++) {
if (arr2[i]){
result[arr1[i]] = arr2[i]
} else {
result[arr1[i]] = null
}
}
return result
}
// Write a function called validParentheses that takes a string of parentheses, and determines if the order of the parentheses is valid. validParentheses should return true if the string is valid, and false if it's invalid.
// validParentheses("()") // true
// validParentheses(")(()))") // false
// validParentheses("(") // false
// validParentheses("(())((()())())") // true
// validParentheses('))((') // false
// validParentheses('())(') // false
// validParentheses('()()()()())()(') // false
<file_sep>/validBraces.js
// Write a function called validBraces that takes a string of braces, and determines if the order of the braces is valid. validBraces should return true if the string is valid, and false if it's invalid.
// This problem is similar to validParenthesis, but introduces four new characters. Open and closed brackets, and open and closed curly braces. All input strings will be nonempty, and will only consist of:
// - open parentheses '('
// - closed parentheses ')'
// - open brackets '['
// - closed brackets ']'
// - open curly braces '{'
// - closed curly braces '}'
// validBraces("()") // true
// validBraces("[]") // true
// validBraces("{}") // true
// validBraces("(){}[]") // true
// validBraces("([{}])") // true
// validBraces("({})[({})]") // true
// validBraces("(({{[[]]}}))") // true
// validBraces("{}({})[]") // true
// validBraces(")(}{][") // false
// validBraces("())({}}{()][][") // false
// validBraces("(((({{") // false
// validBraces("}}]]))}])") // false
// validBraces("(}") // false
// validBraces("[(])") // false
// BONUS - Solve this in O(n) Time
function validBraces(str) {
const openBrace = new Set('{','[','(')
const closeBrase = new Set('}',']',')')
var count = 0
var i = 0
while (i < str.length) {
if (count < 0) {
return false
} else {
if (openBrace.has(str[i])) {
count ++
} else if (closeBrase.has(str[i])) {
count --
}
i++
}
}
if (count === 0) {
return true
} else {
return false
}
}
|
c3b264daf56e376140bf1222b4b0d6309c9c2ffb
|
[
"JavaScript"
] | 10 |
JavaScript
|
kevincchang13/Practice-Problems
|
d8141f7fc9add21748d1c1f607f2fa18590ff9ae
|
c1f59eb85898c4ef4fc383e1c01a7f527e6a9d9e
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.